Proyecto audio control. inicado con panel y control.
This commit is contained in:
202
node_modules/google-auth-library/LICENSE
generated
vendored
Normal file
202
node_modules/google-auth-library/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
1504
node_modules/google-auth-library/README.md
generated
vendored
Normal file
1504
node_modules/google-auth-library/README.md
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
298
node_modules/google-auth-library/build/src/auth/authclient.d.ts
generated
vendored
Normal file
298
node_modules/google-auth-library/build/src/auth/authclient.d.ts
generated
vendored
Normal file
@@ -0,0 +1,298 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import { Gaxios, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios';
|
||||
import { Credentials } from './credentials';
|
||||
import { OriginalAndCamel } from '../util';
|
||||
/**
|
||||
* An interface for enforcing `fetch`-type compliance.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* This provides type guarantees during build-time, ensuring the `fetch` method is 1:1
|
||||
* compatible with the `Gaxios#fetch` API.
|
||||
*/
|
||||
interface GaxiosFetchCompliance {
|
||||
fetch: typeof fetch | Gaxios['fetch'];
|
||||
}
|
||||
/**
|
||||
* Easy access to symbol-indexed strings on config objects.
|
||||
*/
|
||||
export type SymbolIndexString = {
|
||||
[key: symbol]: string | undefined;
|
||||
};
|
||||
/**
|
||||
* Base auth configurations (e.g. from JWT or `.json` files) with conventional
|
||||
* camelCased options.
|
||||
*
|
||||
* @privateRemarks
|
||||
*
|
||||
* This interface is purposely not exported so that it can be removed once
|
||||
* {@link https://github.com/microsoft/TypeScript/issues/50715} has been
|
||||
* resolved. Then, we can use {@link OriginalAndCamel} to shrink this interface.
|
||||
*
|
||||
* Tracking: {@link https://github.com/googleapis/google-auth-library-nodejs/issues/1686}
|
||||
*/
|
||||
interface AuthJSONOptions {
|
||||
/**
|
||||
* The project ID corresponding to the current credentials if available.
|
||||
*/
|
||||
project_id: string | null;
|
||||
/**
|
||||
* An alias for {@link AuthJSONOptions.project_id `project_id`}.
|
||||
*/
|
||||
projectId: AuthJSONOptions['project_id'];
|
||||
/**
|
||||
* The quota project ID. The quota project can be used by client libraries for the billing purpose.
|
||||
* See {@link https://cloud.google.com/docs/quota Working with quotas}
|
||||
*/
|
||||
quota_project_id: string;
|
||||
/**
|
||||
* An alias for {@link AuthJSONOptions.quota_project_id `quota_project_id`}.
|
||||
*/
|
||||
quotaProjectId: AuthJSONOptions['quota_project_id'];
|
||||
/**
|
||||
* The default service domain for a given Cloud universe.
|
||||
*
|
||||
* @example
|
||||
* 'googleapis.com'
|
||||
*/
|
||||
universe_domain: string;
|
||||
/**
|
||||
* An alias for {@link AuthJSONOptions.universe_domain `universe_domain`}.
|
||||
*/
|
||||
universeDomain: AuthJSONOptions['universe_domain'];
|
||||
}
|
||||
/**
|
||||
* Base `AuthClient` configuration.
|
||||
*
|
||||
* The camelCased options are aliases of the snake_cased options, supporting both
|
||||
* JSON API and JS conventions.
|
||||
*/
|
||||
export interface AuthClientOptions extends Partial<OriginalAndCamel<AuthJSONOptions>> {
|
||||
/**
|
||||
* An API key to use, optional.
|
||||
*/
|
||||
apiKey?: string;
|
||||
credentials?: Credentials;
|
||||
/**
|
||||
* The {@link Gaxios `Gaxios`} instance used for making requests.
|
||||
*
|
||||
* @see {@link AuthClientOptions.useAuthRequestParameters}
|
||||
*/
|
||||
transporter?: Gaxios;
|
||||
/**
|
||||
* Provides default options to the transporter, such as {@link GaxiosOptions.agent `agent`} or
|
||||
* {@link GaxiosOptions.retryConfig `retryConfig`}.
|
||||
*
|
||||
* This option is ignored if {@link AuthClientOptions.transporter `gaxios`} has been provided
|
||||
*/
|
||||
transporterOptions?: GaxiosOptions;
|
||||
/**
|
||||
* The expiration threshold in milliseconds before forcing token refresh of
|
||||
* unexpired tokens.
|
||||
*/
|
||||
eagerRefreshThresholdMillis?: number;
|
||||
/**
|
||||
* Whether to attempt to refresh tokens on status 401/403 responses
|
||||
* even if an attempt is made to refresh the token preemptively based
|
||||
* on the expiry_date.
|
||||
*/
|
||||
forceRefreshOnFailure?: boolean;
|
||||
/**
|
||||
* Enables/disables the adding of the AuthClient's default interceptor.
|
||||
*
|
||||
* @see {@link AuthClientOptions.transporter}
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* Disabling is useful for debugging and experimentation.
|
||||
*
|
||||
* @default true
|
||||
*/
|
||||
useAuthRequestParameters?: boolean;
|
||||
}
|
||||
/**
|
||||
* The default cloud universe
|
||||
*
|
||||
* @see {@link AuthJSONOptions.universe_domain}
|
||||
*/
|
||||
export declare const DEFAULT_UNIVERSE = "googleapis.com";
|
||||
/**
|
||||
* The default {@link AuthClientOptions.eagerRefreshThresholdMillis}
|
||||
*/
|
||||
export declare const DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS: number;
|
||||
/**
|
||||
* Defines the root interface for all clients that generate credentials
|
||||
* for calling Google APIs. All clients should implement this interface.
|
||||
*/
|
||||
export interface CredentialsClient {
|
||||
projectId?: AuthClientOptions['projectId'];
|
||||
eagerRefreshThresholdMillis: NonNullable<AuthClientOptions['eagerRefreshThresholdMillis']>;
|
||||
forceRefreshOnFailure: NonNullable<AuthClientOptions['forceRefreshOnFailure']>;
|
||||
/**
|
||||
* @return A promise that resolves with the current GCP access token
|
||||
* response. If the current credential is expired, a new one is retrieved.
|
||||
*/
|
||||
getAccessToken(): Promise<GetAccessTokenResponse>;
|
||||
/**
|
||||
* The main authentication interface. It takes an optional url which when
|
||||
* present is the endpoint being accessed, and returns a Promise which
|
||||
* resolves with authorization header fields.
|
||||
*
|
||||
* The result has the form:
|
||||
* { authorization: 'Bearer <access_token_value>' }
|
||||
* @param url The URI being authorized.
|
||||
*/
|
||||
getRequestHeaders(url?: string | URL): Promise<Headers>;
|
||||
/**
|
||||
* Provides an alternative Gaxios request implementation with auth credentials
|
||||
*/
|
||||
request<T>(opts: GaxiosOptions): GaxiosPromise<T>;
|
||||
/**
|
||||
* Sets the auth credentials.
|
||||
*/
|
||||
setCredentials(credentials: Credentials): void;
|
||||
/**
|
||||
* Subscribes a listener to the tokens event triggered when a token is
|
||||
* generated.
|
||||
*
|
||||
* @param event The tokens event to subscribe to.
|
||||
* @param listener The listener that triggers on event trigger.
|
||||
* @return The current client instance.
|
||||
*/
|
||||
on(event: 'tokens', listener: (tokens: Credentials) => void): this;
|
||||
}
|
||||
export declare interface AuthClient {
|
||||
on(event: 'tokens', listener: (tokens: Credentials) => void): this;
|
||||
}
|
||||
/**
|
||||
* The base of all Auth Clients.
|
||||
*/
|
||||
export declare abstract class AuthClient extends EventEmitter implements CredentialsClient, GaxiosFetchCompliance {
|
||||
apiKey?: string;
|
||||
projectId?: string | null;
|
||||
/**
|
||||
* The quota project ID. The quota project can be used by client libraries for the billing purpose.
|
||||
* See {@link https://cloud.google.com/docs/quota Working with quotas}
|
||||
*/
|
||||
quotaProjectId?: string;
|
||||
/**
|
||||
* The {@link Gaxios `Gaxios`} instance used for making requests.
|
||||
*/
|
||||
transporter: Gaxios;
|
||||
credentials: Credentials;
|
||||
eagerRefreshThresholdMillis: number;
|
||||
forceRefreshOnFailure: boolean;
|
||||
universeDomain: string;
|
||||
/**
|
||||
* Symbols that can be added to GaxiosOptions to specify the method name that is
|
||||
* making an RPC call, for logging purposes, as well as a string ID that can be
|
||||
* used to correlate calls and responses.
|
||||
*/
|
||||
static readonly RequestMethodNameSymbol: unique symbol;
|
||||
static readonly RequestLogIdSymbol: unique symbol;
|
||||
constructor(opts?: AuthClientOptions);
|
||||
/**
|
||||
* A {@link fetch `fetch`} compliant API for {@link AuthClient}.
|
||||
*
|
||||
* @see {@link AuthClient.request} for the classic method.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* This is useful as a drop-in replacement for `fetch` API usage.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```ts
|
||||
* const authClient = new AuthClient();
|
||||
* const fetchWithAuthClient: typeof fetch = (...args) => authClient.fetch(...args);
|
||||
* await fetchWithAuthClient('https://example.com');
|
||||
* ```
|
||||
*
|
||||
* @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters
|
||||
* @returns the {@link GaxiosResponse} with Gaxios-added properties
|
||||
*/
|
||||
fetch<T>(...args: Parameters<Gaxios['fetch']>): GaxiosPromise<T>;
|
||||
/**
|
||||
* The public request API in which credentials may be added to the request.
|
||||
*
|
||||
* @see {@link AuthClient.fetch} for the modern method.
|
||||
*
|
||||
* @param options options for `gaxios`
|
||||
*/
|
||||
abstract request<T>(options: GaxiosOptions): GaxiosPromise<T>;
|
||||
/**
|
||||
* The main authentication interface. It takes an optional url which when
|
||||
* present is the endpoint being accessed, and returns a Promise which
|
||||
* resolves with authorization header fields.
|
||||
*
|
||||
* The result has the form:
|
||||
* ```ts
|
||||
* new Headers({'authorization': 'Bearer <access_token_value>'});
|
||||
* ```
|
||||
*
|
||||
* @param url The URI being authorized.
|
||||
*/
|
||||
abstract getRequestHeaders(url?: string | URL): Promise<Headers>;
|
||||
/**
|
||||
* @return A promise that resolves with the current GCP access token
|
||||
* response. If the current credential is expired, a new one is retrieved.
|
||||
*/
|
||||
abstract getAccessToken(): Promise<{
|
||||
token?: string | null;
|
||||
res?: GaxiosResponse | null;
|
||||
}>;
|
||||
/**
|
||||
* Sets the auth credentials.
|
||||
*/
|
||||
setCredentials(credentials: Credentials): void;
|
||||
/**
|
||||
* Append additional headers, e.g., x-goog-user-project, shared across the
|
||||
* classes inheriting AuthClient. This method should be used by any method
|
||||
* that overrides getRequestMetadataAsync(), which is a shared helper for
|
||||
* setting request information in both gRPC and HTTP API calls.
|
||||
*
|
||||
* @param headers object to append additional headers to.
|
||||
*/
|
||||
protected addSharedMetadataHeaders(headers: Headers): Headers;
|
||||
/**
|
||||
* Adds the `x-goog-user-project` and `authorization` headers to the target Headers
|
||||
* object, if they exist on the source.
|
||||
*
|
||||
* @param target the headers to target
|
||||
* @param source the headers to source from
|
||||
* @returns the target headers
|
||||
*/
|
||||
protected addUserProjectAndAuthHeaders<T extends Headers>(target: T, source: Headers): T;
|
||||
static log: import("google-logging-utils").AdhocDebugLogFunction;
|
||||
static readonly DEFAULT_REQUEST_INTERCEPTOR: Parameters<Gaxios['interceptors']['request']['add']>[0];
|
||||
static readonly DEFAULT_RESPONSE_INTERCEPTOR: Parameters<Gaxios['interceptors']['response']['add']>[0];
|
||||
/**
|
||||
* Sets the method name that is making a Gaxios request, so that logging may tag
|
||||
* log lines with the operation.
|
||||
* @param config A Gaxios request config
|
||||
* @param methodName The method name making the call
|
||||
*/
|
||||
static setMethodName(config: GaxiosOptions, methodName: string): void;
|
||||
/**
|
||||
* Retry config for Auth-related requests.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* This is not a part of the default {@link AuthClient.transporter transporter/gaxios}
|
||||
* config as some downstream APIs would prefer if customers explicitly enable retries,
|
||||
* such as GCS.
|
||||
*/
|
||||
protected static get RETRY_CONFIG(): GaxiosOptions;
|
||||
}
|
||||
export type HeadersInit = ConstructorParameters<typeof Headers>[0];
|
||||
export interface GetAccessTokenResponse {
|
||||
token?: string | null;
|
||||
res?: GaxiosResponse | null;
|
||||
}
|
||||
/**
|
||||
* @deprecated - use the Promise API instead
|
||||
*/
|
||||
export interface BodyResponseCallback<T> {
|
||||
(err: Error | null, res?: GaxiosResponse<T> | null): void;
|
||||
}
|
||||
export {};
|
||||
286
node_modules/google-auth-library/build/src/auth/authclient.js
generated
vendored
Normal file
286
node_modules/google-auth-library/build/src/auth/authclient.js
generated
vendored
Normal file
@@ -0,0 +1,286 @@
|
||||
"use strict";
|
||||
// Copyright 2012 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AuthClient = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = exports.DEFAULT_UNIVERSE = void 0;
|
||||
const events_1 = require("events");
|
||||
const gaxios_1 = require("gaxios");
|
||||
const util_1 = require("../util");
|
||||
const google_logging_utils_1 = require("google-logging-utils");
|
||||
const shared_cjs_1 = require("../shared.cjs");
|
||||
/**
|
||||
* The default cloud universe
|
||||
*
|
||||
* @see {@link AuthJSONOptions.universe_domain}
|
||||
*/
|
||||
exports.DEFAULT_UNIVERSE = 'googleapis.com';
|
||||
/**
|
||||
* The default {@link AuthClientOptions.eagerRefreshThresholdMillis}
|
||||
*/
|
||||
exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1000;
|
||||
/**
|
||||
* The base of all Auth Clients.
|
||||
*/
|
||||
class AuthClient extends events_1.EventEmitter {
|
||||
apiKey;
|
||||
projectId;
|
||||
/**
|
||||
* The quota project ID. The quota project can be used by client libraries for the billing purpose.
|
||||
* See {@link https://cloud.google.com/docs/quota Working with quotas}
|
||||
*/
|
||||
quotaProjectId;
|
||||
/**
|
||||
* The {@link Gaxios `Gaxios`} instance used for making requests.
|
||||
*/
|
||||
transporter;
|
||||
credentials = {};
|
||||
eagerRefreshThresholdMillis = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;
|
||||
forceRefreshOnFailure = false;
|
||||
universeDomain = exports.DEFAULT_UNIVERSE;
|
||||
/**
|
||||
* Symbols that can be added to GaxiosOptions to specify the method name that is
|
||||
* making an RPC call, for logging purposes, as well as a string ID that can be
|
||||
* used to correlate calls and responses.
|
||||
*/
|
||||
static RequestMethodNameSymbol = Symbol('request method name');
|
||||
static RequestLogIdSymbol = Symbol('request log id');
|
||||
constructor(opts = {}) {
|
||||
super();
|
||||
const options = (0, util_1.originalOrCamelOptions)(opts);
|
||||
// Shared auth options
|
||||
this.apiKey = opts.apiKey;
|
||||
this.projectId = options.get('project_id') ?? null;
|
||||
this.quotaProjectId = options.get('quota_project_id');
|
||||
this.credentials = options.get('credentials') ?? {};
|
||||
this.universeDomain = options.get('universe_domain') ?? exports.DEFAULT_UNIVERSE;
|
||||
// Shared client options
|
||||
this.transporter = opts.transporter ?? new gaxios_1.Gaxios(opts.transporterOptions);
|
||||
if (options.get('useAuthRequestParameters') !== false) {
|
||||
this.transporter.interceptors.request.add(AuthClient.DEFAULT_REQUEST_INTERCEPTOR);
|
||||
this.transporter.interceptors.response.add(AuthClient.DEFAULT_RESPONSE_INTERCEPTOR);
|
||||
}
|
||||
if (opts.eagerRefreshThresholdMillis) {
|
||||
this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis;
|
||||
}
|
||||
this.forceRefreshOnFailure = opts.forceRefreshOnFailure ?? false;
|
||||
}
|
||||
/**
|
||||
* A {@link fetch `fetch`} compliant API for {@link AuthClient}.
|
||||
*
|
||||
* @see {@link AuthClient.request} for the classic method.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* This is useful as a drop-in replacement for `fetch` API usage.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```ts
|
||||
* const authClient = new AuthClient();
|
||||
* const fetchWithAuthClient: typeof fetch = (...args) => authClient.fetch(...args);
|
||||
* await fetchWithAuthClient('https://example.com');
|
||||
* ```
|
||||
*
|
||||
* @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters
|
||||
* @returns the {@link GaxiosResponse} with Gaxios-added properties
|
||||
*/
|
||||
fetch(...args) {
|
||||
// Up to 2 parameters in either overload
|
||||
const input = args[0];
|
||||
const init = args[1];
|
||||
let url = undefined;
|
||||
const headers = new Headers();
|
||||
// prepare URL
|
||||
if (typeof input === 'string') {
|
||||
url = new URL(input);
|
||||
}
|
||||
else if (input instanceof URL) {
|
||||
url = input;
|
||||
}
|
||||
else if (input && input.url) {
|
||||
url = new URL(input.url);
|
||||
}
|
||||
// prepare headers
|
||||
if (input && typeof input === 'object' && 'headers' in input) {
|
||||
gaxios_1.Gaxios.mergeHeaders(headers, input.headers);
|
||||
}
|
||||
if (init) {
|
||||
gaxios_1.Gaxios.mergeHeaders(headers, new Headers(init.headers));
|
||||
}
|
||||
// prepare request
|
||||
if (typeof input === 'object' && !(input instanceof URL)) {
|
||||
// input must have been a non-URL object
|
||||
return this.request({ ...init, ...input, headers, url });
|
||||
}
|
||||
else {
|
||||
// input must have been a string or URL
|
||||
return this.request({ ...init, headers, url });
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Sets the auth credentials.
|
||||
*/
|
||||
setCredentials(credentials) {
|
||||
this.credentials = credentials;
|
||||
}
|
||||
/**
|
||||
* Append additional headers, e.g., x-goog-user-project, shared across the
|
||||
* classes inheriting AuthClient. This method should be used by any method
|
||||
* that overrides getRequestMetadataAsync(), which is a shared helper for
|
||||
* setting request information in both gRPC and HTTP API calls.
|
||||
*
|
||||
* @param headers object to append additional headers to.
|
||||
*/
|
||||
addSharedMetadataHeaders(headers) {
|
||||
// quota_project_id, stored in application_default_credentials.json, is set in
|
||||
// the x-goog-user-project header, to indicate an alternate account for
|
||||
// billing and quota:
|
||||
if (!headers.has('x-goog-user-project') && // don't override a value the user sets.
|
||||
this.quotaProjectId) {
|
||||
headers.set('x-goog-user-project', this.quotaProjectId);
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
/**
|
||||
* Adds the `x-goog-user-project` and `authorization` headers to the target Headers
|
||||
* object, if they exist on the source.
|
||||
*
|
||||
* @param target the headers to target
|
||||
* @param source the headers to source from
|
||||
* @returns the target headers
|
||||
*/
|
||||
addUserProjectAndAuthHeaders(target, source) {
|
||||
const xGoogUserProject = source.get('x-goog-user-project');
|
||||
const authorizationHeader = source.get('authorization');
|
||||
if (xGoogUserProject) {
|
||||
target.set('x-goog-user-project', xGoogUserProject);
|
||||
}
|
||||
if (authorizationHeader) {
|
||||
target.set('authorization', authorizationHeader);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
static log = (0, google_logging_utils_1.log)('auth');
|
||||
static DEFAULT_REQUEST_INTERCEPTOR = {
|
||||
resolved: async (config) => {
|
||||
// Set `x-goog-api-client`, if not already set
|
||||
if (!config.headers.has('x-goog-api-client')) {
|
||||
const nodeVersion = process.version.replace(/^v/, '');
|
||||
config.headers.set('x-goog-api-client', `gl-node/${nodeVersion}`);
|
||||
}
|
||||
// Set `User-Agent`
|
||||
const userAgent = config.headers.get('User-Agent');
|
||||
if (!userAgent) {
|
||||
config.headers.set('User-Agent', shared_cjs_1.USER_AGENT);
|
||||
}
|
||||
else if (!userAgent.includes(`${shared_cjs_1.PRODUCT_NAME}/`)) {
|
||||
config.headers.set('User-Agent', `${userAgent} ${shared_cjs_1.USER_AGENT}`);
|
||||
}
|
||||
try {
|
||||
const symbols = config;
|
||||
const methodName = symbols[AuthClient.RequestMethodNameSymbol];
|
||||
// This doesn't need to be very unique or interesting, it's just an aid for
|
||||
// matching requests to responses.
|
||||
const logId = `${Math.floor(Math.random() * 1000)}`;
|
||||
symbols[AuthClient.RequestLogIdSymbol] = logId;
|
||||
// Boil down the object we're printing out.
|
||||
const logObject = {
|
||||
url: config.url,
|
||||
headers: config.headers,
|
||||
};
|
||||
if (methodName) {
|
||||
AuthClient.log.info('%s [%s] request %j', methodName, logId, logObject);
|
||||
}
|
||||
else {
|
||||
AuthClient.log.info('[%s] request %j', logId, logObject);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
// Logging must not create new errors; swallow them all.
|
||||
}
|
||||
return config;
|
||||
},
|
||||
};
|
||||
static DEFAULT_RESPONSE_INTERCEPTOR = {
|
||||
resolved: async (response) => {
|
||||
try {
|
||||
const symbols = response.config;
|
||||
const methodName = symbols[AuthClient.RequestMethodNameSymbol];
|
||||
const logId = symbols[AuthClient.RequestLogIdSymbol];
|
||||
if (methodName) {
|
||||
AuthClient.log.info('%s [%s] response %j', methodName, logId, response.data);
|
||||
}
|
||||
else {
|
||||
AuthClient.log.info('[%s] response %j', logId, response.data);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
// Logging must not create new errors; swallow them all.
|
||||
}
|
||||
return response;
|
||||
},
|
||||
rejected: async (error) => {
|
||||
try {
|
||||
const symbols = error.config;
|
||||
const methodName = symbols[AuthClient.RequestMethodNameSymbol];
|
||||
const logId = symbols[AuthClient.RequestLogIdSymbol];
|
||||
if (methodName) {
|
||||
AuthClient.log.info('%s [%s] error %j', methodName, logId, error.response?.data);
|
||||
}
|
||||
else {
|
||||
AuthClient.log.error('[%s] error %j', logId, error.response?.data);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
// Logging must not create new errors; swallow them all.
|
||||
}
|
||||
// Re-throw the error.
|
||||
throw error;
|
||||
},
|
||||
};
|
||||
/**
|
||||
* Sets the method name that is making a Gaxios request, so that logging may tag
|
||||
* log lines with the operation.
|
||||
* @param config A Gaxios request config
|
||||
* @param methodName The method name making the call
|
||||
*/
|
||||
static setMethodName(config, methodName) {
|
||||
try {
|
||||
const symbols = config;
|
||||
symbols[AuthClient.RequestMethodNameSymbol] = methodName;
|
||||
}
|
||||
catch (e) {
|
||||
// Logging must not create new errors; swallow them all.
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Retry config for Auth-related requests.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* This is not a part of the default {@link AuthClient.transporter transporter/gaxios}
|
||||
* config as some downstream APIs would prefer if customers explicitly enable retries,
|
||||
* such as GCS.
|
||||
*/
|
||||
static get RETRY_CONFIG() {
|
||||
return {
|
||||
retry: true,
|
||||
retryConfig: {
|
||||
httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'],
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.AuthClient = AuthClient;
|
||||
//# sourceMappingURL=authclient.js.map
|
||||
115
node_modules/google-auth-library/build/src/auth/awsclient.d.ts
generated
vendored
Normal file
115
node_modules/google-auth-library/build/src/auth/awsclient.d.ts
generated
vendored
Normal file
@@ -0,0 +1,115 @@
|
||||
import { AwsSecurityCredentials } from './awsrequestsigner';
|
||||
import { BaseExternalAccountClient, BaseExternalAccountClientOptions, ExternalAccountSupplierContext } from './baseexternalclient';
|
||||
import { SnakeToCamelObject } from '../util';
|
||||
/**
|
||||
* AWS credentials JSON interface. This is used for AWS workloads.
|
||||
*/
|
||||
export interface AwsClientOptions extends BaseExternalAccountClientOptions {
|
||||
/**
|
||||
* Object containing options to retrieve AWS security credentials. A valid credential
|
||||
* source or a aws security credentials supplier should be specified.
|
||||
*/
|
||||
credential_source?: {
|
||||
/**
|
||||
* AWS environment ID. Currently only 'AWS1' is supported.
|
||||
*/
|
||||
environment_id: string;
|
||||
/**
|
||||
* The EC2 metadata URL to retrieve the current AWS region from. If this is
|
||||
* not provided, the region should be present in the AWS_REGION or AWS_DEFAULT_REGION
|
||||
* environment variables.
|
||||
*/
|
||||
region_url?: string;
|
||||
/**
|
||||
* The EC2 metadata URL to retrieve AWS security credentials. If this is not provided,
|
||||
* the credentials should be present in the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY,
|
||||
* and AWS_SESSION_TOKEN environment variables.
|
||||
*/
|
||||
url?: string;
|
||||
/**
|
||||
* The regional GetCallerIdentity action URL, used to determine the account
|
||||
* ID and its roles.
|
||||
*/
|
||||
regional_cred_verification_url: string;
|
||||
/**
|
||||
* The imdsv2 session token url is used to fetch session token from AWS
|
||||
* which is later sent through headers for metadata requests. If the
|
||||
* field is missing, then session token won't be fetched and sent with
|
||||
* the metadata requests.
|
||||
* The session token is required for IMDSv2 but optional for IMDSv1
|
||||
*/
|
||||
imdsv2_session_token_url?: string;
|
||||
};
|
||||
/**
|
||||
* The AWS security credentials supplier to call to retrieve the AWS region
|
||||
* and AWS security credentials. Either this or a valid credential source
|
||||
* must be specified.
|
||||
*/
|
||||
aws_security_credentials_supplier?: AwsSecurityCredentialsSupplier;
|
||||
}
|
||||
/**
|
||||
* Supplier interface for AWS security credentials. This can be implemented to
|
||||
* return an AWS region and AWS security credentials. These credentials can
|
||||
* then be exchanged for a GCP token by an {@link AwsClient}.
|
||||
*/
|
||||
export interface AwsSecurityCredentialsSupplier {
|
||||
/**
|
||||
* Gets the active AWS region.
|
||||
* @param context {@link ExternalAccountSupplierContext} from the calling
|
||||
* {@link AwsClient}, contains the requested audience and subject token type
|
||||
* for the external account identity as well as the transport from the
|
||||
* calling client to use for requests.
|
||||
* @return A promise that resolves with the AWS region string.
|
||||
*/
|
||||
getAwsRegion: (context: ExternalAccountSupplierContext) => Promise<string>;
|
||||
/**
|
||||
* Gets valid AWS security credentials for the requested external account
|
||||
* identity. Note that these are not cached by the calling {@link AwsClient},
|
||||
* so caching should be including in the implementation.
|
||||
* @param context {@link ExternalAccountSupplierContext} from the calling
|
||||
* {@link AwsClient}, contains the requested audience and subject token type
|
||||
* for the external account identity as well as the transport from the
|
||||
* calling client to use for requests.
|
||||
* @return A promise that resolves with the requested {@link AwsSecurityCredentials}.
|
||||
*/
|
||||
getAwsSecurityCredentials: (context: ExternalAccountSupplierContext) => Promise<AwsSecurityCredentials>;
|
||||
}
|
||||
/**
|
||||
* AWS external account client. This is used for AWS workloads, where
|
||||
* AWS STS GetCallerIdentity serialized signed requests are exchanged for
|
||||
* GCP access token.
|
||||
*/
|
||||
export declare class AwsClient extends BaseExternalAccountClient {
|
||||
#private;
|
||||
private readonly environmentId?;
|
||||
private readonly awsSecurityCredentialsSupplier;
|
||||
private readonly regionalCredVerificationUrl;
|
||||
private awsRequestSigner;
|
||||
private region;
|
||||
/**
|
||||
* @deprecated AWS client no validates the EC2 metadata address.
|
||||
**/
|
||||
static AWS_EC2_METADATA_IPV4_ADDRESS: string;
|
||||
/**
|
||||
* @deprecated AWS client no validates the EC2 metadata address.
|
||||
**/
|
||||
static AWS_EC2_METADATA_IPV6_ADDRESS: string;
|
||||
/**
|
||||
* Instantiates an AwsClient instance using the provided JSON
|
||||
* object loaded from an external account credentials file.
|
||||
* An error is thrown if the credential is not a valid AWS credential.
|
||||
* @param options The external account options object typically loaded
|
||||
* from the external account JSON credential file.
|
||||
*/
|
||||
constructor(options: AwsClientOptions | SnakeToCamelObject<AwsClientOptions>);
|
||||
private validateEnvironmentId;
|
||||
/**
|
||||
* Triggered when an external subject token is needed to be exchanged for a
|
||||
* GCP access token via GCP STS endpoint. This will call the
|
||||
* {@link AwsSecurityCredentialsSupplier} to retrieve an AWS region and AWS
|
||||
* Security Credentials, then use them to create a signed AWS STS request that
|
||||
* can be exchanged for a GCP access token.
|
||||
* @return A promise that resolves with the external subject token.
|
||||
*/
|
||||
retrieveSubjectToken(): Promise<string>;
|
||||
}
|
||||
154
node_modules/google-auth-library/build/src/auth/awsclient.js
generated
vendored
Normal file
154
node_modules/google-auth-library/build/src/auth/awsclient.js
generated
vendored
Normal file
@@ -0,0 +1,154 @@
|
||||
"use strict";
|
||||
// Copyright 2021 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AwsClient = void 0;
|
||||
const awsrequestsigner_1 = require("./awsrequestsigner");
|
||||
const baseexternalclient_1 = require("./baseexternalclient");
|
||||
const defaultawssecuritycredentialssupplier_1 = require("./defaultawssecuritycredentialssupplier");
|
||||
const util_1 = require("../util");
|
||||
const gaxios_1 = require("gaxios");
|
||||
/**
|
||||
* AWS external account client. This is used for AWS workloads, where
|
||||
* AWS STS GetCallerIdentity serialized signed requests are exchanged for
|
||||
* GCP access token.
|
||||
*/
|
||||
class AwsClient extends baseexternalclient_1.BaseExternalAccountClient {
|
||||
environmentId;
|
||||
awsSecurityCredentialsSupplier;
|
||||
regionalCredVerificationUrl;
|
||||
awsRequestSigner;
|
||||
region;
|
||||
static #DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = 'https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15';
|
||||
/**
|
||||
* @deprecated AWS client no validates the EC2 metadata address.
|
||||
**/
|
||||
static AWS_EC2_METADATA_IPV4_ADDRESS = '169.254.169.254';
|
||||
/**
|
||||
* @deprecated AWS client no validates the EC2 metadata address.
|
||||
**/
|
||||
static AWS_EC2_METADATA_IPV6_ADDRESS = 'fd00:ec2::254';
|
||||
/**
|
||||
* Instantiates an AwsClient instance using the provided JSON
|
||||
* object loaded from an external account credentials file.
|
||||
* An error is thrown if the credential is not a valid AWS credential.
|
||||
* @param options The external account options object typically loaded
|
||||
* from the external account JSON credential file.
|
||||
*/
|
||||
constructor(options) {
|
||||
super(options);
|
||||
const opts = (0, util_1.originalOrCamelOptions)(options);
|
||||
const credentialSource = opts.get('credential_source');
|
||||
const awsSecurityCredentialsSupplier = opts.get('aws_security_credentials_supplier');
|
||||
// Validate credential sourcing configuration.
|
||||
if (!credentialSource && !awsSecurityCredentialsSupplier) {
|
||||
throw new Error('A credential source or AWS security credentials supplier must be specified.');
|
||||
}
|
||||
if (credentialSource && awsSecurityCredentialsSupplier) {
|
||||
throw new Error('Only one of credential source or AWS security credentials supplier can be specified.');
|
||||
}
|
||||
if (awsSecurityCredentialsSupplier) {
|
||||
this.awsSecurityCredentialsSupplier = awsSecurityCredentialsSupplier;
|
||||
this.regionalCredVerificationUrl =
|
||||
AwsClient.#DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL;
|
||||
this.credentialSourceType = 'programmatic';
|
||||
}
|
||||
else {
|
||||
const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource);
|
||||
this.environmentId = credentialSourceOpts.get('environment_id');
|
||||
// This is only required if the AWS region is not available in the
|
||||
// AWS_REGION or AWS_DEFAULT_REGION environment variables.
|
||||
const regionUrl = credentialSourceOpts.get('region_url');
|
||||
// This is only required if AWS security credentials are not available in
|
||||
// environment variables.
|
||||
const securityCredentialsUrl = credentialSourceOpts.get('url');
|
||||
const imdsV2SessionTokenUrl = credentialSourceOpts.get('imdsv2_session_token_url');
|
||||
this.awsSecurityCredentialsSupplier =
|
||||
new defaultawssecuritycredentialssupplier_1.DefaultAwsSecurityCredentialsSupplier({
|
||||
regionUrl: regionUrl,
|
||||
securityCredentialsUrl: securityCredentialsUrl,
|
||||
imdsV2SessionTokenUrl: imdsV2SessionTokenUrl,
|
||||
});
|
||||
this.regionalCredVerificationUrl = credentialSourceOpts.get('regional_cred_verification_url');
|
||||
this.credentialSourceType = 'aws';
|
||||
// Data validators.
|
||||
this.validateEnvironmentId();
|
||||
}
|
||||
this.awsRequestSigner = null;
|
||||
this.region = '';
|
||||
}
|
||||
validateEnvironmentId() {
|
||||
const match = this.environmentId?.match(/^(aws)(\d+)$/);
|
||||
if (!match || !this.regionalCredVerificationUrl) {
|
||||
throw new Error('No valid AWS "credential_source" provided');
|
||||
}
|
||||
else if (parseInt(match[2], 10) !== 1) {
|
||||
throw new Error(`aws version "${match[2]}" is not supported in the current build.`);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Triggered when an external subject token is needed to be exchanged for a
|
||||
* GCP access token via GCP STS endpoint. This will call the
|
||||
* {@link AwsSecurityCredentialsSupplier} to retrieve an AWS region and AWS
|
||||
* Security Credentials, then use them to create a signed AWS STS request that
|
||||
* can be exchanged for a GCP access token.
|
||||
* @return A promise that resolves with the external subject token.
|
||||
*/
|
||||
async retrieveSubjectToken() {
|
||||
// Initialize AWS request signer if not already initialized.
|
||||
if (!this.awsRequestSigner) {
|
||||
this.region = await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext);
|
||||
this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => {
|
||||
return this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext);
|
||||
}, this.region);
|
||||
}
|
||||
// Generate signed request to AWS STS GetCallerIdentity API.
|
||||
// Use the required regional endpoint. Otherwise, the request will fail.
|
||||
const options = await this.awsRequestSigner.getRequestOptions({
|
||||
...AwsClient.RETRY_CONFIG,
|
||||
url: this.regionalCredVerificationUrl.replace('{region}', this.region),
|
||||
method: 'POST',
|
||||
});
|
||||
// The GCP STS endpoint expects the headers to be formatted as:
|
||||
// [
|
||||
// {key: 'x-amz-date', value: '...'},
|
||||
// {key: 'authorization', value: '...'},
|
||||
// ...
|
||||
// ]
|
||||
// And then serialized as:
|
||||
// encodeURIComponent(JSON.stringify({
|
||||
// url: '...',
|
||||
// method: 'POST',
|
||||
// headers: [{key: 'x-amz-date', value: '...'}, ...]
|
||||
// }))
|
||||
const reformattedHeader = [];
|
||||
const extendedHeaders = gaxios_1.Gaxios.mergeHeaders({
|
||||
// The full, canonical resource name of the workload identity pool
|
||||
// provider, with or without the HTTPS prefix.
|
||||
// Including this header as part of the signature is recommended to
|
||||
// ensure data integrity.
|
||||
'x-goog-cloud-target-resource': this.audience,
|
||||
}, options.headers);
|
||||
// Reformat header to GCP STS expected format.
|
||||
extendedHeaders.forEach((value, key) => reformattedHeader.push({ key, value }));
|
||||
// Serialize the reformatted signed request.
|
||||
return encodeURIComponent(JSON.stringify({
|
||||
url: options.url,
|
||||
method: options.method,
|
||||
headers: reformattedHeader,
|
||||
}));
|
||||
}
|
||||
}
|
||||
exports.AwsClient = AwsClient;
|
||||
//# sourceMappingURL=awsclient.js.map
|
||||
40
node_modules/google-auth-library/build/src/auth/awsrequestsigner.d.ts
generated
vendored
Normal file
40
node_modules/google-auth-library/build/src/auth/awsrequestsigner.d.ts
generated
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
import { GaxiosOptions } from 'gaxios';
|
||||
/**
|
||||
* Interface defining AWS security credentials.
|
||||
* These are either determined from AWS security_credentials endpoint or
|
||||
* AWS environment variables.
|
||||
*/
|
||||
export interface AwsSecurityCredentials {
|
||||
accessKeyId: string;
|
||||
secretAccessKey: string;
|
||||
token?: string;
|
||||
}
|
||||
/**
|
||||
* Implements an AWS API request signer based on the AWS Signature Version 4
|
||||
* signing process.
|
||||
* https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
|
||||
*/
|
||||
export declare class AwsRequestSigner {
|
||||
private readonly getCredentials;
|
||||
private readonly region;
|
||||
private readonly crypto;
|
||||
/**
|
||||
* Instantiates an AWS API request signer used to send authenticated signed
|
||||
* requests to AWS APIs based on the AWS Signature Version 4 signing process.
|
||||
* This also provides a mechanism to generate the signed request without
|
||||
* sending it.
|
||||
* @param getCredentials A mechanism to retrieve AWS security credentials
|
||||
* when needed.
|
||||
* @param region The AWS region to use.
|
||||
*/
|
||||
constructor(getCredentials: () => Promise<AwsSecurityCredentials>, region: string);
|
||||
/**
|
||||
* Generates the signed request for the provided HTTP request for calling
|
||||
* an AWS API. This follows the steps described at:
|
||||
* https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
|
||||
* @param amzOptions The AWS request options that need to be signed.
|
||||
* @return A promise that resolves with the GaxiosOptions containing the
|
||||
* signed HTTP request parameters.
|
||||
*/
|
||||
getRequestOptions(amzOptions: GaxiosOptions): Promise<GaxiosOptions>;
|
||||
}
|
||||
213
node_modules/google-auth-library/build/src/auth/awsrequestsigner.js
generated
vendored
Normal file
213
node_modules/google-auth-library/build/src/auth/awsrequestsigner.js
generated
vendored
Normal file
@@ -0,0 +1,213 @@
|
||||
"use strict";
|
||||
// Copyright 2021 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AwsRequestSigner = void 0;
|
||||
const gaxios_1 = require("gaxios");
|
||||
const crypto_1 = require("../crypto/crypto");
|
||||
/** AWS Signature Version 4 signing algorithm identifier. */
|
||||
const AWS_ALGORITHM = 'AWS4-HMAC-SHA256';
|
||||
/**
|
||||
* The termination string for the AWS credential scope value as defined in
|
||||
* https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html
|
||||
*/
|
||||
const AWS_REQUEST_TYPE = 'aws4_request';
|
||||
/**
|
||||
* Implements an AWS API request signer based on the AWS Signature Version 4
|
||||
* signing process.
|
||||
* https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
|
||||
*/
|
||||
class AwsRequestSigner {
|
||||
getCredentials;
|
||||
region;
|
||||
crypto;
|
||||
/**
|
||||
* Instantiates an AWS API request signer used to send authenticated signed
|
||||
* requests to AWS APIs based on the AWS Signature Version 4 signing process.
|
||||
* This also provides a mechanism to generate the signed request without
|
||||
* sending it.
|
||||
* @param getCredentials A mechanism to retrieve AWS security credentials
|
||||
* when needed.
|
||||
* @param region The AWS region to use.
|
||||
*/
|
||||
constructor(getCredentials, region) {
|
||||
this.getCredentials = getCredentials;
|
||||
this.region = region;
|
||||
this.crypto = (0, crypto_1.createCrypto)();
|
||||
}
|
||||
/**
|
||||
* Generates the signed request for the provided HTTP request for calling
|
||||
* an AWS API. This follows the steps described at:
|
||||
* https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
|
||||
* @param amzOptions The AWS request options that need to be signed.
|
||||
* @return A promise that resolves with the GaxiosOptions containing the
|
||||
* signed HTTP request parameters.
|
||||
*/
|
||||
async getRequestOptions(amzOptions) {
|
||||
if (!amzOptions.url) {
|
||||
throw new RangeError('"url" is required in "amzOptions"');
|
||||
}
|
||||
// Stringify JSON requests. This will be set in the request body of the
|
||||
// generated signed request.
|
||||
const requestPayloadData = typeof amzOptions.data === 'object'
|
||||
? JSON.stringify(amzOptions.data)
|
||||
: amzOptions.data;
|
||||
const url = amzOptions.url;
|
||||
const method = amzOptions.method || 'GET';
|
||||
const requestPayload = amzOptions.body || requestPayloadData;
|
||||
const additionalAmzHeaders = amzOptions.headers;
|
||||
const awsSecurityCredentials = await this.getCredentials();
|
||||
const uri = new URL(url);
|
||||
if (typeof requestPayload !== 'string' && requestPayload !== undefined) {
|
||||
throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${requestPayload}`);
|
||||
}
|
||||
const headerMap = await generateAuthenticationHeaderMap({
|
||||
crypto: this.crypto,
|
||||
host: uri.host,
|
||||
canonicalUri: uri.pathname,
|
||||
canonicalQuerystring: uri.search.slice(1),
|
||||
method,
|
||||
region: this.region,
|
||||
securityCredentials: awsSecurityCredentials,
|
||||
requestPayload,
|
||||
additionalAmzHeaders,
|
||||
});
|
||||
// Append additional optional headers, eg. X-Amz-Target, Content-Type, etc.
|
||||
const headers = gaxios_1.Gaxios.mergeHeaders(
|
||||
// Add x-amz-date if available.
|
||||
headerMap.amzDate ? { 'x-amz-date': headerMap.amzDate } : {}, {
|
||||
authorization: headerMap.authorizationHeader,
|
||||
host: uri.host,
|
||||
}, additionalAmzHeaders || {});
|
||||
if (awsSecurityCredentials.token) {
|
||||
gaxios_1.Gaxios.mergeHeaders(headers, {
|
||||
'x-amz-security-token': awsSecurityCredentials.token,
|
||||
});
|
||||
}
|
||||
const awsSignedReq = {
|
||||
url,
|
||||
method: method,
|
||||
headers,
|
||||
};
|
||||
if (requestPayload !== undefined) {
|
||||
awsSignedReq.body = requestPayload;
|
||||
}
|
||||
return awsSignedReq;
|
||||
}
|
||||
}
|
||||
exports.AwsRequestSigner = AwsRequestSigner;
|
||||
/**
|
||||
* Creates the HMAC-SHA256 hash of the provided message using the
|
||||
* provided key.
|
||||
*
|
||||
* @param crypto The crypto instance used to facilitate cryptographic
|
||||
* operations.
|
||||
* @param key The HMAC-SHA256 key to use.
|
||||
* @param msg The message to hash.
|
||||
* @return The computed hash bytes.
|
||||
*/
|
||||
async function sign(crypto, key, msg) {
|
||||
return await crypto.signWithHmacSha256(key, msg);
|
||||
}
|
||||
/**
|
||||
* Calculates the signing key used to calculate the signature for
|
||||
* AWS Signature Version 4 based on:
|
||||
* https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html
|
||||
*
|
||||
* @param crypto The crypto instance used to facilitate cryptographic
|
||||
* operations.
|
||||
* @param key The AWS secret access key.
|
||||
* @param dateStamp The '%Y%m%d' date format.
|
||||
* @param region The AWS region.
|
||||
* @param serviceName The AWS service name, eg. sts.
|
||||
* @return The signing key bytes.
|
||||
*/
|
||||
async function getSigningKey(crypto, key, dateStamp, region, serviceName) {
|
||||
const kDate = await sign(crypto, `AWS4${key}`, dateStamp);
|
||||
const kRegion = await sign(crypto, kDate, region);
|
||||
const kService = await sign(crypto, kRegion, serviceName);
|
||||
const kSigning = await sign(crypto, kService, 'aws4_request');
|
||||
return kSigning;
|
||||
}
|
||||
/**
|
||||
* Generates the authentication header map needed for generating the AWS
|
||||
* Signature Version 4 signed request.
|
||||
*
|
||||
* @param option The options needed to compute the authentication header map.
|
||||
* @return The AWS authentication header map which constitutes of the following
|
||||
* components: amz-date, authorization header and canonical query string.
|
||||
*/
|
||||
async function generateAuthenticationHeaderMap(options) {
|
||||
const additionalAmzHeaders = gaxios_1.Gaxios.mergeHeaders(options.additionalAmzHeaders);
|
||||
const requestPayload = options.requestPayload || '';
|
||||
// iam.amazonaws.com host => iam service.
|
||||
// sts.us-east-2.amazonaws.com => sts service.
|
||||
const serviceName = options.host.split('.')[0];
|
||||
const now = new Date();
|
||||
// Format: '%Y%m%dT%H%M%SZ'.
|
||||
const amzDate = now
|
||||
.toISOString()
|
||||
.replace(/[-:]/g, '')
|
||||
.replace(/\.[0-9]+/, '');
|
||||
// Format: '%Y%m%d'.
|
||||
const dateStamp = now.toISOString().replace(/[-]/g, '').replace(/T.*/, '');
|
||||
// Add AWS token if available.
|
||||
if (options.securityCredentials.token) {
|
||||
additionalAmzHeaders.set('x-amz-security-token', options.securityCredentials.token);
|
||||
}
|
||||
// Header keys need to be sorted alphabetically.
|
||||
const amzHeaders = gaxios_1.Gaxios.mergeHeaders({
|
||||
host: options.host,
|
||||
},
|
||||
// Previously the date was not fixed with x-amz- and could be provided manually.
|
||||
// https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req
|
||||
additionalAmzHeaders.has('date') ? {} : { 'x-amz-date': amzDate }, additionalAmzHeaders);
|
||||
let canonicalHeaders = '';
|
||||
// TypeScript is missing `Headers#keys` at the time of writing
|
||||
const signedHeadersList = [
|
||||
...amzHeaders.keys(),
|
||||
].sort();
|
||||
signedHeadersList.forEach(key => {
|
||||
canonicalHeaders += `${key}:${amzHeaders.get(key)}\n`;
|
||||
});
|
||||
const signedHeaders = signedHeadersList.join(';');
|
||||
const payloadHash = await options.crypto.sha256DigestHex(requestPayload);
|
||||
// https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
|
||||
const canonicalRequest = `${options.method.toUpperCase()}\n` +
|
||||
`${options.canonicalUri}\n` +
|
||||
`${options.canonicalQuerystring}\n` +
|
||||
`${canonicalHeaders}\n` +
|
||||
`${signedHeaders}\n` +
|
||||
`${payloadHash}`;
|
||||
const credentialScope = `${dateStamp}/${options.region}/${serviceName}/${AWS_REQUEST_TYPE}`;
|
||||
// https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html
|
||||
const stringToSign = `${AWS_ALGORITHM}\n` +
|
||||
`${amzDate}\n` +
|
||||
`${credentialScope}\n` +
|
||||
(await options.crypto.sha256DigestHex(canonicalRequest));
|
||||
// https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html
|
||||
const signingKey = await getSigningKey(options.crypto, options.securityCredentials.secretAccessKey, dateStamp, options.region, serviceName);
|
||||
const signature = await sign(options.crypto, signingKey, stringToSign);
|
||||
// https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html
|
||||
const authorizationHeader = `${AWS_ALGORITHM} Credential=${options.securityCredentials.accessKeyId}/` +
|
||||
`${credentialScope}, SignedHeaders=${signedHeaders}, ` +
|
||||
`Signature=${(0, crypto_1.fromArrayBufferToHex)(signature)}`;
|
||||
return {
|
||||
// Do not return x-amz-date if date is available.
|
||||
amzDate: additionalAmzHeaders.has('date') ? undefined : amzDate,
|
||||
authorizationHeader,
|
||||
canonicalQuerystring: options.canonicalQuerystring,
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=awsrequestsigner.js.map
|
||||
318
node_modules/google-auth-library/build/src/auth/baseexternalclient.d.ts
generated
vendored
Normal file
318
node_modules/google-auth-library/build/src/auth/baseexternalclient.d.ts
generated
vendored
Normal file
@@ -0,0 +1,318 @@
|
||||
import { Gaxios, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios';
|
||||
import { Credentials } from './credentials';
|
||||
import { AuthClient, AuthClientOptions, GetAccessTokenResponse, BodyResponseCallback } from './authclient';
|
||||
import * as sts from './stscredentials';
|
||||
import { ClientAuthentication } from './oauth2common';
|
||||
import { SnakeToCamelObject } from '../util';
|
||||
/**
|
||||
* Offset to take into account network delays and server clock skews.
|
||||
*/
|
||||
export declare const EXPIRATION_TIME_OFFSET: number;
|
||||
/**
|
||||
* The credentials JSON file type for external account clients.
|
||||
* There are 3 types of JSON configs:
|
||||
* 1. authorized_user => Google end user credential
|
||||
* 2. service_account => Google service account credential
|
||||
* 3. external_Account => non-GCP service (eg. AWS, Azure, K8s)
|
||||
*/
|
||||
export declare const EXTERNAL_ACCOUNT_TYPE = "external_account";
|
||||
/**
|
||||
* Cloud resource manager URL used to retrieve project information.
|
||||
*
|
||||
* @deprecated use {@link BaseExternalAccountClient.cloudResourceManagerURL} instead
|
||||
**/
|
||||
export declare const CLOUD_RESOURCE_MANAGER = "https://cloudresourcemanager.googleapis.com/v1/projects/";
|
||||
/**
|
||||
* Shared options used to build {@link ExternalAccountClient} and
|
||||
* {@link ExternalAccountAuthorizedUserClient}.
|
||||
*/
|
||||
export interface SharedExternalAccountClientOptions extends AuthClientOptions {
|
||||
/**
|
||||
* The Security Token Service audience, which is usually the fully specified
|
||||
* resource name of the workload or workforce pool provider.
|
||||
*/
|
||||
audience: string;
|
||||
/**
|
||||
* The Security Token Service token URL used to exchange the third party token
|
||||
* for a GCP access token. If not provided, will default to
|
||||
* 'https://sts.googleapis.com/v1/token'
|
||||
*/
|
||||
token_url?: string;
|
||||
}
|
||||
/**
|
||||
* Interface containing context about the requested external identity. This is
|
||||
* passed on all requests from external account clients to external identity suppliers.
|
||||
*/
|
||||
export interface ExternalAccountSupplierContext {
|
||||
/**
|
||||
* The requested external account audience. For example:
|
||||
* * "//iam.googleapis.com/locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID"
|
||||
* * "//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID"
|
||||
*/
|
||||
audience: string;
|
||||
/**
|
||||
* The requested subject token type. Expected values include:
|
||||
* * "urn:ietf:params:oauth:token-type:jwt"
|
||||
* * "urn:ietf:params:aws:token-type:aws4_request"
|
||||
* * "urn:ietf:params:oauth:token-type:saml2"
|
||||
* * "urn:ietf:params:oauth:token-type:id_token"
|
||||
*/
|
||||
subjectTokenType: string;
|
||||
/**
|
||||
* The {@link Gaxios} instance for calling external account
|
||||
* to use for requests.
|
||||
*/
|
||||
transporter: Gaxios;
|
||||
}
|
||||
/**
|
||||
* Base external account credentials json interface.
|
||||
*/
|
||||
export interface BaseExternalAccountClientOptions extends SharedExternalAccountClientOptions {
|
||||
/**
|
||||
* Credential type, should always be 'external_account'.
|
||||
*/
|
||||
type?: string;
|
||||
/**
|
||||
* The Security Token Service subject token type based on the OAuth 2.0
|
||||
* token exchange spec. Expected values include:
|
||||
* * 'urn:ietf:params:oauth:token-type:jwt'
|
||||
* * 'urn:ietf:params:aws:token-type:aws4_request'
|
||||
* * 'urn:ietf:params:oauth:token-type:saml2'
|
||||
* * 'urn:ietf:params:oauth:token-type:id_token'
|
||||
*/
|
||||
subject_token_type: string;
|
||||
/**
|
||||
* The URL for the service account impersonation request. This URL is required
|
||||
* for some APIs. If this URL is not available, the access token from the
|
||||
* Security Token Service is used directly.
|
||||
*/
|
||||
service_account_impersonation_url?: string;
|
||||
/**
|
||||
* Object containing additional options for service account impersonation.
|
||||
*/
|
||||
service_account_impersonation?: {
|
||||
/**
|
||||
* The desired lifetime of the impersonated service account access token.
|
||||
* If not provided, the default lifetime will be 3600 seconds.
|
||||
*/
|
||||
token_lifetime_seconds?: number;
|
||||
};
|
||||
/**
|
||||
* The endpoint used to retrieve account related information.
|
||||
*/
|
||||
token_info_url?: string;
|
||||
/**
|
||||
* Client ID of the service account from the console.
|
||||
*/
|
||||
client_id?: string;
|
||||
/**
|
||||
* Client secret of the service account from the console.
|
||||
*/
|
||||
client_secret?: string;
|
||||
/**
|
||||
* The workforce pool user project. Required when using a workforce identity
|
||||
* pool.
|
||||
*/
|
||||
workforce_pool_user_project?: string;
|
||||
/**
|
||||
* The scopes to request during the authorization grant.
|
||||
*/
|
||||
scopes?: string[];
|
||||
/**
|
||||
* @example
|
||||
* https://cloudresourcemanager.googleapis.com/v1/projects/
|
||||
**/
|
||||
cloud_resource_manager_url?: string | URL;
|
||||
}
|
||||
/**
|
||||
* Interface defining the successful response for iamcredentials
|
||||
* generateAccessToken API.
|
||||
* https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateAccessToken
|
||||
*/
|
||||
export interface IamGenerateAccessTokenResponse {
|
||||
accessToken: string;
|
||||
/**
|
||||
* ISO format used for expiration time.
|
||||
*
|
||||
* @example
|
||||
* '2014-10-02T15:01:23.045123456Z'
|
||||
*/
|
||||
expireTime: string;
|
||||
}
|
||||
/**
|
||||
* Interface defining the project information response returned by the cloud
|
||||
* resource manager.
|
||||
* https://cloud.google.com/resource-manager/reference/rest/v1/projects#Project
|
||||
*/
|
||||
export interface ProjectInfo {
|
||||
projectNumber: string;
|
||||
projectId: string;
|
||||
lifecycleState: string;
|
||||
name: string;
|
||||
createTime?: string;
|
||||
parent: {
|
||||
[key: string]: ReturnType<JSON['parse']>;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Internal interface for tracking the access token expiration time.
|
||||
*/
|
||||
interface CredentialsWithResponse extends Credentials {
|
||||
res?: GaxiosResponse | null;
|
||||
}
|
||||
/**
|
||||
* Base external account client. This is used to instantiate AuthClients for
|
||||
* exchanging external account credentials for GCP access token and authorizing
|
||||
* requests to GCP APIs.
|
||||
* The base class implements common logic for exchanging various type of
|
||||
* external credentials for GCP access token. The logic of determining and
|
||||
* retrieving the external credential based on the environment and
|
||||
* credential_source will be left for the subclasses.
|
||||
*/
|
||||
export declare abstract class BaseExternalAccountClient extends AuthClient {
|
||||
#private;
|
||||
/**
|
||||
* OAuth scopes for the GCP access token to use. When not provided,
|
||||
* the default https://www.googleapis.com/auth/cloud-platform is
|
||||
* used.
|
||||
*/
|
||||
scopes?: string | string[];
|
||||
projectNumber: string | null;
|
||||
protected readonly audience: string;
|
||||
protected readonly subjectTokenType: string;
|
||||
protected stsCredential: sts.StsCredentials;
|
||||
protected readonly clientAuth?: ClientAuthentication;
|
||||
protected credentialSourceType?: string;
|
||||
private cachedAccessToken;
|
||||
private readonly serviceAccountImpersonationUrl?;
|
||||
private readonly serviceAccountImpersonationLifetime?;
|
||||
private readonly workforcePoolUserProject?;
|
||||
private readonly configLifetimeRequested;
|
||||
private readonly tokenUrl;
|
||||
/**
|
||||
* @example
|
||||
* ```ts
|
||||
* new URL('https://cloudresourcemanager.googleapis.com/v1/projects/');
|
||||
* ```
|
||||
*/
|
||||
protected cloudResourceManagerURL: URL | string;
|
||||
protected supplierContext: ExternalAccountSupplierContext;
|
||||
/**
|
||||
* Instantiate a BaseExternalAccountClient instance using the provided JSON
|
||||
* object loaded from an external account credentials file.
|
||||
* @param options The external account options object typically loaded
|
||||
* from the external account JSON credential file. The camelCased options
|
||||
* are aliases for the snake_cased options.
|
||||
*/
|
||||
constructor(options: BaseExternalAccountClientOptions | SnakeToCamelObject<BaseExternalAccountClientOptions>);
|
||||
/** The service account email to be impersonated, if available. */
|
||||
getServiceAccountEmail(): string | null;
|
||||
/**
|
||||
* Provides a mechanism to inject GCP access tokens directly.
|
||||
* When the provided credential expires, a new credential, using the
|
||||
* external account options, is retrieved.
|
||||
* @param credentials The Credentials object to set on the current client.
|
||||
*/
|
||||
setCredentials(credentials: Credentials): void;
|
||||
/**
|
||||
* Triggered when a external subject token is needed to be exchanged for a GCP
|
||||
* access token via GCP STS endpoint.
|
||||
* This abstract method needs to be implemented by subclasses depending on
|
||||
* the type of external credential used.
|
||||
* @return A promise that resolves with the external subject token.
|
||||
*/
|
||||
abstract retrieveSubjectToken(): Promise<string>;
|
||||
/**
|
||||
* @return A promise that resolves with the current GCP access token
|
||||
* response. If the current credential is expired, a new one is retrieved.
|
||||
*/
|
||||
getAccessToken(): Promise<GetAccessTokenResponse>;
|
||||
/**
|
||||
* The main authentication interface. It takes an optional url which when
|
||||
* present is the endpoint being accessed, and returns a Promise which
|
||||
* resolves with authorization header fields.
|
||||
*
|
||||
* The result has the form:
|
||||
* { authorization: 'Bearer <access_token_value>' }
|
||||
*/
|
||||
getRequestHeaders(): Promise<Headers>;
|
||||
/**
|
||||
* Provides a request implementation with OAuth 2.0 flow. In cases of
|
||||
* HTTP 401 and 403 responses, it automatically asks for a new access token
|
||||
* and replays the unsuccessful request.
|
||||
* @param opts Request options.
|
||||
* @param callback callback.
|
||||
* @return A promise that resolves with the HTTP response when no callback is
|
||||
* provided.
|
||||
*/
|
||||
request<T>(opts: GaxiosOptions): GaxiosPromise<T>;
|
||||
request<T>(opts: GaxiosOptions, callback: BodyResponseCallback<T>): void;
|
||||
/**
|
||||
* @return A promise that resolves with the project ID corresponding to the
|
||||
* current workload identity pool or current workforce pool if
|
||||
* determinable. For workforce pool credential, it returns the project ID
|
||||
* corresponding to the workforcePoolUserProject.
|
||||
* This is introduced to match the current pattern of using the Auth
|
||||
* library:
|
||||
* const projectId = await auth.getProjectId();
|
||||
* const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
|
||||
* const res = await client.request({ url });
|
||||
* The resource may not have permission
|
||||
* (resourcemanager.projects.get) to call this API or the required
|
||||
* scopes may not be selected:
|
||||
* https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes
|
||||
*/
|
||||
getProjectId(): Promise<string | null>;
|
||||
/**
|
||||
* Authenticates the provided HTTP request, processes it and resolves with the
|
||||
* returned response.
|
||||
* @param opts The HTTP request options.
|
||||
* @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure.
|
||||
* @return A promise that resolves with the successful response.
|
||||
*/
|
||||
protected requestAsync<T>(opts: GaxiosOptions, reAuthRetried?: boolean): Promise<GaxiosResponse<T>>;
|
||||
/**
|
||||
* Forces token refresh, even if unexpired tokens are currently cached.
|
||||
* External credentials are exchanged for GCP access tokens via the token
|
||||
* exchange endpoint and other settings provided in the client options
|
||||
* object.
|
||||
* If the service_account_impersonation_url is provided, an additional
|
||||
* step to exchange the external account GCP access token for a service
|
||||
* account impersonated token is performed.
|
||||
* @return A promise that resolves with the fresh GCP access tokens.
|
||||
*/
|
||||
protected refreshAccessTokenAsync(): Promise<CredentialsWithResponse>;
|
||||
/**
|
||||
* Returns the workload identity pool project number if it is determinable
|
||||
* from the audience resource name.
|
||||
* @param audience The STS audience used to determine the project number.
|
||||
* @return The project number associated with the workload identity pool, if
|
||||
* this can be determined from the STS audience field. Otherwise, null is
|
||||
* returned.
|
||||
*/
|
||||
private getProjectNumber;
|
||||
/**
|
||||
* Exchanges an external account GCP access token for a service
|
||||
* account impersonated access token using iamcredentials
|
||||
* GenerateAccessToken API.
|
||||
* @param token The access token to exchange for a service account access
|
||||
* token.
|
||||
* @return A promise that resolves with the service account impersonated
|
||||
* credentials response.
|
||||
*/
|
||||
private getImpersonatedAccessToken;
|
||||
/**
|
||||
* Returns whether the provided credentials are expired or not.
|
||||
* If there is no expiry time, assumes the token is not expired or expiring.
|
||||
* @param accessToken The credentials to check for expiration.
|
||||
* @return Whether the credentials are expired or not.
|
||||
*/
|
||||
private isExpired;
|
||||
/**
|
||||
* @return The list of scopes for the requested GCP access token.
|
||||
*/
|
||||
private getScopesArray;
|
||||
private getMetricsHeaderValue;
|
||||
protected getTokenUrl(): string;
|
||||
}
|
||||
export {};
|
||||
475
node_modules/google-auth-library/build/src/auth/baseexternalclient.js
generated
vendored
Normal file
475
node_modules/google-auth-library/build/src/auth/baseexternalclient.js
generated
vendored
Normal file
@@ -0,0 +1,475 @@
|
||||
"use strict";
|
||||
// Copyright 2021 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.BaseExternalAccountClient = exports.CLOUD_RESOURCE_MANAGER = exports.EXTERNAL_ACCOUNT_TYPE = exports.EXPIRATION_TIME_OFFSET = void 0;
|
||||
const gaxios_1 = require("gaxios");
|
||||
const stream = require("stream");
|
||||
const authclient_1 = require("./authclient");
|
||||
const sts = require("./stscredentials");
|
||||
const util_1 = require("../util");
|
||||
const shared_cjs_1 = require("../shared.cjs");
|
||||
/**
|
||||
* The required token exchange grant_type: rfc8693#section-2.1
|
||||
*/
|
||||
const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';
|
||||
/**
|
||||
* The requested token exchange requested_token_type: rfc8693#section-2.1
|
||||
*/
|
||||
const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';
|
||||
/** The default OAuth scope to request when none is provided. */
|
||||
const DEFAULT_OAUTH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform';
|
||||
/** Default impersonated token lifespan in seconds.*/
|
||||
const DEFAULT_TOKEN_LIFESPAN = 3600;
|
||||
/**
|
||||
* Offset to take into account network delays and server clock skews.
|
||||
*/
|
||||
exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000;
|
||||
/**
|
||||
* The credentials JSON file type for external account clients.
|
||||
* There are 3 types of JSON configs:
|
||||
* 1. authorized_user => Google end user credential
|
||||
* 2. service_account => Google service account credential
|
||||
* 3. external_Account => non-GCP service (eg. AWS, Azure, K8s)
|
||||
*/
|
||||
exports.EXTERNAL_ACCOUNT_TYPE = 'external_account';
|
||||
/**
|
||||
* Cloud resource manager URL used to retrieve project information.
|
||||
*
|
||||
* @deprecated use {@link BaseExternalAccountClient.cloudResourceManagerURL} instead
|
||||
**/
|
||||
exports.CLOUD_RESOURCE_MANAGER = 'https://cloudresourcemanager.googleapis.com/v1/projects/';
|
||||
/** The workforce audience pattern. */
|
||||
const WORKFORCE_AUDIENCE_PATTERN = '//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+';
|
||||
const DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/token';
|
||||
/**
|
||||
* Base external account client. This is used to instantiate AuthClients for
|
||||
* exchanging external account credentials for GCP access token and authorizing
|
||||
* requests to GCP APIs.
|
||||
* The base class implements common logic for exchanging various type of
|
||||
* external credentials for GCP access token. The logic of determining and
|
||||
* retrieving the external credential based on the environment and
|
||||
* credential_source will be left for the subclasses.
|
||||
*/
|
||||
class BaseExternalAccountClient extends authclient_1.AuthClient {
|
||||
/**
|
||||
* OAuth scopes for the GCP access token to use. When not provided,
|
||||
* the default https://www.googleapis.com/auth/cloud-platform is
|
||||
* used.
|
||||
*/
|
||||
scopes;
|
||||
projectNumber;
|
||||
audience;
|
||||
subjectTokenType;
|
||||
stsCredential;
|
||||
clientAuth;
|
||||
credentialSourceType;
|
||||
cachedAccessToken;
|
||||
serviceAccountImpersonationUrl;
|
||||
serviceAccountImpersonationLifetime;
|
||||
workforcePoolUserProject;
|
||||
configLifetimeRequested;
|
||||
tokenUrl;
|
||||
/**
|
||||
* @example
|
||||
* ```ts
|
||||
* new URL('https://cloudresourcemanager.googleapis.com/v1/projects/');
|
||||
* ```
|
||||
*/
|
||||
cloudResourceManagerURL;
|
||||
supplierContext;
|
||||
/**
|
||||
* A pending access token request. Used for concurrent calls.
|
||||
*/
|
||||
#pendingAccessToken = null;
|
||||
/**
|
||||
* Instantiate a BaseExternalAccountClient instance using the provided JSON
|
||||
* object loaded from an external account credentials file.
|
||||
* @param options The external account options object typically loaded
|
||||
* from the external account JSON credential file. The camelCased options
|
||||
* are aliases for the snake_cased options.
|
||||
*/
|
||||
constructor(options) {
|
||||
super(options);
|
||||
const opts = (0, util_1.originalOrCamelOptions)(options);
|
||||
const type = opts.get('type');
|
||||
if (type && type !== exports.EXTERNAL_ACCOUNT_TYPE) {
|
||||
throw new Error(`Expected "${exports.EXTERNAL_ACCOUNT_TYPE}" type but ` +
|
||||
`received "${options.type}"`);
|
||||
}
|
||||
const clientId = opts.get('client_id');
|
||||
const clientSecret = opts.get('client_secret');
|
||||
this.tokenUrl =
|
||||
opts.get('token_url') ??
|
||||
DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain);
|
||||
const subjectTokenType = opts.get('subject_token_type');
|
||||
const workforcePoolUserProject = opts.get('workforce_pool_user_project');
|
||||
const serviceAccountImpersonationUrl = opts.get('service_account_impersonation_url');
|
||||
const serviceAccountImpersonation = opts.get('service_account_impersonation');
|
||||
const serviceAccountImpersonationLifetime = (0, util_1.originalOrCamelOptions)(serviceAccountImpersonation).get('token_lifetime_seconds');
|
||||
this.cloudResourceManagerURL = new URL(opts.get('cloud_resource_manager_url') ||
|
||||
`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`);
|
||||
if (clientId) {
|
||||
this.clientAuth = {
|
||||
confidentialClientType: 'basic',
|
||||
clientId,
|
||||
clientSecret,
|
||||
};
|
||||
}
|
||||
this.stsCredential = new sts.StsCredentials({
|
||||
tokenExchangeEndpoint: this.tokenUrl,
|
||||
clientAuthentication: this.clientAuth,
|
||||
});
|
||||
this.scopes = opts.get('scopes') || [DEFAULT_OAUTH_SCOPE];
|
||||
this.cachedAccessToken = null;
|
||||
this.audience = opts.get('audience');
|
||||
this.subjectTokenType = subjectTokenType;
|
||||
this.workforcePoolUserProject = workforcePoolUserProject;
|
||||
const workforceAudiencePattern = new RegExp(WORKFORCE_AUDIENCE_PATTERN);
|
||||
if (this.workforcePoolUserProject &&
|
||||
!this.audience.match(workforceAudiencePattern)) {
|
||||
throw new Error('workforcePoolUserProject should not be set for non-workforce pool ' +
|
||||
'credentials.');
|
||||
}
|
||||
this.serviceAccountImpersonationUrl = serviceAccountImpersonationUrl;
|
||||
this.serviceAccountImpersonationLifetime =
|
||||
serviceAccountImpersonationLifetime;
|
||||
if (this.serviceAccountImpersonationLifetime) {
|
||||
this.configLifetimeRequested = true;
|
||||
}
|
||||
else {
|
||||
this.configLifetimeRequested = false;
|
||||
this.serviceAccountImpersonationLifetime = DEFAULT_TOKEN_LIFESPAN;
|
||||
}
|
||||
this.projectNumber = this.getProjectNumber(this.audience);
|
||||
this.supplierContext = {
|
||||
audience: this.audience,
|
||||
subjectTokenType: this.subjectTokenType,
|
||||
transporter: this.transporter,
|
||||
};
|
||||
}
|
||||
/** The service account email to be impersonated, if available. */
|
||||
getServiceAccountEmail() {
|
||||
if (this.serviceAccountImpersonationUrl) {
|
||||
if (this.serviceAccountImpersonationUrl.length > 256) {
|
||||
/**
|
||||
* Prevents DOS attacks.
|
||||
* @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/84}
|
||||
**/
|
||||
throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);
|
||||
}
|
||||
// Parse email from URL. The formal looks as follows:
|
||||
// https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/name@project-id.iam.gserviceaccount.com:generateAccessToken
|
||||
const re = /serviceAccounts\/(?<email>[^:]+):generateAccessToken$/;
|
||||
const result = re.exec(this.serviceAccountImpersonationUrl);
|
||||
return result?.groups?.email || null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Provides a mechanism to inject GCP access tokens directly.
|
||||
* When the provided credential expires, a new credential, using the
|
||||
* external account options, is retrieved.
|
||||
* @param credentials The Credentials object to set on the current client.
|
||||
*/
|
||||
setCredentials(credentials) {
|
||||
super.setCredentials(credentials);
|
||||
this.cachedAccessToken = credentials;
|
||||
}
|
||||
/**
|
||||
* @return A promise that resolves with the current GCP access token
|
||||
* response. If the current credential is expired, a new one is retrieved.
|
||||
*/
|
||||
async getAccessToken() {
|
||||
// If cached access token is unavailable or expired, force refresh.
|
||||
if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) {
|
||||
await this.refreshAccessTokenAsync();
|
||||
}
|
||||
// Return GCP access token in GetAccessTokenResponse format.
|
||||
return {
|
||||
token: this.cachedAccessToken.access_token,
|
||||
res: this.cachedAccessToken.res,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* The main authentication interface. It takes an optional url which when
|
||||
* present is the endpoint being accessed, and returns a Promise which
|
||||
* resolves with authorization header fields.
|
||||
*
|
||||
* The result has the form:
|
||||
* { authorization: 'Bearer <access_token_value>' }
|
||||
*/
|
||||
async getRequestHeaders() {
|
||||
const accessTokenResponse = await this.getAccessToken();
|
||||
const headers = new Headers({
|
||||
authorization: `Bearer ${accessTokenResponse.token}`,
|
||||
});
|
||||
return this.addSharedMetadataHeaders(headers);
|
||||
}
|
||||
request(opts, callback) {
|
||||
if (callback) {
|
||||
this.requestAsync(opts).then(r => callback(null, r), e => {
|
||||
return callback(e, e.response);
|
||||
});
|
||||
}
|
||||
else {
|
||||
return this.requestAsync(opts);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @return A promise that resolves with the project ID corresponding to the
|
||||
* current workload identity pool or current workforce pool if
|
||||
* determinable. For workforce pool credential, it returns the project ID
|
||||
* corresponding to the workforcePoolUserProject.
|
||||
* This is introduced to match the current pattern of using the Auth
|
||||
* library:
|
||||
* const projectId = await auth.getProjectId();
|
||||
* const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
|
||||
* const res = await client.request({ url });
|
||||
* The resource may not have permission
|
||||
* (resourcemanager.projects.get) to call this API or the required
|
||||
* scopes may not be selected:
|
||||
* https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes
|
||||
*/
|
||||
async getProjectId() {
|
||||
const projectNumber = this.projectNumber || this.workforcePoolUserProject;
|
||||
if (this.projectId) {
|
||||
// Return previously determined project ID.
|
||||
return this.projectId;
|
||||
}
|
||||
else if (projectNumber) {
|
||||
// Preferable not to use request() to avoid retrial policies.
|
||||
const headers = await this.getRequestHeaders();
|
||||
const opts = {
|
||||
...BaseExternalAccountClient.RETRY_CONFIG,
|
||||
headers,
|
||||
url: `${this.cloudResourceManagerURL.toString()}${projectNumber}`,
|
||||
};
|
||||
authclient_1.AuthClient.setMethodName(opts, 'getProjectId');
|
||||
const response = await this.transporter.request(opts);
|
||||
this.projectId = response.data.projectId;
|
||||
return this.projectId;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Authenticates the provided HTTP request, processes it and resolves with the
|
||||
* returned response.
|
||||
* @param opts The HTTP request options.
|
||||
* @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure.
|
||||
* @return A promise that resolves with the successful response.
|
||||
*/
|
||||
async requestAsync(opts, reAuthRetried = false) {
|
||||
let response;
|
||||
try {
|
||||
const requestHeaders = await this.getRequestHeaders();
|
||||
opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);
|
||||
this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);
|
||||
response = await this.transporter.request(opts);
|
||||
}
|
||||
catch (e) {
|
||||
const res = e.response;
|
||||
if (res) {
|
||||
const statusCode = res.status;
|
||||
// Retry the request for metadata if the following criteria are true:
|
||||
// - We haven't already retried. It only makes sense to retry once.
|
||||
// - The response was a 401 or a 403
|
||||
// - The request didn't send a readableStream
|
||||
// - forceRefreshOnFailure is true
|
||||
const isReadableStream = res.config.data instanceof stream.Readable;
|
||||
const isAuthErr = statusCode === 401 || statusCode === 403;
|
||||
if (!reAuthRetried &&
|
||||
isAuthErr &&
|
||||
!isReadableStream &&
|
||||
this.forceRefreshOnFailure) {
|
||||
await this.refreshAccessTokenAsync();
|
||||
return await this.requestAsync(opts, true);
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
return response;
|
||||
}
|
||||
/**
|
||||
* Forces token refresh, even if unexpired tokens are currently cached.
|
||||
* External credentials are exchanged for GCP access tokens via the token
|
||||
* exchange endpoint and other settings provided in the client options
|
||||
* object.
|
||||
* If the service_account_impersonation_url is provided, an additional
|
||||
* step to exchange the external account GCP access token for a service
|
||||
* account impersonated token is performed.
|
||||
* @return A promise that resolves with the fresh GCP access tokens.
|
||||
*/
|
||||
async refreshAccessTokenAsync() {
|
||||
// Use an existing access token request, or cache a new one
|
||||
this.#pendingAccessToken =
|
||||
this.#pendingAccessToken || this.#internalRefreshAccessTokenAsync();
|
||||
try {
|
||||
return await this.#pendingAccessToken;
|
||||
}
|
||||
finally {
|
||||
// clear pending access token for future requests
|
||||
this.#pendingAccessToken = null;
|
||||
}
|
||||
}
|
||||
async #internalRefreshAccessTokenAsync() {
|
||||
// Retrieve the external credential.
|
||||
const subjectToken = await this.retrieveSubjectToken();
|
||||
// Construct the STS credentials options.
|
||||
const stsCredentialsOptions = {
|
||||
grantType: STS_GRANT_TYPE,
|
||||
audience: this.audience,
|
||||
requestedTokenType: STS_REQUEST_TOKEN_TYPE,
|
||||
subjectToken,
|
||||
subjectTokenType: this.subjectTokenType,
|
||||
// generateAccessToken requires the provided access token to have
|
||||
// scopes:
|
||||
// https://www.googleapis.com/auth/iam or
|
||||
// https://www.googleapis.com/auth/cloud-platform
|
||||
// The new service account access token scopes will match the user
|
||||
// provided ones.
|
||||
scope: this.serviceAccountImpersonationUrl
|
||||
? [DEFAULT_OAUTH_SCOPE]
|
||||
: this.getScopesArray(),
|
||||
};
|
||||
// Exchange the external credentials for a GCP access token.
|
||||
// Client auth is prioritized over passing the workforcePoolUserProject
|
||||
// parameter for STS token exchange.
|
||||
const additionalOptions = !this.clientAuth && this.workforcePoolUserProject
|
||||
? { userProject: this.workforcePoolUserProject }
|
||||
: undefined;
|
||||
const additionalHeaders = new Headers({
|
||||
'x-goog-api-client': this.getMetricsHeaderValue(),
|
||||
});
|
||||
const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, additionalHeaders, additionalOptions);
|
||||
if (this.serviceAccountImpersonationUrl) {
|
||||
this.cachedAccessToken = await this.getImpersonatedAccessToken(stsResponse.access_token);
|
||||
}
|
||||
else if (stsResponse.expires_in) {
|
||||
// Save response in cached access token.
|
||||
this.cachedAccessToken = {
|
||||
access_token: stsResponse.access_token,
|
||||
expiry_date: new Date().getTime() + stsResponse.expires_in * 1000,
|
||||
res: stsResponse.res,
|
||||
};
|
||||
}
|
||||
else {
|
||||
// Save response in cached access token.
|
||||
this.cachedAccessToken = {
|
||||
access_token: stsResponse.access_token,
|
||||
res: stsResponse.res,
|
||||
};
|
||||
}
|
||||
// Save credentials.
|
||||
this.credentials = {};
|
||||
Object.assign(this.credentials, this.cachedAccessToken);
|
||||
delete this.credentials.res;
|
||||
// Trigger tokens event to notify external listeners.
|
||||
this.emit('tokens', {
|
||||
refresh_token: null,
|
||||
expiry_date: this.cachedAccessToken.expiry_date,
|
||||
access_token: this.cachedAccessToken.access_token,
|
||||
token_type: 'Bearer',
|
||||
id_token: null,
|
||||
});
|
||||
// Return the cached access token.
|
||||
return this.cachedAccessToken;
|
||||
}
|
||||
/**
|
||||
* Returns the workload identity pool project number if it is determinable
|
||||
* from the audience resource name.
|
||||
* @param audience The STS audience used to determine the project number.
|
||||
* @return The project number associated with the workload identity pool, if
|
||||
* this can be determined from the STS audience field. Otherwise, null is
|
||||
* returned.
|
||||
*/
|
||||
getProjectNumber(audience) {
|
||||
// STS audience pattern:
|
||||
// //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/...
|
||||
const match = audience.match(/\/projects\/([^/]+)/);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
return match[1];
|
||||
}
|
||||
/**
|
||||
* Exchanges an external account GCP access token for a service
|
||||
* account impersonated access token using iamcredentials
|
||||
* GenerateAccessToken API.
|
||||
* @param token The access token to exchange for a service account access
|
||||
* token.
|
||||
* @return A promise that resolves with the service account impersonated
|
||||
* credentials response.
|
||||
*/
|
||||
async getImpersonatedAccessToken(token) {
|
||||
const opts = {
|
||||
...BaseExternalAccountClient.RETRY_CONFIG,
|
||||
url: this.serviceAccountImpersonationUrl,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
data: {
|
||||
scope: this.getScopesArray(),
|
||||
lifetime: this.serviceAccountImpersonationLifetime + 's',
|
||||
},
|
||||
};
|
||||
authclient_1.AuthClient.setMethodName(opts, 'getImpersonatedAccessToken');
|
||||
const response = await this.transporter.request(opts);
|
||||
const successResponse = response.data;
|
||||
return {
|
||||
access_token: successResponse.accessToken,
|
||||
// Convert from ISO format to timestamp.
|
||||
expiry_date: new Date(successResponse.expireTime).getTime(),
|
||||
res: response,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Returns whether the provided credentials are expired or not.
|
||||
* If there is no expiry time, assumes the token is not expired or expiring.
|
||||
* @param accessToken The credentials to check for expiration.
|
||||
* @return Whether the credentials are expired or not.
|
||||
*/
|
||||
isExpired(accessToken) {
|
||||
const now = new Date().getTime();
|
||||
return accessToken.expiry_date
|
||||
? now >= accessToken.expiry_date - this.eagerRefreshThresholdMillis
|
||||
: false;
|
||||
}
|
||||
/**
|
||||
* @return The list of scopes for the requested GCP access token.
|
||||
*/
|
||||
getScopesArray() {
|
||||
// Since scopes can be provided as string or array, the type should
|
||||
// be normalized.
|
||||
if (typeof this.scopes === 'string') {
|
||||
return [this.scopes];
|
||||
}
|
||||
return this.scopes || [DEFAULT_OAUTH_SCOPE];
|
||||
}
|
||||
getMetricsHeaderValue() {
|
||||
const nodeVersion = process.version.replace(/^v/, '');
|
||||
const saImpersonation = this.serviceAccountImpersonationUrl !== undefined;
|
||||
const credentialSourceType = this.credentialSourceType
|
||||
? this.credentialSourceType
|
||||
: 'unknown';
|
||||
return `gl-node/${nodeVersion} auth/${shared_cjs_1.pkg.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`;
|
||||
}
|
||||
getTokenUrl() {
|
||||
return this.tokenUrl;
|
||||
}
|
||||
}
|
||||
exports.BaseExternalAccountClient = BaseExternalAccountClient;
|
||||
//# sourceMappingURL=baseexternalclient.js.map
|
||||
60
node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.d.ts
generated
vendored
Normal file
60
node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.d.ts
generated
vendored
Normal file
@@ -0,0 +1,60 @@
|
||||
import { SubjectTokenSupplier } from './identitypoolclient';
|
||||
import * as https from 'https';
|
||||
export declare const CERTIFICATE_CONFIGURATION_ENV_VARIABLE = "GOOGLE_API_CERTIFICATE_CONFIG";
|
||||
/**
|
||||
* Thrown when the certificate source cannot be located or accessed.
|
||||
*/
|
||||
export declare class CertificateSourceUnavailableError extends Error {
|
||||
constructor(message: string);
|
||||
}
|
||||
/**
|
||||
* Thrown for invalid configuration that is not related to file availability.
|
||||
*/
|
||||
export declare class InvalidConfigurationError extends Error {
|
||||
constructor(message: string);
|
||||
}
|
||||
/**
|
||||
* Defines options for creating a {@link CertificateSubjectTokenSupplier}.
|
||||
*/
|
||||
export interface CertificateSubjectTokenSupplierOptions {
|
||||
/**
|
||||
* If true, uses the default well-known location for the certificate config.
|
||||
* Either this or `certificateConfigLocation` must be provided.
|
||||
*/
|
||||
useDefaultCertificateConfig?: boolean;
|
||||
/**
|
||||
* The file path to the certificate configuration JSON file.
|
||||
* Required if `useDefaultCertificateConfig` is not true.
|
||||
*/
|
||||
certificateConfigLocation?: string;
|
||||
/**
|
||||
* The file path to the trust chain (PEM format).
|
||||
*/
|
||||
trustChainPath?: string;
|
||||
}
|
||||
/**
|
||||
* A subject token supplier that uses a client certificate for authentication.
|
||||
* It provides the certificate chain as the subject token for identity federation.
|
||||
*/
|
||||
export declare class CertificateSubjectTokenSupplier implements SubjectTokenSupplier {
|
||||
#private;
|
||||
private certificateConfigPath;
|
||||
private readonly trustChainPath?;
|
||||
private cert?;
|
||||
private key?;
|
||||
/**
|
||||
* Initializes a new instance of the CertificateSubjectTokenSupplier.
|
||||
* @param opts The configuration options for the supplier.
|
||||
*/
|
||||
constructor(opts: CertificateSubjectTokenSupplierOptions);
|
||||
/**
|
||||
* Creates an HTTPS agent configured with the client certificate and private key for mTLS.
|
||||
* @returns An mTLS-configured https.Agent.
|
||||
*/
|
||||
createMtlsHttpsAgent(): Promise<https.Agent>;
|
||||
/**
|
||||
* Constructs the subject token, which is the base64-encoded certificate chain.
|
||||
* @returns A promise that resolves with the subject token.
|
||||
*/
|
||||
getSubjectToken(): Promise<string>;
|
||||
}
|
||||
223
node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js
generated
vendored
Normal file
223
node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js
generated
vendored
Normal file
@@ -0,0 +1,223 @@
|
||||
"use strict";
|
||||
// Copyright 2025 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.CertificateSubjectTokenSupplier = exports.InvalidConfigurationError = exports.CertificateSourceUnavailableError = exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = void 0;
|
||||
const util_1 = require("../util");
|
||||
const fs = require("fs");
|
||||
const crypto_1 = require("crypto");
|
||||
const https = require("https");
|
||||
exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = 'GOOGLE_API_CERTIFICATE_CONFIG';
|
||||
/**
|
||||
* Thrown when the certificate source cannot be located or accessed.
|
||||
*/
|
||||
class CertificateSourceUnavailableError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = 'CertificateSourceUnavailableError';
|
||||
}
|
||||
}
|
||||
exports.CertificateSourceUnavailableError = CertificateSourceUnavailableError;
|
||||
/**
|
||||
* Thrown for invalid configuration that is not related to file availability.
|
||||
*/
|
||||
class InvalidConfigurationError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = 'InvalidConfigurationError';
|
||||
}
|
||||
}
|
||||
exports.InvalidConfigurationError = InvalidConfigurationError;
|
||||
/**
|
||||
* A subject token supplier that uses a client certificate for authentication.
|
||||
* It provides the certificate chain as the subject token for identity federation.
|
||||
*/
|
||||
class CertificateSubjectTokenSupplier {
|
||||
certificateConfigPath;
|
||||
trustChainPath;
|
||||
cert;
|
||||
key;
|
||||
/**
|
||||
* Initializes a new instance of the CertificateSubjectTokenSupplier.
|
||||
* @param opts The configuration options for the supplier.
|
||||
*/
|
||||
constructor(opts) {
|
||||
if (!opts.useDefaultCertificateConfig && !opts.certificateConfigLocation) {
|
||||
throw new InvalidConfigurationError('Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.');
|
||||
}
|
||||
if (opts.useDefaultCertificateConfig && opts.certificateConfigLocation) {
|
||||
throw new InvalidConfigurationError('Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.');
|
||||
}
|
||||
this.trustChainPath = opts.trustChainPath;
|
||||
this.certificateConfigPath = opts.certificateConfigLocation ?? '';
|
||||
}
|
||||
/**
|
||||
* Creates an HTTPS agent configured with the client certificate and private key for mTLS.
|
||||
* @returns An mTLS-configured https.Agent.
|
||||
*/
|
||||
async createMtlsHttpsAgent() {
|
||||
if (!this.key || !this.cert) {
|
||||
throw new InvalidConfigurationError('Cannot create mTLS Agent with missing certificate or key');
|
||||
}
|
||||
return new https.Agent({ key: this.key, cert: this.cert });
|
||||
}
|
||||
/**
|
||||
* Constructs the subject token, which is the base64-encoded certificate chain.
|
||||
* @returns A promise that resolves with the subject token.
|
||||
*/
|
||||
async getSubjectToken() {
|
||||
// The "subject token" in this context is the processed certificate chain.
|
||||
this.certificateConfigPath = await this.#resolveCertificateConfigFilePath();
|
||||
const { certPath, keyPath } = await this.#getCertAndKeyPaths();
|
||||
({ cert: this.cert, key: this.key } = await this.#getKeyAndCert(certPath, keyPath));
|
||||
return await this.#processChainFromPaths(this.cert);
|
||||
}
|
||||
/**
|
||||
* Resolves the absolute path to the certificate configuration file
|
||||
* by checking the "certificate_config_location" provided in the ADC file,
|
||||
* or the "GOOGLE_API_CERTIFICATE_CONFIG" environment variable
|
||||
* or in the default gcloud path.
|
||||
* @param overridePath An optional path to check first.
|
||||
* @returns The resolved file path.
|
||||
*/
|
||||
async #resolveCertificateConfigFilePath() {
|
||||
// 1. Check for the override path from constructor options.
|
||||
const overridePath = this.certificateConfigPath;
|
||||
if (overridePath) {
|
||||
if (await (0, util_1.isValidFile)(overridePath)) {
|
||||
return overridePath;
|
||||
}
|
||||
throw new CertificateSourceUnavailableError(`Provided certificate config path is invalid: ${overridePath}`);
|
||||
}
|
||||
// 2. Check the standard environment variable.
|
||||
const envPath = process.env[exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];
|
||||
if (envPath) {
|
||||
if (await (0, util_1.isValidFile)(envPath)) {
|
||||
return envPath;
|
||||
}
|
||||
throw new CertificateSourceUnavailableError(`Path from environment variable "${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${envPath}`);
|
||||
}
|
||||
// 3. Check the well-known gcloud config location.
|
||||
const wellKnownPath = (0, util_1.getWellKnownCertificateConfigFileLocation)();
|
||||
if (await (0, util_1.isValidFile)(wellKnownPath)) {
|
||||
return wellKnownPath;
|
||||
}
|
||||
// 4. If none are found, throw an error.
|
||||
throw new CertificateSourceUnavailableError('Could not find certificate configuration file. Searched override path, ' +
|
||||
`the "${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${wellKnownPath}).`);
|
||||
}
|
||||
/**
|
||||
* Reads and parses the certificate config JSON file to extract the certificate and key paths.
|
||||
* @returns An object containing the certificate and key paths.
|
||||
*/
|
||||
async #getCertAndKeyPaths() {
|
||||
const configPath = this.certificateConfigPath;
|
||||
let fileContents;
|
||||
try {
|
||||
fileContents = await fs.promises.readFile(configPath, 'utf8');
|
||||
}
|
||||
catch (err) {
|
||||
throw new CertificateSourceUnavailableError(`Failed to read certificate config file at: ${configPath}`);
|
||||
}
|
||||
try {
|
||||
const config = JSON.parse(fileContents);
|
||||
const certPath = config?.cert_configs?.workload?.cert_path;
|
||||
const keyPath = config?.cert_configs?.workload?.key_path;
|
||||
if (!certPath || !keyPath) {
|
||||
throw new InvalidConfigurationError(`Certificate config file (${configPath}) is missing required "cert_path" or "key_path" in the workload config.`);
|
||||
}
|
||||
return { certPath, keyPath };
|
||||
}
|
||||
catch (e) {
|
||||
if (e instanceof InvalidConfigurationError)
|
||||
throw e;
|
||||
throw new InvalidConfigurationError(`Failed to parse certificate config from ${configPath}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Reads and parses the cert and key files get their content and check valid format.
|
||||
* @returns An object containing the cert content and key content in buffer format.
|
||||
*/
|
||||
async #getKeyAndCert(certPath, keyPath) {
|
||||
let cert, key;
|
||||
try {
|
||||
cert = await fs.promises.readFile(certPath);
|
||||
new crypto_1.X509Certificate(cert);
|
||||
}
|
||||
catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
throw new CertificateSourceUnavailableError(`Failed to read certificate file at ${certPath}: ${message}`);
|
||||
}
|
||||
try {
|
||||
key = await fs.promises.readFile(keyPath);
|
||||
(0, crypto_1.createPrivateKey)(key);
|
||||
}
|
||||
catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
throw new CertificateSourceUnavailableError(`Failed to read private key file at ${keyPath}: ${message}`);
|
||||
}
|
||||
return { cert, key };
|
||||
}
|
||||
/**
|
||||
* Reads the leaf certificate and trust chain, combines them,
|
||||
* and returns a JSON array of base64-encoded certificates.
|
||||
* @returns A stringified JSON array of the certificate chain.
|
||||
*/
|
||||
async #processChainFromPaths(leafCertBuffer) {
|
||||
const leafCert = new crypto_1.X509Certificate(leafCertBuffer);
|
||||
// If no trust chain is provided, just use the successfully parsed leaf certificate.
|
||||
if (!this.trustChainPath) {
|
||||
return JSON.stringify([leafCert.raw.toString('base64')]);
|
||||
}
|
||||
// Handle the trust chain logic.
|
||||
try {
|
||||
const chainPems = await fs.promises.readFile(this.trustChainPath, 'utf8');
|
||||
const pemBlocks = chainPems.match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g) ?? [];
|
||||
const chainCerts = pemBlocks.map((pem, index) => {
|
||||
try {
|
||||
return new crypto_1.X509Certificate(pem);
|
||||
}
|
||||
catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
// Throw a more precise error if a single certificate in the chain is invalid.
|
||||
throw new InvalidConfigurationError(`Failed to parse certificate at index ${index} in trust chain file ${this.trustChainPath}: ${message}`);
|
||||
}
|
||||
});
|
||||
const leafIndex = chainCerts.findIndex(chainCert => leafCert.raw.equals(chainCert.raw));
|
||||
let finalChain;
|
||||
if (leafIndex === -1) {
|
||||
// Leaf not found, so prepend it to the chain.
|
||||
finalChain = [leafCert, ...chainCerts];
|
||||
}
|
||||
else if (leafIndex === 0) {
|
||||
// Leaf is already the first element, so the chain is correctly ordered.
|
||||
finalChain = chainCerts;
|
||||
}
|
||||
else {
|
||||
// Leaf is in the chain but not at the top, which is invalid.
|
||||
throw new InvalidConfigurationError(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${leafIndex}).`);
|
||||
}
|
||||
return JSON.stringify(finalChain.map(cert => cert.raw.toString('base64')));
|
||||
}
|
||||
catch (err) {
|
||||
// Re-throw our specific configuration errors.
|
||||
if (err instanceof InvalidConfigurationError)
|
||||
throw err;
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
throw new CertificateSourceUnavailableError(`Failed to process certificate chain from ${this.trustChainPath}: ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.CertificateSubjectTokenSupplier = CertificateSubjectTokenSupplier;
|
||||
//# sourceMappingURL=certificatesubjecttokensupplier.js.map
|
||||
37
node_modules/google-auth-library/build/src/auth/computeclient.d.ts
generated
vendored
Normal file
37
node_modules/google-auth-library/build/src/auth/computeclient.d.ts
generated
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
import { GaxiosError } from 'gaxios';
|
||||
import { GetTokenResponse, OAuth2Client, OAuth2ClientOptions } from './oauth2client';
|
||||
export interface ComputeOptions extends OAuth2ClientOptions {
|
||||
/**
|
||||
* The service account email to use, or 'default'. A Compute Engine instance
|
||||
* may have multiple service accounts.
|
||||
*/
|
||||
serviceAccountEmail?: string;
|
||||
/**
|
||||
* The scopes that will be requested when acquiring service account
|
||||
* credentials. Only applicable to modern App Engine and Cloud Function
|
||||
* runtimes as of March 2019.
|
||||
*/
|
||||
scopes?: string | string[];
|
||||
}
|
||||
export declare class Compute extends OAuth2Client {
|
||||
readonly serviceAccountEmail: string;
|
||||
scopes: string[];
|
||||
/**
|
||||
* Google Compute Engine service account credentials.
|
||||
*
|
||||
* Retrieve access token from the metadata server.
|
||||
* See: https://cloud.google.com/compute/docs/access/authenticate-workloads#applications
|
||||
*/
|
||||
constructor(options?: ComputeOptions);
|
||||
/**
|
||||
* Refreshes the access token.
|
||||
* @param refreshToken Unused parameter
|
||||
*/
|
||||
protected refreshTokenNoCache(): Promise<GetTokenResponse>;
|
||||
/**
|
||||
* Fetches an ID token.
|
||||
* @param targetAudience the audience for the fetched ID token.
|
||||
*/
|
||||
fetchIdToken(targetAudience: string): Promise<string>;
|
||||
protected wrapError(e: GaxiosError): void;
|
||||
}
|
||||
118
node_modules/google-auth-library/build/src/auth/computeclient.js
generated
vendored
Normal file
118
node_modules/google-auth-library/build/src/auth/computeclient.js
generated
vendored
Normal file
@@ -0,0 +1,118 @@
|
||||
"use strict";
|
||||
// Copyright 2013 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Compute = void 0;
|
||||
const gaxios_1 = require("gaxios");
|
||||
const gcpMetadata = require("gcp-metadata");
|
||||
const oauth2client_1 = require("./oauth2client");
|
||||
class Compute extends oauth2client_1.OAuth2Client {
|
||||
serviceAccountEmail;
|
||||
scopes;
|
||||
/**
|
||||
* Google Compute Engine service account credentials.
|
||||
*
|
||||
* Retrieve access token from the metadata server.
|
||||
* See: https://cloud.google.com/compute/docs/access/authenticate-workloads#applications
|
||||
*/
|
||||
constructor(options = {}) {
|
||||
super(options);
|
||||
// Start with an expired refresh token, which will automatically be
|
||||
// refreshed before the first API call is made.
|
||||
this.credentials = { expiry_date: 1, refresh_token: 'compute-placeholder' };
|
||||
this.serviceAccountEmail = options.serviceAccountEmail || 'default';
|
||||
this.scopes = Array.isArray(options.scopes)
|
||||
? options.scopes
|
||||
: options.scopes
|
||||
? [options.scopes]
|
||||
: [];
|
||||
}
|
||||
/**
|
||||
* Refreshes the access token.
|
||||
* @param refreshToken Unused parameter
|
||||
*/
|
||||
async refreshTokenNoCache() {
|
||||
const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`;
|
||||
let data;
|
||||
try {
|
||||
const instanceOptions = {
|
||||
property: tokenPath,
|
||||
};
|
||||
if (this.scopes.length > 0) {
|
||||
instanceOptions.params = {
|
||||
scopes: this.scopes.join(','),
|
||||
};
|
||||
}
|
||||
data = await gcpMetadata.instance(instanceOptions);
|
||||
}
|
||||
catch (e) {
|
||||
if (e instanceof gaxios_1.GaxiosError) {
|
||||
e.message = `Could not refresh access token: ${e.message}`;
|
||||
this.wrapError(e);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
const tokens = data;
|
||||
if (data && data.expires_in) {
|
||||
tokens.expiry_date = new Date().getTime() + data.expires_in * 1000;
|
||||
delete tokens.expires_in;
|
||||
}
|
||||
this.emit('tokens', tokens);
|
||||
return { tokens, res: null };
|
||||
}
|
||||
/**
|
||||
* Fetches an ID token.
|
||||
* @param targetAudience the audience for the fetched ID token.
|
||||
*/
|
||||
async fetchIdToken(targetAudience) {
|
||||
const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` +
|
||||
`?format=full&audience=${targetAudience}`;
|
||||
let idToken;
|
||||
try {
|
||||
const instanceOptions = {
|
||||
property: idTokenPath,
|
||||
};
|
||||
idToken = await gcpMetadata.instance(instanceOptions);
|
||||
}
|
||||
catch (e) {
|
||||
if (e instanceof Error) {
|
||||
e.message = `Could not fetch ID token: ${e.message}`;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
return idToken;
|
||||
}
|
||||
wrapError(e) {
|
||||
const res = e.response;
|
||||
if (res && res.status) {
|
||||
e.status = res.status;
|
||||
if (res.status === 403) {
|
||||
e.message =
|
||||
'A Forbidden error was returned while attempting to retrieve an access ' +
|
||||
'token for the Compute Engine built-in service account. This may be because the Compute ' +
|
||||
'Engine instance does not have the correct permission scopes specified: ' +
|
||||
e.message;
|
||||
}
|
||||
else if (res.status === 404) {
|
||||
e.message =
|
||||
'A Not Found error was returned while attempting to retrieve an access' +
|
||||
'token for the Compute Engine built-in service account. This may be because the Compute ' +
|
||||
'Engine instance does not have any permission scopes specified: ' +
|
||||
e.message;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.Compute = Compute;
|
||||
//# sourceMappingURL=computeclient.js.map
|
||||
76
node_modules/google-auth-library/build/src/auth/credentials.d.ts
generated
vendored
Normal file
76
node_modules/google-auth-library/build/src/auth/credentials.d.ts
generated
vendored
Normal file
@@ -0,0 +1,76 @@
|
||||
export interface Credentials {
|
||||
/**
|
||||
* This field is only present if the access_type parameter was set to offline in the authentication request. For details, see Refresh tokens.
|
||||
*/
|
||||
refresh_token?: string | null;
|
||||
/**
|
||||
* The time in ms at which this token is thought to expire.
|
||||
*/
|
||||
expiry_date?: number | null;
|
||||
/**
|
||||
* A token that can be sent to a Google API.
|
||||
*/
|
||||
access_token?: string | null;
|
||||
/**
|
||||
* Identifies the type of token returned. At this time, this field always has the value Bearer.
|
||||
*/
|
||||
token_type?: string | null;
|
||||
/**
|
||||
* A JWT that contains identity information about the user that is digitally signed by Google.
|
||||
*/
|
||||
id_token?: string | null;
|
||||
/**
|
||||
* The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings.
|
||||
*/
|
||||
scope?: string;
|
||||
}
|
||||
export interface CredentialRequest {
|
||||
/**
|
||||
* This field is only present if the access_type parameter was set to offline in the authentication request. For details, see Refresh tokens.
|
||||
*/
|
||||
refresh_token?: string;
|
||||
/**
|
||||
* A token that can be sent to a Google API.
|
||||
*/
|
||||
access_token?: string;
|
||||
/**
|
||||
* Identifies the type of token returned. At this time, this field always has the value Bearer.
|
||||
*/
|
||||
token_type?: string;
|
||||
/**
|
||||
* The remaining lifetime of the access token in seconds.
|
||||
*/
|
||||
expires_in?: number;
|
||||
/**
|
||||
* A JWT that contains identity information about the user that is digitally signed by Google.
|
||||
*/
|
||||
id_token?: string;
|
||||
/**
|
||||
* The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings.
|
||||
*/
|
||||
scope?: string;
|
||||
}
|
||||
export interface JWTInput {
|
||||
type?: string;
|
||||
client_email?: string;
|
||||
private_key?: string;
|
||||
private_key_id?: string;
|
||||
project_id?: string;
|
||||
client_id?: string;
|
||||
client_secret?: string;
|
||||
refresh_token?: string;
|
||||
quota_project_id?: string;
|
||||
universe_domain?: string;
|
||||
}
|
||||
export interface ImpersonatedJWTInput {
|
||||
type?: string;
|
||||
source_credentials?: JWTInput;
|
||||
service_account_impersonation_url?: string;
|
||||
delegates?: string[];
|
||||
scopes?: string[];
|
||||
}
|
||||
export interface CredentialBody {
|
||||
client_email?: string;
|
||||
private_key?: string;
|
||||
universe_domain?: string;
|
||||
}
|
||||
16
node_modules/google-auth-library/build/src/auth/credentials.js
generated
vendored
Normal file
16
node_modules/google-auth-library/build/src/auth/credentials.js
generated
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
"use strict";
|
||||
// Copyright 2014 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
//# sourceMappingURL=credentials.js.map
|
||||
79
node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.d.ts
generated
vendored
Normal file
79
node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.d.ts
generated
vendored
Normal file
@@ -0,0 +1,79 @@
|
||||
import { ExternalAccountSupplierContext } from './baseexternalclient';
|
||||
import { GaxiosOptions } from 'gaxios';
|
||||
import { AwsSecurityCredentialsSupplier } from './awsclient';
|
||||
import { AwsSecurityCredentials } from './awsrequestsigner';
|
||||
/**
|
||||
* Interface defining the options used to build a {@link DefaultAwsSecurityCredentialsSupplier}.
|
||||
*/
|
||||
export interface DefaultAwsSecurityCredentialsSupplierOptions {
|
||||
/**
|
||||
* The URL to call to retrieve the active AWS region.
|
||||
**/
|
||||
regionUrl?: string;
|
||||
/**
|
||||
* The URL to call to retrieve AWS security credentials.
|
||||
**/
|
||||
securityCredentialsUrl?: string;
|
||||
/**
|
||||
** The URL to call to retrieve the IMDSV2 session token.
|
||||
**/
|
||||
imdsV2SessionTokenUrl?: string;
|
||||
/**
|
||||
* Additional Gaxios options to use when making requests to the AWS metadata
|
||||
* endpoints.
|
||||
*/
|
||||
additionalGaxiosOptions?: GaxiosOptions;
|
||||
}
|
||||
/**
|
||||
* Internal AWS security credentials supplier implementation used by {@link AwsClient}
|
||||
* when a credential source is provided instead of a user defined supplier.
|
||||
* The logic is summarized as:
|
||||
* 1. If imdsv2_session_token_url is provided in the credential source, then
|
||||
* fetch the aws session token and include it in the headers of the
|
||||
* metadata requests. This is a requirement for IDMSv2 but optional
|
||||
* for IDMSv1.
|
||||
* 2. Retrieve AWS region from availability-zone.
|
||||
* 3a. Check AWS credentials in environment variables. If not found, get
|
||||
* from security-credentials endpoint.
|
||||
* 3b. Get AWS credentials from security-credentials endpoint. In order
|
||||
* to retrieve this, the AWS role needs to be determined by calling
|
||||
* security-credentials endpoint without any argument. Then the
|
||||
* credentials can be retrieved via: security-credentials/role_name
|
||||
* 4. Generate the signed request to AWS STS GetCallerIdentity action.
|
||||
* 5. Inject x-goog-cloud-target-resource into header and serialize the
|
||||
* signed request. This will be the subject-token to pass to GCP STS.
|
||||
*/
|
||||
export declare class DefaultAwsSecurityCredentialsSupplier implements AwsSecurityCredentialsSupplier {
|
||||
#private;
|
||||
private readonly regionUrl?;
|
||||
private readonly securityCredentialsUrl?;
|
||||
private readonly imdsV2SessionTokenUrl?;
|
||||
private readonly additionalGaxiosOptions?;
|
||||
/**
|
||||
* Instantiates a new DefaultAwsSecurityCredentialsSupplier using information
|
||||
* from the credential_source stored in the ADC file.
|
||||
* @param opts The default aws security credentials supplier options object to
|
||||
* build the supplier with.
|
||||
*/
|
||||
constructor(opts: DefaultAwsSecurityCredentialsSupplierOptions);
|
||||
/**
|
||||
* Returns the active AWS region. This first checks to see if the region
|
||||
* is available as an environment variable. If it is not, then the supplier
|
||||
* will call the region URL.
|
||||
* @param context {@link ExternalAccountSupplierContext} from the calling
|
||||
* {@link AwsClient}, contains the requested audience and subject token type
|
||||
* for the external account identity.
|
||||
* @return A promise that resolves with the AWS region string.
|
||||
*/
|
||||
getAwsRegion(context: ExternalAccountSupplierContext): Promise<string>;
|
||||
/**
|
||||
* Returns AWS security credentials. This first checks to see if the credentials
|
||||
* is available as environment variables. If it is not, then the supplier
|
||||
* will call the security credentials URL.
|
||||
* @param context {@link ExternalAccountSupplierContext} from the calling
|
||||
* {@link AwsClient}, contains the requested audience and subject token type
|
||||
* for the external account identity.
|
||||
* @return A promise that resolves with the AWS security credentials.
|
||||
*/
|
||||
getAwsSecurityCredentials(context: ExternalAccountSupplierContext): Promise<AwsSecurityCredentials>;
|
||||
}
|
||||
195
node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js
generated
vendored
Normal file
195
node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js
generated
vendored
Normal file
@@ -0,0 +1,195 @@
|
||||
"use strict";
|
||||
// Copyright 2024 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DefaultAwsSecurityCredentialsSupplier = void 0;
|
||||
const authclient_1 = require("./authclient");
|
||||
/**
|
||||
* Internal AWS security credentials supplier implementation used by {@link AwsClient}
|
||||
* when a credential source is provided instead of a user defined supplier.
|
||||
* The logic is summarized as:
|
||||
* 1. If imdsv2_session_token_url is provided in the credential source, then
|
||||
* fetch the aws session token and include it in the headers of the
|
||||
* metadata requests. This is a requirement for IDMSv2 but optional
|
||||
* for IDMSv1.
|
||||
* 2. Retrieve AWS region from availability-zone.
|
||||
* 3a. Check AWS credentials in environment variables. If not found, get
|
||||
* from security-credentials endpoint.
|
||||
* 3b. Get AWS credentials from security-credentials endpoint. In order
|
||||
* to retrieve this, the AWS role needs to be determined by calling
|
||||
* security-credentials endpoint without any argument. Then the
|
||||
* credentials can be retrieved via: security-credentials/role_name
|
||||
* 4. Generate the signed request to AWS STS GetCallerIdentity action.
|
||||
* 5. Inject x-goog-cloud-target-resource into header and serialize the
|
||||
* signed request. This will be the subject-token to pass to GCP STS.
|
||||
*/
|
||||
class DefaultAwsSecurityCredentialsSupplier {
|
||||
regionUrl;
|
||||
securityCredentialsUrl;
|
||||
imdsV2SessionTokenUrl;
|
||||
additionalGaxiosOptions;
|
||||
/**
|
||||
* Instantiates a new DefaultAwsSecurityCredentialsSupplier using information
|
||||
* from the credential_source stored in the ADC file.
|
||||
* @param opts The default aws security credentials supplier options object to
|
||||
* build the supplier with.
|
||||
*/
|
||||
constructor(opts) {
|
||||
this.regionUrl = opts.regionUrl;
|
||||
this.securityCredentialsUrl = opts.securityCredentialsUrl;
|
||||
this.imdsV2SessionTokenUrl = opts.imdsV2SessionTokenUrl;
|
||||
this.additionalGaxiosOptions = opts.additionalGaxiosOptions;
|
||||
}
|
||||
/**
|
||||
* Returns the active AWS region. This first checks to see if the region
|
||||
* is available as an environment variable. If it is not, then the supplier
|
||||
* will call the region URL.
|
||||
* @param context {@link ExternalAccountSupplierContext} from the calling
|
||||
* {@link AwsClient}, contains the requested audience and subject token type
|
||||
* for the external account identity.
|
||||
* @return A promise that resolves with the AWS region string.
|
||||
*/
|
||||
async getAwsRegion(context) {
|
||||
// Priority order for region determination:
|
||||
// AWS_REGION > AWS_DEFAULT_REGION > metadata server.
|
||||
if (this.#regionFromEnv) {
|
||||
return this.#regionFromEnv;
|
||||
}
|
||||
const metadataHeaders = new Headers();
|
||||
if (!this.#regionFromEnv && this.imdsV2SessionTokenUrl) {
|
||||
metadataHeaders.set('x-aws-ec2-metadata-token', await this.#getImdsV2SessionToken(context.transporter));
|
||||
}
|
||||
if (!this.regionUrl) {
|
||||
throw new RangeError('Unable to determine AWS region due to missing ' +
|
||||
'"options.credential_source.region_url"');
|
||||
}
|
||||
const opts = {
|
||||
...this.additionalGaxiosOptions,
|
||||
url: this.regionUrl,
|
||||
method: 'GET',
|
||||
headers: metadataHeaders,
|
||||
};
|
||||
authclient_1.AuthClient.setMethodName(opts, 'getAwsRegion');
|
||||
const response = await context.transporter.request(opts);
|
||||
// Remove last character. For example, if us-east-2b is returned,
|
||||
// the region would be us-east-2.
|
||||
return response.data.substr(0, response.data.length - 1);
|
||||
}
|
||||
/**
|
||||
* Returns AWS security credentials. This first checks to see if the credentials
|
||||
* is available as environment variables. If it is not, then the supplier
|
||||
* will call the security credentials URL.
|
||||
* @param context {@link ExternalAccountSupplierContext} from the calling
|
||||
* {@link AwsClient}, contains the requested audience and subject token type
|
||||
* for the external account identity.
|
||||
* @return A promise that resolves with the AWS security credentials.
|
||||
*/
|
||||
async getAwsSecurityCredentials(context) {
|
||||
// Check environment variables for permanent credentials first.
|
||||
// https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html
|
||||
if (this.#securityCredentialsFromEnv) {
|
||||
return this.#securityCredentialsFromEnv;
|
||||
}
|
||||
const metadataHeaders = new Headers();
|
||||
if (this.imdsV2SessionTokenUrl) {
|
||||
metadataHeaders.set('x-aws-ec2-metadata-token', await this.#getImdsV2SessionToken(context.transporter));
|
||||
}
|
||||
// Since the role on a VM can change, we don't need to cache it.
|
||||
const roleName = await this.#getAwsRoleName(metadataHeaders, context.transporter);
|
||||
// Temporary credentials typically last for several hours.
|
||||
// Expiration is returned in response.
|
||||
// Consider future optimization of this logic to cache AWS tokens
|
||||
// until their natural expiration.
|
||||
const awsCreds = await this.#retrieveAwsSecurityCredentials(roleName, metadataHeaders, context.transporter);
|
||||
return {
|
||||
accessKeyId: awsCreds.AccessKeyId,
|
||||
secretAccessKey: awsCreds.SecretAccessKey,
|
||||
token: awsCreds.Token,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* @param transporter The transporter to use for requests.
|
||||
* @return A promise that resolves with the IMDSv2 Session Token.
|
||||
*/
|
||||
async #getImdsV2SessionToken(transporter) {
|
||||
const opts = {
|
||||
...this.additionalGaxiosOptions,
|
||||
url: this.imdsV2SessionTokenUrl,
|
||||
method: 'PUT',
|
||||
headers: { 'x-aws-ec2-metadata-token-ttl-seconds': '300' },
|
||||
};
|
||||
authclient_1.AuthClient.setMethodName(opts, '#getImdsV2SessionToken');
|
||||
const response = await transporter.request(opts);
|
||||
return response.data;
|
||||
}
|
||||
/**
|
||||
* @param headers The headers to be used in the metadata request.
|
||||
* @param transporter The transporter to use for requests.
|
||||
* @return A promise that resolves with the assigned role to the current
|
||||
* AWS VM. This is needed for calling the security-credentials endpoint.
|
||||
*/
|
||||
async #getAwsRoleName(headers, transporter) {
|
||||
if (!this.securityCredentialsUrl) {
|
||||
throw new Error('Unable to determine AWS role name due to missing ' +
|
||||
'"options.credential_source.url"');
|
||||
}
|
||||
const opts = {
|
||||
...this.additionalGaxiosOptions,
|
||||
url: this.securityCredentialsUrl,
|
||||
method: 'GET',
|
||||
headers: headers,
|
||||
};
|
||||
authclient_1.AuthClient.setMethodName(opts, '#getAwsRoleName');
|
||||
const response = await transporter.request(opts);
|
||||
return response.data;
|
||||
}
|
||||
/**
|
||||
* Retrieves the temporary AWS credentials by calling the security-credentials
|
||||
* endpoint as specified in the `credential_source` object.
|
||||
* @param roleName The role attached to the current VM.
|
||||
* @param headers The headers to be used in the metadata request.
|
||||
* @param transporter The transporter to use for requests.
|
||||
* @return A promise that resolves with the temporary AWS credentials
|
||||
* needed for creating the GetCallerIdentity signed request.
|
||||
*/
|
||||
async #retrieveAwsSecurityCredentials(roleName, headers, transporter) {
|
||||
const opts = {
|
||||
...this.additionalGaxiosOptions,
|
||||
url: `${this.securityCredentialsUrl}/${roleName}`,
|
||||
headers: headers,
|
||||
};
|
||||
authclient_1.AuthClient.setMethodName(opts, '#retrieveAwsSecurityCredentials');
|
||||
const response = await transporter.request(opts);
|
||||
return response.data;
|
||||
}
|
||||
get #regionFromEnv() {
|
||||
// The AWS region can be provided through AWS_REGION or AWS_DEFAULT_REGION.
|
||||
// Only one is required.
|
||||
return (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION'] || null);
|
||||
}
|
||||
get #securityCredentialsFromEnv() {
|
||||
// Both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required.
|
||||
if (process.env['AWS_ACCESS_KEY_ID'] &&
|
||||
process.env['AWS_SECRET_ACCESS_KEY']) {
|
||||
return {
|
||||
accessKeyId: process.env['AWS_ACCESS_KEY_ID'],
|
||||
secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'],
|
||||
token: process.env['AWS_SESSION_TOKEN'],
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
exports.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier;
|
||||
//# sourceMappingURL=defaultawssecuritycredentialssupplier.js.map
|
||||
149
node_modules/google-auth-library/build/src/auth/downscopedclient.d.ts
generated
vendored
Normal file
149
node_modules/google-auth-library/build/src/auth/downscopedclient.d.ts
generated
vendored
Normal file
@@ -0,0 +1,149 @@
|
||||
import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios';
|
||||
import { Credentials } from './credentials';
|
||||
import { AuthClient, AuthClientOptions, GetAccessTokenResponse, BodyResponseCallback } from './authclient';
|
||||
/**
|
||||
* The maximum number of access boundary rules a Credential Access Boundary
|
||||
* can contain.
|
||||
*/
|
||||
export declare const MAX_ACCESS_BOUNDARY_RULES_COUNT = 10;
|
||||
/**
|
||||
* Offset to take into account network delays and server clock skews.
|
||||
*/
|
||||
export declare const EXPIRATION_TIME_OFFSET: number;
|
||||
/**
|
||||
* Internal interface for tracking the access token expiration time.
|
||||
*/
|
||||
interface CredentialsWithResponse extends Credentials {
|
||||
res?: GaxiosResponse | null;
|
||||
}
|
||||
/**
|
||||
* Internal interface for tracking and returning the Downscoped access token
|
||||
* expiration time in epoch time (seconds).
|
||||
*/
|
||||
interface DownscopedAccessTokenResponse extends GetAccessTokenResponse {
|
||||
expirationTime?: number | null;
|
||||
}
|
||||
/**
|
||||
* Defines an upper bound of permissions available for a GCP credential.
|
||||
*/
|
||||
export interface CredentialAccessBoundary {
|
||||
accessBoundary: {
|
||||
accessBoundaryRules: AccessBoundaryRule[];
|
||||
};
|
||||
}
|
||||
/** Defines an upper bound of permissions on a particular resource. */
|
||||
interface AccessBoundaryRule {
|
||||
availablePermissions: string[];
|
||||
availableResource: string;
|
||||
availabilityCondition?: AvailabilityCondition;
|
||||
}
|
||||
/**
|
||||
* An optional condition that can be used as part of a
|
||||
* CredentialAccessBoundary to further restrict permissions.
|
||||
*/
|
||||
interface AvailabilityCondition {
|
||||
expression: string;
|
||||
title?: string;
|
||||
description?: string;
|
||||
}
|
||||
export interface DownscopedClientOptions extends AuthClientOptions {
|
||||
/**
|
||||
* The source AuthClient to be downscoped based on the provided Credential Access Boundary rules.
|
||||
*/
|
||||
authClient: AuthClient;
|
||||
/**
|
||||
* The Credential Access Boundary which contains a list of access boundary rules.
|
||||
* Each rule contains information on the resource that the rule applies to, the upper bound of the
|
||||
* permissions that are available on that resource and an optional
|
||||
* condition to further restrict permissions.
|
||||
*/
|
||||
credentialAccessBoundary: CredentialAccessBoundary;
|
||||
}
|
||||
/**
|
||||
* Defines a set of Google credentials that are downscoped from an existing set
|
||||
* of Google OAuth2 credentials. This is useful to restrict the Identity and
|
||||
* Access Management (IAM) permissions that a short-lived credential can use.
|
||||
* The common pattern of usage is to have a token broker with elevated access
|
||||
* generate these downscoped credentials from higher access source credentials
|
||||
* and pass the downscoped short-lived access tokens to a token consumer via
|
||||
* some secure authenticated channel for limited access to Google Cloud Storage
|
||||
* resources.
|
||||
*/
|
||||
export declare class DownscopedClient extends AuthClient {
|
||||
private readonly authClient;
|
||||
private readonly credentialAccessBoundary;
|
||||
private cachedDownscopedAccessToken;
|
||||
private readonly stsCredential;
|
||||
/**
|
||||
* Instantiates a downscoped client object using the provided source
|
||||
* AuthClient and credential access boundary rules.
|
||||
* To downscope permissions of a source AuthClient, a Credential Access
|
||||
* Boundary that specifies which resources the new credential can access, as
|
||||
* well as an upper bound on the permissions that are available on each
|
||||
* resource, has to be defined. A downscoped client can then be instantiated
|
||||
* using the source AuthClient and the Credential Access Boundary.
|
||||
* @param options the {@link DownscopedClientOptions `DownscopedClientOptions`} to use. Passing an `AuthClient` directly is **@DEPRECATED**.
|
||||
* @param credentialAccessBoundary **@DEPRECATED**. Provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead.
|
||||
*/
|
||||
constructor(
|
||||
/**
|
||||
* AuthClient is for backwards-compatibility.
|
||||
*/
|
||||
options: AuthClient | DownscopedClientOptions,
|
||||
/**
|
||||
* @deprecated - provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead
|
||||
*/
|
||||
credentialAccessBoundary?: CredentialAccessBoundary);
|
||||
/**
|
||||
* Provides a mechanism to inject Downscoped access tokens directly.
|
||||
* The expiry_date field is required to facilitate determination of the token
|
||||
* expiration which would make it easier for the token consumer to handle.
|
||||
* @param credentials The Credentials object to set on the current client.
|
||||
*/
|
||||
setCredentials(credentials: Credentials): void;
|
||||
getAccessToken(): Promise<DownscopedAccessTokenResponse>;
|
||||
/**
|
||||
* The main authentication interface. It takes an optional url which when
|
||||
* present is the endpoint being accessed, and returns a Promise which
|
||||
* resolves with authorization header fields.
|
||||
*
|
||||
* The result has the form:
|
||||
* { authorization: 'Bearer <access_token_value>' }
|
||||
*/
|
||||
getRequestHeaders(): Promise<Headers>;
|
||||
/**
|
||||
* Provides a request implementation with OAuth 2.0 flow. In cases of
|
||||
* HTTP 401 and 403 responses, it automatically asks for a new access token
|
||||
* and replays the unsuccessful request.
|
||||
* @param opts Request options.
|
||||
* @param callback callback.
|
||||
* @return A promise that resolves with the HTTP response when no callback
|
||||
* is provided.
|
||||
*/
|
||||
request<T>(opts: GaxiosOptions): GaxiosPromise<T>;
|
||||
request<T>(opts: GaxiosOptions, callback: BodyResponseCallback<T>): void;
|
||||
/**
|
||||
* Authenticates the provided HTTP request, processes it and resolves with the
|
||||
* returned response.
|
||||
* @param opts The HTTP request options.
|
||||
* @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure
|
||||
* @return A promise that resolves with the successful response.
|
||||
*/
|
||||
protected requestAsync<T>(opts: GaxiosOptions, reAuthRetried?: boolean): Promise<GaxiosResponse<T>>;
|
||||
/**
|
||||
* Forces token refresh, even if unexpired tokens are currently cached.
|
||||
* GCP access tokens are retrieved from authclient object/source credential.
|
||||
* Then GCP access tokens are exchanged for downscoped access tokens via the
|
||||
* token exchange endpoint.
|
||||
* @return A promise that resolves with the fresh downscoped access token.
|
||||
*/
|
||||
protected refreshAccessTokenAsync(): Promise<CredentialsWithResponse>;
|
||||
/**
|
||||
* Returns whether the provided credentials are expired or not.
|
||||
* If there is no expiry time, assumes the token is not expired or expiring.
|
||||
* @param downscopedAccessToken The credentials to check for expiration.
|
||||
* @return Whether the credentials are expired or not.
|
||||
*/
|
||||
private isExpired;
|
||||
}
|
||||
export {};
|
||||
273
node_modules/google-auth-library/build/src/auth/downscopedclient.js
generated
vendored
Normal file
273
node_modules/google-auth-library/build/src/auth/downscopedclient.js
generated
vendored
Normal file
@@ -0,0 +1,273 @@
|
||||
"use strict";
|
||||
// Copyright 2021 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DownscopedClient = exports.EXPIRATION_TIME_OFFSET = exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = void 0;
|
||||
const gaxios_1 = require("gaxios");
|
||||
const stream = require("stream");
|
||||
const authclient_1 = require("./authclient");
|
||||
const sts = require("./stscredentials");
|
||||
/**
|
||||
* The required token exchange grant_type: rfc8693#section-2.1
|
||||
*/
|
||||
const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';
|
||||
/**
|
||||
* The requested token exchange requested_token_type: rfc8693#section-2.1
|
||||
*/
|
||||
const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';
|
||||
/**
|
||||
* The requested token exchange subject_token_type: rfc8693#section-2.1
|
||||
*/
|
||||
const STS_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';
|
||||
/**
|
||||
* The maximum number of access boundary rules a Credential Access Boundary
|
||||
* can contain.
|
||||
*/
|
||||
exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = 10;
|
||||
/**
|
||||
* Offset to take into account network delays and server clock skews.
|
||||
*/
|
||||
exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000;
|
||||
/**
|
||||
* Defines a set of Google credentials that are downscoped from an existing set
|
||||
* of Google OAuth2 credentials. This is useful to restrict the Identity and
|
||||
* Access Management (IAM) permissions that a short-lived credential can use.
|
||||
* The common pattern of usage is to have a token broker with elevated access
|
||||
* generate these downscoped credentials from higher access source credentials
|
||||
* and pass the downscoped short-lived access tokens to a token consumer via
|
||||
* some secure authenticated channel for limited access to Google Cloud Storage
|
||||
* resources.
|
||||
*/
|
||||
class DownscopedClient extends authclient_1.AuthClient {
|
||||
authClient;
|
||||
credentialAccessBoundary;
|
||||
cachedDownscopedAccessToken;
|
||||
stsCredential;
|
||||
/**
|
||||
* Instantiates a downscoped client object using the provided source
|
||||
* AuthClient and credential access boundary rules.
|
||||
* To downscope permissions of a source AuthClient, a Credential Access
|
||||
* Boundary that specifies which resources the new credential can access, as
|
||||
* well as an upper bound on the permissions that are available on each
|
||||
* resource, has to be defined. A downscoped client can then be instantiated
|
||||
* using the source AuthClient and the Credential Access Boundary.
|
||||
* @param options the {@link DownscopedClientOptions `DownscopedClientOptions`} to use. Passing an `AuthClient` directly is **@DEPRECATED**.
|
||||
* @param credentialAccessBoundary **@DEPRECATED**. Provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead.
|
||||
*/
|
||||
constructor(
|
||||
/**
|
||||
* AuthClient is for backwards-compatibility.
|
||||
*/
|
||||
options,
|
||||
/**
|
||||
* @deprecated - provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead
|
||||
*/
|
||||
credentialAccessBoundary = {
|
||||
accessBoundary: {
|
||||
accessBoundaryRules: [],
|
||||
},
|
||||
}) {
|
||||
super(options instanceof authclient_1.AuthClient ? {} : options);
|
||||
if (options instanceof authclient_1.AuthClient) {
|
||||
this.authClient = options;
|
||||
this.credentialAccessBoundary = credentialAccessBoundary;
|
||||
}
|
||||
else {
|
||||
this.authClient = options.authClient;
|
||||
this.credentialAccessBoundary = options.credentialAccessBoundary;
|
||||
}
|
||||
// Check 1-10 Access Boundary Rules are defined within Credential Access
|
||||
// Boundary.
|
||||
if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules
|
||||
.length === 0) {
|
||||
throw new Error('At least one access boundary rule needs to be defined.');
|
||||
}
|
||||
else if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length >
|
||||
exports.MAX_ACCESS_BOUNDARY_RULES_COUNT) {
|
||||
throw new Error('The provided access boundary has more than ' +
|
||||
`${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);
|
||||
}
|
||||
// Check at least one permission should be defined in each Access Boundary
|
||||
// Rule.
|
||||
for (const rule of this.credentialAccessBoundary.accessBoundary
|
||||
.accessBoundaryRules) {
|
||||
if (rule.availablePermissions.length === 0) {
|
||||
throw new Error('At least one permission should be defined in access boundary rules.');
|
||||
}
|
||||
}
|
||||
this.stsCredential = new sts.StsCredentials({
|
||||
tokenExchangeEndpoint: `https://sts.${this.universeDomain}/v1/token`,
|
||||
});
|
||||
this.cachedDownscopedAccessToken = null;
|
||||
}
|
||||
/**
|
||||
* Provides a mechanism to inject Downscoped access tokens directly.
|
||||
* The expiry_date field is required to facilitate determination of the token
|
||||
* expiration which would make it easier for the token consumer to handle.
|
||||
* @param credentials The Credentials object to set on the current client.
|
||||
*/
|
||||
setCredentials(credentials) {
|
||||
if (!credentials.expiry_date) {
|
||||
throw new Error('The access token expiry_date field is missing in the provided ' +
|
||||
'credentials.');
|
||||
}
|
||||
super.setCredentials(credentials);
|
||||
this.cachedDownscopedAccessToken = credentials;
|
||||
}
|
||||
async getAccessToken() {
|
||||
// If the cached access token is unavailable or expired, force refresh.
|
||||
// The Downscoped access token will be returned in
|
||||
// DownscopedAccessTokenResponse format.
|
||||
if (!this.cachedDownscopedAccessToken ||
|
||||
this.isExpired(this.cachedDownscopedAccessToken)) {
|
||||
await this.refreshAccessTokenAsync();
|
||||
}
|
||||
// Return Downscoped access token in DownscopedAccessTokenResponse format.
|
||||
return {
|
||||
token: this.cachedDownscopedAccessToken.access_token,
|
||||
expirationTime: this.cachedDownscopedAccessToken.expiry_date,
|
||||
res: this.cachedDownscopedAccessToken.res,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* The main authentication interface. It takes an optional url which when
|
||||
* present is the endpoint being accessed, and returns a Promise which
|
||||
* resolves with authorization header fields.
|
||||
*
|
||||
* The result has the form:
|
||||
* { authorization: 'Bearer <access_token_value>' }
|
||||
*/
|
||||
async getRequestHeaders() {
|
||||
const accessTokenResponse = await this.getAccessToken();
|
||||
const headers = new Headers({
|
||||
authorization: `Bearer ${accessTokenResponse.token}`,
|
||||
});
|
||||
return this.addSharedMetadataHeaders(headers);
|
||||
}
|
||||
request(opts, callback) {
|
||||
if (callback) {
|
||||
this.requestAsync(opts).then(r => callback(null, r), e => {
|
||||
return callback(e, e.response);
|
||||
});
|
||||
}
|
||||
else {
|
||||
return this.requestAsync(opts);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Authenticates the provided HTTP request, processes it and resolves with the
|
||||
* returned response.
|
||||
* @param opts The HTTP request options.
|
||||
* @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure
|
||||
* @return A promise that resolves with the successful response.
|
||||
*/
|
||||
async requestAsync(opts, reAuthRetried = false) {
|
||||
let response;
|
||||
try {
|
||||
const requestHeaders = await this.getRequestHeaders();
|
||||
opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);
|
||||
this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);
|
||||
response = await this.transporter.request(opts);
|
||||
}
|
||||
catch (e) {
|
||||
const res = e.response;
|
||||
if (res) {
|
||||
const statusCode = res.status;
|
||||
// Retry the request for metadata if the following criteria are true:
|
||||
// - We haven't already retried. It only makes sense to retry once.
|
||||
// - The response was a 401 or a 403
|
||||
// - The request didn't send a readableStream
|
||||
// - forceRefreshOnFailure is true
|
||||
const isReadableStream = res.config.data instanceof stream.Readable;
|
||||
const isAuthErr = statusCode === 401 || statusCode === 403;
|
||||
if (!reAuthRetried &&
|
||||
isAuthErr &&
|
||||
!isReadableStream &&
|
||||
this.forceRefreshOnFailure) {
|
||||
await this.refreshAccessTokenAsync();
|
||||
return await this.requestAsync(opts, true);
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
return response;
|
||||
}
|
||||
/**
|
||||
* Forces token refresh, even if unexpired tokens are currently cached.
|
||||
* GCP access tokens are retrieved from authclient object/source credential.
|
||||
* Then GCP access tokens are exchanged for downscoped access tokens via the
|
||||
* token exchange endpoint.
|
||||
* @return A promise that resolves with the fresh downscoped access token.
|
||||
*/
|
||||
async refreshAccessTokenAsync() {
|
||||
// Retrieve GCP access token from source credential.
|
||||
const subjectToken = (await this.authClient.getAccessToken()).token;
|
||||
// Construct the STS credentials options.
|
||||
const stsCredentialsOptions = {
|
||||
grantType: STS_GRANT_TYPE,
|
||||
requestedTokenType: STS_REQUEST_TOKEN_TYPE,
|
||||
subjectToken: subjectToken,
|
||||
subjectTokenType: STS_SUBJECT_TOKEN_TYPE,
|
||||
};
|
||||
// Exchange the source AuthClient access token for a Downscoped access
|
||||
// token.
|
||||
const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, this.credentialAccessBoundary);
|
||||
/**
|
||||
* The STS endpoint will only return the expiration time for the downscoped
|
||||
* access token if the original access token represents a service account.
|
||||
* The downscoped token's expiration time will always match the source
|
||||
* credential expiration. When no expires_in is returned, we can copy the
|
||||
* source credential's expiration time.
|
||||
*/
|
||||
const sourceCredExpireDate = this.authClient.credentials?.expiry_date || null;
|
||||
const expiryDate = stsResponse.expires_in
|
||||
? new Date().getTime() + stsResponse.expires_in * 1000
|
||||
: sourceCredExpireDate;
|
||||
// Save response in cached access token.
|
||||
this.cachedDownscopedAccessToken = {
|
||||
access_token: stsResponse.access_token,
|
||||
expiry_date: expiryDate,
|
||||
res: stsResponse.res,
|
||||
};
|
||||
// Save credentials.
|
||||
this.credentials = {};
|
||||
Object.assign(this.credentials, this.cachedDownscopedAccessToken);
|
||||
delete this.credentials.res;
|
||||
// Trigger tokens event to notify external listeners.
|
||||
this.emit('tokens', {
|
||||
refresh_token: null,
|
||||
expiry_date: this.cachedDownscopedAccessToken.expiry_date,
|
||||
access_token: this.cachedDownscopedAccessToken.access_token,
|
||||
token_type: 'Bearer',
|
||||
id_token: null,
|
||||
});
|
||||
// Return the cached access token.
|
||||
return this.cachedDownscopedAccessToken;
|
||||
}
|
||||
/**
|
||||
* Returns whether the provided credentials are expired or not.
|
||||
* If there is no expiry time, assumes the token is not expired or expiring.
|
||||
* @param downscopedAccessToken The credentials to check for expiration.
|
||||
* @return Whether the credentials are expired or not.
|
||||
*/
|
||||
isExpired(downscopedAccessToken) {
|
||||
const now = new Date().getTime();
|
||||
return downscopedAccessToken.expiry_date
|
||||
? now >=
|
||||
downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis
|
||||
: false;
|
||||
}
|
||||
}
|
||||
exports.DownscopedClient = DownscopedClient;
|
||||
//# sourceMappingURL=downscopedclient.js.map
|
||||
11
node_modules/google-auth-library/build/src/auth/envDetect.d.ts
generated
vendored
Normal file
11
node_modules/google-auth-library/build/src/auth/envDetect.d.ts
generated
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
export declare enum GCPEnv {
|
||||
APP_ENGINE = "APP_ENGINE",
|
||||
KUBERNETES_ENGINE = "KUBERNETES_ENGINE",
|
||||
CLOUD_FUNCTIONS = "CLOUD_FUNCTIONS",
|
||||
COMPUTE_ENGINE = "COMPUTE_ENGINE",
|
||||
CLOUD_RUN = "CLOUD_RUN",
|
||||
CLOUD_RUN_JOBS = "CLOUD_RUN_JOBS",
|
||||
NONE = "NONE"
|
||||
}
|
||||
export declare function clear(): void;
|
||||
export declare function getEnv(): Promise<GCPEnv>;
|
||||
97
node_modules/google-auth-library/build/src/auth/envDetect.js
generated
vendored
Normal file
97
node_modules/google-auth-library/build/src/auth/envDetect.js
generated
vendored
Normal file
@@ -0,0 +1,97 @@
|
||||
"use strict";
|
||||
// Copyright 2018 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.GCPEnv = void 0;
|
||||
exports.clear = clear;
|
||||
exports.getEnv = getEnv;
|
||||
const gcpMetadata = require("gcp-metadata");
|
||||
var GCPEnv;
|
||||
(function (GCPEnv) {
|
||||
GCPEnv["APP_ENGINE"] = "APP_ENGINE";
|
||||
GCPEnv["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE";
|
||||
GCPEnv["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS";
|
||||
GCPEnv["COMPUTE_ENGINE"] = "COMPUTE_ENGINE";
|
||||
GCPEnv["CLOUD_RUN"] = "CLOUD_RUN";
|
||||
GCPEnv["CLOUD_RUN_JOBS"] = "CLOUD_RUN_JOBS";
|
||||
GCPEnv["NONE"] = "NONE";
|
||||
})(GCPEnv || (exports.GCPEnv = GCPEnv = {}));
|
||||
let envPromise;
|
||||
function clear() {
|
||||
envPromise = undefined;
|
||||
}
|
||||
async function getEnv() {
|
||||
if (envPromise) {
|
||||
return envPromise;
|
||||
}
|
||||
envPromise = getEnvMemoized();
|
||||
return envPromise;
|
||||
}
|
||||
async function getEnvMemoized() {
|
||||
let env = GCPEnv.NONE;
|
||||
if (isAppEngine()) {
|
||||
env = GCPEnv.APP_ENGINE;
|
||||
}
|
||||
else if (isCloudFunction()) {
|
||||
env = GCPEnv.CLOUD_FUNCTIONS;
|
||||
}
|
||||
else if (await isComputeEngine()) {
|
||||
if (await isKubernetesEngine()) {
|
||||
env = GCPEnv.KUBERNETES_ENGINE;
|
||||
}
|
||||
else if (isCloudRun()) {
|
||||
env = GCPEnv.CLOUD_RUN;
|
||||
}
|
||||
else if (isCloudRunJob()) {
|
||||
env = GCPEnv.CLOUD_RUN_JOBS;
|
||||
}
|
||||
else {
|
||||
env = GCPEnv.COMPUTE_ENGINE;
|
||||
}
|
||||
}
|
||||
else {
|
||||
env = GCPEnv.NONE;
|
||||
}
|
||||
return env;
|
||||
}
|
||||
function isAppEngine() {
|
||||
return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME);
|
||||
}
|
||||
function isCloudFunction() {
|
||||
return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET);
|
||||
}
|
||||
/**
|
||||
* This check only verifies that the environment is running knative.
|
||||
* This must be run *after* checking for Kubernetes, otherwise it will
|
||||
* return a false positive.
|
||||
*/
|
||||
function isCloudRun() {
|
||||
return !!process.env.K_CONFIGURATION;
|
||||
}
|
||||
function isCloudRunJob() {
|
||||
return !!process.env.CLOUD_RUN_JOB;
|
||||
}
|
||||
async function isKubernetesEngine() {
|
||||
try {
|
||||
await gcpMetadata.instance('attributes/cluster-name');
|
||||
return true;
|
||||
}
|
||||
catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
async function isComputeEngine() {
|
||||
return gcpMetadata.isAvailable();
|
||||
}
|
||||
//# sourceMappingURL=envDetect.js.map
|
||||
137
node_modules/google-auth-library/build/src/auth/executable-response.d.ts
generated
vendored
Normal file
137
node_modules/google-auth-library/build/src/auth/executable-response.d.ts
generated
vendored
Normal file
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* Interface defining the JSON formatted response of a 3rd party executable
|
||||
* used by the pluggable auth client.
|
||||
*/
|
||||
export interface ExecutableResponseJson {
|
||||
/**
|
||||
* The version of the JSON response. Only version 1 is currently supported.
|
||||
* Always required.
|
||||
*/
|
||||
version: number;
|
||||
/**
|
||||
* Whether the executable ran successfully. Always required.
|
||||
*/
|
||||
success: boolean;
|
||||
/**
|
||||
* The epoch time for expiration of the token in seconds, required for
|
||||
* successful responses.
|
||||
*/
|
||||
expiration_time?: number;
|
||||
/**
|
||||
* The type of subject token in the response, currently supported values are:
|
||||
* urn:ietf:params:oauth:token-type:saml2
|
||||
* urn:ietf:params:oauth:token-type:id_token
|
||||
* urn:ietf:params:oauth:token-type:jwt
|
||||
*/
|
||||
token_type?: string;
|
||||
/**
|
||||
* The error code from the executable, required when unsuccessful.
|
||||
*/
|
||||
code?: string;
|
||||
/**
|
||||
* The error message from the executable, required when unsuccessful.
|
||||
*/
|
||||
message?: string;
|
||||
/**
|
||||
* The ID token to be used as a subject token when token_type is id_token or jwt.
|
||||
*/
|
||||
id_token?: string;
|
||||
/**
|
||||
* The response to be used as a subject token when token_type is saml2.
|
||||
*/
|
||||
saml_response?: string;
|
||||
}
|
||||
/**
|
||||
* Defines the response of a 3rd party executable run by the pluggable auth client.
|
||||
*/
|
||||
export declare class ExecutableResponse {
|
||||
/**
|
||||
* The version of the Executable response. Only version 1 is currently supported.
|
||||
*/
|
||||
readonly version: number;
|
||||
/**
|
||||
* Whether the executable ran successfully.
|
||||
*/
|
||||
readonly success: boolean;
|
||||
/**
|
||||
* The epoch time for expiration of the token in seconds.
|
||||
*/
|
||||
readonly expirationTime?: number;
|
||||
/**
|
||||
* The type of subject token in the response, currently supported values are:
|
||||
* urn:ietf:params:oauth:token-type:saml2
|
||||
* urn:ietf:params:oauth:token-type:id_token
|
||||
* urn:ietf:params:oauth:token-type:jwt
|
||||
*/
|
||||
readonly tokenType?: string;
|
||||
/**
|
||||
* The error code from the executable.
|
||||
*/
|
||||
readonly errorCode?: string;
|
||||
/**
|
||||
* The error message from the executable.
|
||||
*/
|
||||
readonly errorMessage?: string;
|
||||
/**
|
||||
* The subject token from the executable, format depends on tokenType.
|
||||
*/
|
||||
readonly subjectToken?: string;
|
||||
/**
|
||||
* Instantiates an ExecutableResponse instance using the provided JSON object
|
||||
* from the output of the executable.
|
||||
* @param responseJson Response from a 3rd party executable, loaded from a
|
||||
* run of the executable or a cached output file.
|
||||
*/
|
||||
constructor(responseJson: ExecutableResponseJson);
|
||||
/**
|
||||
* @return A boolean representing if the response has a valid token. Returns
|
||||
* true when the response was successful and the token is not expired.
|
||||
*/
|
||||
isValid(): boolean;
|
||||
/**
|
||||
* @return A boolean representing if the response is expired. Returns true if the
|
||||
* provided timeout has passed.
|
||||
*/
|
||||
isExpired(): boolean;
|
||||
}
|
||||
/**
|
||||
* An error thrown by the ExecutableResponse class.
|
||||
*/
|
||||
export declare class ExecutableResponseError extends Error {
|
||||
constructor(message: string);
|
||||
}
|
||||
/**
|
||||
* An error thrown when the 'version' field in an executable response is missing or invalid.
|
||||
*/
|
||||
export declare class InvalidVersionFieldError extends ExecutableResponseError {
|
||||
}
|
||||
/**
|
||||
* An error thrown when the 'success' field in an executable response is missing or invalid.
|
||||
*/
|
||||
export declare class InvalidSuccessFieldError extends ExecutableResponseError {
|
||||
}
|
||||
/**
|
||||
* An error thrown when the 'expiration_time' field in an executable response is missing or invalid.
|
||||
*/
|
||||
export declare class InvalidExpirationTimeFieldError extends ExecutableResponseError {
|
||||
}
|
||||
/**
|
||||
* An error thrown when the 'token_type' field in an executable response is missing or invalid.
|
||||
*/
|
||||
export declare class InvalidTokenTypeFieldError extends ExecutableResponseError {
|
||||
}
|
||||
/**
|
||||
* An error thrown when the 'code' field in an executable response is missing or invalid.
|
||||
*/
|
||||
export declare class InvalidCodeFieldError extends ExecutableResponseError {
|
||||
}
|
||||
/**
|
||||
* An error thrown when the 'message' field in an executable response is missing or invalid.
|
||||
*/
|
||||
export declare class InvalidMessageFieldError extends ExecutableResponseError {
|
||||
}
|
||||
/**
|
||||
* An error thrown when the subject token in an executable response is missing or invalid.
|
||||
*/
|
||||
export declare class InvalidSubjectTokenError extends ExecutableResponseError {
|
||||
}
|
||||
178
node_modules/google-auth-library/build/src/auth/executable-response.js
generated
vendored
Normal file
178
node_modules/google-auth-library/build/src/auth/executable-response.js
generated
vendored
Normal file
@@ -0,0 +1,178 @@
|
||||
"use strict";
|
||||
// Copyright 2022 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.InvalidSubjectTokenError = exports.InvalidMessageFieldError = exports.InvalidCodeFieldError = exports.InvalidTokenTypeFieldError = exports.InvalidExpirationTimeFieldError = exports.InvalidSuccessFieldError = exports.InvalidVersionFieldError = exports.ExecutableResponseError = exports.ExecutableResponse = void 0;
|
||||
const SAML_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:saml2';
|
||||
const OIDC_SUBJECT_TOKEN_TYPE1 = 'urn:ietf:params:oauth:token-type:id_token';
|
||||
const OIDC_SUBJECT_TOKEN_TYPE2 = 'urn:ietf:params:oauth:token-type:jwt';
|
||||
/**
|
||||
* Defines the response of a 3rd party executable run by the pluggable auth client.
|
||||
*/
|
||||
class ExecutableResponse {
|
||||
/**
|
||||
* The version of the Executable response. Only version 1 is currently supported.
|
||||
*/
|
||||
version;
|
||||
/**
|
||||
* Whether the executable ran successfully.
|
||||
*/
|
||||
success;
|
||||
/**
|
||||
* The epoch time for expiration of the token in seconds.
|
||||
*/
|
||||
expirationTime;
|
||||
/**
|
||||
* The type of subject token in the response, currently supported values are:
|
||||
* urn:ietf:params:oauth:token-type:saml2
|
||||
* urn:ietf:params:oauth:token-type:id_token
|
||||
* urn:ietf:params:oauth:token-type:jwt
|
||||
*/
|
||||
tokenType;
|
||||
/**
|
||||
* The error code from the executable.
|
||||
*/
|
||||
errorCode;
|
||||
/**
|
||||
* The error message from the executable.
|
||||
*/
|
||||
errorMessage;
|
||||
/**
|
||||
* The subject token from the executable, format depends on tokenType.
|
||||
*/
|
||||
subjectToken;
|
||||
/**
|
||||
* Instantiates an ExecutableResponse instance using the provided JSON object
|
||||
* from the output of the executable.
|
||||
* @param responseJson Response from a 3rd party executable, loaded from a
|
||||
* run of the executable or a cached output file.
|
||||
*/
|
||||
constructor(responseJson) {
|
||||
// Check that the required fields exist in the json response.
|
||||
if (!responseJson.version) {
|
||||
throw new InvalidVersionFieldError("Executable response must contain a 'version' field.");
|
||||
}
|
||||
if (responseJson.success === undefined) {
|
||||
throw new InvalidSuccessFieldError("Executable response must contain a 'success' field.");
|
||||
}
|
||||
this.version = responseJson.version;
|
||||
this.success = responseJson.success;
|
||||
// Validate required fields for a successful response.
|
||||
if (this.success) {
|
||||
this.expirationTime = responseJson.expiration_time;
|
||||
this.tokenType = responseJson.token_type;
|
||||
// Validate token type field.
|
||||
if (this.tokenType !== SAML_SUBJECT_TOKEN_TYPE &&
|
||||
this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE1 &&
|
||||
this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE2) {
|
||||
throw new InvalidTokenTypeFieldError("Executable response must contain a 'token_type' field when successful " +
|
||||
`and it must be one of ${OIDC_SUBJECT_TOKEN_TYPE1}, ${OIDC_SUBJECT_TOKEN_TYPE2}, or ${SAML_SUBJECT_TOKEN_TYPE}.`);
|
||||
}
|
||||
// Validate subject token.
|
||||
if (this.tokenType === SAML_SUBJECT_TOKEN_TYPE) {
|
||||
if (!responseJson.saml_response) {
|
||||
throw new InvalidSubjectTokenError(`Executable response must contain a 'saml_response' field when token_type=${SAML_SUBJECT_TOKEN_TYPE}.`);
|
||||
}
|
||||
this.subjectToken = responseJson.saml_response;
|
||||
}
|
||||
else {
|
||||
if (!responseJson.id_token) {
|
||||
throw new InvalidSubjectTokenError("Executable response must contain a 'id_token' field when " +
|
||||
`token_type=${OIDC_SUBJECT_TOKEN_TYPE1} or ${OIDC_SUBJECT_TOKEN_TYPE2}.`);
|
||||
}
|
||||
this.subjectToken = responseJson.id_token;
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Both code and message must be provided for unsuccessful responses.
|
||||
if (!responseJson.code) {
|
||||
throw new InvalidCodeFieldError("Executable response must contain a 'code' field when unsuccessful.");
|
||||
}
|
||||
if (!responseJson.message) {
|
||||
throw new InvalidMessageFieldError("Executable response must contain a 'message' field when unsuccessful.");
|
||||
}
|
||||
this.errorCode = responseJson.code;
|
||||
this.errorMessage = responseJson.message;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @return A boolean representing if the response has a valid token. Returns
|
||||
* true when the response was successful and the token is not expired.
|
||||
*/
|
||||
isValid() {
|
||||
return !this.isExpired() && this.success;
|
||||
}
|
||||
/**
|
||||
* @return A boolean representing if the response is expired. Returns true if the
|
||||
* provided timeout has passed.
|
||||
*/
|
||||
isExpired() {
|
||||
return (this.expirationTime !== undefined &&
|
||||
this.expirationTime < Math.round(Date.now() / 1000));
|
||||
}
|
||||
}
|
||||
exports.ExecutableResponse = ExecutableResponse;
|
||||
/**
|
||||
* An error thrown by the ExecutableResponse class.
|
||||
*/
|
||||
class ExecutableResponseError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
exports.ExecutableResponseError = ExecutableResponseError;
|
||||
/**
|
||||
* An error thrown when the 'version' field in an executable response is missing or invalid.
|
||||
*/
|
||||
class InvalidVersionFieldError extends ExecutableResponseError {
|
||||
}
|
||||
exports.InvalidVersionFieldError = InvalidVersionFieldError;
|
||||
/**
|
||||
* An error thrown when the 'success' field in an executable response is missing or invalid.
|
||||
*/
|
||||
class InvalidSuccessFieldError extends ExecutableResponseError {
|
||||
}
|
||||
exports.InvalidSuccessFieldError = InvalidSuccessFieldError;
|
||||
/**
|
||||
* An error thrown when the 'expiration_time' field in an executable response is missing or invalid.
|
||||
*/
|
||||
class InvalidExpirationTimeFieldError extends ExecutableResponseError {
|
||||
}
|
||||
exports.InvalidExpirationTimeFieldError = InvalidExpirationTimeFieldError;
|
||||
/**
|
||||
* An error thrown when the 'token_type' field in an executable response is missing or invalid.
|
||||
*/
|
||||
class InvalidTokenTypeFieldError extends ExecutableResponseError {
|
||||
}
|
||||
exports.InvalidTokenTypeFieldError = InvalidTokenTypeFieldError;
|
||||
/**
|
||||
* An error thrown when the 'code' field in an executable response is missing or invalid.
|
||||
*/
|
||||
class InvalidCodeFieldError extends ExecutableResponseError {
|
||||
}
|
||||
exports.InvalidCodeFieldError = InvalidCodeFieldError;
|
||||
/**
|
||||
* An error thrown when the 'message' field in an executable response is missing or invalid.
|
||||
*/
|
||||
class InvalidMessageFieldError extends ExecutableResponseError {
|
||||
}
|
||||
exports.InvalidMessageFieldError = InvalidMessageFieldError;
|
||||
/**
|
||||
* An error thrown when the subject token in an executable response is missing or invalid.
|
||||
*/
|
||||
class InvalidSubjectTokenError extends ExecutableResponseError {
|
||||
}
|
||||
exports.InvalidSubjectTokenError = InvalidSubjectTokenError;
|
||||
//# sourceMappingURL=executable-response.js.map
|
||||
72
node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.d.ts
generated
vendored
Normal file
72
node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.d.ts
generated
vendored
Normal file
@@ -0,0 +1,72 @@
|
||||
import { AuthClient, BodyResponseCallback } from './authclient';
|
||||
import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios';
|
||||
import { Credentials } from './credentials';
|
||||
import { SharedExternalAccountClientOptions } from './baseexternalclient';
|
||||
/**
|
||||
* The credentials JSON file type for external account authorized user clients.
|
||||
*/
|
||||
export declare const EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = "external_account_authorized_user";
|
||||
/**
|
||||
* External Account Authorized User Credentials JSON interface.
|
||||
*/
|
||||
export interface ExternalAccountAuthorizedUserClientOptions extends SharedExternalAccountClientOptions {
|
||||
type: typeof EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE;
|
||||
client_id: string;
|
||||
client_secret: string;
|
||||
refresh_token: string;
|
||||
token_info_url: string;
|
||||
revoke_url?: string;
|
||||
}
|
||||
/**
|
||||
* Internal interface for tracking the access token expiration time.
|
||||
*/
|
||||
interface CredentialsWithResponse extends Credentials {
|
||||
res?: GaxiosResponse | null;
|
||||
}
|
||||
/**
|
||||
* External Account Authorized User Client. This is used for OAuth2 credentials
|
||||
* sourced using external identities through Workforce Identity Federation.
|
||||
* Obtaining the initial access and refresh token can be done through the
|
||||
* Google Cloud CLI.
|
||||
*/
|
||||
export declare class ExternalAccountAuthorizedUserClient extends AuthClient {
|
||||
private cachedAccessToken;
|
||||
private readonly externalAccountAuthorizedUserHandler;
|
||||
private refreshToken;
|
||||
/**
|
||||
* Instantiates an ExternalAccountAuthorizedUserClient instances using the
|
||||
* provided JSON object loaded from a credentials files.
|
||||
* An error is throws if the credential is not valid.
|
||||
* @param options The external account authorized user option object typically
|
||||
* from the external accoutn authorized user JSON credential file.
|
||||
*/
|
||||
constructor(options: ExternalAccountAuthorizedUserClientOptions);
|
||||
getAccessToken(): Promise<{
|
||||
token?: string | null;
|
||||
res?: GaxiosResponse | null;
|
||||
}>;
|
||||
getRequestHeaders(): Promise<Headers>;
|
||||
request<T>(opts: GaxiosOptions): GaxiosPromise<T>;
|
||||
request<T>(opts: GaxiosOptions, callback: BodyResponseCallback<T>): void;
|
||||
/**
|
||||
* Authenticates the provided HTTP request, processes it and resolves with the
|
||||
* returned response.
|
||||
* @param opts The HTTP request options.
|
||||
* @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure.
|
||||
* @return A promise that resolves with the successful response.
|
||||
*/
|
||||
protected requestAsync<T>(opts: GaxiosOptions, reAuthRetried?: boolean): Promise<GaxiosResponse<T>>;
|
||||
/**
|
||||
* Forces token refresh, even if unexpired tokens are currently cached.
|
||||
* @return A promise that resolves with the refreshed credential.
|
||||
*/
|
||||
protected refreshAccessTokenAsync(): Promise<CredentialsWithResponse>;
|
||||
/**
|
||||
* Returns whether the provided credentials are expired or not.
|
||||
* If there is no expiry time, assumes the token is not expired or expiring.
|
||||
* @param credentials The credentials to check for expiration.
|
||||
* @return Whether the credentials are expired or not.
|
||||
*/
|
||||
private isExpired;
|
||||
}
|
||||
export {};
|
||||
232
node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js
generated
vendored
Normal file
232
node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js
generated
vendored
Normal file
@@ -0,0 +1,232 @@
|
||||
"use strict";
|
||||
// Copyright 2023 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ExternalAccountAuthorizedUserClient = exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = void 0;
|
||||
const authclient_1 = require("./authclient");
|
||||
const oauth2common_1 = require("./oauth2common");
|
||||
const gaxios_1 = require("gaxios");
|
||||
const stream = require("stream");
|
||||
const baseexternalclient_1 = require("./baseexternalclient");
|
||||
/**
|
||||
* The credentials JSON file type for external account authorized user clients.
|
||||
*/
|
||||
exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = 'external_account_authorized_user';
|
||||
const DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/oauthtoken';
|
||||
/**
|
||||
* Handler for token refresh requests sent to the token_url endpoint for external
|
||||
* authorized user credentials.
|
||||
*/
|
||||
class ExternalAccountAuthorizedUserHandler extends oauth2common_1.OAuthClientAuthHandler {
|
||||
#tokenRefreshEndpoint;
|
||||
/**
|
||||
* Initializes an ExternalAccountAuthorizedUserHandler instance.
|
||||
* @param url The URL of the token refresh endpoint.
|
||||
* @param transporter The transporter to use for the refresh request.
|
||||
* @param clientAuthentication The client authentication credentials to use
|
||||
* for the refresh request.
|
||||
*/
|
||||
constructor(options) {
|
||||
super(options);
|
||||
this.#tokenRefreshEndpoint = options.tokenRefreshEndpoint;
|
||||
}
|
||||
/**
|
||||
* Requests a new access token from the token_url endpoint using the provided
|
||||
* refresh token.
|
||||
* @param refreshToken The refresh token to use to generate a new access token.
|
||||
* @param additionalHeaders Optional additional headers to pass along the
|
||||
* request.
|
||||
* @return A promise that resolves with the token refresh response containing
|
||||
* the requested access token and its expiration time.
|
||||
*/
|
||||
async refreshToken(refreshToken, headers) {
|
||||
const opts = {
|
||||
...ExternalAccountAuthorizedUserHandler.RETRY_CONFIG,
|
||||
url: this.#tokenRefreshEndpoint,
|
||||
method: 'POST',
|
||||
headers,
|
||||
data: new URLSearchParams({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: refreshToken,
|
||||
}),
|
||||
};
|
||||
authclient_1.AuthClient.setMethodName(opts, 'refreshToken');
|
||||
// Apply OAuth client authentication.
|
||||
this.applyClientAuthenticationOptions(opts);
|
||||
try {
|
||||
const response = await this.transporter.request(opts);
|
||||
// Successful response.
|
||||
const tokenRefreshResponse = response.data;
|
||||
tokenRefreshResponse.res = response;
|
||||
return tokenRefreshResponse;
|
||||
}
|
||||
catch (error) {
|
||||
// Translate error to OAuthError.
|
||||
if (error instanceof gaxios_1.GaxiosError && error.response) {
|
||||
throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data,
|
||||
// Preserve other fields from the original error.
|
||||
error);
|
||||
}
|
||||
// Request could fail before the server responds.
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* External Account Authorized User Client. This is used for OAuth2 credentials
|
||||
* sourced using external identities through Workforce Identity Federation.
|
||||
* Obtaining the initial access and refresh token can be done through the
|
||||
* Google Cloud CLI.
|
||||
*/
|
||||
class ExternalAccountAuthorizedUserClient extends authclient_1.AuthClient {
|
||||
cachedAccessToken;
|
||||
externalAccountAuthorizedUserHandler;
|
||||
refreshToken;
|
||||
/**
|
||||
* Instantiates an ExternalAccountAuthorizedUserClient instances using the
|
||||
* provided JSON object loaded from a credentials files.
|
||||
* An error is throws if the credential is not valid.
|
||||
* @param options The external account authorized user option object typically
|
||||
* from the external accoutn authorized user JSON credential file.
|
||||
*/
|
||||
constructor(options) {
|
||||
super(options);
|
||||
if (options.universe_domain) {
|
||||
this.universeDomain = options.universe_domain;
|
||||
}
|
||||
this.refreshToken = options.refresh_token;
|
||||
const clientAuthentication = {
|
||||
confidentialClientType: 'basic',
|
||||
clientId: options.client_id,
|
||||
clientSecret: options.client_secret,
|
||||
};
|
||||
this.externalAccountAuthorizedUserHandler =
|
||||
new ExternalAccountAuthorizedUserHandler({
|
||||
tokenRefreshEndpoint: options.token_url ??
|
||||
DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain),
|
||||
transporter: this.transporter,
|
||||
clientAuthentication,
|
||||
});
|
||||
this.cachedAccessToken = null;
|
||||
this.quotaProjectId = options.quota_project_id;
|
||||
// As threshold could be zero,
|
||||
// eagerRefreshThresholdMillis || EXPIRATION_TIME_OFFSET will override the
|
||||
// zero value.
|
||||
if (typeof options?.eagerRefreshThresholdMillis !== 'number') {
|
||||
this.eagerRefreshThresholdMillis = baseexternalclient_1.EXPIRATION_TIME_OFFSET;
|
||||
}
|
||||
else {
|
||||
this.eagerRefreshThresholdMillis = options
|
||||
.eagerRefreshThresholdMillis;
|
||||
}
|
||||
this.forceRefreshOnFailure = !!options?.forceRefreshOnFailure;
|
||||
}
|
||||
async getAccessToken() {
|
||||
// If cached access token is unavailable or expired, force refresh.
|
||||
if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) {
|
||||
await this.refreshAccessTokenAsync();
|
||||
}
|
||||
// Return GCP access token in GetAccessTokenResponse format.
|
||||
return {
|
||||
token: this.cachedAccessToken.access_token,
|
||||
res: this.cachedAccessToken.res,
|
||||
};
|
||||
}
|
||||
async getRequestHeaders() {
|
||||
const accessTokenResponse = await this.getAccessToken();
|
||||
const headers = new Headers({
|
||||
authorization: `Bearer ${accessTokenResponse.token}`,
|
||||
});
|
||||
return this.addSharedMetadataHeaders(headers);
|
||||
}
|
||||
request(opts, callback) {
|
||||
if (callback) {
|
||||
this.requestAsync(opts).then(r => callback(null, r), e => {
|
||||
return callback(e, e.response);
|
||||
});
|
||||
}
|
||||
else {
|
||||
return this.requestAsync(opts);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Authenticates the provided HTTP request, processes it and resolves with the
|
||||
* returned response.
|
||||
* @param opts The HTTP request options.
|
||||
* @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure.
|
||||
* @return A promise that resolves with the successful response.
|
||||
*/
|
||||
async requestAsync(opts, reAuthRetried = false) {
|
||||
let response;
|
||||
try {
|
||||
const requestHeaders = await this.getRequestHeaders();
|
||||
opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);
|
||||
this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);
|
||||
response = await this.transporter.request(opts);
|
||||
}
|
||||
catch (e) {
|
||||
const res = e.response;
|
||||
if (res) {
|
||||
const statusCode = res.status;
|
||||
// Retry the request for metadata if the following criteria are true:
|
||||
// - We haven't already retried. It only makes sense to retry once.
|
||||
// - The response was a 401 or a 403
|
||||
// - The request didn't send a readableStream
|
||||
// - forceRefreshOnFailure is true
|
||||
const isReadableStream = res.config.data instanceof stream.Readable;
|
||||
const isAuthErr = statusCode === 401 || statusCode === 403;
|
||||
if (!reAuthRetried &&
|
||||
isAuthErr &&
|
||||
!isReadableStream &&
|
||||
this.forceRefreshOnFailure) {
|
||||
await this.refreshAccessTokenAsync();
|
||||
return await this.requestAsync(opts, true);
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
return response;
|
||||
}
|
||||
/**
|
||||
* Forces token refresh, even if unexpired tokens are currently cached.
|
||||
* @return A promise that resolves with the refreshed credential.
|
||||
*/
|
||||
async refreshAccessTokenAsync() {
|
||||
// Refresh the access token using the refresh token.
|
||||
const refreshResponse = await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);
|
||||
this.cachedAccessToken = {
|
||||
access_token: refreshResponse.access_token,
|
||||
expiry_date: new Date().getTime() + refreshResponse.expires_in * 1000,
|
||||
res: refreshResponse.res,
|
||||
};
|
||||
if (refreshResponse.refresh_token !== undefined) {
|
||||
this.refreshToken = refreshResponse.refresh_token;
|
||||
}
|
||||
return this.cachedAccessToken;
|
||||
}
|
||||
/**
|
||||
* Returns whether the provided credentials are expired or not.
|
||||
* If there is no expiry time, assumes the token is not expired or expiring.
|
||||
* @param credentials The credentials to check for expiration.
|
||||
* @return Whether the credentials are expired or not.
|
||||
*/
|
||||
isExpired(credentials) {
|
||||
const now = new Date().getTime();
|
||||
return credentials.expiry_date
|
||||
? now >= credentials.expiry_date - this.eagerRefreshThresholdMillis
|
||||
: false;
|
||||
}
|
||||
}
|
||||
exports.ExternalAccountAuthorizedUserClient = ExternalAccountAuthorizedUserClient;
|
||||
//# sourceMappingURL=externalAccountAuthorizedUserClient.js.map
|
||||
29
node_modules/google-auth-library/build/src/auth/externalclient.d.ts
generated
vendored
Normal file
29
node_modules/google-auth-library/build/src/auth/externalclient.d.ts
generated
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
import { BaseExternalAccountClient } from './baseexternalclient';
|
||||
import { IdentityPoolClientOptions } from './identitypoolclient';
|
||||
import { AwsClientOptions } from './awsclient';
|
||||
import { PluggableAuthClientOptions } from './pluggable-auth-client';
|
||||
export type ExternalAccountClientOptions = IdentityPoolClientOptions | AwsClientOptions | PluggableAuthClientOptions;
|
||||
/**
|
||||
* Dummy class with no constructor. Developers are expected to use fromJSON.
|
||||
*/
|
||||
export declare class ExternalAccountClient {
|
||||
constructor();
|
||||
/**
|
||||
* This static method will instantiate the
|
||||
* corresponding type of external account credential depending on the
|
||||
* underlying credential source.
|
||||
*
|
||||
* **IMPORTANT**: This method does not validate the credential configuration.
|
||||
* A security risk occurs when a credential configuration configured with
|
||||
* malicious URLs is used. When the credential configuration is accepted from
|
||||
* an untrusted source, you should validate it before using it with this
|
||||
* method. For more details, see
|
||||
* https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
|
||||
*
|
||||
* @param options The external account options object typically loaded
|
||||
* from the external account JSON credential file.
|
||||
* @return A BaseExternalAccountClient instance or null if the options
|
||||
* provided do not correspond to an external account credential.
|
||||
*/
|
||||
static fromJSON(options: ExternalAccountClientOptions): BaseExternalAccountClient | null;
|
||||
}
|
||||
68
node_modules/google-auth-library/build/src/auth/externalclient.js
generated
vendored
Normal file
68
node_modules/google-auth-library/build/src/auth/externalclient.js
generated
vendored
Normal file
@@ -0,0 +1,68 @@
|
||||
"use strict";
|
||||
// Copyright 2021 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ExternalAccountClient = void 0;
|
||||
const baseexternalclient_1 = require("./baseexternalclient");
|
||||
const identitypoolclient_1 = require("./identitypoolclient");
|
||||
const awsclient_1 = require("./awsclient");
|
||||
const pluggable_auth_client_1 = require("./pluggable-auth-client");
|
||||
/**
|
||||
* Dummy class with no constructor. Developers are expected to use fromJSON.
|
||||
*/
|
||||
class ExternalAccountClient {
|
||||
constructor() {
|
||||
throw new Error('ExternalAccountClients should be initialized via: ' +
|
||||
'ExternalAccountClient.fromJSON(), ' +
|
||||
'directly via explicit constructors, eg. ' +
|
||||
'new AwsClient(options), new IdentityPoolClient(options), new' +
|
||||
'PluggableAuthClientOptions, or via ' +
|
||||
'new GoogleAuth(options).getClient()');
|
||||
}
|
||||
/**
|
||||
* This static method will instantiate the
|
||||
* corresponding type of external account credential depending on the
|
||||
* underlying credential source.
|
||||
*
|
||||
* **IMPORTANT**: This method does not validate the credential configuration.
|
||||
* A security risk occurs when a credential configuration configured with
|
||||
* malicious URLs is used. When the credential configuration is accepted from
|
||||
* an untrusted source, you should validate it before using it with this
|
||||
* method. For more details, see
|
||||
* https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
|
||||
*
|
||||
* @param options The external account options object typically loaded
|
||||
* from the external account JSON credential file.
|
||||
* @return A BaseExternalAccountClient instance or null if the options
|
||||
* provided do not correspond to an external account credential.
|
||||
*/
|
||||
static fromJSON(options) {
|
||||
if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {
|
||||
if (options.credential_source?.environment_id) {
|
||||
return new awsclient_1.AwsClient(options);
|
||||
}
|
||||
else if (options.credential_source?.executable) {
|
||||
return new pluggable_auth_client_1.PluggableAuthClient(options);
|
||||
}
|
||||
else {
|
||||
return new identitypoolclient_1.IdentityPoolClient(options);
|
||||
}
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.ExternalAccountClient = ExternalAccountClient;
|
||||
//# sourceMappingURL=externalclient.js.map
|
||||
41
node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.d.ts
generated
vendored
Normal file
41
node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.d.ts
generated
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
import { SubjectTokenFormatType, SubjectTokenSupplier } from './identitypoolclient';
|
||||
/**
|
||||
* Interface that defines options used to build a {@link FileSubjectTokenSupplier}
|
||||
*/
|
||||
export interface FileSubjectTokenSupplierOptions {
|
||||
/**
|
||||
* The file path where the external credential is located.
|
||||
*/
|
||||
filePath: string;
|
||||
/**
|
||||
* The token file or URL response type (JSON or text).
|
||||
*/
|
||||
formatType: SubjectTokenFormatType;
|
||||
/**
|
||||
* For JSON response types, this is the subject_token field name. For Azure,
|
||||
* this is access_token. For text response types, this is ignored.
|
||||
*/
|
||||
subjectTokenFieldName?: string;
|
||||
}
|
||||
/**
|
||||
* Internal subject token supplier implementation used when a file location
|
||||
* is configured in the credential configuration used to build an {@link IdentityPoolClient}
|
||||
*/
|
||||
export declare class FileSubjectTokenSupplier implements SubjectTokenSupplier {
|
||||
private readonly filePath;
|
||||
private readonly formatType;
|
||||
private readonly subjectTokenFieldName?;
|
||||
/**
|
||||
* Instantiates a new file based subject token supplier.
|
||||
* @param opts The file subject token supplier options to build the supplier
|
||||
* with.
|
||||
*/
|
||||
constructor(opts: FileSubjectTokenSupplierOptions);
|
||||
/**
|
||||
* Returns the subject token stored at the file specified in the constructor.
|
||||
* @param context {@link ExternalAccountSupplierContext} from the calling
|
||||
* {@link IdentityPoolClient}, contains the requested audience and subject
|
||||
* token type for the external account identity. Not used.
|
||||
*/
|
||||
getSubjectToken(): Promise<string>;
|
||||
}
|
||||
84
node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js
generated
vendored
Normal file
84
node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js
generated
vendored
Normal file
@@ -0,0 +1,84 @@
|
||||
"use strict";
|
||||
// Copyright 2024 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.FileSubjectTokenSupplier = void 0;
|
||||
const util_1 = require("util");
|
||||
const fs = require("fs");
|
||||
// fs.readfile is undefined in browser karma tests causing
|
||||
// `npm run browser-test` to fail as test.oauth2.ts imports this file via
|
||||
// src/index.ts.
|
||||
// Fallback to void function to avoid promisify throwing a TypeError.
|
||||
const readFile = (0, util_1.promisify)(fs.readFile ?? (() => { }));
|
||||
const realpath = (0, util_1.promisify)(fs.realpath ?? (() => { }));
|
||||
const lstat = (0, util_1.promisify)(fs.lstat ?? (() => { }));
|
||||
/**
|
||||
* Internal subject token supplier implementation used when a file location
|
||||
* is configured in the credential configuration used to build an {@link IdentityPoolClient}
|
||||
*/
|
||||
class FileSubjectTokenSupplier {
|
||||
filePath;
|
||||
formatType;
|
||||
subjectTokenFieldName;
|
||||
/**
|
||||
* Instantiates a new file based subject token supplier.
|
||||
* @param opts The file subject token supplier options to build the supplier
|
||||
* with.
|
||||
*/
|
||||
constructor(opts) {
|
||||
this.filePath = opts.filePath;
|
||||
this.formatType = opts.formatType;
|
||||
this.subjectTokenFieldName = opts.subjectTokenFieldName;
|
||||
}
|
||||
/**
|
||||
* Returns the subject token stored at the file specified in the constructor.
|
||||
* @param context {@link ExternalAccountSupplierContext} from the calling
|
||||
* {@link IdentityPoolClient}, contains the requested audience and subject
|
||||
* token type for the external account identity. Not used.
|
||||
*/
|
||||
async getSubjectToken() {
|
||||
// Make sure there is a file at the path. lstatSync will throw if there is
|
||||
// nothing there.
|
||||
let parsedFilePath = this.filePath;
|
||||
try {
|
||||
// Resolve path to actual file in case of symlink. Expect a thrown error
|
||||
// if not resolvable.
|
||||
parsedFilePath = await realpath(parsedFilePath);
|
||||
if (!(await lstat(parsedFilePath)).isFile()) {
|
||||
throw new Error();
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
if (err instanceof Error) {
|
||||
err.message = `The file at ${parsedFilePath} does not exist, or it is not a file. ${err.message}`;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
let subjectToken;
|
||||
const rawText = await readFile(parsedFilePath, { encoding: 'utf8' });
|
||||
if (this.formatType === 'text') {
|
||||
subjectToken = rawText;
|
||||
}
|
||||
else if (this.formatType === 'json' && this.subjectTokenFieldName) {
|
||||
const json = JSON.parse(rawText);
|
||||
subjectToken = json[this.subjectTokenFieldName];
|
||||
}
|
||||
if (!subjectToken) {
|
||||
throw new Error('Unable to parse the subject_token from the credential_source file');
|
||||
}
|
||||
return subjectToken;
|
||||
}
|
||||
}
|
||||
exports.FileSubjectTokenSupplier = FileSubjectTokenSupplier;
|
||||
//# sourceMappingURL=filesubjecttokensupplier.js.map
|
||||
527
node_modules/google-auth-library/build/src/auth/googleauth.d.ts
generated
vendored
Normal file
527
node_modules/google-auth-library/build/src/auth/googleauth.d.ts
generated
vendored
Normal file
@@ -0,0 +1,527 @@
|
||||
import { GaxiosOptions, GaxiosResponse } from 'gaxios';
|
||||
import * as stream from 'stream';
|
||||
import { CredentialBody, ImpersonatedJWTInput, JWTInput } from './credentials';
|
||||
import { IdTokenClient } from './idtokenclient';
|
||||
import { GCPEnv } from './envDetect';
|
||||
import { JWT } from './jwtclient';
|
||||
import { UserRefreshClient } from './refreshclient';
|
||||
import { Impersonated } from './impersonated';
|
||||
import { ExternalAccountClientOptions } from './externalclient';
|
||||
import { BaseExternalAccountClient } from './baseexternalclient';
|
||||
import { AuthClient, AuthClientOptions } from './authclient';
|
||||
import { ExternalAccountAuthorizedUserClient } from './externalAccountAuthorizedUserClient';
|
||||
import { AnyAuthClient, AnyAuthClientConstructor } from '..';
|
||||
/**
|
||||
* Defines all types of explicit clients that are determined via ADC JSON
|
||||
* config file.
|
||||
*/
|
||||
export type JSONClient = JWT | UserRefreshClient | BaseExternalAccountClient | ExternalAccountAuthorizedUserClient | Impersonated;
|
||||
export interface ProjectIdCallback {
|
||||
(err?: Error | null, projectId?: string | null): void;
|
||||
}
|
||||
export interface CredentialCallback {
|
||||
(err: Error | null, result?: JSONClient): void;
|
||||
}
|
||||
export interface ADCCallback {
|
||||
(err: Error | null, credential?: AuthClient, projectId?: string | null): void;
|
||||
}
|
||||
export interface ADCResponse {
|
||||
credential: AuthClient;
|
||||
projectId: string | null;
|
||||
}
|
||||
export interface GoogleAuthOptions<T extends AuthClient = AnyAuthClient> {
|
||||
/**
|
||||
* An API key to use, optional. Cannot be used with {@link GoogleAuthOptions.credentials `credentials`}.
|
||||
*/
|
||||
apiKey?: string;
|
||||
/**
|
||||
* An `AuthClient` to use
|
||||
*/
|
||||
authClient?: T;
|
||||
/**
|
||||
* @deprecated This option is being deprecated because of a potential security risk.
|
||||
*
|
||||
* This option does not validate the credential configuration. The security
|
||||
* risk occurs when a credential configuration is accepted from a source that
|
||||
* is not under your control and used without validation on your side.
|
||||
*
|
||||
* The recommended way to provide credentials is to create an `auth` object
|
||||
* using `google-auth-library` and pass it to the client constructor.
|
||||
* This will ensure that unexpected credential types with potential for
|
||||
* malicious intent are not loaded unintentionally. For example:
|
||||
* ```
|
||||
* const {GoogleAuth} = require('google-auth-library');
|
||||
* const auth = new GoogleAuth({
|
||||
* // Scopes can be specified either as an array or as a single, space-delimited string.
|
||||
* scopes: 'https://www.googleapis.com/auth/cloud-platform'
|
||||
* });
|
||||
* const client = new MyClient({ auth: auth });
|
||||
* ```
|
||||
*
|
||||
* If you are loading your credential configuration from an untrusted source and have
|
||||
* not mitigated the risks (e.g. by validating the configuration yourself), make
|
||||
* these changes as soon as possible to prevent security risks to your environment.
|
||||
*
|
||||
* Regardless of the method used, it is always your responsibility to validate
|
||||
* configurations received from external sources.
|
||||
*
|
||||
* For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
|
||||
*/
|
||||
keyFilename?: string;
|
||||
/**
|
||||
* @deprecated This option is being deprecated because of a potential security risk.
|
||||
*
|
||||
* This option does not validate the credential configuration. The security
|
||||
* risk occurs when a credential configuration is accepted from a source that
|
||||
* is not under your control and used without validation on your side.
|
||||
*
|
||||
* The recommended way to provide credentials is to create an `auth` object
|
||||
* using `google-auth-library` and pass it to the client constructor.
|
||||
* This will ensure that unexpected credential types with potential for
|
||||
* malicious intent are not loaded unintentionally. For example:
|
||||
* ```
|
||||
* const {GoogleAuth} = require('google-auth-library');
|
||||
* const auth = new GoogleAuth({
|
||||
* // Scopes can be specified either as an array or as a single, space-delimited string.
|
||||
* scopes: 'https://www.googleapis.com/auth/cloud-platform'
|
||||
* });
|
||||
* const client = new MyClient({ auth: auth });
|
||||
* ```
|
||||
*
|
||||
* If you are loading your credential configuration from an untrusted source and have
|
||||
* not mitigated the risks (e.g. by validating the configuration yourself), make
|
||||
* these changes as soon as possible to prevent security risks to your environment.
|
||||
*
|
||||
* Regardless of the method used, it is always your responsibility to validate
|
||||
* configurations received from external sources.
|
||||
*
|
||||
* For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
|
||||
*/
|
||||
keyFile?: string;
|
||||
/**
|
||||
* @deprecated This option is being deprecated because of a potential security risk.
|
||||
*
|
||||
* This option does not validate the credential configuration. The security
|
||||
* risk occurs when a credential configuration is accepted from a source that
|
||||
* is not under your control and used without validation on your side.
|
||||
*
|
||||
* The recommended way to provide credentials is to create an `auth` object
|
||||
* using `google-auth-library` and pass it to the client constructor.
|
||||
* This will ensure that unexpected credential types with potential for
|
||||
* malicious intent are not loaded unintentionally. For example:
|
||||
* ```
|
||||
* const {GoogleAuth} = require('google-auth-library');
|
||||
* const auth = new GoogleAuth({
|
||||
* // Scopes can be specified either as an array or as a single, space-delimited string.
|
||||
* scopes: 'https://www.googleapis.com/auth/cloud-platform'
|
||||
* });
|
||||
* const client = new MyClient({ auth: auth });
|
||||
* ```
|
||||
*
|
||||
* If you are loading your credential configuration from an untrusted source and have
|
||||
* not mitigated the risks (e.g. by validating the configuration yourself), make
|
||||
* these changes as soon as possible to prevent security risks to your environment.
|
||||
*
|
||||
* Regardless of the method used, it is always your responsibility to validate
|
||||
* configurations received from external sources.
|
||||
*
|
||||
* For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
|
||||
*/
|
||||
credentials?: JWTInput | ExternalAccountClientOptions;
|
||||
/**
|
||||
* `AuthClientOptions` object passed to the constructor of the client
|
||||
*/
|
||||
clientOptions?: Extract<ConstructorParameters<AnyAuthClientConstructor>[0], AuthClientOptions>;
|
||||
/**
|
||||
* Required scopes for the desired API request
|
||||
*/
|
||||
scopes?: string | string[];
|
||||
/**
|
||||
* Your project ID.
|
||||
*/
|
||||
projectId?: string;
|
||||
/**
|
||||
* The default service domain for a given Cloud universe.
|
||||
*
|
||||
* This is an ergonomic equivalent to {@link clientOptions}'s `universeDomain`
|
||||
* property and will be set for all generated {@link AuthClient}s.
|
||||
*/
|
||||
universeDomain?: string;
|
||||
}
|
||||
export declare const GoogleAuthExceptionMessages: {
|
||||
readonly API_KEY_WITH_CREDENTIALS: "API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.";
|
||||
readonly NO_PROJECT_ID_FOUND: string;
|
||||
readonly NO_CREDENTIALS_FOUND: string;
|
||||
readonly NO_ADC_FOUND: "Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.";
|
||||
readonly NO_UNIVERSE_DOMAIN_FOUND: string;
|
||||
};
|
||||
export declare class GoogleAuth<T extends AuthClient = AuthClient> {
|
||||
#private;
|
||||
/**
|
||||
* Caches a value indicating whether the auth layer is running on Google
|
||||
* Compute Engine.
|
||||
* @private
|
||||
*/
|
||||
private checkIsGCE?;
|
||||
useJWTAccessWithScope?: boolean;
|
||||
defaultServicePath?: string;
|
||||
get isGCE(): boolean | undefined;
|
||||
private _findProjectIdPromise?;
|
||||
private _cachedProjectId?;
|
||||
jsonContent: JWTInput | ExternalAccountClientOptions | null;
|
||||
apiKey: string | null;
|
||||
cachedCredential: AnyAuthClient | T | null;
|
||||
/**
|
||||
* Scopes populated by the client library by default. We differentiate between
|
||||
* these and user defined scopes when deciding whether to use a self-signed JWT.
|
||||
*/
|
||||
defaultScopes?: string | string[];
|
||||
private keyFilename?;
|
||||
private scopes?;
|
||||
private clientOptions;
|
||||
/**
|
||||
* Configuration is resolved in the following order of precedence:
|
||||
* - {@link GoogleAuthOptions.credentials `credentials`}
|
||||
* - {@link GoogleAuthOptions.keyFilename `keyFilename`}
|
||||
* - {@link GoogleAuthOptions.keyFile `keyFile`}
|
||||
*
|
||||
* {@link GoogleAuthOptions.clientOptions `clientOptions`} are passed to the
|
||||
* {@link AuthClient `AuthClient`s}.
|
||||
*
|
||||
* @param opts
|
||||
*/
|
||||
constructor(opts?: GoogleAuthOptions<T>);
|
||||
setGapicJWTValues(client: JWT): void;
|
||||
/**
|
||||
* Obtains the default project ID for the application.
|
||||
*
|
||||
* Retrieves in the following order of precedence:
|
||||
* - The `projectId` provided in this object's construction
|
||||
* - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable
|
||||
* - GOOGLE_APPLICATION_CREDENTIALS JSON file
|
||||
* - Cloud SDK: `gcloud config config-helper --format json`
|
||||
* - GCE project ID from metadata server
|
||||
*/
|
||||
getProjectId(): Promise<string>;
|
||||
getProjectId(callback: ProjectIdCallback): void;
|
||||
/**
|
||||
* A temporary method for internal `getProjectId` usages where `null` is
|
||||
* acceptable. In a future major release, `getProjectId` should return `null`
|
||||
* (as the `Promise<string | null>` base signature describes) and this private
|
||||
* method should be removed.
|
||||
*
|
||||
* @returns Promise that resolves with project id (or `null`)
|
||||
*/
|
||||
private getProjectIdOptional;
|
||||
/**
|
||||
* A private method for finding and caching a projectId.
|
||||
*
|
||||
* Supports environments in order of precedence:
|
||||
* - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable
|
||||
* - GOOGLE_APPLICATION_CREDENTIALS JSON file
|
||||
* - Cloud SDK: `gcloud config config-helper --format json`
|
||||
* - GCE project ID from metadata server
|
||||
*
|
||||
* @returns projectId
|
||||
*/
|
||||
private findAndCacheProjectId;
|
||||
private getProjectIdAsync;
|
||||
/**
|
||||
* Retrieves a universe domain from the metadata server via
|
||||
* {@link gcpMetadata.universe}.
|
||||
*
|
||||
* @returns a universe domain
|
||||
*/
|
||||
getUniverseDomainFromMetadataServer(): Promise<string>;
|
||||
/**
|
||||
* Retrieves, caches, and returns the universe domain in the following order
|
||||
* of precedence:
|
||||
* - The universe domain in {@link GoogleAuth.clientOptions}
|
||||
* - An existing or ADC {@link AuthClient}'s universe domain
|
||||
* - {@link gcpMetadata.universe}, if {@link Compute} client
|
||||
*
|
||||
* @returns The universe domain
|
||||
*/
|
||||
getUniverseDomain(): Promise<string>;
|
||||
/**
|
||||
* @returns Any scopes (user-specified or default scopes specified by the
|
||||
* client library) that need to be set on the current Auth client.
|
||||
*/
|
||||
private getAnyScopes;
|
||||
/**
|
||||
* Obtains the default service-level credentials for the application.
|
||||
* @param callback Optional callback.
|
||||
* @returns Promise that resolves with the ADCResponse (if no callback was
|
||||
* passed).
|
||||
*/
|
||||
getApplicationDefault(): Promise<ADCResponse>;
|
||||
getApplicationDefault(callback: ADCCallback): void;
|
||||
getApplicationDefault(options: AuthClientOptions): Promise<ADCResponse>;
|
||||
getApplicationDefault(options: AuthClientOptions, callback: ADCCallback): void;
|
||||
private getApplicationDefaultAsync;
|
||||
/**
|
||||
* Determines whether the auth layer is running on Google Compute Engine.
|
||||
* Checks for GCP Residency, then fallback to checking if metadata server
|
||||
* is available.
|
||||
*
|
||||
* @returns A promise that resolves with the boolean.
|
||||
* @api private
|
||||
*/
|
||||
_checkIsGCE(): Promise<boolean>;
|
||||
/**
|
||||
* Attempts to load default credentials from the environment variable path..
|
||||
* @returns Promise that resolves with the OAuth2Client or null.
|
||||
* @api private
|
||||
*/
|
||||
_tryGetApplicationCredentialsFromEnvironmentVariable(options?: AuthClientOptions): Promise<JSONClient | null>;
|
||||
/**
|
||||
* Attempts to load default credentials from a well-known file location
|
||||
* @return Promise that resolves with the OAuth2Client or null.
|
||||
* @api private
|
||||
*/
|
||||
_tryGetApplicationCredentialsFromWellKnownFile(options?: AuthClientOptions): Promise<JSONClient | null>;
|
||||
/**
|
||||
* Attempts to load default credentials from a file at the given path..
|
||||
* @param filePath The path to the file to read.
|
||||
* @returns Promise that resolves with the OAuth2Client
|
||||
* @api private
|
||||
*/
|
||||
_getApplicationCredentialsFromFilePath(filePath: string, options?: AuthClientOptions): Promise<JSONClient>;
|
||||
/**
|
||||
* Create a credentials instance using a given impersonated input options.
|
||||
* @param json The impersonated input object.
|
||||
* @returns JWT or UserRefresh Client with data
|
||||
*/
|
||||
fromImpersonatedJSON(json: ImpersonatedJWTInput): Impersonated;
|
||||
/**
|
||||
* Create a credentials instance using the given input options.
|
||||
* This client is not cached.
|
||||
*
|
||||
* **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}.
|
||||
*
|
||||
* @deprecated This method is being deprecated because of a potential security risk.
|
||||
*
|
||||
* This method does not validate the credential configuration. The security
|
||||
* risk occurs when a credential configuration is accepted from a source that
|
||||
* is not under your control and used without validation on your side.
|
||||
*
|
||||
* If you know that you will be loading credential configurations of a
|
||||
* specific type, it is recommended to use a credential-type-specific
|
||||
* constructor. This will ensure that an unexpected credential type with
|
||||
* potential for malicious intent is not loaded unintentionally. You might
|
||||
* still have to do validation for certain credential types. Please follow
|
||||
* the recommendation for that method. For example, if you want to load only
|
||||
* service accounts, you can use the `JWT` constructor:
|
||||
* ```
|
||||
* const {JWT} = require('google-auth-library');
|
||||
* const keys = require('/path/to/key.json');
|
||||
* const client = new JWT({
|
||||
* email: keys.client_email,
|
||||
* key: keys.private_key,
|
||||
* scopes: ['https://www.googleapis.com/auth/cloud-platform'],
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* If you are loading your credential configuration from an untrusted source and have
|
||||
* not mitigated the risks (e.g. by validating the configuration yourself), make
|
||||
* these changes as soon as possible to prevent security risks to your environment.
|
||||
*
|
||||
* Regardless of the method used, it is always your responsibility to validate
|
||||
* configurations received from external sources.
|
||||
*
|
||||
* For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
|
||||
*
|
||||
* @param json The input object.
|
||||
* @param options The JWT or UserRefresh options for the client
|
||||
* @returns JWT or UserRefresh Client with data
|
||||
*/
|
||||
fromJSON(json: JWTInput | ImpersonatedJWTInput, options?: AuthClientOptions): JSONClient;
|
||||
/**
|
||||
* Return a JWT or UserRefreshClient from JavaScript object, caching both the
|
||||
* object used to instantiate and the client.
|
||||
* @param json The input object.
|
||||
* @param options The JWT or UserRefresh options for the client
|
||||
* @returns JWT or UserRefresh Client with data
|
||||
*/
|
||||
private _cacheClientFromJSON;
|
||||
/**
|
||||
* Create a credentials instance using the given input stream.
|
||||
*
|
||||
* @deprecated This method is being deprecated because of a potential security risk.
|
||||
*
|
||||
* This method does not validate the credential configuration. The security
|
||||
* risk occurs when a credential configuration is accepted from a source that
|
||||
* is not under your control and used without validation on your side.
|
||||
*
|
||||
* If you know that you will be loading credential configurations of a
|
||||
* specific type, it is recommended to read and parse the stream, and then
|
||||
* use a credential-type-specific constructor. This will ensure that an
|
||||
* unexpected credential type with potential for malicious intent is not
|
||||
* loaded unintentionally. You might still have to do validation for certain
|
||||
* credential types. Please follow the recommendation for that method. For
|
||||
* example, if you want to load only service accounts, you can do:
|
||||
* ```
|
||||
* const {JWT} = require('google-auth-library');
|
||||
* const fs = require('fs');
|
||||
*
|
||||
* const stream = fs.createReadStream('path/to/key.json');
|
||||
* const chunks = [];
|
||||
* stream.on('data', (chunk) => chunks.push(chunk));
|
||||
* stream.on('end', () => {
|
||||
* const keys = JSON.parse(Buffer.concat(chunks).toString());
|
||||
* const client = new JWT({
|
||||
* email: keys.client_email,
|
||||
* key: keys.private_key,
|
||||
* scopes: ['https://www.googleapis.com/auth/cloud-platform'],
|
||||
* });
|
||||
* // use client
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* If you are loading your credential configuration from an untrusted source and have
|
||||
* not mitigated the risks (e.g. by validating the configuration yourself), make
|
||||
* these changes as soon as possible to prevent security risks to your environment.
|
||||
*
|
||||
* Regardless of the method used, it is always your responsibility to validate
|
||||
* configurations received from external sources.
|
||||
*
|
||||
* For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
|
||||
* @param inputStream The input stream.
|
||||
* @param callback Optional callback.
|
||||
*/
|
||||
fromStream(inputStream: stream.Readable): Promise<JSONClient>;
|
||||
fromStream(inputStream: stream.Readable, callback: CredentialCallback): void;
|
||||
fromStream(inputStream: stream.Readable, options: AuthClientOptions): Promise<JSONClient>;
|
||||
fromStream(inputStream: stream.Readable, options: AuthClientOptions, callback: CredentialCallback): void;
|
||||
private fromStreamAsync;
|
||||
/**
|
||||
* Create a credentials instance using the given API key string.
|
||||
* The created client is not cached. In order to create and cache it use the {@link GoogleAuth.getClient `getClient`} method after first providing an {@link GoogleAuth.apiKey `apiKey`}.
|
||||
*
|
||||
* @param apiKey The API key string
|
||||
* @param options An optional options object.
|
||||
* @returns A JWT loaded from the key
|
||||
*/
|
||||
fromAPIKey(apiKey: string, options?: AuthClientOptions): JWT;
|
||||
/**
|
||||
* Determines whether the current operating system is Windows.
|
||||
* @api private
|
||||
*/
|
||||
private _isWindows;
|
||||
/**
|
||||
* Run the Google Cloud SDK command that prints the default project ID
|
||||
*/
|
||||
private getDefaultServiceProjectId;
|
||||
/**
|
||||
* Loads the project id from environment variables.
|
||||
* @api private
|
||||
*/
|
||||
private getProductionProjectId;
|
||||
/**
|
||||
* Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file.
|
||||
* @api private
|
||||
*/
|
||||
private getFileProjectId;
|
||||
/**
|
||||
* Gets the project ID from external account client if available.
|
||||
*/
|
||||
private getExternalAccountClientProjectId;
|
||||
/**
|
||||
* Gets the Compute Engine project ID if it can be inferred.
|
||||
*/
|
||||
private getGCEProjectId;
|
||||
/**
|
||||
* The callback function handles a credential object that contains the
|
||||
* client_email and private_key (if exists).
|
||||
* getCredentials first checks if the client is using an external account and
|
||||
* uses the service account email in place of client_email.
|
||||
* If that doesn't exist, it checks for these values from the user JSON.
|
||||
* If the user JSON doesn't exist, and the environment is on GCE, it gets the
|
||||
* client_email from the cloud metadata server.
|
||||
* @param callback Callback that handles the credential object that contains
|
||||
* a client_email and optional private key, or the error.
|
||||
* returned
|
||||
*/
|
||||
getCredentials(): Promise<CredentialBody>;
|
||||
getCredentials(callback: (err: Error | null, credentials?: CredentialBody) => void): void;
|
||||
private getCredentialsAsync;
|
||||
/**
|
||||
* Automatically obtain an {@link AuthClient `AuthClient`} based on the
|
||||
* provided configuration. If no options were passed, use Application
|
||||
* Default Credentials.
|
||||
*/
|
||||
getClient(): Promise<AnyAuthClient | T>;
|
||||
/**
|
||||
* Creates a client which will fetch an ID token for authorization.
|
||||
* @param targetAudience the audience for the fetched ID token.
|
||||
* @returns IdTokenClient for making HTTP calls authenticated with ID tokens.
|
||||
*/
|
||||
getIdTokenClient(targetAudience: string): Promise<IdTokenClient>;
|
||||
/**
|
||||
* Automatically obtain application default credentials, and return
|
||||
* an access token for making requests.
|
||||
*/
|
||||
getAccessToken(): Promise<string | null | undefined>;
|
||||
/**
|
||||
* Obtain the HTTP headers that will provide authorization for a given
|
||||
* request.
|
||||
*/
|
||||
getRequestHeaders(url?: string | URL): Promise<Headers>;
|
||||
/**
|
||||
* Obtain credentials for a request, then attach the appropriate headers to
|
||||
* the request options.
|
||||
* @param opts Axios or Request options on which to attach the headers
|
||||
*/
|
||||
authorizeRequest(opts?: Pick<GaxiosOptions, 'url' | 'headers'>): Promise<Pick<GaxiosOptions, "headers" | "url">>;
|
||||
/**
|
||||
* A {@link fetch `fetch`} compliant API for {@link GoogleAuth}.
|
||||
*
|
||||
* @see {@link GoogleAuth.request} for the classic method.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* This is useful as a drop-in replacement for `fetch` API usage.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```ts
|
||||
* const auth = new GoogleAuth();
|
||||
* const fetchWithAuth: typeof fetch = (...args) => auth.fetch(...args);
|
||||
* await fetchWithAuth('https://example.com');
|
||||
* ```
|
||||
*
|
||||
* @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters
|
||||
* @returns the {@link GaxiosResponse} with Gaxios-added properties
|
||||
*/
|
||||
fetch<T>(...args: Parameters<AuthClient['fetch']>): Promise<GaxiosResponse<T>>;
|
||||
/**
|
||||
* Automatically obtain application default credentials, and make an
|
||||
* HTTP request using the given options.
|
||||
*
|
||||
* @see {@link GoogleAuth.fetch} for the modern method.
|
||||
*
|
||||
* @param opts Axios request options for the HTTP request.
|
||||
*/
|
||||
request<T>(opts: GaxiosOptions): Promise<GaxiosResponse<T>>;
|
||||
/**
|
||||
* Determine the compute environment in which the code is running.
|
||||
*/
|
||||
getEnv(): Promise<GCPEnv>;
|
||||
/**
|
||||
* Sign the given data with the current private key, or go out
|
||||
* to the IAM API to sign it.
|
||||
* @param data The data to be signed.
|
||||
* @param endpoint A custom endpoint to use.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* sign('data', 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/');
|
||||
* ```
|
||||
*/
|
||||
sign(data: string, endpoint?: string): Promise<string>;
|
||||
private signBlob;
|
||||
}
|
||||
export interface SignBlobResponse {
|
||||
keyId: string;
|
||||
signedBlob: string;
|
||||
}
|
||||
899
node_modules/google-auth-library/build/src/auth/googleauth.js
generated
vendored
Normal file
899
node_modules/google-auth-library/build/src/auth/googleauth.js
generated
vendored
Normal file
@@ -0,0 +1,899 @@
|
||||
"use strict";
|
||||
// Copyright 2019 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.GoogleAuth = exports.GoogleAuthExceptionMessages = void 0;
|
||||
const child_process_1 = require("child_process");
|
||||
const fs = require("fs");
|
||||
const gaxios_1 = require("gaxios");
|
||||
const gcpMetadata = require("gcp-metadata");
|
||||
const os = require("os");
|
||||
const path = require("path");
|
||||
const crypto_1 = require("../crypto/crypto");
|
||||
const computeclient_1 = require("./computeclient");
|
||||
const idtokenclient_1 = require("./idtokenclient");
|
||||
const envDetect_1 = require("./envDetect");
|
||||
const jwtclient_1 = require("./jwtclient");
|
||||
const refreshclient_1 = require("./refreshclient");
|
||||
const impersonated_1 = require("./impersonated");
|
||||
const externalclient_1 = require("./externalclient");
|
||||
const baseexternalclient_1 = require("./baseexternalclient");
|
||||
const authclient_1 = require("./authclient");
|
||||
const externalAccountAuthorizedUserClient_1 = require("./externalAccountAuthorizedUserClient");
|
||||
const util_1 = require("../util");
|
||||
exports.GoogleAuthExceptionMessages = {
|
||||
API_KEY_WITH_CREDENTIALS: 'API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.',
|
||||
NO_PROJECT_ID_FOUND: 'Unable to detect a Project Id in the current environment. \n' +
|
||||
'To learn more about authentication and Google APIs, visit: \n' +
|
||||
'https://cloud.google.com/docs/authentication/getting-started',
|
||||
NO_CREDENTIALS_FOUND: 'Unable to find credentials in current environment. \n' +
|
||||
'To learn more about authentication and Google APIs, visit: \n' +
|
||||
'https://cloud.google.com/docs/authentication/getting-started',
|
||||
NO_ADC_FOUND: 'Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.',
|
||||
NO_UNIVERSE_DOMAIN_FOUND: 'Unable to detect a Universe Domain in the current environment.\n' +
|
||||
'To learn more about Universe Domain retrieval, visit: \n' +
|
||||
'https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys',
|
||||
};
|
||||
class GoogleAuth {
|
||||
/**
|
||||
* Caches a value indicating whether the auth layer is running on Google
|
||||
* Compute Engine.
|
||||
* @private
|
||||
*/
|
||||
checkIsGCE = undefined;
|
||||
useJWTAccessWithScope;
|
||||
defaultServicePath;
|
||||
// Note: this properly is only public to satisfy unit tests.
|
||||
// https://github.com/Microsoft/TypeScript/issues/5228
|
||||
get isGCE() {
|
||||
return this.checkIsGCE;
|
||||
}
|
||||
_findProjectIdPromise;
|
||||
_cachedProjectId;
|
||||
// To save the contents of the JSON credential file
|
||||
jsonContent = null;
|
||||
apiKey;
|
||||
cachedCredential = null;
|
||||
/**
|
||||
* A pending {@link AuthClient}. Used for concurrent {@link GoogleAuth.getClient} calls.
|
||||
*/
|
||||
#pendingAuthClient = null;
|
||||
/**
|
||||
* Scopes populated by the client library by default. We differentiate between
|
||||
* these and user defined scopes when deciding whether to use a self-signed JWT.
|
||||
*/
|
||||
defaultScopes;
|
||||
keyFilename;
|
||||
scopes;
|
||||
clientOptions = {};
|
||||
/**
|
||||
* Configuration is resolved in the following order of precedence:
|
||||
* - {@link GoogleAuthOptions.credentials `credentials`}
|
||||
* - {@link GoogleAuthOptions.keyFilename `keyFilename`}
|
||||
* - {@link GoogleAuthOptions.keyFile `keyFile`}
|
||||
*
|
||||
* {@link GoogleAuthOptions.clientOptions `clientOptions`} are passed to the
|
||||
* {@link AuthClient `AuthClient`s}.
|
||||
*
|
||||
* @param opts
|
||||
*/
|
||||
constructor(opts = {}) {
|
||||
this._cachedProjectId = opts.projectId || null;
|
||||
this.cachedCredential = opts.authClient || null;
|
||||
this.keyFilename = opts.keyFilename || opts.keyFile;
|
||||
this.scopes = opts.scopes;
|
||||
this.clientOptions = opts.clientOptions || {};
|
||||
this.jsonContent = opts.credentials || null;
|
||||
this.apiKey = opts.apiKey || this.clientOptions.apiKey || null;
|
||||
// Cannot use both API Key + Credentials
|
||||
if (this.apiKey && (this.jsonContent || this.clientOptions.credentials)) {
|
||||
throw new RangeError(exports.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);
|
||||
}
|
||||
if (opts.universeDomain) {
|
||||
this.clientOptions.universeDomain = opts.universeDomain;
|
||||
}
|
||||
}
|
||||
// GAPIC client libraries should always use self-signed JWTs. The following
|
||||
// variables are set on the JWT client in order to indicate the type of library,
|
||||
// and sign the JWT with the correct audience and scopes (if not supplied).
|
||||
setGapicJWTValues(client) {
|
||||
client.defaultServicePath = this.defaultServicePath;
|
||||
client.useJWTAccessWithScope = this.useJWTAccessWithScope;
|
||||
client.defaultScopes = this.defaultScopes;
|
||||
}
|
||||
getProjectId(callback) {
|
||||
if (callback) {
|
||||
this.getProjectIdAsync().then(r => callback(null, r), callback);
|
||||
}
|
||||
else {
|
||||
return this.getProjectIdAsync();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* A temporary method for internal `getProjectId` usages where `null` is
|
||||
* acceptable. In a future major release, `getProjectId` should return `null`
|
||||
* (as the `Promise<string | null>` base signature describes) and this private
|
||||
* method should be removed.
|
||||
*
|
||||
* @returns Promise that resolves with project id (or `null`)
|
||||
*/
|
||||
async getProjectIdOptional() {
|
||||
try {
|
||||
return await this.getProjectId();
|
||||
}
|
||||
catch (e) {
|
||||
if (e instanceof Error &&
|
||||
e.message === exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) {
|
||||
return null;
|
||||
}
|
||||
else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* A private method for finding and caching a projectId.
|
||||
*
|
||||
* Supports environments in order of precedence:
|
||||
* - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable
|
||||
* - GOOGLE_APPLICATION_CREDENTIALS JSON file
|
||||
* - Cloud SDK: `gcloud config config-helper --format json`
|
||||
* - GCE project ID from metadata server
|
||||
*
|
||||
* @returns projectId
|
||||
*/
|
||||
async findAndCacheProjectId() {
|
||||
let projectId = null;
|
||||
projectId ||= await this.getProductionProjectId();
|
||||
projectId ||= await this.getFileProjectId();
|
||||
projectId ||= await this.getDefaultServiceProjectId();
|
||||
projectId ||= await this.getGCEProjectId();
|
||||
projectId ||= await this.getExternalAccountClientProjectId();
|
||||
if (projectId) {
|
||||
this._cachedProjectId = projectId;
|
||||
return projectId;
|
||||
}
|
||||
else {
|
||||
throw new Error(exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND);
|
||||
}
|
||||
}
|
||||
async getProjectIdAsync() {
|
||||
if (this._cachedProjectId) {
|
||||
return this._cachedProjectId;
|
||||
}
|
||||
if (!this._findProjectIdPromise) {
|
||||
this._findProjectIdPromise = this.findAndCacheProjectId();
|
||||
}
|
||||
return this._findProjectIdPromise;
|
||||
}
|
||||
/**
|
||||
* Retrieves a universe domain from the metadata server via
|
||||
* {@link gcpMetadata.universe}.
|
||||
*
|
||||
* @returns a universe domain
|
||||
*/
|
||||
async getUniverseDomainFromMetadataServer() {
|
||||
let universeDomain;
|
||||
try {
|
||||
universeDomain = await gcpMetadata.universe('universe-domain');
|
||||
universeDomain ||= authclient_1.DEFAULT_UNIVERSE;
|
||||
}
|
||||
catch (e) {
|
||||
if (e && e?.response?.status === 404) {
|
||||
universeDomain = authclient_1.DEFAULT_UNIVERSE;
|
||||
}
|
||||
else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
return universeDomain;
|
||||
}
|
||||
/**
|
||||
* Retrieves, caches, and returns the universe domain in the following order
|
||||
* of precedence:
|
||||
* - The universe domain in {@link GoogleAuth.clientOptions}
|
||||
* - An existing or ADC {@link AuthClient}'s universe domain
|
||||
* - {@link gcpMetadata.universe}, if {@link Compute} client
|
||||
*
|
||||
* @returns The universe domain
|
||||
*/
|
||||
async getUniverseDomain() {
|
||||
let universeDomain = (0, util_1.originalOrCamelOptions)(this.clientOptions).get('universe_domain');
|
||||
try {
|
||||
universeDomain ??= (await this.getClient()).universeDomain;
|
||||
}
|
||||
catch {
|
||||
// client or ADC is not available
|
||||
universeDomain ??= authclient_1.DEFAULT_UNIVERSE;
|
||||
}
|
||||
return universeDomain;
|
||||
}
|
||||
/**
|
||||
* @returns Any scopes (user-specified or default scopes specified by the
|
||||
* client library) that need to be set on the current Auth client.
|
||||
*/
|
||||
getAnyScopes() {
|
||||
return this.scopes || this.defaultScopes;
|
||||
}
|
||||
getApplicationDefault(optionsOrCallback = {}, callback) {
|
||||
let options;
|
||||
if (typeof optionsOrCallback === 'function') {
|
||||
callback = optionsOrCallback;
|
||||
}
|
||||
else {
|
||||
options = optionsOrCallback;
|
||||
}
|
||||
if (callback) {
|
||||
this.getApplicationDefaultAsync(options).then(r => callback(null, r.credential, r.projectId), callback);
|
||||
}
|
||||
else {
|
||||
return this.getApplicationDefaultAsync(options);
|
||||
}
|
||||
}
|
||||
async getApplicationDefaultAsync(options = {}) {
|
||||
// If we've already got a cached credential, return it.
|
||||
// This will also preserve one's configured quota project, in case they
|
||||
// set one directly on the credential previously.
|
||||
if (this.cachedCredential) {
|
||||
// cache, while preserving existing quota project preferences
|
||||
return await this.#prepareAndCacheClient(this.cachedCredential, null);
|
||||
}
|
||||
let credential;
|
||||
// Check for the existence of a local environment variable pointing to the
|
||||
// location of the credential file. This is typically used in local
|
||||
// developer scenarios.
|
||||
credential =
|
||||
await this._tryGetApplicationCredentialsFromEnvironmentVariable(options);
|
||||
if (credential) {
|
||||
if (credential instanceof jwtclient_1.JWT) {
|
||||
credential.scopes = this.scopes;
|
||||
}
|
||||
else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {
|
||||
credential.scopes = this.getAnyScopes();
|
||||
}
|
||||
return await this.#prepareAndCacheClient(credential);
|
||||
}
|
||||
// Look in the well-known credential file location.
|
||||
credential =
|
||||
await this._tryGetApplicationCredentialsFromWellKnownFile(options);
|
||||
if (credential) {
|
||||
if (credential instanceof jwtclient_1.JWT) {
|
||||
credential.scopes = this.scopes;
|
||||
}
|
||||
else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {
|
||||
credential.scopes = this.getAnyScopes();
|
||||
}
|
||||
return await this.#prepareAndCacheClient(credential);
|
||||
}
|
||||
// Determine if we're running on GCE.
|
||||
if (await this._checkIsGCE()) {
|
||||
options.scopes = this.getAnyScopes();
|
||||
return await this.#prepareAndCacheClient(new computeclient_1.Compute(options));
|
||||
}
|
||||
throw new Error(exports.GoogleAuthExceptionMessages.NO_ADC_FOUND);
|
||||
}
|
||||
async #prepareAndCacheClient(credential, quotaProjectIdOverride = process.env['GOOGLE_CLOUD_QUOTA_PROJECT'] || null) {
|
||||
const projectId = await this.getProjectIdOptional();
|
||||
if (quotaProjectIdOverride) {
|
||||
credential.quotaProjectId = quotaProjectIdOverride;
|
||||
}
|
||||
this.cachedCredential = credential;
|
||||
return { credential, projectId };
|
||||
}
|
||||
/**
|
||||
* Determines whether the auth layer is running on Google Compute Engine.
|
||||
* Checks for GCP Residency, then fallback to checking if metadata server
|
||||
* is available.
|
||||
*
|
||||
* @returns A promise that resolves with the boolean.
|
||||
* @api private
|
||||
*/
|
||||
async _checkIsGCE() {
|
||||
if (this.checkIsGCE === undefined) {
|
||||
this.checkIsGCE =
|
||||
gcpMetadata.getGCPResidency() || (await gcpMetadata.isAvailable());
|
||||
}
|
||||
return this.checkIsGCE;
|
||||
}
|
||||
/**
|
||||
* Attempts to load default credentials from the environment variable path..
|
||||
* @returns Promise that resolves with the OAuth2Client or null.
|
||||
* @api private
|
||||
*/
|
||||
async _tryGetApplicationCredentialsFromEnvironmentVariable(options) {
|
||||
const credentialsPath = process.env['GOOGLE_APPLICATION_CREDENTIALS'] ||
|
||||
process.env['google_application_credentials'];
|
||||
if (!credentialsPath || credentialsPath.length === 0) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return this._getApplicationCredentialsFromFilePath(credentialsPath, options);
|
||||
}
|
||||
catch (e) {
|
||||
if (e instanceof Error) {
|
||||
e.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Attempts to load default credentials from a well-known file location
|
||||
* @return Promise that resolves with the OAuth2Client or null.
|
||||
* @api private
|
||||
*/
|
||||
async _tryGetApplicationCredentialsFromWellKnownFile(options) {
|
||||
// First, figure out the location of the file, depending upon the OS type.
|
||||
let location = null;
|
||||
if (this._isWindows()) {
|
||||
// Windows
|
||||
location = process.env['APPDATA'];
|
||||
}
|
||||
else {
|
||||
// Linux or Mac
|
||||
const home = process.env['HOME'];
|
||||
if (home) {
|
||||
location = path.join(home, '.config');
|
||||
}
|
||||
}
|
||||
// If we found the root path, expand it.
|
||||
if (location) {
|
||||
location = path.join(location, 'gcloud', 'application_default_credentials.json');
|
||||
if (!fs.existsSync(location)) {
|
||||
location = null;
|
||||
}
|
||||
}
|
||||
// The file does not exist.
|
||||
if (!location) {
|
||||
return null;
|
||||
}
|
||||
// The file seems to exist. Try to use it.
|
||||
const client = await this._getApplicationCredentialsFromFilePath(location, options);
|
||||
return client;
|
||||
}
|
||||
/**
|
||||
* Attempts to load default credentials from a file at the given path..
|
||||
* @param filePath The path to the file to read.
|
||||
* @returns Promise that resolves with the OAuth2Client
|
||||
* @api private
|
||||
*/
|
||||
async _getApplicationCredentialsFromFilePath(filePath, options = {}) {
|
||||
// Make sure the path looks like a string.
|
||||
if (!filePath || filePath.length === 0) {
|
||||
throw new Error('The file path is invalid.');
|
||||
}
|
||||
// Make sure there is a file at the path. lstatSync will throw if there is
|
||||
// nothing there.
|
||||
try {
|
||||
// Resolve path to actual file in case of symlink. Expect a thrown error
|
||||
// if not resolvable.
|
||||
filePath = fs.realpathSync(filePath);
|
||||
if (!fs.lstatSync(filePath).isFile()) {
|
||||
throw new Error();
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
if (err instanceof Error) {
|
||||
err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
// Now open a read stream on the file, and parse it.
|
||||
const readStream = fs.createReadStream(filePath);
|
||||
return this.fromStream(readStream, options);
|
||||
}
|
||||
/**
|
||||
* Create a credentials instance using a given impersonated input options.
|
||||
* @param json The impersonated input object.
|
||||
* @returns JWT or UserRefresh Client with data
|
||||
*/
|
||||
fromImpersonatedJSON(json) {
|
||||
if (!json) {
|
||||
throw new Error('Must pass in a JSON object containing an impersonated refresh token');
|
||||
}
|
||||
if (json.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {
|
||||
throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`);
|
||||
}
|
||||
if (!json.source_credentials) {
|
||||
throw new Error('The incoming JSON object does not contain a source_credentials field');
|
||||
}
|
||||
if (!json.service_account_impersonation_url) {
|
||||
throw new Error('The incoming JSON object does not contain a service_account_impersonation_url field');
|
||||
}
|
||||
const sourceClient = this.fromJSON(json.source_credentials);
|
||||
if (json.service_account_impersonation_url?.length > 256) {
|
||||
/**
|
||||
* Prevents DOS attacks.
|
||||
* @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/85}
|
||||
**/
|
||||
throw new RangeError(`Target principal is too long: ${json.service_account_impersonation_url}`);
|
||||
}
|
||||
// Extract service account from service_account_impersonation_url
|
||||
const targetPrincipal = /(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(json.service_account_impersonation_url)?.groups?.target;
|
||||
if (!targetPrincipal) {
|
||||
throw new RangeError(`Cannot extract target principal from ${json.service_account_impersonation_url}`);
|
||||
}
|
||||
const targetScopes = (this.scopes || json.scopes || this.defaultScopes) ?? [];
|
||||
return new impersonated_1.Impersonated({
|
||||
...json,
|
||||
sourceClient,
|
||||
targetPrincipal,
|
||||
targetScopes: Array.isArray(targetScopes) ? targetScopes : [targetScopes],
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Create a credentials instance using the given input options.
|
||||
* This client is not cached.
|
||||
*
|
||||
* **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}.
|
||||
*
|
||||
* @deprecated This method is being deprecated because of a potential security risk.
|
||||
*
|
||||
* This method does not validate the credential configuration. The security
|
||||
* risk occurs when a credential configuration is accepted from a source that
|
||||
* is not under your control and used without validation on your side.
|
||||
*
|
||||
* If you know that you will be loading credential configurations of a
|
||||
* specific type, it is recommended to use a credential-type-specific
|
||||
* constructor. This will ensure that an unexpected credential type with
|
||||
* potential for malicious intent is not loaded unintentionally. You might
|
||||
* still have to do validation for certain credential types. Please follow
|
||||
* the recommendation for that method. For example, if you want to load only
|
||||
* service accounts, you can use the `JWT` constructor:
|
||||
* ```
|
||||
* const {JWT} = require('google-auth-library');
|
||||
* const keys = require('/path/to/key.json');
|
||||
* const client = new JWT({
|
||||
* email: keys.client_email,
|
||||
* key: keys.private_key,
|
||||
* scopes: ['https://www.googleapis.com/auth/cloud-platform'],
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* If you are loading your credential configuration from an untrusted source and have
|
||||
* not mitigated the risks (e.g. by validating the configuration yourself), make
|
||||
* these changes as soon as possible to prevent security risks to your environment.
|
||||
*
|
||||
* Regardless of the method used, it is always your responsibility to validate
|
||||
* configurations received from external sources.
|
||||
*
|
||||
* For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
|
||||
*
|
||||
* @param json The input object.
|
||||
* @param options The JWT or UserRefresh options for the client
|
||||
* @returns JWT or UserRefresh Client with data
|
||||
*/
|
||||
fromJSON(json, options = {}) {
|
||||
let client;
|
||||
// user's preferred universe domain
|
||||
const preferredUniverseDomain = (0, util_1.originalOrCamelOptions)(options).get('universe_domain');
|
||||
if (json.type === refreshclient_1.USER_REFRESH_ACCOUNT_TYPE) {
|
||||
client = new refreshclient_1.UserRefreshClient(options);
|
||||
client.fromJSON(json);
|
||||
}
|
||||
else if (json.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {
|
||||
client = this.fromImpersonatedJSON(json);
|
||||
}
|
||||
else if (json.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {
|
||||
client = externalclient_1.ExternalAccountClient.fromJSON({
|
||||
...json,
|
||||
...options,
|
||||
});
|
||||
client.scopes = this.getAnyScopes();
|
||||
}
|
||||
else if (json.type === externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE) {
|
||||
client = new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient({
|
||||
...json,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
else {
|
||||
options.scopes = this.scopes;
|
||||
client = new jwtclient_1.JWT(options);
|
||||
this.setGapicJWTValues(client);
|
||||
client.fromJSON(json);
|
||||
}
|
||||
if (preferredUniverseDomain) {
|
||||
client.universeDomain = preferredUniverseDomain;
|
||||
}
|
||||
return client;
|
||||
}
|
||||
/**
|
||||
* Return a JWT or UserRefreshClient from JavaScript object, caching both the
|
||||
* object used to instantiate and the client.
|
||||
* @param json The input object.
|
||||
* @param options The JWT or UserRefresh options for the client
|
||||
* @returns JWT or UserRefresh Client with data
|
||||
*/
|
||||
_cacheClientFromJSON(json, options) {
|
||||
const client = this.fromJSON(json, options);
|
||||
// cache both raw data used to instantiate client and client itself.
|
||||
this.jsonContent = json;
|
||||
this.cachedCredential = client;
|
||||
return client;
|
||||
}
|
||||
fromStream(inputStream, optionsOrCallback = {}, callback) {
|
||||
let options = {};
|
||||
if (typeof optionsOrCallback === 'function') {
|
||||
callback = optionsOrCallback;
|
||||
}
|
||||
else {
|
||||
options = optionsOrCallback;
|
||||
}
|
||||
if (callback) {
|
||||
this.fromStreamAsync(inputStream, options).then(r => callback(null, r), callback);
|
||||
}
|
||||
else {
|
||||
return this.fromStreamAsync(inputStream, options);
|
||||
}
|
||||
}
|
||||
fromStreamAsync(inputStream, options) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!inputStream) {
|
||||
throw new Error('Must pass in a stream containing the Google auth settings.');
|
||||
}
|
||||
const chunks = [];
|
||||
inputStream
|
||||
.setEncoding('utf8')
|
||||
.on('error', reject)
|
||||
.on('data', chunk => chunks.push(chunk))
|
||||
.on('end', () => {
|
||||
try {
|
||||
try {
|
||||
const data = JSON.parse(chunks.join(''));
|
||||
const r = this._cacheClientFromJSON(data, options);
|
||||
return resolve(r);
|
||||
}
|
||||
catch (err) {
|
||||
// If we failed parsing this.keyFileName, assume that it
|
||||
// is a PEM or p12 certificate:
|
||||
if (!this.keyFilename)
|
||||
throw err;
|
||||
const client = new jwtclient_1.JWT({
|
||||
...this.clientOptions,
|
||||
keyFile: this.keyFilename,
|
||||
});
|
||||
this.cachedCredential = client;
|
||||
this.setGapicJWTValues(client);
|
||||
return resolve(client);
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
return reject(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Create a credentials instance using the given API key string.
|
||||
* The created client is not cached. In order to create and cache it use the {@link GoogleAuth.getClient `getClient`} method after first providing an {@link GoogleAuth.apiKey `apiKey`}.
|
||||
*
|
||||
* @param apiKey The API key string
|
||||
* @param options An optional options object.
|
||||
* @returns A JWT loaded from the key
|
||||
*/
|
||||
fromAPIKey(apiKey, options = {}) {
|
||||
return new jwtclient_1.JWT({ ...options, apiKey });
|
||||
}
|
||||
/**
|
||||
* Determines whether the current operating system is Windows.
|
||||
* @api private
|
||||
*/
|
||||
_isWindows() {
|
||||
const sys = os.platform();
|
||||
if (sys && sys.length >= 3) {
|
||||
if (sys.substring(0, 3).toLowerCase() === 'win') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Run the Google Cloud SDK command that prints the default project ID
|
||||
*/
|
||||
async getDefaultServiceProjectId() {
|
||||
return new Promise(resolve => {
|
||||
(0, child_process_1.exec)('gcloud config config-helper --format json', (err, stdout) => {
|
||||
if (!err && stdout) {
|
||||
try {
|
||||
const projectId = JSON.parse(stdout).configuration.properties.core.project;
|
||||
resolve(projectId);
|
||||
return;
|
||||
}
|
||||
catch (e) {
|
||||
// ignore errors
|
||||
}
|
||||
}
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Loads the project id from environment variables.
|
||||
* @api private
|
||||
*/
|
||||
getProductionProjectId() {
|
||||
return (process.env['GCLOUD_PROJECT'] ||
|
||||
process.env['GOOGLE_CLOUD_PROJECT'] ||
|
||||
process.env['gcloud_project'] ||
|
||||
process.env['google_cloud_project']);
|
||||
}
|
||||
/**
|
||||
* Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file.
|
||||
* @api private
|
||||
*/
|
||||
async getFileProjectId() {
|
||||
if (this.cachedCredential) {
|
||||
// Try to read the project ID from the cached credentials file
|
||||
return this.cachedCredential.projectId;
|
||||
}
|
||||
// Ensure the projectId is loaded from the keyFile if available.
|
||||
if (this.keyFilename) {
|
||||
const creds = await this.getClient();
|
||||
if (creds && creds.projectId) {
|
||||
return creds.projectId;
|
||||
}
|
||||
}
|
||||
// Try to load a credentials file and read its project ID
|
||||
const r = await this._tryGetApplicationCredentialsFromEnvironmentVariable();
|
||||
if (r) {
|
||||
return r.projectId;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Gets the project ID from external account client if available.
|
||||
*/
|
||||
async getExternalAccountClientProjectId() {
|
||||
if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {
|
||||
return null;
|
||||
}
|
||||
const creds = await this.getClient();
|
||||
// Do not suppress the underlying error, as the error could contain helpful
|
||||
// information for debugging and fixing. This is especially true for
|
||||
// external account creds as in order to get the project ID, the following
|
||||
// operations have to succeed:
|
||||
// 1. Valid credentials file should be supplied.
|
||||
// 2. Ability to retrieve access tokens from STS token exchange API.
|
||||
// 3. Ability to exchange for service account impersonated credentials (if
|
||||
// enabled).
|
||||
// 4. Ability to get project info using the access token from step 2 or 3.
|
||||
// Without surfacing the error, it is harder for developers to determine
|
||||
// which step went wrong.
|
||||
return await creds.getProjectId();
|
||||
}
|
||||
/**
|
||||
* Gets the Compute Engine project ID if it can be inferred.
|
||||
*/
|
||||
async getGCEProjectId() {
|
||||
try {
|
||||
const r = await gcpMetadata.project('project-id');
|
||||
return r;
|
||||
}
|
||||
catch (e) {
|
||||
// Ignore any errors
|
||||
return null;
|
||||
}
|
||||
}
|
||||
getCredentials(callback) {
|
||||
if (callback) {
|
||||
this.getCredentialsAsync().then(r => callback(null, r), callback);
|
||||
}
|
||||
else {
|
||||
return this.getCredentialsAsync();
|
||||
}
|
||||
}
|
||||
async getCredentialsAsync() {
|
||||
const client = await this.getClient();
|
||||
if (client instanceof impersonated_1.Impersonated) {
|
||||
return { client_email: client.getTargetPrincipal() };
|
||||
}
|
||||
if (client instanceof baseexternalclient_1.BaseExternalAccountClient) {
|
||||
const serviceAccountEmail = client.getServiceAccountEmail();
|
||||
if (serviceAccountEmail) {
|
||||
return {
|
||||
client_email: serviceAccountEmail,
|
||||
universe_domain: client.universeDomain,
|
||||
};
|
||||
}
|
||||
}
|
||||
if (this.jsonContent) {
|
||||
return {
|
||||
client_email: this.jsonContent.client_email,
|
||||
private_key: this.jsonContent.private_key,
|
||||
universe_domain: this.jsonContent.universe_domain,
|
||||
};
|
||||
}
|
||||
if (await this._checkIsGCE()) {
|
||||
const [client_email, universe_domain] = await Promise.all([
|
||||
gcpMetadata.instance('service-accounts/default/email'),
|
||||
this.getUniverseDomain(),
|
||||
]);
|
||||
return { client_email, universe_domain };
|
||||
}
|
||||
throw new Error(exports.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND);
|
||||
}
|
||||
/**
|
||||
* Automatically obtain an {@link AuthClient `AuthClient`} based on the
|
||||
* provided configuration. If no options were passed, use Application
|
||||
* Default Credentials.
|
||||
*/
|
||||
async getClient() {
|
||||
if (this.cachedCredential) {
|
||||
return this.cachedCredential;
|
||||
}
|
||||
// Use an existing auth client request, or cache a new one
|
||||
this.#pendingAuthClient =
|
||||
this.#pendingAuthClient || this.#determineClient();
|
||||
try {
|
||||
return await this.#pendingAuthClient;
|
||||
}
|
||||
finally {
|
||||
// reset the pending auth client in case it is changed later
|
||||
this.#pendingAuthClient = null;
|
||||
}
|
||||
}
|
||||
async #determineClient() {
|
||||
if (this.jsonContent) {
|
||||
return this._cacheClientFromJSON(this.jsonContent, this.clientOptions);
|
||||
}
|
||||
else if (this.keyFilename) {
|
||||
const filePath = path.resolve(this.keyFilename);
|
||||
const stream = fs.createReadStream(filePath);
|
||||
return await this.fromStreamAsync(stream, this.clientOptions);
|
||||
}
|
||||
else if (this.apiKey) {
|
||||
const client = await this.fromAPIKey(this.apiKey, this.clientOptions);
|
||||
client.scopes = this.scopes;
|
||||
const { credential } = await this.#prepareAndCacheClient(client);
|
||||
return credential;
|
||||
}
|
||||
else {
|
||||
const { credential } = await this.getApplicationDefaultAsync(this.clientOptions);
|
||||
return credential;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Creates a client which will fetch an ID token for authorization.
|
||||
* @param targetAudience the audience for the fetched ID token.
|
||||
* @returns IdTokenClient for making HTTP calls authenticated with ID tokens.
|
||||
*/
|
||||
async getIdTokenClient(targetAudience) {
|
||||
const client = await this.getClient();
|
||||
if (!('fetchIdToken' in client)) {
|
||||
throw new Error('Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.');
|
||||
}
|
||||
return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client });
|
||||
}
|
||||
/**
|
||||
* Automatically obtain application default credentials, and return
|
||||
* an access token for making requests.
|
||||
*/
|
||||
async getAccessToken() {
|
||||
const client = await this.getClient();
|
||||
return (await client.getAccessToken()).token;
|
||||
}
|
||||
/**
|
||||
* Obtain the HTTP headers that will provide authorization for a given
|
||||
* request.
|
||||
*/
|
||||
async getRequestHeaders(url) {
|
||||
const client = await this.getClient();
|
||||
return client.getRequestHeaders(url);
|
||||
}
|
||||
/**
|
||||
* Obtain credentials for a request, then attach the appropriate headers to
|
||||
* the request options.
|
||||
* @param opts Axios or Request options on which to attach the headers
|
||||
*/
|
||||
async authorizeRequest(opts = {}) {
|
||||
const url = opts.url;
|
||||
const client = await this.getClient();
|
||||
const headers = await client.getRequestHeaders(url);
|
||||
opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, headers);
|
||||
return opts;
|
||||
}
|
||||
/**
|
||||
* A {@link fetch `fetch`} compliant API for {@link GoogleAuth}.
|
||||
*
|
||||
* @see {@link GoogleAuth.request} for the classic method.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* This is useful as a drop-in replacement for `fetch` API usage.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```ts
|
||||
* const auth = new GoogleAuth();
|
||||
* const fetchWithAuth: typeof fetch = (...args) => auth.fetch(...args);
|
||||
* await fetchWithAuth('https://example.com');
|
||||
* ```
|
||||
*
|
||||
* @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters
|
||||
* @returns the {@link GaxiosResponse} with Gaxios-added properties
|
||||
*/
|
||||
async fetch(...args) {
|
||||
const client = await this.getClient();
|
||||
return client.fetch(...args);
|
||||
}
|
||||
/**
|
||||
* Automatically obtain application default credentials, and make an
|
||||
* HTTP request using the given options.
|
||||
*
|
||||
* @see {@link GoogleAuth.fetch} for the modern method.
|
||||
*
|
||||
* @param opts Axios request options for the HTTP request.
|
||||
*/
|
||||
async request(opts) {
|
||||
const client = await this.getClient();
|
||||
return client.request(opts);
|
||||
}
|
||||
/**
|
||||
* Determine the compute environment in which the code is running.
|
||||
*/
|
||||
getEnv() {
|
||||
return (0, envDetect_1.getEnv)();
|
||||
}
|
||||
/**
|
||||
* Sign the given data with the current private key, or go out
|
||||
* to the IAM API to sign it.
|
||||
* @param data The data to be signed.
|
||||
* @param endpoint A custom endpoint to use.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* sign('data', 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/');
|
||||
* ```
|
||||
*/
|
||||
async sign(data, endpoint) {
|
||||
const client = await this.getClient();
|
||||
const universe = await this.getUniverseDomain();
|
||||
endpoint =
|
||||
endpoint ||
|
||||
`https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`;
|
||||
if (client instanceof impersonated_1.Impersonated) {
|
||||
const signed = await client.sign(data);
|
||||
return signed.signedBlob;
|
||||
}
|
||||
const crypto = (0, crypto_1.createCrypto)();
|
||||
if (client instanceof jwtclient_1.JWT && client.key) {
|
||||
const sign = await crypto.sign(client.key, data);
|
||||
return sign;
|
||||
}
|
||||
const creds = await this.getCredentials();
|
||||
if (!creds.client_email) {
|
||||
throw new Error('Cannot sign data without `client_email`.');
|
||||
}
|
||||
return this.signBlob(crypto, creds.client_email, data, endpoint);
|
||||
}
|
||||
async signBlob(crypto, emailOrUniqueId, data, endpoint) {
|
||||
const url = new URL(endpoint + `${emailOrUniqueId}:signBlob`);
|
||||
const res = await this.request({
|
||||
method: 'POST',
|
||||
url: url.href,
|
||||
data: {
|
||||
payload: crypto.encodeBase64StringUtf8(data),
|
||||
},
|
||||
retry: true,
|
||||
retryConfig: {
|
||||
httpMethodsToRetry: ['POST'],
|
||||
},
|
||||
});
|
||||
return res.data.signedBlob;
|
||||
}
|
||||
}
|
||||
exports.GoogleAuth = GoogleAuth;
|
||||
//# sourceMappingURL=googleauth.js.map
|
||||
23
node_modules/google-auth-library/build/src/auth/iam.d.ts
generated
vendored
Normal file
23
node_modules/google-auth-library/build/src/auth/iam.d.ts
generated
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
export interface RequestMetadata {
|
||||
'x-goog-iam-authority-selector': string;
|
||||
'x-goog-iam-authorization-token': string;
|
||||
}
|
||||
export declare class IAMAuth {
|
||||
selector: string;
|
||||
token: string;
|
||||
/**
|
||||
* IAM credentials.
|
||||
*
|
||||
* @param selector the iam authority selector
|
||||
* @param token the token
|
||||
* @constructor
|
||||
*/
|
||||
constructor(selector: string, token: string);
|
||||
/**
|
||||
* Acquire the HTTP headers required to make an authenticated request.
|
||||
*/
|
||||
getRequestHeaders(): {
|
||||
'x-goog-iam-authority-selector': string;
|
||||
'x-goog-iam-authorization-token': string;
|
||||
};
|
||||
}
|
||||
44
node_modules/google-auth-library/build/src/auth/iam.js
generated
vendored
Normal file
44
node_modules/google-auth-library/build/src/auth/iam.js
generated
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
"use strict";
|
||||
// Copyright 2014 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.IAMAuth = void 0;
|
||||
class IAMAuth {
|
||||
selector;
|
||||
token;
|
||||
/**
|
||||
* IAM credentials.
|
||||
*
|
||||
* @param selector the iam authority selector
|
||||
* @param token the token
|
||||
* @constructor
|
||||
*/
|
||||
constructor(selector, token) {
|
||||
this.selector = selector;
|
||||
this.token = token;
|
||||
this.selector = selector;
|
||||
this.token = token;
|
||||
}
|
||||
/**
|
||||
* Acquire the HTTP headers required to make an authenticated request.
|
||||
*/
|
||||
getRequestHeaders() {
|
||||
return {
|
||||
'x-goog-iam-authority-selector': this.selector,
|
||||
'x-goog-iam-authorization-token': this.token,
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.IAMAuth = IAMAuth;
|
||||
//# sourceMappingURL=iam.js.map
|
||||
132
node_modules/google-auth-library/build/src/auth/identitypoolclient.d.ts
generated
vendored
Normal file
132
node_modules/google-auth-library/build/src/auth/identitypoolclient.d.ts
generated
vendored
Normal file
@@ -0,0 +1,132 @@
|
||||
import { BaseExternalAccountClient, BaseExternalAccountClientOptions, ExternalAccountSupplierContext } from './baseexternalclient';
|
||||
import { SnakeToCamelObject } from '../util';
|
||||
export type SubjectTokenFormatType = 'json' | 'text';
|
||||
export interface SubjectTokenJsonResponse {
|
||||
[key: string]: string;
|
||||
}
|
||||
/**
|
||||
* Supplier interface for subject tokens. This can be implemented to
|
||||
* return a subject token which can then be exchanged for a GCP token by an
|
||||
* {@link IdentityPoolClient}.
|
||||
*/
|
||||
export interface SubjectTokenSupplier {
|
||||
/**
|
||||
* Gets a valid subject token for the requested external account identity.
|
||||
* Note that these are not cached by the calling {@link IdentityPoolClient},
|
||||
* so caching should be including in the implementation.
|
||||
* @param context {@link ExternalAccountSupplierContext} from the calling
|
||||
* {@link IdentityPoolClient}, contains the requested audience and subject token type
|
||||
* for the external account identity as well as the transport from the
|
||||
* calling client to use for requests.
|
||||
* @return A promise that resolves with the requested subject token string.
|
||||
*/
|
||||
getSubjectToken: (context: ExternalAccountSupplierContext) => Promise<string>;
|
||||
}
|
||||
/**
|
||||
* Url-sourced/file-sourced credentials json interface.
|
||||
* This is used for K8s and Azure workloads.
|
||||
*/
|
||||
export interface IdentityPoolClientOptions extends BaseExternalAccountClientOptions {
|
||||
/**
|
||||
* Object containing options to retrieve identity pool credentials. A valid credential
|
||||
* source or a subject token supplier must be specified.
|
||||
*/
|
||||
credential_source?: {
|
||||
/**
|
||||
* The file location to read the subject token from. Either this, a URL
|
||||
* or a certificate location should be specified.
|
||||
*/
|
||||
file?: string;
|
||||
/**
|
||||
* The URL to call to retrieve the subject token. Either this, a file
|
||||
* location or a certificate location should be specified.
|
||||
*/
|
||||
url?: string;
|
||||
/**
|
||||
* Optional headers to send on the request to the specified URL.
|
||||
*/
|
||||
headers?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
/**
|
||||
* The format that the subject token is in the file or the URL response.
|
||||
* If not provided, will default to reading the text string directly.
|
||||
*/
|
||||
format?: {
|
||||
/**
|
||||
* The format type. Can either be 'text' or 'json'.
|
||||
*/
|
||||
type: SubjectTokenFormatType;
|
||||
/**
|
||||
* The field name containing the subject token value if the type is 'json'.
|
||||
*/
|
||||
subject_token_field_name?: string;
|
||||
};
|
||||
/**
|
||||
* The certificate location to call to retrieve the subject token. Either this, a file
|
||||
* location, or an url should be specified.
|
||||
* @example
|
||||
* File Format:
|
||||
* ```json
|
||||
* {
|
||||
* "cert_configs": {
|
||||
* "workload": {
|
||||
* "key_path": "$PATH_TO_LEAF_KEY",
|
||||
* "cert_path": "$PATH_TO_LEAF_CERT"
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
certificate?: {
|
||||
/**
|
||||
* Specify whether the certificate config should be used from the default location.
|
||||
* Either this or the certificate_config_location must be provided.
|
||||
* The certificate config file must be in the following JSON format:
|
||||
*/
|
||||
use_default_certificate_config?: boolean;
|
||||
/**
|
||||
* Location to fetch certificate config from in case default config is not to be used.
|
||||
* Either this or use_default_certificate_config=true should be provided.
|
||||
*/
|
||||
certificate_config_location?: string;
|
||||
/**
|
||||
* TrustChainPath specifies the path to a PEM-formatted file containing the X.509 certificate trust chain.
|
||||
* The file should contain any intermediate certificates needed to connect
|
||||
* the mTLS leaf certificate to a root certificate in the trust store.
|
||||
*/
|
||||
trust_chain_path?: string;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* The subject token supplier to call to retrieve the subject token to exchange
|
||||
* for a GCP access token. Either this or a valid credential source should
|
||||
* be specified.
|
||||
*/
|
||||
subject_token_supplier?: SubjectTokenSupplier;
|
||||
}
|
||||
/**
|
||||
* Defines the Url-sourced and file-sourced external account clients mainly
|
||||
* used for K8s and Azure workloads.
|
||||
*/
|
||||
export declare class IdentityPoolClient extends BaseExternalAccountClient {
|
||||
private readonly subjectTokenSupplier;
|
||||
/**
|
||||
* Instantiate an IdentityPoolClient instance using the provided JSON
|
||||
* object loaded from an external account credentials file.
|
||||
* An error is thrown if the credential is not a valid file-sourced or
|
||||
* url-sourced credential or a workforce pool user project is provided
|
||||
* with a non workforce audience.
|
||||
* @param options The external account options object typically loaded
|
||||
* from the external account JSON credential file. The camelCased options
|
||||
* are aliases for the snake_cased options.
|
||||
*/
|
||||
constructor(options: IdentityPoolClientOptions | SnakeToCamelObject<IdentityPoolClientOptions>);
|
||||
/**
|
||||
* Triggered when a external subject token is needed to be exchanged for a GCP
|
||||
* access token via GCP STS endpoint. Gets a subject token by calling
|
||||
* the configured {@link SubjectTokenSupplier}
|
||||
* @return A promise that resolves with the external subject token.
|
||||
*/
|
||||
retrieveSubjectToken(): Promise<string>;
|
||||
}
|
||||
131
node_modules/google-auth-library/build/src/auth/identitypoolclient.js
generated
vendored
Normal file
131
node_modules/google-auth-library/build/src/auth/identitypoolclient.js
generated
vendored
Normal file
@@ -0,0 +1,131 @@
|
||||
"use strict";
|
||||
// Copyright 2021 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.IdentityPoolClient = void 0;
|
||||
const baseexternalclient_1 = require("./baseexternalclient");
|
||||
const util_1 = require("../util");
|
||||
const filesubjecttokensupplier_1 = require("./filesubjecttokensupplier");
|
||||
const urlsubjecttokensupplier_1 = require("./urlsubjecttokensupplier");
|
||||
const certificatesubjecttokensupplier_1 = require("./certificatesubjecttokensupplier");
|
||||
const stscredentials_1 = require("./stscredentials");
|
||||
const gaxios_1 = require("gaxios");
|
||||
/**
|
||||
* Defines the Url-sourced and file-sourced external account clients mainly
|
||||
* used for K8s and Azure workloads.
|
||||
*/
|
||||
class IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient {
|
||||
subjectTokenSupplier;
|
||||
/**
|
||||
* Instantiate an IdentityPoolClient instance using the provided JSON
|
||||
* object loaded from an external account credentials file.
|
||||
* An error is thrown if the credential is not a valid file-sourced or
|
||||
* url-sourced credential or a workforce pool user project is provided
|
||||
* with a non workforce audience.
|
||||
* @param options The external account options object typically loaded
|
||||
* from the external account JSON credential file. The camelCased options
|
||||
* are aliases for the snake_cased options.
|
||||
*/
|
||||
constructor(options) {
|
||||
super(options);
|
||||
const opts = (0, util_1.originalOrCamelOptions)(options);
|
||||
const credentialSource = opts.get('credential_source');
|
||||
const subjectTokenSupplier = opts.get('subject_token_supplier');
|
||||
// Validate credential sourcing configuration.
|
||||
if (!credentialSource && !subjectTokenSupplier) {
|
||||
throw new Error('A credential source or subject token supplier must be specified.');
|
||||
}
|
||||
if (credentialSource && subjectTokenSupplier) {
|
||||
throw new Error('Only one of credential source or subject token supplier can be specified.');
|
||||
}
|
||||
if (subjectTokenSupplier) {
|
||||
this.subjectTokenSupplier = subjectTokenSupplier;
|
||||
this.credentialSourceType = 'programmatic';
|
||||
}
|
||||
else {
|
||||
const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource);
|
||||
const formatOpts = (0, util_1.originalOrCamelOptions)(credentialSourceOpts.get('format'));
|
||||
// Text is the default format type.
|
||||
const formatType = formatOpts.get('type') || 'text';
|
||||
const formatSubjectTokenFieldName = formatOpts.get('subject_token_field_name');
|
||||
if (formatType !== 'json' && formatType !== 'text') {
|
||||
throw new Error(`Invalid credential_source format "${formatType}"`);
|
||||
}
|
||||
if (formatType === 'json' && !formatSubjectTokenFieldName) {
|
||||
throw new Error('Missing subject_token_field_name for JSON credential_source format');
|
||||
}
|
||||
const file = credentialSourceOpts.get('file');
|
||||
const url = credentialSourceOpts.get('url');
|
||||
const certificate = credentialSourceOpts.get('certificate');
|
||||
const headers = credentialSourceOpts.get('headers');
|
||||
if ((file && url) || (url && certificate) || (file && certificate)) {
|
||||
throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');
|
||||
}
|
||||
else if (file) {
|
||||
this.credentialSourceType = 'file';
|
||||
this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({
|
||||
filePath: file,
|
||||
formatType: formatType,
|
||||
subjectTokenFieldName: formatSubjectTokenFieldName,
|
||||
});
|
||||
}
|
||||
else if (url) {
|
||||
this.credentialSourceType = 'url';
|
||||
this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({
|
||||
url: url,
|
||||
formatType: formatType,
|
||||
subjectTokenFieldName: formatSubjectTokenFieldName,
|
||||
headers: headers,
|
||||
additionalGaxiosOptions: IdentityPoolClient.RETRY_CONFIG,
|
||||
});
|
||||
}
|
||||
else if (certificate) {
|
||||
this.credentialSourceType = 'certificate';
|
||||
const certificateSubjecttokensupplier = new certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier({
|
||||
useDefaultCertificateConfig: certificate.use_default_certificate_config,
|
||||
certificateConfigLocation: certificate.certificate_config_location,
|
||||
trustChainPath: certificate.trust_chain_path,
|
||||
});
|
||||
this.subjectTokenSupplier = certificateSubjecttokensupplier;
|
||||
}
|
||||
else {
|
||||
throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Triggered when a external subject token is needed to be exchanged for a GCP
|
||||
* access token via GCP STS endpoint. Gets a subject token by calling
|
||||
* the configured {@link SubjectTokenSupplier}
|
||||
* @return A promise that resolves with the external subject token.
|
||||
*/
|
||||
async retrieveSubjectToken() {
|
||||
const subjectToken = await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);
|
||||
if (this.subjectTokenSupplier instanceof certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier) {
|
||||
const mtlsAgent = await this.subjectTokenSupplier.createMtlsHttpsAgent();
|
||||
this.stsCredential = new stscredentials_1.StsCredentials({
|
||||
tokenExchangeEndpoint: this.getTokenUrl(),
|
||||
clientAuthentication: this.clientAuth,
|
||||
transporter: new gaxios_1.Gaxios({ agent: mtlsAgent }),
|
||||
});
|
||||
this.transporter = new gaxios_1.Gaxios({
|
||||
...(this.transporter.defaults || {}),
|
||||
agent: mtlsAgent,
|
||||
});
|
||||
}
|
||||
return subjectToken;
|
||||
}
|
||||
}
|
||||
exports.IdentityPoolClient = IdentityPoolClient;
|
||||
//# sourceMappingURL=identitypoolclient.js.map
|
||||
27
node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts
generated
vendored
Normal file
27
node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts
generated
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
import { OAuth2Client, OAuth2ClientOptions, RequestMetadataResponse } from './oauth2client';
|
||||
export interface IdTokenOptions extends OAuth2ClientOptions {
|
||||
/**
|
||||
* The client to make the request to fetch an ID token.
|
||||
*/
|
||||
idTokenProvider: IdTokenProvider;
|
||||
/**
|
||||
* The audience to use when requesting an ID token.
|
||||
*/
|
||||
targetAudience: string;
|
||||
}
|
||||
export interface IdTokenProvider {
|
||||
fetchIdToken: (targetAudience: string) => Promise<string>;
|
||||
}
|
||||
export declare class IdTokenClient extends OAuth2Client {
|
||||
targetAudience: string;
|
||||
idTokenProvider: IdTokenProvider;
|
||||
/**
|
||||
* Google ID Token client
|
||||
*
|
||||
* Retrieve ID token from the metadata server.
|
||||
* See: https://cloud.google.com/docs/authentication/get-id-token#metadata-server
|
||||
*/
|
||||
constructor(options: IdTokenOptions);
|
||||
protected getRequestMetadataAsync(): Promise<RequestMetadataResponse>;
|
||||
private getIdTokenExpiryDate;
|
||||
}
|
||||
56
node_modules/google-auth-library/build/src/auth/idtokenclient.js
generated
vendored
Normal file
56
node_modules/google-auth-library/build/src/auth/idtokenclient.js
generated
vendored
Normal file
@@ -0,0 +1,56 @@
|
||||
"use strict";
|
||||
// Copyright 2020 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.IdTokenClient = void 0;
|
||||
const oauth2client_1 = require("./oauth2client");
|
||||
class IdTokenClient extends oauth2client_1.OAuth2Client {
|
||||
targetAudience;
|
||||
idTokenProvider;
|
||||
/**
|
||||
* Google ID Token client
|
||||
*
|
||||
* Retrieve ID token from the metadata server.
|
||||
* See: https://cloud.google.com/docs/authentication/get-id-token#metadata-server
|
||||
*/
|
||||
constructor(options) {
|
||||
super(options);
|
||||
this.targetAudience = options.targetAudience;
|
||||
this.idTokenProvider = options.idTokenProvider;
|
||||
}
|
||||
async getRequestMetadataAsync() {
|
||||
if (!this.credentials.id_token ||
|
||||
!this.credentials.expiry_date ||
|
||||
this.isTokenExpiring()) {
|
||||
const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience);
|
||||
this.credentials = {
|
||||
id_token: idToken,
|
||||
expiry_date: this.getIdTokenExpiryDate(idToken),
|
||||
};
|
||||
}
|
||||
const headers = new Headers({
|
||||
authorization: 'Bearer ' + this.credentials.id_token,
|
||||
});
|
||||
return { headers };
|
||||
}
|
||||
getIdTokenExpiryDate(idToken) {
|
||||
const payloadB64 = idToken.split('.')[1];
|
||||
if (payloadB64) {
|
||||
const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('ascii'));
|
||||
return payload.exp * 1000;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.IdTokenClient = IdTokenClient;
|
||||
//# sourceMappingURL=idtokenclient.js.map
|
||||
134
node_modules/google-auth-library/build/src/auth/impersonated.d.ts
generated
vendored
Normal file
134
node_modules/google-auth-library/build/src/auth/impersonated.d.ts
generated
vendored
Normal file
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* Copyright 2021 Google LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import { GetTokenResponse, OAuth2Client, OAuth2ClientOptions } from './oauth2client';
|
||||
import { AuthClient } from './authclient';
|
||||
import { IdTokenProvider } from './idtokenclient';
|
||||
import { SignBlobResponse } from './googleauth';
|
||||
export interface ImpersonatedOptions extends OAuth2ClientOptions {
|
||||
/**
|
||||
* Client used to perform exchange for impersonated client.
|
||||
*/
|
||||
sourceClient?: AuthClient;
|
||||
/**
|
||||
* The service account to impersonate.
|
||||
*/
|
||||
targetPrincipal?: string;
|
||||
/**
|
||||
* Scopes to request during the authorization grant.
|
||||
*/
|
||||
targetScopes?: string[];
|
||||
/**
|
||||
* The chained list of delegates required to grant the final access_token.
|
||||
*/
|
||||
delegates?: string[];
|
||||
/**
|
||||
* Number of seconds the delegated credential should be valid.
|
||||
*/
|
||||
lifetime?: number | 3600;
|
||||
/**
|
||||
* API endpoint to fetch token from.
|
||||
*/
|
||||
endpoint?: string;
|
||||
}
|
||||
export declare const IMPERSONATED_ACCOUNT_TYPE = "impersonated_service_account";
|
||||
export interface TokenResponse {
|
||||
accessToken: string;
|
||||
expireTime: string;
|
||||
}
|
||||
export interface FetchIdTokenOptions {
|
||||
/**
|
||||
* Include the service account email in the token.
|
||||
* If set to `true`, the token will contain `email` and `email_verified` claims.
|
||||
*/
|
||||
includeEmail: boolean;
|
||||
}
|
||||
export interface FetchIdTokenResponse {
|
||||
/** The OpenId Connect ID token. */
|
||||
token: string;
|
||||
}
|
||||
export declare class Impersonated extends OAuth2Client implements IdTokenProvider {
|
||||
private sourceClient;
|
||||
private targetPrincipal;
|
||||
private targetScopes;
|
||||
private delegates;
|
||||
private lifetime;
|
||||
private endpoint;
|
||||
/**
|
||||
* Impersonated service account credentials.
|
||||
*
|
||||
* Create a new access token by impersonating another service account.
|
||||
*
|
||||
* Impersonated Credentials allowing credentials issued to a user or
|
||||
* service account to impersonate another. The source project using
|
||||
* Impersonated Credentials must enable the "IAMCredentials" API.
|
||||
* Also, the target service account must grant the orginating principal
|
||||
* the "Service Account Token Creator" IAM role.
|
||||
*
|
||||
* **IMPORTANT**: This method does not validate the credential configuration.
|
||||
* A security risk occurs when a credential configuration configured with
|
||||
* malicious URLs is used. When the credential configuration is accepted from
|
||||
* an untrusted source, you should validate it before using it with this
|
||||
* method. For more details, see
|
||||
* https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
|
||||
*
|
||||
* @param {object} options - The configuration object.
|
||||
* @param {object} [options.sourceClient] the source credential used as to
|
||||
* acquire the impersonated credentials.
|
||||
* @param {string} [options.targetPrincipal] the service account to
|
||||
* impersonate.
|
||||
* @param {string[]} [options.delegates] the chained list of delegates
|
||||
* required to grant the final access_token. If set, the sequence of
|
||||
* identities must have "Service Account Token Creator" capability granted to
|
||||
* the preceding identity. For example, if set to [serviceAccountB,
|
||||
* serviceAccountC], the sourceCredential must have the Token Creator role on
|
||||
* serviceAccountB. serviceAccountB must have the Token Creator on
|
||||
* serviceAccountC. Finally, C must have Token Creator on target_principal.
|
||||
* If left unset, sourceCredential must have that role on targetPrincipal.
|
||||
* @param {string[]} [options.targetScopes] scopes to request during the
|
||||
* authorization grant.
|
||||
* @param {number} [options.lifetime] number of seconds the delegated
|
||||
* credential should be valid for up to 3600 seconds by default, or 43,200
|
||||
* seconds by extending the token's lifetime, see:
|
||||
* https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth
|
||||
* @param {string} [options.endpoint] api endpoint override.
|
||||
*/
|
||||
constructor(options?: ImpersonatedOptions);
|
||||
/**
|
||||
* Signs some bytes.
|
||||
*
|
||||
* {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob Reference Documentation}
|
||||
* @param blobToSign String to sign.
|
||||
*
|
||||
* @returns A {@link SignBlobResponse} denoting the keyID and signedBlob in base64 string
|
||||
*/
|
||||
sign(blobToSign: string): Promise<SignBlobResponse>;
|
||||
/** The service account email to be impersonated. */
|
||||
getTargetPrincipal(): string;
|
||||
/**
|
||||
* Refreshes the access token.
|
||||
*/
|
||||
protected refreshToken(): Promise<GetTokenResponse>;
|
||||
/**
|
||||
* Generates an OpenID Connect ID token for a service account.
|
||||
*
|
||||
* {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation}
|
||||
*
|
||||
* @param targetAudience the audience for the fetched ID token.
|
||||
* @param options the for the request
|
||||
* @return an OpenID Connect ID token
|
||||
*/
|
||||
fetchIdToken(targetAudience: string, options?: FetchIdTokenOptions): Promise<string>;
|
||||
}
|
||||
197
node_modules/google-auth-library/build/src/auth/impersonated.js
generated
vendored
Normal file
197
node_modules/google-auth-library/build/src/auth/impersonated.js
generated
vendored
Normal file
@@ -0,0 +1,197 @@
|
||||
"use strict";
|
||||
/**
|
||||
* Copyright 2021 Google LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Impersonated = exports.IMPERSONATED_ACCOUNT_TYPE = void 0;
|
||||
const oauth2client_1 = require("./oauth2client");
|
||||
const gaxios_1 = require("gaxios");
|
||||
const util_1 = require("../util");
|
||||
exports.IMPERSONATED_ACCOUNT_TYPE = 'impersonated_service_account';
|
||||
class Impersonated extends oauth2client_1.OAuth2Client {
|
||||
sourceClient;
|
||||
targetPrincipal;
|
||||
targetScopes;
|
||||
delegates;
|
||||
lifetime;
|
||||
endpoint;
|
||||
/**
|
||||
* Impersonated service account credentials.
|
||||
*
|
||||
* Create a new access token by impersonating another service account.
|
||||
*
|
||||
* Impersonated Credentials allowing credentials issued to a user or
|
||||
* service account to impersonate another. The source project using
|
||||
* Impersonated Credentials must enable the "IAMCredentials" API.
|
||||
* Also, the target service account must grant the orginating principal
|
||||
* the "Service Account Token Creator" IAM role.
|
||||
*
|
||||
* **IMPORTANT**: This method does not validate the credential configuration.
|
||||
* A security risk occurs when a credential configuration configured with
|
||||
* malicious URLs is used. When the credential configuration is accepted from
|
||||
* an untrusted source, you should validate it before using it with this
|
||||
* method. For more details, see
|
||||
* https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.
|
||||
*
|
||||
* @param {object} options - The configuration object.
|
||||
* @param {object} [options.sourceClient] the source credential used as to
|
||||
* acquire the impersonated credentials.
|
||||
* @param {string} [options.targetPrincipal] the service account to
|
||||
* impersonate.
|
||||
* @param {string[]} [options.delegates] the chained list of delegates
|
||||
* required to grant the final access_token. If set, the sequence of
|
||||
* identities must have "Service Account Token Creator" capability granted to
|
||||
* the preceding identity. For example, if set to [serviceAccountB,
|
||||
* serviceAccountC], the sourceCredential must have the Token Creator role on
|
||||
* serviceAccountB. serviceAccountB must have the Token Creator on
|
||||
* serviceAccountC. Finally, C must have Token Creator on target_principal.
|
||||
* If left unset, sourceCredential must have that role on targetPrincipal.
|
||||
* @param {string[]} [options.targetScopes] scopes to request during the
|
||||
* authorization grant.
|
||||
* @param {number} [options.lifetime] number of seconds the delegated
|
||||
* credential should be valid for up to 3600 seconds by default, or 43,200
|
||||
* seconds by extending the token's lifetime, see:
|
||||
* https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth
|
||||
* @param {string} [options.endpoint] api endpoint override.
|
||||
*/
|
||||
constructor(options = {}) {
|
||||
super(options);
|
||||
// Start with an expired refresh token, which will automatically be
|
||||
// refreshed before the first API call is made.
|
||||
this.credentials = {
|
||||
expiry_date: 1,
|
||||
refresh_token: 'impersonated-placeholder',
|
||||
};
|
||||
this.sourceClient = options.sourceClient ?? new oauth2client_1.OAuth2Client();
|
||||
this.targetPrincipal = options.targetPrincipal ?? '';
|
||||
this.delegates = options.delegates ?? [];
|
||||
this.targetScopes = options.targetScopes ?? [];
|
||||
this.lifetime = options.lifetime ?? 3600;
|
||||
const usingExplicitUniverseDomain = !!(0, util_1.originalOrCamelOptions)(options).get('universe_domain');
|
||||
if (!usingExplicitUniverseDomain) {
|
||||
// override the default universe with the source's universe
|
||||
this.universeDomain = this.sourceClient.universeDomain;
|
||||
}
|
||||
else if (this.sourceClient.universeDomain !== this.universeDomain) {
|
||||
// non-default universe and is not matching the source - this could be a credential leak
|
||||
throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);
|
||||
}
|
||||
this.endpoint =
|
||||
options.endpoint ?? `https://iamcredentials.${this.universeDomain}`;
|
||||
}
|
||||
/**
|
||||
* Signs some bytes.
|
||||
*
|
||||
* {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob Reference Documentation}
|
||||
* @param blobToSign String to sign.
|
||||
*
|
||||
* @returns A {@link SignBlobResponse} denoting the keyID and signedBlob in base64 string
|
||||
*/
|
||||
async sign(blobToSign) {
|
||||
await this.sourceClient.getAccessToken();
|
||||
const name = `projects/-/serviceAccounts/${this.targetPrincipal}`;
|
||||
const u = `${this.endpoint}/v1/${name}:signBlob`;
|
||||
const body = {
|
||||
delegates: this.delegates,
|
||||
payload: Buffer.from(blobToSign).toString('base64'),
|
||||
};
|
||||
const res = await this.sourceClient.request({
|
||||
...Impersonated.RETRY_CONFIG,
|
||||
url: u,
|
||||
data: body,
|
||||
method: 'POST',
|
||||
});
|
||||
return res.data;
|
||||
}
|
||||
/** The service account email to be impersonated. */
|
||||
getTargetPrincipal() {
|
||||
return this.targetPrincipal;
|
||||
}
|
||||
/**
|
||||
* Refreshes the access token.
|
||||
*/
|
||||
async refreshToken() {
|
||||
try {
|
||||
await this.sourceClient.getAccessToken();
|
||||
const name = 'projects/-/serviceAccounts/' + this.targetPrincipal;
|
||||
const u = `${this.endpoint}/v1/${name}:generateAccessToken`;
|
||||
const body = {
|
||||
delegates: this.delegates,
|
||||
scope: this.targetScopes,
|
||||
lifetime: this.lifetime + 's',
|
||||
};
|
||||
const res = await this.sourceClient.request({
|
||||
...Impersonated.RETRY_CONFIG,
|
||||
url: u,
|
||||
data: body,
|
||||
method: 'POST',
|
||||
});
|
||||
const tokenResponse = res.data;
|
||||
this.credentials.access_token = tokenResponse.accessToken;
|
||||
this.credentials.expiry_date = Date.parse(tokenResponse.expireTime);
|
||||
return {
|
||||
tokens: this.credentials,
|
||||
res,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
if (!(error instanceof Error))
|
||||
throw error;
|
||||
let status = 0;
|
||||
let message = '';
|
||||
if (error instanceof gaxios_1.GaxiosError) {
|
||||
status = error?.response?.data?.error?.status;
|
||||
message = error?.response?.data?.error?.message;
|
||||
}
|
||||
if (status && message) {
|
||||
error.message = `${status}: unable to impersonate: ${message}`;
|
||||
throw error;
|
||||
}
|
||||
else {
|
||||
error.message = `unable to impersonate: ${error}`;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Generates an OpenID Connect ID token for a service account.
|
||||
*
|
||||
* {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation}
|
||||
*
|
||||
* @param targetAudience the audience for the fetched ID token.
|
||||
* @param options the for the request
|
||||
* @return an OpenID Connect ID token
|
||||
*/
|
||||
async fetchIdToken(targetAudience, options) {
|
||||
await this.sourceClient.getAccessToken();
|
||||
const name = `projects/-/serviceAccounts/${this.targetPrincipal}`;
|
||||
const u = `${this.endpoint}/v1/${name}:generateIdToken`;
|
||||
const body = {
|
||||
delegates: this.delegates,
|
||||
audience: targetAudience,
|
||||
includeEmail: options?.includeEmail ?? true,
|
||||
useEmailAzp: options?.includeEmail ?? true,
|
||||
};
|
||||
const res = await this.sourceClient.request({
|
||||
...Impersonated.RETRY_CONFIG,
|
||||
url: u,
|
||||
data: body,
|
||||
method: 'POST',
|
||||
});
|
||||
return res.data.token;
|
||||
}
|
||||
}
|
||||
exports.Impersonated = Impersonated;
|
||||
//# sourceMappingURL=impersonated.js.map
|
||||
61
node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts
generated
vendored
Normal file
61
node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts
generated
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
import * as stream from 'stream';
|
||||
import { JWTInput } from './credentials';
|
||||
export interface Claims {
|
||||
[index: string]: string;
|
||||
}
|
||||
export declare class JWTAccess {
|
||||
email?: string | null;
|
||||
key?: string | null;
|
||||
keyId?: string | null;
|
||||
projectId?: string;
|
||||
eagerRefreshThresholdMillis: number;
|
||||
private cache;
|
||||
/**
|
||||
* JWTAccess service account credentials.
|
||||
*
|
||||
* Create a new access token by using the credential to create a new JWT token
|
||||
* that's recognized as the access token.
|
||||
*
|
||||
* @param email the service account email address.
|
||||
* @param key the private key that will be used to sign the token.
|
||||
* @param keyId the ID of the private key used to sign the token.
|
||||
*/
|
||||
constructor(email?: string | null, key?: string | null, keyId?: string | null, eagerRefreshThresholdMillis?: number);
|
||||
/**
|
||||
* Ensures that we're caching a key appropriately, giving precedence to scopes vs. url
|
||||
*
|
||||
* @param url The URI being authorized.
|
||||
* @param scopes The scope or scopes being authorized
|
||||
* @returns A string that returns the cached key.
|
||||
*/
|
||||
getCachedKey(url?: string, scopes?: string | string[]): string;
|
||||
/**
|
||||
* Get a non-expired access token, after refreshing if necessary.
|
||||
*
|
||||
* @param url The URI being authorized.
|
||||
* @param additionalClaims An object with a set of additional claims to
|
||||
* include in the payload.
|
||||
* @returns An object that includes the authorization header.
|
||||
*/
|
||||
getRequestHeaders(url?: string, additionalClaims?: Claims, scopes?: string | string[]): Headers;
|
||||
/**
|
||||
* Returns an expiration time for the JWT token.
|
||||
*
|
||||
* @param iat The issued at time for the JWT.
|
||||
* @returns An expiration time for the JWT.
|
||||
*/
|
||||
private static getExpirationTime;
|
||||
/**
|
||||
* Create a JWTAccess credentials instance using the given input options.
|
||||
* @param json The input object.
|
||||
*/
|
||||
fromJSON(json: JWTInput): void;
|
||||
/**
|
||||
* Create a JWTAccess credentials instance using the given input stream.
|
||||
* @param inputStream The input stream.
|
||||
* @param callback Optional callback.
|
||||
*/
|
||||
fromStream(inputStream: stream.Readable): Promise<void>;
|
||||
fromStream(inputStream: stream.Readable, callback: (err?: Error) => void): void;
|
||||
private fromStreamAsync;
|
||||
}
|
||||
201
node_modules/google-auth-library/build/src/auth/jwtaccess.js
generated
vendored
Normal file
201
node_modules/google-auth-library/build/src/auth/jwtaccess.js
generated
vendored
Normal file
@@ -0,0 +1,201 @@
|
||||
"use strict";
|
||||
// Copyright 2015 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.JWTAccess = void 0;
|
||||
const jws = require("jws");
|
||||
const util_1 = require("../util");
|
||||
const DEFAULT_HEADER = {
|
||||
alg: 'RS256',
|
||||
typ: 'JWT',
|
||||
};
|
||||
class JWTAccess {
|
||||
email;
|
||||
key;
|
||||
keyId;
|
||||
projectId;
|
||||
eagerRefreshThresholdMillis;
|
||||
cache = new util_1.LRUCache({
|
||||
capacity: 500,
|
||||
maxAge: 60 * 60 * 1000,
|
||||
});
|
||||
/**
|
||||
* JWTAccess service account credentials.
|
||||
*
|
||||
* Create a new access token by using the credential to create a new JWT token
|
||||
* that's recognized as the access token.
|
||||
*
|
||||
* @param email the service account email address.
|
||||
* @param key the private key that will be used to sign the token.
|
||||
* @param keyId the ID of the private key used to sign the token.
|
||||
*/
|
||||
constructor(email, key, keyId, eagerRefreshThresholdMillis) {
|
||||
this.email = email;
|
||||
this.key = key;
|
||||
this.keyId = keyId;
|
||||
this.eagerRefreshThresholdMillis =
|
||||
eagerRefreshThresholdMillis ?? 5 * 60 * 1000;
|
||||
}
|
||||
/**
|
||||
* Ensures that we're caching a key appropriately, giving precedence to scopes vs. url
|
||||
*
|
||||
* @param url The URI being authorized.
|
||||
* @param scopes The scope or scopes being authorized
|
||||
* @returns A string that returns the cached key.
|
||||
*/
|
||||
getCachedKey(url, scopes) {
|
||||
let cacheKey = url;
|
||||
if (scopes && Array.isArray(scopes) && scopes.length) {
|
||||
cacheKey = url ? `${url}_${scopes.join('_')}` : `${scopes.join('_')}`;
|
||||
}
|
||||
else if (typeof scopes === 'string') {
|
||||
cacheKey = url ? `${url}_${scopes}` : scopes;
|
||||
}
|
||||
if (!cacheKey) {
|
||||
throw Error('Scopes or url must be provided');
|
||||
}
|
||||
return cacheKey;
|
||||
}
|
||||
/**
|
||||
* Get a non-expired access token, after refreshing if necessary.
|
||||
*
|
||||
* @param url The URI being authorized.
|
||||
* @param additionalClaims An object with a set of additional claims to
|
||||
* include in the payload.
|
||||
* @returns An object that includes the authorization header.
|
||||
*/
|
||||
getRequestHeaders(url, additionalClaims, scopes) {
|
||||
// Return cached authorization headers, unless we are within
|
||||
// eagerRefreshThresholdMillis ms of them expiring:
|
||||
const key = this.getCachedKey(url, scopes);
|
||||
const cachedToken = this.cache.get(key);
|
||||
const now = Date.now();
|
||||
if (cachedToken &&
|
||||
cachedToken.expiration - now > this.eagerRefreshThresholdMillis) {
|
||||
// Copying headers into a new `Headers` object to avoid potential leakage -
|
||||
// as this is a cache it is possible for multiple requests to reference this
|
||||
// same value.
|
||||
return new Headers(cachedToken.headers);
|
||||
}
|
||||
const iat = Math.floor(Date.now() / 1000);
|
||||
const exp = JWTAccess.getExpirationTime(iat);
|
||||
let defaultClaims;
|
||||
// Turn scopes into space-separated string
|
||||
if (Array.isArray(scopes)) {
|
||||
scopes = scopes.join(' ');
|
||||
}
|
||||
// If scopes are specified, sign with scopes
|
||||
if (scopes) {
|
||||
defaultClaims = {
|
||||
iss: this.email,
|
||||
sub: this.email,
|
||||
scope: scopes,
|
||||
exp,
|
||||
iat,
|
||||
};
|
||||
}
|
||||
else {
|
||||
defaultClaims = {
|
||||
iss: this.email,
|
||||
sub: this.email,
|
||||
aud: url,
|
||||
exp,
|
||||
iat,
|
||||
};
|
||||
}
|
||||
// if additionalClaims are provided, ensure they do not collide with
|
||||
// other required claims.
|
||||
if (additionalClaims) {
|
||||
for (const claim in defaultClaims) {
|
||||
if (additionalClaims[claim]) {
|
||||
throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const header = this.keyId
|
||||
? { ...DEFAULT_HEADER, kid: this.keyId }
|
||||
: DEFAULT_HEADER;
|
||||
const payload = Object.assign(defaultClaims, additionalClaims);
|
||||
// Sign the jwt and add it to the cache
|
||||
const signedJWT = jws.sign({ header, payload, secret: this.key });
|
||||
const headers = new Headers({ authorization: `Bearer ${signedJWT}` });
|
||||
this.cache.set(key, {
|
||||
expiration: exp * 1000,
|
||||
headers,
|
||||
});
|
||||
return headers;
|
||||
}
|
||||
/**
|
||||
* Returns an expiration time for the JWT token.
|
||||
*
|
||||
* @param iat The issued at time for the JWT.
|
||||
* @returns An expiration time for the JWT.
|
||||
*/
|
||||
static getExpirationTime(iat) {
|
||||
const exp = iat + 3600; // 3600 seconds = 1 hour
|
||||
return exp;
|
||||
}
|
||||
/**
|
||||
* Create a JWTAccess credentials instance using the given input options.
|
||||
* @param json The input object.
|
||||
*/
|
||||
fromJSON(json) {
|
||||
if (!json) {
|
||||
throw new Error('Must pass in a JSON object containing the service account auth settings.');
|
||||
}
|
||||
if (!json.client_email) {
|
||||
throw new Error('The incoming JSON object does not contain a client_email field');
|
||||
}
|
||||
if (!json.private_key) {
|
||||
throw new Error('The incoming JSON object does not contain a private_key field');
|
||||
}
|
||||
// Extract the relevant information from the json key file.
|
||||
this.email = json.client_email;
|
||||
this.key = json.private_key;
|
||||
this.keyId = json.private_key_id;
|
||||
this.projectId = json.project_id;
|
||||
}
|
||||
fromStream(inputStream, callback) {
|
||||
if (callback) {
|
||||
this.fromStreamAsync(inputStream).then(() => callback(), callback);
|
||||
}
|
||||
else {
|
||||
return this.fromStreamAsync(inputStream);
|
||||
}
|
||||
}
|
||||
fromStreamAsync(inputStream) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!inputStream) {
|
||||
reject(new Error('Must pass in a stream containing the service account auth settings.'));
|
||||
}
|
||||
let s = '';
|
||||
inputStream
|
||||
.setEncoding('utf8')
|
||||
.on('data', chunk => (s += chunk))
|
||||
.on('error', reject)
|
||||
.on('end', () => {
|
||||
try {
|
||||
const data = JSON.parse(s);
|
||||
this.fromJSON(data);
|
||||
resolve();
|
||||
}
|
||||
catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.JWTAccess = JWTAccess;
|
||||
//# sourceMappingURL=jwtaccess.js.map
|
||||
137
node_modules/google-auth-library/build/src/auth/jwtclient.d.ts
generated
vendored
Normal file
137
node_modules/google-auth-library/build/src/auth/jwtclient.d.ts
generated
vendored
Normal file
@@ -0,0 +1,137 @@
|
||||
import { GoogleToken } from 'gtoken';
|
||||
import * as stream from 'stream';
|
||||
import { CredentialBody, Credentials, JWTInput } from './credentials';
|
||||
import { IdTokenProvider } from './idtokenclient';
|
||||
import { GetTokenResponse, OAuth2Client, OAuth2ClientOptions, RequestMetadataResponse } from './oauth2client';
|
||||
export interface JWTOptions extends OAuth2ClientOptions {
|
||||
/**
|
||||
* The service account email address.
|
||||
*/
|
||||
email?: string;
|
||||
/**
|
||||
* The path to private key file. Not necessary if {@link JWTOptions.key} has been provided.
|
||||
*/
|
||||
keyFile?: string;
|
||||
/**
|
||||
* The value of key. Not necessary if {@link JWTOptions.keyFile} has been provided.
|
||||
*/
|
||||
key?: string;
|
||||
/**
|
||||
* The list of requested scopes or a single scope.
|
||||
*/
|
||||
keyId?: string;
|
||||
/**
|
||||
* The impersonated account's email address.
|
||||
*/
|
||||
scopes?: string | string[];
|
||||
/**
|
||||
* The ID of the key.
|
||||
*/
|
||||
subject?: string;
|
||||
/**
|
||||
* Additional claims, such as target audience.
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* {target_audience: 'targetAudience'}
|
||||
* ```
|
||||
*/
|
||||
additionalClaims?: {};
|
||||
}
|
||||
export declare class JWT extends OAuth2Client implements IdTokenProvider {
|
||||
email?: string;
|
||||
keyFile?: string;
|
||||
key?: string;
|
||||
keyId?: string;
|
||||
defaultScopes?: string | string[];
|
||||
scopes?: string | string[];
|
||||
scope?: string;
|
||||
subject?: string;
|
||||
gtoken?: GoogleToken;
|
||||
additionalClaims?: {};
|
||||
useJWTAccessWithScope?: boolean;
|
||||
defaultServicePath?: string;
|
||||
private access?;
|
||||
/**
|
||||
* JWT service account credentials.
|
||||
*
|
||||
* Retrieve access token using gtoken.
|
||||
*
|
||||
* @param options the
|
||||
*/
|
||||
constructor(options?: JWTOptions);
|
||||
/**
|
||||
* Creates a copy of the credential with the specified scopes.
|
||||
* @param scopes List of requested scopes or a single scope.
|
||||
* @return The cloned instance.
|
||||
*/
|
||||
createScoped(scopes?: string | string[]): JWT;
|
||||
/**
|
||||
* Obtains the metadata to be sent with the request.
|
||||
*
|
||||
* @param url the URI being authorized.
|
||||
*/
|
||||
protected getRequestMetadataAsync(url?: string | null): Promise<RequestMetadataResponse>;
|
||||
/**
|
||||
* Fetches an ID token.
|
||||
* @param targetAudience the audience for the fetched ID token.
|
||||
*/
|
||||
fetchIdToken(targetAudience: string): Promise<string>;
|
||||
/**
|
||||
* Determine if there are currently scopes available.
|
||||
*/
|
||||
private hasUserScopes;
|
||||
/**
|
||||
* Are there any default or user scopes defined.
|
||||
*/
|
||||
private hasAnyScopes;
|
||||
/**
|
||||
* Get the initial access token using gToken.
|
||||
* @param callback Optional callback.
|
||||
* @returns Promise that resolves with credentials
|
||||
*/
|
||||
authorize(): Promise<Credentials>;
|
||||
authorize(callback: (err: Error | null, result?: Credentials) => void): void;
|
||||
private authorizeAsync;
|
||||
/**
|
||||
* Refreshes the access token.
|
||||
* @param refreshToken ignored
|
||||
* @private
|
||||
*/
|
||||
protected refreshTokenNoCache(): Promise<GetTokenResponse>;
|
||||
/**
|
||||
* Create a gToken if it doesn't already exist.
|
||||
*/
|
||||
private createGToken;
|
||||
/**
|
||||
* Create a JWT credentials instance using the given input options.
|
||||
* @param json The input object.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}.
|
||||
*/
|
||||
fromJSON(json: JWTInput): void;
|
||||
/**
|
||||
* Create a JWT credentials instance using the given input stream.
|
||||
* @param inputStream The input stream.
|
||||
* @param callback Optional callback.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}.
|
||||
*/
|
||||
fromStream(inputStream: stream.Readable): Promise<void>;
|
||||
fromStream(inputStream: stream.Readable, callback: (err?: Error | null) => void): void;
|
||||
private fromStreamAsync;
|
||||
/**
|
||||
* Creates a JWT credentials instance using an API Key for authentication.
|
||||
* @param apiKey The API Key in string form.
|
||||
*/
|
||||
fromAPIKey(apiKey: string): void;
|
||||
/**
|
||||
* Using the key or keyFile on the JWT client, obtain an object that contains
|
||||
* the key and the client email.
|
||||
*/
|
||||
getCredentials(): Promise<CredentialBody>;
|
||||
}
|
||||
300
node_modules/google-auth-library/build/src/auth/jwtclient.js
generated
vendored
Normal file
300
node_modules/google-auth-library/build/src/auth/jwtclient.js
generated
vendored
Normal file
@@ -0,0 +1,300 @@
|
||||
"use strict";
|
||||
// Copyright 2013 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.JWT = void 0;
|
||||
const gtoken_1 = require("gtoken");
|
||||
const jwtaccess_1 = require("./jwtaccess");
|
||||
const oauth2client_1 = require("./oauth2client");
|
||||
const authclient_1 = require("./authclient");
|
||||
class JWT extends oauth2client_1.OAuth2Client {
|
||||
email;
|
||||
keyFile;
|
||||
key;
|
||||
keyId;
|
||||
defaultScopes;
|
||||
scopes;
|
||||
scope;
|
||||
subject;
|
||||
gtoken;
|
||||
additionalClaims;
|
||||
useJWTAccessWithScope;
|
||||
defaultServicePath;
|
||||
access;
|
||||
/**
|
||||
* JWT service account credentials.
|
||||
*
|
||||
* Retrieve access token using gtoken.
|
||||
*
|
||||
* @param options the
|
||||
*/
|
||||
constructor(options = {}) {
|
||||
super(options);
|
||||
this.email = options.email;
|
||||
this.keyFile = options.keyFile;
|
||||
this.key = options.key;
|
||||
this.keyId = options.keyId;
|
||||
this.scopes = options.scopes;
|
||||
this.subject = options.subject;
|
||||
this.additionalClaims = options.additionalClaims;
|
||||
// Start with an expired refresh token, which will automatically be
|
||||
// refreshed before the first API call is made.
|
||||
this.credentials = { refresh_token: 'jwt-placeholder', expiry_date: 1 };
|
||||
}
|
||||
/**
|
||||
* Creates a copy of the credential with the specified scopes.
|
||||
* @param scopes List of requested scopes or a single scope.
|
||||
* @return The cloned instance.
|
||||
*/
|
||||
createScoped(scopes) {
|
||||
const jwt = new JWT(this);
|
||||
jwt.scopes = scopes;
|
||||
return jwt;
|
||||
}
|
||||
/**
|
||||
* Obtains the metadata to be sent with the request.
|
||||
*
|
||||
* @param url the URI being authorized.
|
||||
*/
|
||||
async getRequestMetadataAsync(url) {
|
||||
url = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url;
|
||||
const useSelfSignedJWT = (!this.hasUserScopes() && url) ||
|
||||
(this.useJWTAccessWithScope && this.hasAnyScopes()) ||
|
||||
this.universeDomain !== authclient_1.DEFAULT_UNIVERSE;
|
||||
if (this.subject && this.universeDomain !== authclient_1.DEFAULT_UNIVERSE) {
|
||||
throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${authclient_1.DEFAULT_UNIVERSE}`);
|
||||
}
|
||||
if (!this.apiKey && useSelfSignedJWT) {
|
||||
if (this.additionalClaims &&
|
||||
this.additionalClaims.target_audience) {
|
||||
const { tokens } = await this.refreshToken();
|
||||
return {
|
||||
headers: this.addSharedMetadataHeaders(new Headers({
|
||||
authorization: `Bearer ${tokens.id_token}`,
|
||||
})),
|
||||
};
|
||||
}
|
||||
else {
|
||||
// no scopes have been set, but a uri has been provided. Use JWTAccess
|
||||
// credentials.
|
||||
if (!this.access) {
|
||||
this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis);
|
||||
}
|
||||
let scopes;
|
||||
if (this.hasUserScopes()) {
|
||||
scopes = this.scopes;
|
||||
}
|
||||
else if (!url) {
|
||||
scopes = this.defaultScopes;
|
||||
}
|
||||
const useScopes = this.useJWTAccessWithScope ||
|
||||
this.universeDomain !== authclient_1.DEFAULT_UNIVERSE;
|
||||
const headers = await this.access.getRequestHeaders(url ?? undefined, this.additionalClaims,
|
||||
// Scopes take precedent over audience for signing,
|
||||
// so we only provide them if `useJWTAccessWithScope` is on or
|
||||
// if we are in a non-default universe
|
||||
useScopes ? scopes : undefined);
|
||||
return { headers: this.addSharedMetadataHeaders(headers) };
|
||||
}
|
||||
}
|
||||
else if (this.hasAnyScopes() || this.apiKey) {
|
||||
return super.getRequestMetadataAsync(url);
|
||||
}
|
||||
else {
|
||||
// If no audience, apiKey, or scopes are provided, we should not attempt
|
||||
// to populate any headers:
|
||||
return { headers: new Headers() };
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Fetches an ID token.
|
||||
* @param targetAudience the audience for the fetched ID token.
|
||||
*/
|
||||
async fetchIdToken(targetAudience) {
|
||||
// Create a new gToken for fetching an ID token
|
||||
const gtoken = new gtoken_1.GoogleToken({
|
||||
iss: this.email,
|
||||
sub: this.subject,
|
||||
scope: this.scopes || this.defaultScopes,
|
||||
keyFile: this.keyFile,
|
||||
key: this.key,
|
||||
additionalClaims: { target_audience: targetAudience },
|
||||
transporter: this.transporter,
|
||||
});
|
||||
await gtoken.getToken({
|
||||
forceRefresh: true,
|
||||
});
|
||||
if (!gtoken.idToken) {
|
||||
throw new Error('Unknown error: Failed to fetch ID token');
|
||||
}
|
||||
return gtoken.idToken;
|
||||
}
|
||||
/**
|
||||
* Determine if there are currently scopes available.
|
||||
*/
|
||||
hasUserScopes() {
|
||||
if (!this.scopes) {
|
||||
return false;
|
||||
}
|
||||
return this.scopes.length > 0;
|
||||
}
|
||||
/**
|
||||
* Are there any default or user scopes defined.
|
||||
*/
|
||||
hasAnyScopes() {
|
||||
if (this.scopes && this.scopes.length > 0)
|
||||
return true;
|
||||
if (this.defaultScopes && this.defaultScopes.length > 0)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
authorize(callback) {
|
||||
if (callback) {
|
||||
this.authorizeAsync().then(r => callback(null, r), callback);
|
||||
}
|
||||
else {
|
||||
return this.authorizeAsync();
|
||||
}
|
||||
}
|
||||
async authorizeAsync() {
|
||||
const result = await this.refreshToken();
|
||||
if (!result) {
|
||||
throw new Error('No result returned');
|
||||
}
|
||||
this.credentials = result.tokens;
|
||||
this.credentials.refresh_token = 'jwt-placeholder';
|
||||
this.key = this.gtoken.key;
|
||||
this.email = this.gtoken.iss;
|
||||
return result.tokens;
|
||||
}
|
||||
/**
|
||||
* Refreshes the access token.
|
||||
* @param refreshToken ignored
|
||||
* @private
|
||||
*/
|
||||
async refreshTokenNoCache() {
|
||||
const gtoken = this.createGToken();
|
||||
const token = await gtoken.getToken({
|
||||
forceRefresh: this.isTokenExpiring(),
|
||||
});
|
||||
const tokens = {
|
||||
access_token: token.access_token,
|
||||
token_type: 'Bearer',
|
||||
expiry_date: gtoken.expiresAt,
|
||||
id_token: gtoken.idToken,
|
||||
};
|
||||
this.emit('tokens', tokens);
|
||||
return { res: null, tokens };
|
||||
}
|
||||
/**
|
||||
* Create a gToken if it doesn't already exist.
|
||||
*/
|
||||
createGToken() {
|
||||
if (!this.gtoken) {
|
||||
this.gtoken = new gtoken_1.GoogleToken({
|
||||
iss: this.email,
|
||||
sub: this.subject,
|
||||
scope: this.scopes || this.defaultScopes,
|
||||
keyFile: this.keyFile,
|
||||
key: this.key,
|
||||
additionalClaims: this.additionalClaims,
|
||||
transporter: this.transporter,
|
||||
});
|
||||
}
|
||||
return this.gtoken;
|
||||
}
|
||||
/**
|
||||
* Create a JWT credentials instance using the given input options.
|
||||
* @param json The input object.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}.
|
||||
*/
|
||||
fromJSON(json) {
|
||||
if (!json) {
|
||||
throw new Error('Must pass in a JSON object containing the service account auth settings.');
|
||||
}
|
||||
if (!json.client_email) {
|
||||
throw new Error('The incoming JSON object does not contain a client_email field');
|
||||
}
|
||||
if (!json.private_key) {
|
||||
throw new Error('The incoming JSON object does not contain a private_key field');
|
||||
}
|
||||
// Extract the relevant information from the json key file.
|
||||
this.email = json.client_email;
|
||||
this.key = json.private_key;
|
||||
this.keyId = json.private_key_id;
|
||||
this.projectId = json.project_id;
|
||||
this.quotaProjectId = json.quota_project_id;
|
||||
this.universeDomain = json.universe_domain || this.universeDomain;
|
||||
}
|
||||
fromStream(inputStream, callback) {
|
||||
if (callback) {
|
||||
this.fromStreamAsync(inputStream).then(() => callback(), callback);
|
||||
}
|
||||
else {
|
||||
return this.fromStreamAsync(inputStream);
|
||||
}
|
||||
}
|
||||
fromStreamAsync(inputStream) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!inputStream) {
|
||||
throw new Error('Must pass in a stream containing the service account auth settings.');
|
||||
}
|
||||
let s = '';
|
||||
inputStream
|
||||
.setEncoding('utf8')
|
||||
.on('error', reject)
|
||||
.on('data', chunk => (s += chunk))
|
||||
.on('end', () => {
|
||||
try {
|
||||
const data = JSON.parse(s);
|
||||
this.fromJSON(data);
|
||||
resolve();
|
||||
}
|
||||
catch (e) {
|
||||
reject(e);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Creates a JWT credentials instance using an API Key for authentication.
|
||||
* @param apiKey The API Key in string form.
|
||||
*/
|
||||
fromAPIKey(apiKey) {
|
||||
if (typeof apiKey !== 'string') {
|
||||
throw new Error('Must provide an API Key string.');
|
||||
}
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
/**
|
||||
* Using the key or keyFile on the JWT client, obtain an object that contains
|
||||
* the key and the client email.
|
||||
*/
|
||||
async getCredentials() {
|
||||
if (this.key) {
|
||||
return { private_key: this.key, client_email: this.email };
|
||||
}
|
||||
else if (this.keyFile) {
|
||||
const gtoken = this.createGToken();
|
||||
const creds = await gtoken.getCredentials(this.keyFile);
|
||||
return { private_key: creds.privateKey, client_email: creds.clientEmail };
|
||||
}
|
||||
throw new Error('A key or a keyFile must be provided to getCredentials.');
|
||||
}
|
||||
}
|
||||
exports.JWT = JWT;
|
||||
//# sourceMappingURL=jwtclient.js.map
|
||||
140
node_modules/google-auth-library/build/src/auth/loginticket.d.ts
generated
vendored
Normal file
140
node_modules/google-auth-library/build/src/auth/loginticket.d.ts
generated
vendored
Normal file
@@ -0,0 +1,140 @@
|
||||
export declare class LoginTicket {
|
||||
private envelope?;
|
||||
private payload?;
|
||||
/**
|
||||
* Create a simple class to extract user ID from an ID Token
|
||||
*
|
||||
* @param {string} env Envelope of the jwt
|
||||
* @param {TokenPayload} pay Payload of the jwt
|
||||
* @constructor
|
||||
*/
|
||||
constructor(env?: string, pay?: TokenPayload);
|
||||
getEnvelope(): string | undefined;
|
||||
getPayload(): TokenPayload | undefined;
|
||||
/**
|
||||
* Create a simple class to extract user ID from an ID Token
|
||||
*
|
||||
* @return The user ID
|
||||
*/
|
||||
getUserId(): string | null;
|
||||
/**
|
||||
* Returns attributes from the login ticket. This can contain
|
||||
* various information about the user session.
|
||||
*
|
||||
* @return The envelope and payload
|
||||
*/
|
||||
getAttributes(): {
|
||||
envelope: string | undefined;
|
||||
payload: TokenPayload | undefined;
|
||||
};
|
||||
}
|
||||
export interface TokenPayload {
|
||||
/**
|
||||
* The Issuer Identifier for the Issuer of the response. Always
|
||||
* https://accounts.google.com or accounts.google.com for Google ID tokens.
|
||||
*/
|
||||
iss: string;
|
||||
/**
|
||||
* Access token hash. Provides validation that the access token is tied to the
|
||||
* identity token. If the ID token is issued with an access token in the
|
||||
* server flow, this is always included. This can be used as an alternate
|
||||
* mechanism to protect against cross-site request forgery attacks, but if you
|
||||
* follow Step 1 and Step 3 it is not necessary to verify the access token.
|
||||
*/
|
||||
at_hash?: string;
|
||||
/**
|
||||
* True if the user's e-mail address has been verified; otherwise false.
|
||||
*/
|
||||
email_verified?: boolean;
|
||||
/**
|
||||
* An identifier for the user, unique among all Google accounts and never
|
||||
* reused. A Google account can have multiple emails at different points in
|
||||
* time, but the sub value is never changed. Use sub within your application
|
||||
* as the unique-identifier key for the user.
|
||||
*/
|
||||
sub: string;
|
||||
/**
|
||||
* The client_id of the authorized presenter. This claim is only needed when
|
||||
* the party requesting the ID token is not the same as the audience of the ID
|
||||
* token. This may be the case at Google for hybrid apps where a web
|
||||
* application and Android app have a different client_id but share the same
|
||||
* project.
|
||||
*/
|
||||
azp?: string;
|
||||
/**
|
||||
* The user's email address. This may not be unique and is not suitable for
|
||||
* use as a primary key. Provided only if your scope included the string
|
||||
* "email".
|
||||
*/
|
||||
email?: string;
|
||||
/**
|
||||
* The URL of the user's profile page. Might be provided when:
|
||||
* - The request scope included the string "profile"
|
||||
* - The ID token is returned from a token refresh
|
||||
* - When profile claims are present, you can use them to update your app's
|
||||
* user records. Note that this claim is never guaranteed to be present.
|
||||
*/
|
||||
profile?: string;
|
||||
/**
|
||||
* The URL of the user's profile picture. Might be provided when:
|
||||
* - The request scope included the string "profile"
|
||||
* - The ID token is returned from a token refresh
|
||||
* - When picture claims are present, you can use them to update your app's
|
||||
* user records. Note that this claim is never guaranteed to be present.
|
||||
*/
|
||||
picture?: string;
|
||||
/**
|
||||
* The user's full name, in a displayable form. Might be provided when:
|
||||
* - The request scope included the string "profile"
|
||||
* - The ID token is returned from a token refresh
|
||||
* - When name claims are present, you can use them to update your app's user
|
||||
* records. Note that this claim is never guaranteed to be present.
|
||||
*/
|
||||
name?: string;
|
||||
/**
|
||||
* The user's given name, in a displayable form. Might be provided when:
|
||||
* - The request scope included the string "profile"
|
||||
* - The ID token is returned from a token refresh
|
||||
* - When name claims are present, you can use them to update your app's user
|
||||
* records. Note that this claim is never guaranteed to be present.
|
||||
*/
|
||||
given_name?: string;
|
||||
/**
|
||||
* The user's family name, in a displayable form. Might be provided when:
|
||||
* - The request scope included the string "profile"
|
||||
* - The ID token is returned from a token refresh
|
||||
* - When name claims are present, you can use them to update your app's user
|
||||
* records. Note that this claim is never guaranteed to be present.
|
||||
*/
|
||||
family_name?: string;
|
||||
/**
|
||||
* Identifies the audience that this ID token is intended for. It must be one
|
||||
* of the OAuth 2.0 client IDs of your application.
|
||||
*/
|
||||
aud: string;
|
||||
/**
|
||||
* The time the ID token was issued, represented in Unix time (integer
|
||||
* seconds).
|
||||
*/
|
||||
iat: number;
|
||||
/**
|
||||
* The time the ID token expires, represented in Unix time (integer seconds).
|
||||
*/
|
||||
exp: number;
|
||||
/**
|
||||
* The value of the nonce supplied by your app in the authentication request.
|
||||
* You should enforce protection against replay attacks by ensuring it is
|
||||
* presented only once.
|
||||
*/
|
||||
nonce?: string;
|
||||
/**
|
||||
* The hosted G Suite domain of the user. Provided only if the user belongs to
|
||||
* a hosted domain.
|
||||
*/
|
||||
hd?: string;
|
||||
/**
|
||||
* The user's locale, represented by a BCP 47 language tag.
|
||||
* Might be provided when a name claim is present.
|
||||
*/
|
||||
locale?: string;
|
||||
}
|
||||
60
node_modules/google-auth-library/build/src/auth/loginticket.js
generated
vendored
Normal file
60
node_modules/google-auth-library/build/src/auth/loginticket.js
generated
vendored
Normal file
@@ -0,0 +1,60 @@
|
||||
"use strict";
|
||||
// Copyright 2014 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.LoginTicket = void 0;
|
||||
class LoginTicket {
|
||||
envelope;
|
||||
payload;
|
||||
/**
|
||||
* Create a simple class to extract user ID from an ID Token
|
||||
*
|
||||
* @param {string} env Envelope of the jwt
|
||||
* @param {TokenPayload} pay Payload of the jwt
|
||||
* @constructor
|
||||
*/
|
||||
constructor(env, pay) {
|
||||
this.envelope = env;
|
||||
this.payload = pay;
|
||||
}
|
||||
getEnvelope() {
|
||||
return this.envelope;
|
||||
}
|
||||
getPayload() {
|
||||
return this.payload;
|
||||
}
|
||||
/**
|
||||
* Create a simple class to extract user ID from an ID Token
|
||||
*
|
||||
* @return The user ID
|
||||
*/
|
||||
getUserId() {
|
||||
const payload = this.getPayload();
|
||||
if (payload && payload.sub) {
|
||||
return payload.sub;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Returns attributes from the login ticket. This can contain
|
||||
* various information about the user session.
|
||||
*
|
||||
* @return The envelope and payload
|
||||
*/
|
||||
getAttributes() {
|
||||
return { envelope: this.getEnvelope(), payload: this.getPayload() };
|
||||
}
|
||||
}
|
||||
exports.LoginTicket = LoginTicket;
|
||||
//# sourceMappingURL=loginticket.js.map
|
||||
610
node_modules/google-auth-library/build/src/auth/oauth2client.d.ts
generated
vendored
Normal file
610
node_modules/google-auth-library/build/src/auth/oauth2client.d.ts
generated
vendored
Normal file
@@ -0,0 +1,610 @@
|
||||
import { GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios';
|
||||
import * as querystring from 'querystring';
|
||||
import { JwkCertificate } from '../crypto/crypto';
|
||||
import { AuthClient, AuthClientOptions, GetAccessTokenResponse, BodyResponseCallback } from './authclient';
|
||||
import { Credentials } from './credentials';
|
||||
import { LoginTicket } from './loginticket';
|
||||
/**
|
||||
* The results from the `generateCodeVerifierAsync` method. To learn more,
|
||||
* See the sample:
|
||||
* https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js
|
||||
*/
|
||||
export interface CodeVerifierResults {
|
||||
/**
|
||||
* The code verifier that will be used when calling `getToken` to obtain a new
|
||||
* access token.
|
||||
*/
|
||||
codeVerifier: string;
|
||||
/**
|
||||
* The code_challenge that should be sent with the `generateAuthUrl` call
|
||||
* to obtain a verifiable authentication url.
|
||||
*/
|
||||
codeChallenge?: string;
|
||||
}
|
||||
export interface Certificates {
|
||||
[index: string]: string | JwkCertificate;
|
||||
}
|
||||
export interface PublicKeys {
|
||||
[index: string]: string;
|
||||
}
|
||||
export declare enum CodeChallengeMethod {
|
||||
Plain = "plain",
|
||||
S256 = "S256"
|
||||
}
|
||||
export declare enum CertificateFormat {
|
||||
PEM = "PEM",
|
||||
JWK = "JWK"
|
||||
}
|
||||
/**
|
||||
* The client authentication type. Supported values are basic, post, and none.
|
||||
* https://datatracker.ietf.org/doc/html/rfc7591#section-2
|
||||
*/
|
||||
export declare enum ClientAuthentication {
|
||||
ClientSecretPost = "ClientSecretPost",
|
||||
ClientSecretBasic = "ClientSecretBasic",
|
||||
None = "None"
|
||||
}
|
||||
export interface GetTokenOptions {
|
||||
code: string;
|
||||
codeVerifier?: string;
|
||||
/**
|
||||
* The client ID for your application. The value passed into the constructor
|
||||
* will be used if not provided. Must match any client_id option passed to
|
||||
* a corresponding call to generateAuthUrl.
|
||||
*/
|
||||
client_id?: string;
|
||||
/**
|
||||
* Determines where the API server redirects the user after the user
|
||||
* completes the authorization flow. The value passed into the constructor
|
||||
* will be used if not provided. Must match any redirect_uri option passed to
|
||||
* a corresponding call to generateAuthUrl.
|
||||
*/
|
||||
redirect_uri?: string;
|
||||
}
|
||||
export interface TokenInfo {
|
||||
/**
|
||||
* The application that is the intended user of the access token.
|
||||
*/
|
||||
aud: string;
|
||||
/**
|
||||
* This value lets you correlate profile information from multiple Google
|
||||
* APIs. It is only present in the response if you included the profile scope
|
||||
* in your request in step 1. The field value is an immutable identifier for
|
||||
* the logged-in user that can be used to create and manage user sessions in
|
||||
* your application. The identifier is the same regardless of which client ID
|
||||
* is used to retrieve it. This enables multiple applications in the same
|
||||
* organization to correlate profile information.
|
||||
*/
|
||||
user_id?: string;
|
||||
/**
|
||||
* An array of scopes that the user granted access to.
|
||||
*/
|
||||
scopes: string[];
|
||||
/**
|
||||
* The datetime when the token becomes invalid.
|
||||
*/
|
||||
expiry_date: number;
|
||||
/**
|
||||
* An identifier for the user, unique among all Google accounts and never
|
||||
* reused. A Google account can have multiple emails at different points in
|
||||
* time, but the sub value is never changed. Use sub within your application
|
||||
* as the unique-identifier key for the user.
|
||||
*/
|
||||
sub?: string;
|
||||
/**
|
||||
* The client_id of the authorized presenter. This claim is only needed when
|
||||
* the party requesting the ID token is not the same as the audience of the ID
|
||||
* token. This may be the case at Google for hybrid apps where a web
|
||||
* application and Android app have a different client_id but share the same
|
||||
* project.
|
||||
*/
|
||||
azp?: string;
|
||||
/**
|
||||
* Indicates whether your application can refresh access tokens
|
||||
* when the user is not present at the browser. Valid parameter values are
|
||||
* 'online', which is the default value, and 'offline'. Set the value to
|
||||
* 'offline' if your application needs to refresh access tokens when the user
|
||||
* is not present at the browser. This value instructs the Google
|
||||
* authorization server to return a refresh token and an access token the
|
||||
* first time that your application exchanges an authorization code for
|
||||
* tokens.
|
||||
*/
|
||||
access_type?: string;
|
||||
/**
|
||||
* The user's email address. This value may not be unique to this user and
|
||||
* is not suitable for use as a primary key. Provided only if your scope
|
||||
* included the email scope value.
|
||||
*/
|
||||
email?: string;
|
||||
/**
|
||||
* True if the user's e-mail address has been verified; otherwise false.
|
||||
*/
|
||||
email_verified?: boolean;
|
||||
}
|
||||
export interface GenerateAuthUrlOpts {
|
||||
/**
|
||||
* Recommended. Indicates whether your application can refresh access tokens
|
||||
* when the user is not present at the browser. Valid parameter values are
|
||||
* 'online', which is the default value, and 'offline'. Set the value to
|
||||
* 'offline' if your application needs to refresh access tokens when the user
|
||||
* is not present at the browser. This value instructs the Google
|
||||
* authorization server to return a refresh token and an access token the
|
||||
* first time that your application exchanges an authorization code for
|
||||
* tokens.
|
||||
*/
|
||||
access_type?: string;
|
||||
/**
|
||||
* The hd (hosted domain) parameter streamlines the login process for G Suite
|
||||
* hosted accounts. By including the domain of the G Suite user (for example,
|
||||
* mycollege.edu), you can indicate that the account selection UI should be
|
||||
* optimized for accounts at that domain. To optimize for G Suite accounts
|
||||
* generally instead of just one domain, use an asterisk: hd=*.
|
||||
* Don't rely on this UI optimization to control who can access your app,
|
||||
* as client-side requests can be modified. Be sure to validate that the
|
||||
* returned ID token has an hd claim value that matches what you expect
|
||||
* (e.g. mycolledge.edu). Unlike the request parameter, the ID token claim is
|
||||
* contained within a security token from Google, so the value can be trusted.
|
||||
*/
|
||||
hd?: string;
|
||||
/**
|
||||
* The 'response_type' will always be set to 'CODE'.
|
||||
*/
|
||||
response_type?: string;
|
||||
/**
|
||||
* The client ID for your application. The value passed into the constructor
|
||||
* will be used if not provided. You can find this value in the API Console.
|
||||
*/
|
||||
client_id?: string;
|
||||
/**
|
||||
* Determines where the API server redirects the user after the user
|
||||
* completes the authorization flow. The value must exactly match one of the
|
||||
* 'redirect_uri' values listed for your project in the API Console. Note that
|
||||
* the http or https scheme, case, and trailing slash ('/') must all match.
|
||||
* The value passed into the constructor will be used if not provided.
|
||||
*/
|
||||
redirect_uri?: string;
|
||||
/**
|
||||
* Required. A space-delimited list of scopes that identify the resources that
|
||||
* your application could access on the user's behalf. These values inform the
|
||||
* consent screen that Google displays to the user. Scopes enable your
|
||||
* application to only request access to the resources that it needs while
|
||||
* also enabling users to control the amount of access that they grant to your
|
||||
* application. Thus, there is an inverse relationship between the number of
|
||||
* scopes requested and the likelihood of obtaining user consent. The
|
||||
* OAuth 2.0 API Scopes document provides a full list of scopes that you might
|
||||
* use to access Google APIs. We recommend that your application request
|
||||
* access to authorization scopes in context whenever possible. By requesting
|
||||
* access to user data in context, via incremental authorization, you help
|
||||
* users to more easily understand why your application needs the access it is
|
||||
* requesting.
|
||||
*/
|
||||
scope?: string[] | string;
|
||||
/**
|
||||
* Recommended. Specifies any string value that your application uses to
|
||||
* maintain state between your authorization request and the authorization
|
||||
* server's response. The server returns the exact value that you send as a
|
||||
* name=value pair in the hash (#) fragment of the 'redirect_uri' after the
|
||||
* user consents to or denies your application's access request. You can use
|
||||
* this parameter for several purposes, such as directing the user to the
|
||||
* correct resource in your application, sending nonces, and mitigating
|
||||
* cross-site request forgery. Since your redirect_uri can be guessed, using a
|
||||
* state value can increase your assurance that an incoming connection is the
|
||||
* result of an authentication request. If you generate a random string or
|
||||
* encode the hash of a cookie or another value that captures the client's
|
||||
* state, you can validate the response to additionally ensure that the
|
||||
* request and response originated in the same browser, providing protection
|
||||
* against attacks such as cross-site request forgery. See the OpenID Connect
|
||||
* documentation for an example of how to create and confirm a state token.
|
||||
*/
|
||||
state?: string;
|
||||
/**
|
||||
* Optional. Enables applications to use incremental authorization to request
|
||||
* access to additional scopes in context. If you set this parameter's value
|
||||
* to true and the authorization request is granted, then the new access token
|
||||
* will also cover any scopes to which the user previously granted the
|
||||
* application access. See the incremental authorization section for examples.
|
||||
*/
|
||||
include_granted_scopes?: boolean;
|
||||
/**
|
||||
* Optional. If your application knows which user is trying to authenticate,
|
||||
* it can use this parameter to provide a hint to the Google Authentication
|
||||
* Server. The server uses the hint to simplify the login flow either by
|
||||
* prefilling the email field in the sign-in form or by selecting the
|
||||
* appropriate multi-login session. Set the parameter value to an email
|
||||
* address or sub identifier, which is equivalent to the user's Google ID.
|
||||
*/
|
||||
login_hint?: string;
|
||||
/**
|
||||
* Optional. A space-delimited, case-sensitive list of prompts to present the
|
||||
* user. If you don't specify this parameter, the user will be prompted only
|
||||
* the first time your app requests access. Possible values are:
|
||||
*
|
||||
* 'none' - Donot display any authentication or consent screens. Must not be
|
||||
* specified with other values.
|
||||
* 'consent' - Prompt the user for consent.
|
||||
* 'select_account' - Prompt the user to select an account.
|
||||
*/
|
||||
prompt?: string;
|
||||
/**
|
||||
* Recommended. Specifies what method was used to encode a 'code_verifier'
|
||||
* that will be used during authorization code exchange. This parameter must
|
||||
* be used with the 'code_challenge' parameter. The value of the
|
||||
* 'code_challenge_method' defaults to "plain" if not present in the request
|
||||
* that includes a 'code_challenge'. The only supported values for this
|
||||
* parameter are "S256" or "plain".
|
||||
*/
|
||||
code_challenge_method?: CodeChallengeMethod;
|
||||
/**
|
||||
* Recommended. Specifies an encoded 'code_verifier' that will be used as a
|
||||
* server-side challenge during authorization code exchange. This parameter
|
||||
* must be used with the 'code_challenge' parameter described above.
|
||||
*/
|
||||
code_challenge?: string;
|
||||
/**
|
||||
* A way for developers and/or the auth team to provide a set of key value
|
||||
* pairs to be added as query parameters to the authorization url.
|
||||
*/
|
||||
[key: string]: querystring.ParsedUrlQueryInput[keyof querystring.ParsedUrlQueryInput];
|
||||
}
|
||||
export interface AccessTokenResponse {
|
||||
access_token: string;
|
||||
expiry_date: number;
|
||||
}
|
||||
export interface GetRefreshHandlerCallback {
|
||||
(): Promise<AccessTokenResponse>;
|
||||
}
|
||||
export interface GetTokenCallback {
|
||||
(err: GaxiosError | null, token?: Credentials | null, res?: GaxiosResponse | null): void;
|
||||
}
|
||||
export interface GetTokenResponse {
|
||||
tokens: Credentials;
|
||||
res: GaxiosResponse | null;
|
||||
}
|
||||
export interface GetAccessTokenCallback {
|
||||
(err: GaxiosError | null, token?: string | null, res?: GaxiosResponse | null): void;
|
||||
}
|
||||
export interface RefreshAccessTokenCallback {
|
||||
(err: GaxiosError | null, credentials?: Credentials | null, res?: GaxiosResponse | null): void;
|
||||
}
|
||||
export interface RefreshAccessTokenResponse {
|
||||
credentials: Credentials;
|
||||
res: GaxiosResponse | null;
|
||||
}
|
||||
export interface RequestMetadataResponse {
|
||||
headers: Headers;
|
||||
res?: GaxiosResponse<void> | null;
|
||||
}
|
||||
export interface RequestMetadataCallback {
|
||||
(err: GaxiosError | null, headers?: Headers, res?: GaxiosResponse<void> | null): void;
|
||||
}
|
||||
export interface GetFederatedSignonCertsCallback {
|
||||
(err: GaxiosError | null, certs?: Certificates, response?: GaxiosResponse<void> | null): void;
|
||||
}
|
||||
export interface FederatedSignonCertsResponse {
|
||||
certs: Certificates;
|
||||
format: CertificateFormat;
|
||||
res?: GaxiosResponse<void> | null;
|
||||
}
|
||||
export interface GetIapPublicKeysCallback {
|
||||
(err: GaxiosError | null, pubkeys?: PublicKeys, response?: GaxiosResponse<void> | null): void;
|
||||
}
|
||||
export interface IapPublicKeysResponse {
|
||||
pubkeys: PublicKeys;
|
||||
res?: GaxiosResponse<void> | null;
|
||||
}
|
||||
export interface RevokeCredentialsResult {
|
||||
success: boolean;
|
||||
}
|
||||
export interface VerifyIdTokenOptions {
|
||||
idToken: string;
|
||||
audience?: string | string[];
|
||||
maxExpiry?: number;
|
||||
}
|
||||
export interface OAuth2ClientEndpoints {
|
||||
/**
|
||||
* The endpoint for viewing access token information
|
||||
*
|
||||
* @example
|
||||
* 'https://oauth2.googleapis.com/tokeninfo'
|
||||
*/
|
||||
tokenInfoUrl: string | URL;
|
||||
/**
|
||||
* The base URL for auth endpoints.
|
||||
*
|
||||
* @example
|
||||
* 'https://accounts.google.com/o/oauth2/v2/auth'
|
||||
*/
|
||||
oauth2AuthBaseUrl: string | URL;
|
||||
/**
|
||||
* The base endpoint for token retrieval
|
||||
* .
|
||||
* @example
|
||||
* 'https://oauth2.googleapis.com/token'
|
||||
*/
|
||||
oauth2TokenUrl: string | URL;
|
||||
/**
|
||||
* The base endpoint to revoke tokens.
|
||||
*
|
||||
* @example
|
||||
* 'https://oauth2.googleapis.com/revoke'
|
||||
*/
|
||||
oauth2RevokeUrl: string | URL;
|
||||
/**
|
||||
* Sign on certificates in PEM format.
|
||||
*
|
||||
* @example
|
||||
* 'https://www.googleapis.com/oauth2/v1/certs'
|
||||
*/
|
||||
oauth2FederatedSignonPemCertsUrl: string | URL;
|
||||
/**
|
||||
* Sign on certificates in JWK format.
|
||||
*
|
||||
* @example
|
||||
* 'https://www.googleapis.com/oauth2/v3/certs'
|
||||
*/
|
||||
oauth2FederatedSignonJwkCertsUrl: string | URL;
|
||||
/**
|
||||
* IAP Public Key URL.
|
||||
* This URL contains a JSON dictionary that maps the `kid` claims to the public key values.
|
||||
*
|
||||
* @example
|
||||
* 'https://www.gstatic.com/iap/verify/public_key'
|
||||
*/
|
||||
oauth2IapPublicKeyUrl: string | URL;
|
||||
}
|
||||
/**
|
||||
* A convenient interface for those looking to pass the OAuth2 Client config via a parsed
|
||||
* JSON file.
|
||||
*/
|
||||
interface OAuth2JSONOptions {
|
||||
/**
|
||||
* The authentication client ID.
|
||||
*
|
||||
* @alias {@link OAuth2ClientOptions.clientId}
|
||||
*/
|
||||
client_id?: string;
|
||||
/**
|
||||
* The authentication client secret.
|
||||
*
|
||||
* @alias {@link OAuth2ClientOptions.clientSecret}
|
||||
*/
|
||||
client_secret?: string;
|
||||
/**
|
||||
* The URIs to redirect to after completing the auth request.
|
||||
*
|
||||
* @alias {@link OAuth2ClientOptions.redirectUri}
|
||||
*/
|
||||
redirect_uris?: string[];
|
||||
}
|
||||
export interface OAuth2ClientOptions extends AuthClientOptions, OAuth2JSONOptions {
|
||||
/**
|
||||
* The authentication client ID.
|
||||
*
|
||||
* @alias {@link OAuth2JSONOptions.client_id}
|
||||
*/
|
||||
clientId?: string;
|
||||
/**
|
||||
* The authentication client secret.
|
||||
*
|
||||
* @alias {@link OAuth2JSONOptions.client_secret}
|
||||
*/
|
||||
clientSecret?: string;
|
||||
/**
|
||||
* The URI to redirect to after completing the auth request.
|
||||
*
|
||||
* @alias {@link OAuth2JSONOptions.redirect_uris}
|
||||
*/
|
||||
redirectUri?: string;
|
||||
/**
|
||||
* Customizable endpoints.
|
||||
*/
|
||||
endpoints?: Partial<OAuth2ClientEndpoints>;
|
||||
/**
|
||||
* The allowed OAuth2 token issuers.
|
||||
*/
|
||||
issuers?: string[];
|
||||
/**
|
||||
* The client authentication type. Supported values are basic, post, and none.
|
||||
* Defaults to post if not provided.
|
||||
* https://datatracker.ietf.org/doc/html/rfc7591#section-2
|
||||
*/
|
||||
clientAuthentication?: ClientAuthentication;
|
||||
}
|
||||
export type RefreshOptions = Pick<AuthClientOptions, 'eagerRefreshThresholdMillis' | 'forceRefreshOnFailure'>;
|
||||
export declare class OAuth2Client extends AuthClient {
|
||||
private redirectUri?;
|
||||
private certificateCache;
|
||||
private certificateExpiry;
|
||||
private certificateCacheFormat;
|
||||
protected refreshTokenPromises: Map<string, Promise<GetTokenResponse>>;
|
||||
readonly endpoints: Readonly<OAuth2ClientEndpoints>;
|
||||
readonly issuers: string[];
|
||||
readonly clientAuthentication: ClientAuthentication;
|
||||
_clientId?: string;
|
||||
_clientSecret?: string;
|
||||
refreshHandler?: GetRefreshHandlerCallback;
|
||||
/**
|
||||
* An OAuth2 Client for Google APIs.
|
||||
*
|
||||
* @param options The OAuth2 Client Options. Passing an `clientId` directly is **@DEPRECATED**.
|
||||
* @param clientSecret **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead.
|
||||
* @param redirectUri **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead.
|
||||
*/
|
||||
constructor(options?: OAuth2ClientOptions | OAuth2ClientOptions['clientId'],
|
||||
/**
|
||||
* @deprecated - provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead
|
||||
*/
|
||||
clientSecret?: OAuth2ClientOptions['clientSecret'],
|
||||
/**
|
||||
* @deprecated - provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead
|
||||
*/
|
||||
redirectUri?: OAuth2ClientOptions['redirectUri']);
|
||||
/**
|
||||
* @deprecated use instance's {@link OAuth2Client.endpoints}
|
||||
*/
|
||||
protected static readonly GOOGLE_TOKEN_INFO_URL = "https://oauth2.googleapis.com/tokeninfo";
|
||||
/**
|
||||
* Clock skew - five minutes in seconds
|
||||
*/
|
||||
private static readonly CLOCK_SKEW_SECS_;
|
||||
/**
|
||||
* The default max Token Lifetime is one day in seconds
|
||||
*/
|
||||
private static readonly DEFAULT_MAX_TOKEN_LIFETIME_SECS_;
|
||||
/**
|
||||
* Generates URL for consent page landing.
|
||||
* @param opts Options.
|
||||
* @return URL to consent page.
|
||||
*/
|
||||
generateAuthUrl(opts?: GenerateAuthUrlOpts): string;
|
||||
generateCodeVerifier(): void;
|
||||
/**
|
||||
* Convenience method to automatically generate a code_verifier, and its
|
||||
* resulting SHA256. If used, this must be paired with a S256
|
||||
* code_challenge_method.
|
||||
*
|
||||
* For a full example see:
|
||||
* https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js
|
||||
*/
|
||||
generateCodeVerifierAsync(): Promise<CodeVerifierResults>;
|
||||
/**
|
||||
* Gets the access token for the given code.
|
||||
* @param code The authorization code.
|
||||
* @param callback Optional callback fn.
|
||||
*/
|
||||
getToken(code: string): Promise<GetTokenResponse>;
|
||||
getToken(options: GetTokenOptions): Promise<GetTokenResponse>;
|
||||
getToken(code: string, callback: GetTokenCallback): void;
|
||||
getToken(options: GetTokenOptions, callback: GetTokenCallback): void;
|
||||
private getTokenAsync;
|
||||
/**
|
||||
* Refreshes the access token.
|
||||
* @param refresh_token Existing refresh token.
|
||||
* @private
|
||||
*/
|
||||
protected refreshToken(refreshToken?: string | null): Promise<GetTokenResponse>;
|
||||
protected refreshTokenNoCache(refreshToken?: string | null): Promise<GetTokenResponse>;
|
||||
/**
|
||||
* Retrieves the access token using refresh token
|
||||
*
|
||||
* @param callback callback
|
||||
*/
|
||||
refreshAccessToken(): Promise<RefreshAccessTokenResponse>;
|
||||
refreshAccessToken(callback: RefreshAccessTokenCallback): void;
|
||||
private refreshAccessTokenAsync;
|
||||
/**
|
||||
* Get a non-expired access token, after refreshing if necessary
|
||||
*
|
||||
* @param callback Callback to call with the access token
|
||||
*/
|
||||
getAccessToken(): Promise<GetAccessTokenResponse>;
|
||||
getAccessToken(callback: GetAccessTokenCallback): void;
|
||||
private getAccessTokenAsync;
|
||||
/**
|
||||
* The main authentication interface. It takes an optional url which when
|
||||
* present is the endpoint being accessed, and returns a Promise which
|
||||
* resolves with authorization header fields.
|
||||
*
|
||||
* In OAuth2Client, the result has the form:
|
||||
* { authorization: 'Bearer <access_token_value>' }
|
||||
*/
|
||||
getRequestHeaders(url?: string | URL): Promise<Headers>;
|
||||
protected getRequestMetadataAsync(url?: string | URL | null): Promise<RequestMetadataResponse>;
|
||||
/**
|
||||
* Generates an URL to revoke the given token.
|
||||
* @param token The existing token to be revoked.
|
||||
*
|
||||
* @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL}
|
||||
*/
|
||||
static getRevokeTokenUrl(token: string): string;
|
||||
/**
|
||||
* Generates a URL to revoke the given token.
|
||||
*
|
||||
* @param token The existing token to be revoked.
|
||||
*/
|
||||
getRevokeTokenURL(token: string): URL;
|
||||
/**
|
||||
* Revokes the access given to token.
|
||||
* @param token The existing token to be revoked.
|
||||
* @param callback Optional callback fn.
|
||||
*/
|
||||
revokeToken(token: string): GaxiosPromise<RevokeCredentialsResult>;
|
||||
revokeToken(token: string, callback: BodyResponseCallback<RevokeCredentialsResult>): void;
|
||||
/**
|
||||
* Revokes access token and clears the credentials object
|
||||
* @param callback callback
|
||||
*/
|
||||
revokeCredentials(): GaxiosPromise<RevokeCredentialsResult>;
|
||||
revokeCredentials(callback: BodyResponseCallback<RevokeCredentialsResult>): void;
|
||||
private revokeCredentialsAsync;
|
||||
/**
|
||||
* Provides a request implementation with OAuth 2.0 flow. If credentials have
|
||||
* a refresh_token, in cases of HTTP 401 and 403 responses, it automatically
|
||||
* asks for a new access token and replays the unsuccessful request.
|
||||
* @param opts Request options.
|
||||
* @param callback callback.
|
||||
* @return Request object
|
||||
*/
|
||||
request<T>(opts: GaxiosOptions): GaxiosPromise<T>;
|
||||
request<T>(opts: GaxiosOptions, callback: BodyResponseCallback<T>): void;
|
||||
protected requestAsync<T>(opts: GaxiosOptions, reAuthRetried?: boolean): Promise<GaxiosResponse<T>>;
|
||||
/**
|
||||
* Verify id token is token by checking the certs and audience
|
||||
* @param options that contains all options.
|
||||
* @param callback Callback supplying GoogleLogin if successful
|
||||
*/
|
||||
verifyIdToken(options: VerifyIdTokenOptions): Promise<LoginTicket>;
|
||||
verifyIdToken(options: VerifyIdTokenOptions, callback: (err: Error | null, login?: LoginTicket) => void): void;
|
||||
private verifyIdTokenAsync;
|
||||
/**
|
||||
* Obtains information about the provisioned access token. Especially useful
|
||||
* if you want to check the scopes that were provisioned to a given token.
|
||||
*
|
||||
* @param accessToken Required. The Access Token for which you want to get
|
||||
* user info.
|
||||
*/
|
||||
getTokenInfo(accessToken: string): Promise<TokenInfo>;
|
||||
/**
|
||||
* Gets federated sign-on certificates to use for verifying identity tokens.
|
||||
* Returns certs as array structure, where keys are key ids, and values
|
||||
* are certificates in either PEM or JWK format.
|
||||
* @param callback Callback supplying the certificates
|
||||
*/
|
||||
getFederatedSignonCerts(): Promise<FederatedSignonCertsResponse>;
|
||||
getFederatedSignonCerts(callback: GetFederatedSignonCertsCallback): void;
|
||||
getFederatedSignonCertsAsync(): Promise<FederatedSignonCertsResponse>;
|
||||
/**
|
||||
* Gets federated sign-on certificates to use for verifying identity tokens.
|
||||
* Returns certs as array structure, where keys are key ids, and values
|
||||
* are certificates in either PEM or JWK format.
|
||||
* @param callback Callback supplying the certificates
|
||||
*/
|
||||
getIapPublicKeys(): Promise<IapPublicKeysResponse>;
|
||||
getIapPublicKeys(callback: GetIapPublicKeysCallback): void;
|
||||
getIapPublicKeysAsync(): Promise<IapPublicKeysResponse>;
|
||||
verifySignedJwtWithCerts(): void;
|
||||
/**
|
||||
* Verify the id token is signed with the correct certificate
|
||||
* and is from the correct audience.
|
||||
* @param jwt The jwt to verify (The ID Token in this case).
|
||||
* @param certs The array of certs to test the jwt against.
|
||||
* @param requiredAudience The audience to test the jwt against.
|
||||
* @param issuers The allowed issuers of the jwt (Optional).
|
||||
* @param maxExpiry The max expiry the certificate can be (Optional).
|
||||
* @return Returns a promise resolving to LoginTicket on verification.
|
||||
*/
|
||||
verifySignedJwtWithCertsAsync(jwt: string, certs: Certificates | PublicKeys, requiredAudience?: string | string[], issuers?: string[], maxExpiry?: number): Promise<LoginTicket>;
|
||||
/**
|
||||
* Returns a promise that resolves with AccessTokenResponse type if
|
||||
* refreshHandler is defined.
|
||||
* If not, nothing is returned.
|
||||
*/
|
||||
private processAndValidateRefreshHandler;
|
||||
/**
|
||||
* Returns true if a token is expired or will expire within
|
||||
* eagerRefreshThresholdMillismilliseconds.
|
||||
* If there is no expiry time, assumes the token is not expired or expiring.
|
||||
*/
|
||||
protected isTokenExpiring(): boolean;
|
||||
}
|
||||
export {};
|
||||
820
node_modules/google-auth-library/build/src/auth/oauth2client.js
generated
vendored
Normal file
820
node_modules/google-auth-library/build/src/auth/oauth2client.js
generated
vendored
Normal file
@@ -0,0 +1,820 @@
|
||||
"use strict";
|
||||
// Copyright 2019 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.OAuth2Client = exports.ClientAuthentication = exports.CertificateFormat = exports.CodeChallengeMethod = void 0;
|
||||
const gaxios_1 = require("gaxios");
|
||||
const querystring = require("querystring");
|
||||
const stream = require("stream");
|
||||
const formatEcdsa = require("ecdsa-sig-formatter");
|
||||
const util_1 = require("../util");
|
||||
const crypto_1 = require("../crypto/crypto");
|
||||
const authclient_1 = require("./authclient");
|
||||
const loginticket_1 = require("./loginticket");
|
||||
var CodeChallengeMethod;
|
||||
(function (CodeChallengeMethod) {
|
||||
CodeChallengeMethod["Plain"] = "plain";
|
||||
CodeChallengeMethod["S256"] = "S256";
|
||||
})(CodeChallengeMethod || (exports.CodeChallengeMethod = CodeChallengeMethod = {}));
|
||||
var CertificateFormat;
|
||||
(function (CertificateFormat) {
|
||||
CertificateFormat["PEM"] = "PEM";
|
||||
CertificateFormat["JWK"] = "JWK";
|
||||
})(CertificateFormat || (exports.CertificateFormat = CertificateFormat = {}));
|
||||
/**
|
||||
* The client authentication type. Supported values are basic, post, and none.
|
||||
* https://datatracker.ietf.org/doc/html/rfc7591#section-2
|
||||
*/
|
||||
var ClientAuthentication;
|
||||
(function (ClientAuthentication) {
|
||||
ClientAuthentication["ClientSecretPost"] = "ClientSecretPost";
|
||||
ClientAuthentication["ClientSecretBasic"] = "ClientSecretBasic";
|
||||
ClientAuthentication["None"] = "None";
|
||||
})(ClientAuthentication || (exports.ClientAuthentication = ClientAuthentication = {}));
|
||||
class OAuth2Client extends authclient_1.AuthClient {
|
||||
redirectUri;
|
||||
certificateCache = {};
|
||||
certificateExpiry = null;
|
||||
certificateCacheFormat = CertificateFormat.PEM;
|
||||
refreshTokenPromises = new Map();
|
||||
endpoints;
|
||||
issuers;
|
||||
clientAuthentication;
|
||||
// TODO: refactor tests to make this private
|
||||
_clientId;
|
||||
// TODO: refactor tests to make this private
|
||||
_clientSecret;
|
||||
refreshHandler;
|
||||
/**
|
||||
* An OAuth2 Client for Google APIs.
|
||||
*
|
||||
* @param options The OAuth2 Client Options. Passing an `clientId` directly is **@DEPRECATED**.
|
||||
* @param clientSecret **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead.
|
||||
* @param redirectUri **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead.
|
||||
*/
|
||||
constructor(options = {},
|
||||
/**
|
||||
* @deprecated - provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead
|
||||
*/
|
||||
clientSecret,
|
||||
/**
|
||||
* @deprecated - provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead
|
||||
*/
|
||||
redirectUri) {
|
||||
super(typeof options === 'object' ? options : {});
|
||||
if (typeof options !== 'object') {
|
||||
options = {
|
||||
clientId: options,
|
||||
clientSecret,
|
||||
redirectUri,
|
||||
};
|
||||
}
|
||||
this._clientId = options.clientId || options.client_id;
|
||||
this._clientSecret = options.clientSecret || options.client_secret;
|
||||
this.redirectUri = options.redirectUri || options.redirect_uris?.[0];
|
||||
this.endpoints = {
|
||||
tokenInfoUrl: 'https://oauth2.googleapis.com/tokeninfo',
|
||||
oauth2AuthBaseUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
|
||||
oauth2TokenUrl: 'https://oauth2.googleapis.com/token',
|
||||
oauth2RevokeUrl: 'https://oauth2.googleapis.com/revoke',
|
||||
oauth2FederatedSignonPemCertsUrl: 'https://www.googleapis.com/oauth2/v1/certs',
|
||||
oauth2FederatedSignonJwkCertsUrl: 'https://www.googleapis.com/oauth2/v3/certs',
|
||||
oauth2IapPublicKeyUrl: 'https://www.gstatic.com/iap/verify/public_key',
|
||||
...options.endpoints,
|
||||
};
|
||||
this.clientAuthentication =
|
||||
options.clientAuthentication || ClientAuthentication.ClientSecretPost;
|
||||
this.issuers = options.issuers || [
|
||||
'accounts.google.com',
|
||||
'https://accounts.google.com',
|
||||
this.universeDomain,
|
||||
];
|
||||
}
|
||||
/**
|
||||
* @deprecated use instance's {@link OAuth2Client.endpoints}
|
||||
*/
|
||||
static GOOGLE_TOKEN_INFO_URL = 'https://oauth2.googleapis.com/tokeninfo';
|
||||
/**
|
||||
* Clock skew - five minutes in seconds
|
||||
*/
|
||||
static CLOCK_SKEW_SECS_ = 300;
|
||||
/**
|
||||
* The default max Token Lifetime is one day in seconds
|
||||
*/
|
||||
static DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400;
|
||||
/**
|
||||
* Generates URL for consent page landing.
|
||||
* @param opts Options.
|
||||
* @return URL to consent page.
|
||||
*/
|
||||
generateAuthUrl(opts = {}) {
|
||||
if (opts.code_challenge_method && !opts.code_challenge) {
|
||||
throw new Error('If a code_challenge_method is provided, code_challenge must be included.');
|
||||
}
|
||||
opts.response_type = opts.response_type || 'code';
|
||||
opts.client_id = opts.client_id || this._clientId;
|
||||
opts.redirect_uri = opts.redirect_uri || this.redirectUri;
|
||||
// Allow scopes to be passed either as array or a string
|
||||
if (Array.isArray(opts.scope)) {
|
||||
opts.scope = opts.scope.join(' ');
|
||||
}
|
||||
const rootUrl = this.endpoints.oauth2AuthBaseUrl.toString();
|
||||
return (rootUrl +
|
||||
'?' +
|
||||
querystring.stringify(opts));
|
||||
}
|
||||
generateCodeVerifier() {
|
||||
// To make the code compatible with browser SubtleCrypto we need to make
|
||||
// this method async.
|
||||
throw new Error('generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.');
|
||||
}
|
||||
/**
|
||||
* Convenience method to automatically generate a code_verifier, and its
|
||||
* resulting SHA256. If used, this must be paired with a S256
|
||||
* code_challenge_method.
|
||||
*
|
||||
* For a full example see:
|
||||
* https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js
|
||||
*/
|
||||
async generateCodeVerifierAsync() {
|
||||
// base64 encoding uses 6 bits per character, and we want to generate128
|
||||
// characters. 6*128/8 = 96.
|
||||
const crypto = (0, crypto_1.createCrypto)();
|
||||
const randomString = crypto.randomBytesBase64(96);
|
||||
// The valid characters in the code_verifier are [A-Z]/[a-z]/[0-9]/
|
||||
// "-"/"."/"_"/"~". Base64 encoded strings are pretty close, so we're just
|
||||
// swapping out a few chars.
|
||||
const codeVerifier = randomString
|
||||
.replace(/\+/g, '~')
|
||||
.replace(/=/g, '_')
|
||||
.replace(/\//g, '-');
|
||||
// Generate the base64 encoded SHA256
|
||||
const unencodedCodeChallenge = await crypto.sha256DigestBase64(codeVerifier);
|
||||
// We need to use base64UrlEncoding instead of standard base64
|
||||
const codeChallenge = unencodedCodeChallenge
|
||||
.split('=')[0]
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_');
|
||||
return { codeVerifier, codeChallenge };
|
||||
}
|
||||
getToken(codeOrOptions, callback) {
|
||||
const options = typeof codeOrOptions === 'string' ? { code: codeOrOptions } : codeOrOptions;
|
||||
if (callback) {
|
||||
this.getTokenAsync(options).then(r => callback(null, r.tokens, r.res), e => callback(e, null, e.response));
|
||||
}
|
||||
else {
|
||||
return this.getTokenAsync(options);
|
||||
}
|
||||
}
|
||||
async getTokenAsync(options) {
|
||||
const url = this.endpoints.oauth2TokenUrl.toString();
|
||||
const headers = new Headers();
|
||||
const values = {
|
||||
client_id: options.client_id || this._clientId,
|
||||
code_verifier: options.codeVerifier,
|
||||
code: options.code,
|
||||
grant_type: 'authorization_code',
|
||||
redirect_uri: options.redirect_uri || this.redirectUri,
|
||||
};
|
||||
if (this.clientAuthentication === ClientAuthentication.ClientSecretBasic) {
|
||||
const basic = Buffer.from(`${this._clientId}:${this._clientSecret}`);
|
||||
headers.set('authorization', `Basic ${basic.toString('base64')}`);
|
||||
}
|
||||
if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) {
|
||||
values.client_secret = this._clientSecret;
|
||||
}
|
||||
const opts = {
|
||||
...OAuth2Client.RETRY_CONFIG,
|
||||
method: 'POST',
|
||||
url,
|
||||
data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)),
|
||||
headers,
|
||||
};
|
||||
authclient_1.AuthClient.setMethodName(opts, 'getTokenAsync');
|
||||
const res = await this.transporter.request(opts);
|
||||
const tokens = res.data;
|
||||
if (res.data && res.data.expires_in) {
|
||||
tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;
|
||||
delete tokens.expires_in;
|
||||
}
|
||||
this.emit('tokens', tokens);
|
||||
return { tokens, res };
|
||||
}
|
||||
/**
|
||||
* Refreshes the access token.
|
||||
* @param refresh_token Existing refresh token.
|
||||
* @private
|
||||
*/
|
||||
async refreshToken(refreshToken) {
|
||||
if (!refreshToken) {
|
||||
return this.refreshTokenNoCache(refreshToken);
|
||||
}
|
||||
// If a request to refresh using the same token has started,
|
||||
// return the same promise.
|
||||
if (this.refreshTokenPromises.has(refreshToken)) {
|
||||
return this.refreshTokenPromises.get(refreshToken);
|
||||
}
|
||||
const p = this.refreshTokenNoCache(refreshToken).then(r => {
|
||||
this.refreshTokenPromises.delete(refreshToken);
|
||||
return r;
|
||||
}, e => {
|
||||
this.refreshTokenPromises.delete(refreshToken);
|
||||
throw e;
|
||||
});
|
||||
this.refreshTokenPromises.set(refreshToken, p);
|
||||
return p;
|
||||
}
|
||||
async refreshTokenNoCache(refreshToken) {
|
||||
if (!refreshToken) {
|
||||
throw new Error('No refresh token is set.');
|
||||
}
|
||||
const url = this.endpoints.oauth2TokenUrl.toString();
|
||||
const data = {
|
||||
refresh_token: refreshToken,
|
||||
client_id: this._clientId,
|
||||
client_secret: this._clientSecret,
|
||||
grant_type: 'refresh_token',
|
||||
};
|
||||
let res;
|
||||
try {
|
||||
const opts = {
|
||||
...OAuth2Client.RETRY_CONFIG,
|
||||
method: 'POST',
|
||||
url,
|
||||
data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(data)),
|
||||
};
|
||||
authclient_1.AuthClient.setMethodName(opts, 'refreshTokenNoCache');
|
||||
// request for new token
|
||||
res = await this.transporter.request(opts);
|
||||
}
|
||||
catch (e) {
|
||||
if (e instanceof gaxios_1.GaxiosError &&
|
||||
e.message === 'invalid_grant' &&
|
||||
e.response?.data &&
|
||||
/ReAuth/i.test(e.response.data.error_description)) {
|
||||
e.message = JSON.stringify(e.response.data);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
const tokens = res.data;
|
||||
// TODO: de-duplicate this code from a few spots
|
||||
if (res.data && res.data.expires_in) {
|
||||
tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;
|
||||
delete tokens.expires_in;
|
||||
}
|
||||
this.emit('tokens', tokens);
|
||||
return { tokens, res };
|
||||
}
|
||||
refreshAccessToken(callback) {
|
||||
if (callback) {
|
||||
this.refreshAccessTokenAsync().then(r => callback(null, r.credentials, r.res), callback);
|
||||
}
|
||||
else {
|
||||
return this.refreshAccessTokenAsync();
|
||||
}
|
||||
}
|
||||
async refreshAccessTokenAsync() {
|
||||
const r = await this.refreshToken(this.credentials.refresh_token);
|
||||
const tokens = r.tokens;
|
||||
tokens.refresh_token = this.credentials.refresh_token;
|
||||
this.credentials = tokens;
|
||||
return { credentials: this.credentials, res: r.res };
|
||||
}
|
||||
getAccessToken(callback) {
|
||||
if (callback) {
|
||||
this.getAccessTokenAsync().then(r => callback(null, r.token, r.res), callback);
|
||||
}
|
||||
else {
|
||||
return this.getAccessTokenAsync();
|
||||
}
|
||||
}
|
||||
async getAccessTokenAsync() {
|
||||
const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring();
|
||||
if (shouldRefresh) {
|
||||
if (!this.credentials.refresh_token) {
|
||||
if (this.refreshHandler) {
|
||||
const refreshedAccessToken = await this.processAndValidateRefreshHandler();
|
||||
if (refreshedAccessToken?.access_token) {
|
||||
this.setCredentials(refreshedAccessToken);
|
||||
return { token: this.credentials.access_token };
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw new Error('No refresh token or refresh handler callback is set.');
|
||||
}
|
||||
}
|
||||
const r = await this.refreshAccessTokenAsync();
|
||||
if (!r.credentials || (r.credentials && !r.credentials.access_token)) {
|
||||
throw new Error('Could not refresh access token.');
|
||||
}
|
||||
return { token: r.credentials.access_token, res: r.res };
|
||||
}
|
||||
else {
|
||||
return { token: this.credentials.access_token };
|
||||
}
|
||||
}
|
||||
/**
|
||||
* The main authentication interface. It takes an optional url which when
|
||||
* present is the endpoint being accessed, and returns a Promise which
|
||||
* resolves with authorization header fields.
|
||||
*
|
||||
* In OAuth2Client, the result has the form:
|
||||
* { authorization: 'Bearer <access_token_value>' }
|
||||
*/
|
||||
async getRequestHeaders(url) {
|
||||
const headers = (await this.getRequestMetadataAsync(url)).headers;
|
||||
return headers;
|
||||
}
|
||||
async getRequestMetadataAsync(url) {
|
||||
url;
|
||||
const thisCreds = this.credentials;
|
||||
if (!thisCreds.access_token &&
|
||||
!thisCreds.refresh_token &&
|
||||
!this.apiKey &&
|
||||
!this.refreshHandler) {
|
||||
throw new Error('No access, refresh token, API key or refresh handler callback is set.');
|
||||
}
|
||||
if (thisCreds.access_token && !this.isTokenExpiring()) {
|
||||
thisCreds.token_type = thisCreds.token_type || 'Bearer';
|
||||
const headers = new Headers({
|
||||
authorization: thisCreds.token_type + ' ' + thisCreds.access_token,
|
||||
});
|
||||
return { headers: this.addSharedMetadataHeaders(headers) };
|
||||
}
|
||||
// If refreshHandler exists, call processAndValidateRefreshHandler().
|
||||
if (this.refreshHandler) {
|
||||
const refreshedAccessToken = await this.processAndValidateRefreshHandler();
|
||||
if (refreshedAccessToken?.access_token) {
|
||||
this.setCredentials(refreshedAccessToken);
|
||||
const headers = new Headers({
|
||||
authorization: 'Bearer ' + this.credentials.access_token,
|
||||
});
|
||||
return { headers: this.addSharedMetadataHeaders(headers) };
|
||||
}
|
||||
}
|
||||
if (this.apiKey) {
|
||||
return { headers: new Headers({ 'X-Goog-Api-Key': this.apiKey }) };
|
||||
}
|
||||
let r = null;
|
||||
let tokens = null;
|
||||
try {
|
||||
r = await this.refreshToken(thisCreds.refresh_token);
|
||||
tokens = r.tokens;
|
||||
}
|
||||
catch (err) {
|
||||
const e = err;
|
||||
if (e.response &&
|
||||
(e.response.status === 403 || e.response.status === 404)) {
|
||||
e.message = `Could not refresh access token: ${e.message}`;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
const credentials = this.credentials;
|
||||
credentials.token_type = credentials.token_type || 'Bearer';
|
||||
tokens.refresh_token = credentials.refresh_token;
|
||||
this.credentials = tokens;
|
||||
const headers = new Headers({
|
||||
authorization: credentials.token_type + ' ' + tokens.access_token,
|
||||
});
|
||||
return { headers: this.addSharedMetadataHeaders(headers), res: r.res };
|
||||
}
|
||||
/**
|
||||
* Generates an URL to revoke the given token.
|
||||
* @param token The existing token to be revoked.
|
||||
*
|
||||
* @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL}
|
||||
*/
|
||||
static getRevokeTokenUrl(token) {
|
||||
return new OAuth2Client().getRevokeTokenURL(token).toString();
|
||||
}
|
||||
/**
|
||||
* Generates a URL to revoke the given token.
|
||||
*
|
||||
* @param token The existing token to be revoked.
|
||||
*/
|
||||
getRevokeTokenURL(token) {
|
||||
const url = new URL(this.endpoints.oauth2RevokeUrl);
|
||||
url.searchParams.append('token', token);
|
||||
return url;
|
||||
}
|
||||
revokeToken(token, callback) {
|
||||
const opts = {
|
||||
...OAuth2Client.RETRY_CONFIG,
|
||||
url: this.getRevokeTokenURL(token).toString(),
|
||||
method: 'POST',
|
||||
};
|
||||
authclient_1.AuthClient.setMethodName(opts, 'revokeToken');
|
||||
if (callback) {
|
||||
this.transporter
|
||||
.request(opts)
|
||||
.then(r => callback(null, r), callback);
|
||||
}
|
||||
else {
|
||||
return this.transporter.request(opts);
|
||||
}
|
||||
}
|
||||
revokeCredentials(callback) {
|
||||
if (callback) {
|
||||
this.revokeCredentialsAsync().then(res => callback(null, res), callback);
|
||||
}
|
||||
else {
|
||||
return this.revokeCredentialsAsync();
|
||||
}
|
||||
}
|
||||
async revokeCredentialsAsync() {
|
||||
const token = this.credentials.access_token;
|
||||
this.credentials = {};
|
||||
if (token) {
|
||||
return this.revokeToken(token);
|
||||
}
|
||||
else {
|
||||
throw new Error('No access token to revoke.');
|
||||
}
|
||||
}
|
||||
request(opts, callback) {
|
||||
if (callback) {
|
||||
this.requestAsync(opts).then(r => callback(null, r), e => {
|
||||
return callback(e, e.response);
|
||||
});
|
||||
}
|
||||
else {
|
||||
return this.requestAsync(opts);
|
||||
}
|
||||
}
|
||||
async requestAsync(opts, reAuthRetried = false) {
|
||||
try {
|
||||
const r = await this.getRequestMetadataAsync();
|
||||
opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);
|
||||
this.addUserProjectAndAuthHeaders(opts.headers, r.headers);
|
||||
if (this.apiKey) {
|
||||
opts.headers.set('X-Goog-Api-Key', this.apiKey);
|
||||
}
|
||||
return await this.transporter.request(opts);
|
||||
}
|
||||
catch (e) {
|
||||
const res = e.response;
|
||||
if (res) {
|
||||
const statusCode = res.status;
|
||||
// Retry the request for metadata if the following criteria are true:
|
||||
// - We haven't already retried. It only makes sense to retry once.
|
||||
// - The response was a 401 or a 403
|
||||
// - The request didn't send a readableStream
|
||||
// - An access_token and refresh_token were available, but either no
|
||||
// expiry_date was available or the forceRefreshOnFailure flag is set.
|
||||
// The absent expiry_date case can happen when developers stash the
|
||||
// access_token and refresh_token for later use, but the access_token
|
||||
// fails on the first try because it's expired. Some developers may
|
||||
// choose to enable forceRefreshOnFailure to mitigate time-related
|
||||
// errors.
|
||||
// Or the following criteria are true:
|
||||
// - We haven't already retried. It only makes sense to retry once.
|
||||
// - The response was a 401 or a 403
|
||||
// - The request didn't send a readableStream
|
||||
// - No refresh_token was available
|
||||
// - An access_token and a refreshHandler callback were available, but
|
||||
// either no expiry_date was available or the forceRefreshOnFailure
|
||||
// flag is set. The access_token fails on the first try because it's
|
||||
// expired. Some developers may choose to enable forceRefreshOnFailure
|
||||
// to mitigate time-related errors.
|
||||
const mayRequireRefresh = this.credentials &&
|
||||
this.credentials.access_token &&
|
||||
this.credentials.refresh_token &&
|
||||
(!this.credentials.expiry_date || this.forceRefreshOnFailure);
|
||||
const mayRequireRefreshWithNoRefreshToken = this.credentials &&
|
||||
this.credentials.access_token &&
|
||||
!this.credentials.refresh_token &&
|
||||
(!this.credentials.expiry_date || this.forceRefreshOnFailure) &&
|
||||
this.refreshHandler;
|
||||
const isReadableStream = res.config.data instanceof stream.Readable;
|
||||
const isAuthErr = statusCode === 401 || statusCode === 403;
|
||||
if (!reAuthRetried &&
|
||||
isAuthErr &&
|
||||
!isReadableStream &&
|
||||
mayRequireRefresh) {
|
||||
await this.refreshAccessTokenAsync();
|
||||
return this.requestAsync(opts, true);
|
||||
}
|
||||
else if (!reAuthRetried &&
|
||||
isAuthErr &&
|
||||
!isReadableStream &&
|
||||
mayRequireRefreshWithNoRefreshToken) {
|
||||
const refreshedAccessToken = await this.processAndValidateRefreshHandler();
|
||||
if (refreshedAccessToken?.access_token) {
|
||||
this.setCredentials(refreshedAccessToken);
|
||||
}
|
||||
return this.requestAsync(opts, true);
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
verifyIdToken(options, callback) {
|
||||
// This function used to accept two arguments instead of an options object.
|
||||
// Check the types to help users upgrade with less pain.
|
||||
// This check can be removed after a 2.0 release.
|
||||
if (callback && typeof callback !== 'function') {
|
||||
throw new Error('This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.');
|
||||
}
|
||||
if (callback) {
|
||||
this.verifyIdTokenAsync(options).then(r => callback(null, r), callback);
|
||||
}
|
||||
else {
|
||||
return this.verifyIdTokenAsync(options);
|
||||
}
|
||||
}
|
||||
async verifyIdTokenAsync(options) {
|
||||
if (!options.idToken) {
|
||||
throw new Error('The verifyIdToken method requires an ID Token');
|
||||
}
|
||||
const response = await this.getFederatedSignonCertsAsync();
|
||||
const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, this.issuers, options.maxExpiry);
|
||||
return login;
|
||||
}
|
||||
/**
|
||||
* Obtains information about the provisioned access token. Especially useful
|
||||
* if you want to check the scopes that were provisioned to a given token.
|
||||
*
|
||||
* @param accessToken Required. The Access Token for which you want to get
|
||||
* user info.
|
||||
*/
|
||||
async getTokenInfo(accessToken) {
|
||||
const { data } = await this.transporter.request({
|
||||
...OAuth2Client.RETRY_CONFIG,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
|
||||
authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
url: this.endpoints.tokenInfoUrl.toString(),
|
||||
});
|
||||
const info = Object.assign({
|
||||
expiry_date: new Date().getTime() + data.expires_in * 1000,
|
||||
scopes: data.scope.split(' '),
|
||||
}, data);
|
||||
delete info.expires_in;
|
||||
delete info.scope;
|
||||
return info;
|
||||
}
|
||||
getFederatedSignonCerts(callback) {
|
||||
if (callback) {
|
||||
this.getFederatedSignonCertsAsync().then(r => callback(null, r.certs, r.res), callback);
|
||||
}
|
||||
else {
|
||||
return this.getFederatedSignonCertsAsync();
|
||||
}
|
||||
}
|
||||
async getFederatedSignonCertsAsync() {
|
||||
const nowTime = new Date().getTime();
|
||||
const format = (0, crypto_1.hasBrowserCrypto)()
|
||||
? CertificateFormat.JWK
|
||||
: CertificateFormat.PEM;
|
||||
if (this.certificateExpiry &&
|
||||
nowTime < this.certificateExpiry.getTime() &&
|
||||
this.certificateCacheFormat === format) {
|
||||
return { certs: this.certificateCache, format };
|
||||
}
|
||||
let res;
|
||||
let url;
|
||||
switch (format) {
|
||||
case CertificateFormat.PEM:
|
||||
url = this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();
|
||||
break;
|
||||
case CertificateFormat.JWK:
|
||||
url = this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Unsupported certificate format ${format}`);
|
||||
}
|
||||
try {
|
||||
const opts = {
|
||||
...OAuth2Client.RETRY_CONFIG,
|
||||
url,
|
||||
};
|
||||
authclient_1.AuthClient.setMethodName(opts, 'getFederatedSignonCertsAsync');
|
||||
res = await this.transporter.request(opts);
|
||||
}
|
||||
catch (e) {
|
||||
if (e instanceof Error) {
|
||||
e.message = `Failed to retrieve verification certificates: ${e.message}`;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
const cacheControl = res?.headers.get('cache-control');
|
||||
let cacheAge = -1;
|
||||
if (cacheControl) {
|
||||
const maxAge = /max-age=(?<maxAge>[0-9]+)/.exec(cacheControl)?.groups
|
||||
?.maxAge;
|
||||
if (maxAge) {
|
||||
// Cache results with max-age (in seconds)
|
||||
cacheAge = Number(maxAge) * 1000; // milliseconds
|
||||
}
|
||||
}
|
||||
let certificates = {};
|
||||
switch (format) {
|
||||
case CertificateFormat.PEM:
|
||||
certificates = res.data;
|
||||
break;
|
||||
case CertificateFormat.JWK:
|
||||
for (const key of res.data.keys) {
|
||||
certificates[key.kid] = key;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Unsupported certificate format ${format}`);
|
||||
}
|
||||
const now = new Date();
|
||||
this.certificateExpiry =
|
||||
cacheAge === -1 ? null : new Date(now.getTime() + cacheAge);
|
||||
this.certificateCache = certificates;
|
||||
this.certificateCacheFormat = format;
|
||||
return { certs: certificates, format, res };
|
||||
}
|
||||
getIapPublicKeys(callback) {
|
||||
if (callback) {
|
||||
this.getIapPublicKeysAsync().then(r => callback(null, r.pubkeys, r.res), callback);
|
||||
}
|
||||
else {
|
||||
return this.getIapPublicKeysAsync();
|
||||
}
|
||||
}
|
||||
async getIapPublicKeysAsync() {
|
||||
let res;
|
||||
const url = this.endpoints.oauth2IapPublicKeyUrl.toString();
|
||||
try {
|
||||
const opts = {
|
||||
...OAuth2Client.RETRY_CONFIG,
|
||||
url,
|
||||
};
|
||||
authclient_1.AuthClient.setMethodName(opts, 'getIapPublicKeysAsync');
|
||||
res = await this.transporter.request(opts);
|
||||
}
|
||||
catch (e) {
|
||||
if (e instanceof Error) {
|
||||
e.message = `Failed to retrieve verification certificates: ${e.message}`;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
return { pubkeys: res.data, res };
|
||||
}
|
||||
verifySignedJwtWithCerts() {
|
||||
// To make the code compatible with browser SubtleCrypto we need to make
|
||||
// this method async.
|
||||
throw new Error('verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.');
|
||||
}
|
||||
/**
|
||||
* Verify the id token is signed with the correct certificate
|
||||
* and is from the correct audience.
|
||||
* @param jwt The jwt to verify (The ID Token in this case).
|
||||
* @param certs The array of certs to test the jwt against.
|
||||
* @param requiredAudience The audience to test the jwt against.
|
||||
* @param issuers The allowed issuers of the jwt (Optional).
|
||||
* @param maxExpiry The max expiry the certificate can be (Optional).
|
||||
* @return Returns a promise resolving to LoginTicket on verification.
|
||||
*/
|
||||
async verifySignedJwtWithCertsAsync(jwt, certs, requiredAudience, issuers, maxExpiry) {
|
||||
const crypto = (0, crypto_1.createCrypto)();
|
||||
if (!maxExpiry) {
|
||||
maxExpiry = OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_;
|
||||
}
|
||||
const segments = jwt.split('.');
|
||||
if (segments.length !== 3) {
|
||||
throw new Error('Wrong number of segments in token: ' + jwt);
|
||||
}
|
||||
const signed = segments[0] + '.' + segments[1];
|
||||
let signature = segments[2];
|
||||
let envelope;
|
||||
let payload;
|
||||
try {
|
||||
envelope = JSON.parse(crypto.decodeBase64StringUtf8(segments[0]));
|
||||
}
|
||||
catch (err) {
|
||||
if (err instanceof Error) {
|
||||
err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
if (!envelope) {
|
||||
throw new Error("Can't parse token envelope: " + segments[0]);
|
||||
}
|
||||
try {
|
||||
payload = JSON.parse(crypto.decodeBase64StringUtf8(segments[1]));
|
||||
}
|
||||
catch (err) {
|
||||
if (err instanceof Error) {
|
||||
err.message = `Can't parse token payload '${segments[0]}`;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
if (!payload) {
|
||||
throw new Error("Can't parse token payload: " + segments[1]);
|
||||
}
|
||||
if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) {
|
||||
// If this is not present, then there's no reason to attempt verification
|
||||
throw new Error('No pem found for envelope: ' + JSON.stringify(envelope));
|
||||
}
|
||||
const cert = certs[envelope.kid];
|
||||
if (envelope.alg === 'ES256') {
|
||||
signature = formatEcdsa.joseToDer(signature, 'ES256').toString('base64');
|
||||
}
|
||||
const verified = await crypto.verify(cert, signed, signature);
|
||||
if (!verified) {
|
||||
throw new Error('Invalid token signature: ' + jwt);
|
||||
}
|
||||
if (!payload.iat) {
|
||||
throw new Error('No issue time in token: ' + JSON.stringify(payload));
|
||||
}
|
||||
if (!payload.exp) {
|
||||
throw new Error('No expiration time in token: ' + JSON.stringify(payload));
|
||||
}
|
||||
const iat = Number(payload.iat);
|
||||
if (isNaN(iat))
|
||||
throw new Error('iat field using invalid format');
|
||||
const exp = Number(payload.exp);
|
||||
if (isNaN(exp))
|
||||
throw new Error('exp field using invalid format');
|
||||
const now = new Date().getTime() / 1000;
|
||||
if (exp >= now + maxExpiry) {
|
||||
throw new Error('Expiration time too far in future: ' + JSON.stringify(payload));
|
||||
}
|
||||
const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_;
|
||||
const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_;
|
||||
if (now < earliest) {
|
||||
throw new Error('Token used too early, ' +
|
||||
now +
|
||||
' < ' +
|
||||
earliest +
|
||||
': ' +
|
||||
JSON.stringify(payload));
|
||||
}
|
||||
if (now > latest) {
|
||||
throw new Error('Token used too late, ' +
|
||||
now +
|
||||
' > ' +
|
||||
latest +
|
||||
': ' +
|
||||
JSON.stringify(payload));
|
||||
}
|
||||
if (issuers && issuers.indexOf(payload.iss) < 0) {
|
||||
throw new Error('Invalid issuer, expected one of [' +
|
||||
issuers +
|
||||
'], but got ' +
|
||||
payload.iss);
|
||||
}
|
||||
// Check the audience matches if we have one
|
||||
if (typeof requiredAudience !== 'undefined' && requiredAudience !== null) {
|
||||
const aud = payload.aud;
|
||||
let audVerified = false;
|
||||
// If the requiredAudience is an array, check if it contains token
|
||||
// audience
|
||||
if (requiredAudience.constructor === Array) {
|
||||
audVerified = requiredAudience.indexOf(aud) > -1;
|
||||
}
|
||||
else {
|
||||
audVerified = aud === requiredAudience;
|
||||
}
|
||||
if (!audVerified) {
|
||||
throw new Error('Wrong recipient, payload audience != requiredAudience');
|
||||
}
|
||||
}
|
||||
return new loginticket_1.LoginTicket(envelope, payload);
|
||||
}
|
||||
/**
|
||||
* Returns a promise that resolves with AccessTokenResponse type if
|
||||
* refreshHandler is defined.
|
||||
* If not, nothing is returned.
|
||||
*/
|
||||
async processAndValidateRefreshHandler() {
|
||||
if (this.refreshHandler) {
|
||||
const accessTokenResponse = await this.refreshHandler();
|
||||
if (!accessTokenResponse.access_token) {
|
||||
throw new Error('No access token is returned by the refreshHandler callback.');
|
||||
}
|
||||
return accessTokenResponse;
|
||||
}
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Returns true if a token is expired or will expire within
|
||||
* eagerRefreshThresholdMillismilliseconds.
|
||||
* If there is no expiry time, assumes the token is not expired or expiring.
|
||||
*/
|
||||
isTokenExpiring() {
|
||||
const expiryDate = this.credentials.expiry_date;
|
||||
return expiryDate
|
||||
? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis
|
||||
: false;
|
||||
}
|
||||
}
|
||||
exports.OAuth2Client = OAuth2Client;
|
||||
//# sourceMappingURL=oauth2client.js.map
|
||||
103
node_modules/google-auth-library/build/src/auth/oauth2common.d.ts
generated
vendored
Normal file
103
node_modules/google-auth-library/build/src/auth/oauth2common.d.ts
generated
vendored
Normal file
@@ -0,0 +1,103 @@
|
||||
import { Gaxios, GaxiosOptions } from 'gaxios';
|
||||
/**
|
||||
* OAuth error codes.
|
||||
* https://tools.ietf.org/html/rfc6749#section-5.2
|
||||
*/
|
||||
type OAuthErrorCode = 'invalid_request' | 'invalid_client' | 'invalid_grant' | 'unauthorized_client' | 'unsupported_grant_type' | 'invalid_scope' | string;
|
||||
/**
|
||||
* The standard OAuth error response.
|
||||
* https://tools.ietf.org/html/rfc6749#section-5.2
|
||||
*/
|
||||
export interface OAuthErrorResponse {
|
||||
error: OAuthErrorCode;
|
||||
error_description?: string;
|
||||
error_uri?: string;
|
||||
}
|
||||
/**
|
||||
* OAuth client authentication types.
|
||||
* https://tools.ietf.org/html/rfc6749#section-2.3
|
||||
*/
|
||||
export type ConfidentialClientType = 'basic' | 'request-body';
|
||||
/**
|
||||
* Defines the client authentication credentials for basic and request-body
|
||||
* credentials.
|
||||
* https://tools.ietf.org/html/rfc6749#section-2.3.1
|
||||
*/
|
||||
export interface ClientAuthentication {
|
||||
confidentialClientType: ConfidentialClientType;
|
||||
clientId: string;
|
||||
clientSecret?: string;
|
||||
}
|
||||
export interface OAuthClientAuthHandlerOptions {
|
||||
/**
|
||||
* Defines the client authentication credentials for basic and request-body
|
||||
* credentials.
|
||||
*/
|
||||
clientAuthentication?: ClientAuthentication;
|
||||
/**
|
||||
* An optional transporter to use.
|
||||
*/
|
||||
transporter?: Gaxios;
|
||||
}
|
||||
/**
|
||||
* Abstract class for handling client authentication in OAuth-based
|
||||
* operations.
|
||||
* When request-body client authentication is used, only application/json and
|
||||
* application/x-www-form-urlencoded content types for HTTP methods that support
|
||||
* request bodies are supported.
|
||||
*/
|
||||
export declare abstract class OAuthClientAuthHandler {
|
||||
#private;
|
||||
protected transporter: Gaxios;
|
||||
/**
|
||||
* Instantiates an OAuth client authentication handler.
|
||||
* @param options The OAuth Client Auth Handler instance options. Passing an `ClientAuthentication` directly is **@DEPRECATED**.
|
||||
*/
|
||||
constructor(options?: ClientAuthentication | OAuthClientAuthHandlerOptions);
|
||||
/**
|
||||
* Applies client authentication on the OAuth request's headers or POST
|
||||
* body but does not process the request.
|
||||
* @param opts The GaxiosOptions whose headers or data are to be modified
|
||||
* depending on the client authentication mechanism to be used.
|
||||
* @param bearerToken The optional bearer token to use for authentication.
|
||||
* When this is used, no client authentication credentials are needed.
|
||||
*/
|
||||
protected applyClientAuthenticationOptions(opts: GaxiosOptions, bearerToken?: string): void;
|
||||
/**
|
||||
* Applies client authentication on the request's header if either
|
||||
* basic authentication or bearer token authentication is selected.
|
||||
*
|
||||
* @param opts The GaxiosOptions whose headers or data are to be modified
|
||||
* depending on the client authentication mechanism to be used.
|
||||
* @param bearerToken The optional bearer token to use for authentication.
|
||||
* When this is used, no client authentication credentials are needed.
|
||||
*/
|
||||
private injectAuthenticatedHeaders;
|
||||
/**
|
||||
* Applies client authentication on the request's body if request-body
|
||||
* client authentication is selected.
|
||||
*
|
||||
* @param opts The GaxiosOptions whose headers or data are to be modified
|
||||
* depending on the client authentication mechanism to be used.
|
||||
*/
|
||||
private injectAuthenticatedRequestBody;
|
||||
/**
|
||||
* Retry config for Auth-related requests.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* This is not a part of the default {@link AuthClient.transporter transporter/gaxios}
|
||||
* config as some downstream APIs would prefer if customers explicitly enable retries,
|
||||
* such as GCS.
|
||||
*/
|
||||
protected static get RETRY_CONFIG(): GaxiosOptions;
|
||||
}
|
||||
/**
|
||||
* Converts an OAuth error response to a native JavaScript Error.
|
||||
* @param resp The OAuth error response to convert to a native Error object.
|
||||
* @param err The optional original error. If provided, the error properties
|
||||
* will be copied to the new error.
|
||||
* @return The converted native Error object.
|
||||
*/
|
||||
export declare function getErrorFromOAuthErrorResponse(resp: OAuthErrorResponse, err?: Error): Error;
|
||||
export {};
|
||||
189
node_modules/google-auth-library/build/src/auth/oauth2common.js
generated
vendored
Normal file
189
node_modules/google-auth-library/build/src/auth/oauth2common.js
generated
vendored
Normal file
@@ -0,0 +1,189 @@
|
||||
"use strict";
|
||||
// Copyright 2021 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.OAuthClientAuthHandler = void 0;
|
||||
exports.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse;
|
||||
const gaxios_1 = require("gaxios");
|
||||
const crypto_1 = require("../crypto/crypto");
|
||||
/** List of HTTP methods that accept request bodies. */
|
||||
const METHODS_SUPPORTING_REQUEST_BODY = ['PUT', 'POST', 'PATCH'];
|
||||
/**
|
||||
* Abstract class for handling client authentication in OAuth-based
|
||||
* operations.
|
||||
* When request-body client authentication is used, only application/json and
|
||||
* application/x-www-form-urlencoded content types for HTTP methods that support
|
||||
* request bodies are supported.
|
||||
*/
|
||||
class OAuthClientAuthHandler {
|
||||
#crypto = (0, crypto_1.createCrypto)();
|
||||
#clientAuthentication;
|
||||
transporter;
|
||||
/**
|
||||
* Instantiates an OAuth client authentication handler.
|
||||
* @param options The OAuth Client Auth Handler instance options. Passing an `ClientAuthentication` directly is **@DEPRECATED**.
|
||||
*/
|
||||
constructor(options) {
|
||||
if (options && 'clientId' in options) {
|
||||
this.#clientAuthentication = options;
|
||||
this.transporter = new gaxios_1.Gaxios();
|
||||
}
|
||||
else {
|
||||
this.#clientAuthentication = options?.clientAuthentication;
|
||||
this.transporter = options?.transporter || new gaxios_1.Gaxios();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Applies client authentication on the OAuth request's headers or POST
|
||||
* body but does not process the request.
|
||||
* @param opts The GaxiosOptions whose headers or data are to be modified
|
||||
* depending on the client authentication mechanism to be used.
|
||||
* @param bearerToken The optional bearer token to use for authentication.
|
||||
* When this is used, no client authentication credentials are needed.
|
||||
*/
|
||||
applyClientAuthenticationOptions(opts, bearerToken) {
|
||||
opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);
|
||||
// Inject authenticated header.
|
||||
this.injectAuthenticatedHeaders(opts, bearerToken);
|
||||
// Inject authenticated request body.
|
||||
if (!bearerToken) {
|
||||
this.injectAuthenticatedRequestBody(opts);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Applies client authentication on the request's header if either
|
||||
* basic authentication or bearer token authentication is selected.
|
||||
*
|
||||
* @param opts The GaxiosOptions whose headers or data are to be modified
|
||||
* depending on the client authentication mechanism to be used.
|
||||
* @param bearerToken The optional bearer token to use for authentication.
|
||||
* When this is used, no client authentication credentials are needed.
|
||||
*/
|
||||
injectAuthenticatedHeaders(opts, bearerToken) {
|
||||
// Bearer token prioritized higher than basic Auth.
|
||||
if (bearerToken) {
|
||||
opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, {
|
||||
authorization: `Bearer ${bearerToken}`,
|
||||
});
|
||||
}
|
||||
else if (this.#clientAuthentication?.confidentialClientType === 'basic') {
|
||||
opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);
|
||||
const clientId = this.#clientAuthentication.clientId;
|
||||
const clientSecret = this.#clientAuthentication.clientSecret || '';
|
||||
const base64EncodedCreds = this.#crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`);
|
||||
gaxios_1.Gaxios.mergeHeaders(opts.headers, {
|
||||
authorization: `Basic ${base64EncodedCreds}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Applies client authentication on the request's body if request-body
|
||||
* client authentication is selected.
|
||||
*
|
||||
* @param opts The GaxiosOptions whose headers or data are to be modified
|
||||
* depending on the client authentication mechanism to be used.
|
||||
*/
|
||||
injectAuthenticatedRequestBody(opts) {
|
||||
if (this.#clientAuthentication?.confidentialClientType === 'request-body') {
|
||||
const method = (opts.method || 'GET').toUpperCase();
|
||||
if (!METHODS_SUPPORTING_REQUEST_BODY.includes(method)) {
|
||||
throw new Error(`${method} HTTP method does not support ` +
|
||||
`${this.#clientAuthentication.confidentialClientType} ` +
|
||||
'client authentication');
|
||||
}
|
||||
// Get content-type
|
||||
const headers = new Headers(opts.headers);
|
||||
const contentType = headers.get('content-type');
|
||||
// Inject authenticated request body
|
||||
if (contentType?.startsWith('application/x-www-form-urlencoded') ||
|
||||
opts.data instanceof URLSearchParams) {
|
||||
const data = new URLSearchParams(opts.data ?? '');
|
||||
data.append('client_id', this.#clientAuthentication.clientId);
|
||||
data.append('client_secret', this.#clientAuthentication.clientSecret || '');
|
||||
opts.data = data;
|
||||
}
|
||||
else if (contentType?.startsWith('application/json')) {
|
||||
opts.data = opts.data || {};
|
||||
Object.assign(opts.data, {
|
||||
client_id: this.#clientAuthentication.clientId,
|
||||
client_secret: this.#clientAuthentication.clientSecret || '',
|
||||
});
|
||||
}
|
||||
else {
|
||||
throw new Error(`${contentType} content-types are not supported with ` +
|
||||
`${this.#clientAuthentication.confidentialClientType} ` +
|
||||
'client authentication');
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Retry config for Auth-related requests.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* This is not a part of the default {@link AuthClient.transporter transporter/gaxios}
|
||||
* config as some downstream APIs would prefer if customers explicitly enable retries,
|
||||
* such as GCS.
|
||||
*/
|
||||
static get RETRY_CONFIG() {
|
||||
return {
|
||||
retry: true,
|
||||
retryConfig: {
|
||||
httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'],
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.OAuthClientAuthHandler = OAuthClientAuthHandler;
|
||||
/**
|
||||
* Converts an OAuth error response to a native JavaScript Error.
|
||||
* @param resp The OAuth error response to convert to a native Error object.
|
||||
* @param err The optional original error. If provided, the error properties
|
||||
* will be copied to the new error.
|
||||
* @return The converted native Error object.
|
||||
*/
|
||||
function getErrorFromOAuthErrorResponse(resp, err) {
|
||||
// Error response.
|
||||
const errorCode = resp.error;
|
||||
const errorDescription = resp.error_description;
|
||||
const errorUri = resp.error_uri;
|
||||
let message = `Error code ${errorCode}`;
|
||||
if (typeof errorDescription !== 'undefined') {
|
||||
message += `: ${errorDescription}`;
|
||||
}
|
||||
if (typeof errorUri !== 'undefined') {
|
||||
message += ` - ${errorUri}`;
|
||||
}
|
||||
const newError = new Error(message);
|
||||
// Copy properties from original error to newly generated error.
|
||||
if (err) {
|
||||
const keys = Object.keys(err);
|
||||
if (err.stack) {
|
||||
// Copy error.stack if available.
|
||||
keys.push('stack');
|
||||
}
|
||||
keys.forEach(key => {
|
||||
// Do not overwrite the message field.
|
||||
if (key !== 'message') {
|
||||
Object.defineProperty(newError, key, {
|
||||
value: err[key],
|
||||
writable: false,
|
||||
enumerable: true,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
return newError;
|
||||
}
|
||||
//# sourceMappingURL=oauth2common.js.map
|
||||
37
node_modules/google-auth-library/build/src/auth/passthrough.d.ts
generated
vendored
Normal file
37
node_modules/google-auth-library/build/src/auth/passthrough.d.ts
generated
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
import { GaxiosOptions } from 'gaxios';
|
||||
import { AuthClient, GetAccessTokenResponse } from './authclient';
|
||||
/**
|
||||
* An AuthClient without any Authentication information. Useful for:
|
||||
* - Anonymous access
|
||||
* - Local Emulators
|
||||
* - Testing Environments
|
||||
*
|
||||
*/
|
||||
export declare class PassThroughClient extends AuthClient {
|
||||
/**
|
||||
* Creates a request without any authentication headers or checks.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* In testing environments it may be useful to change the provided
|
||||
* {@link AuthClient.transporter} for any desired request overrides/handling.
|
||||
*
|
||||
* @param opts
|
||||
* @returns The response of the request.
|
||||
*/
|
||||
request<T>(opts: GaxiosOptions): Promise<import("gaxios").GaxiosResponse<T>>;
|
||||
/**
|
||||
* A required method of the base class.
|
||||
* Always will return an empty object.
|
||||
*
|
||||
* @returns {}
|
||||
*/
|
||||
getAccessToken(): Promise<GetAccessTokenResponse>;
|
||||
/**
|
||||
* A required method of the base class.
|
||||
* Always will return an empty object.
|
||||
*
|
||||
* @returns {}
|
||||
*/
|
||||
getRequestHeaders(): Promise<Headers>;
|
||||
}
|
||||
60
node_modules/google-auth-library/build/src/auth/passthrough.js
generated
vendored
Normal file
60
node_modules/google-auth-library/build/src/auth/passthrough.js
generated
vendored
Normal file
@@ -0,0 +1,60 @@
|
||||
"use strict";
|
||||
// Copyright 2024 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.PassThroughClient = void 0;
|
||||
const authclient_1 = require("./authclient");
|
||||
/**
|
||||
* An AuthClient without any Authentication information. Useful for:
|
||||
* - Anonymous access
|
||||
* - Local Emulators
|
||||
* - Testing Environments
|
||||
*
|
||||
*/
|
||||
class PassThroughClient extends authclient_1.AuthClient {
|
||||
/**
|
||||
* Creates a request without any authentication headers or checks.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* In testing environments it may be useful to change the provided
|
||||
* {@link AuthClient.transporter} for any desired request overrides/handling.
|
||||
*
|
||||
* @param opts
|
||||
* @returns The response of the request.
|
||||
*/
|
||||
async request(opts) {
|
||||
return this.transporter.request(opts);
|
||||
}
|
||||
/**
|
||||
* A required method of the base class.
|
||||
* Always will return an empty object.
|
||||
*
|
||||
* @returns {}
|
||||
*/
|
||||
async getAccessToken() {
|
||||
return {};
|
||||
}
|
||||
/**
|
||||
* A required method of the base class.
|
||||
* Always will return an empty object.
|
||||
*
|
||||
* @returns {}
|
||||
*/
|
||||
async getRequestHeaders() {
|
||||
return new Headers();
|
||||
}
|
||||
}
|
||||
exports.PassThroughClient = PassThroughClient;
|
||||
//# sourceMappingURL=passthrough.js.map
|
||||
141
node_modules/google-auth-library/build/src/auth/pluggable-auth-client.d.ts
generated
vendored
Normal file
141
node_modules/google-auth-library/build/src/auth/pluggable-auth-client.d.ts
generated
vendored
Normal file
@@ -0,0 +1,141 @@
|
||||
import { BaseExternalAccountClient, BaseExternalAccountClientOptions } from './baseexternalclient';
|
||||
export { ExecutableError } from './pluggable-auth-handler';
|
||||
/**
|
||||
* Defines the credential source portion of the configuration for PluggableAuthClient.
|
||||
*
|
||||
* <p>Command is the only required field. If timeout_millis is not specified, the library will
|
||||
* default to a 30-second timeout.
|
||||
*
|
||||
* <pre>
|
||||
* Sample credential source for Pluggable Auth Client:
|
||||
* {
|
||||
* ...
|
||||
* "credential_source": {
|
||||
* "executable": {
|
||||
* "command": "/path/to/get/credentials.sh --arg1=value1 --arg2=value2",
|
||||
* "timeout_millis": 5000,
|
||||
* "output_file": "/path/to/generated/cached/credentials"
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
* </pre>
|
||||
*/
|
||||
export interface PluggableAuthClientOptions extends BaseExternalAccountClientOptions {
|
||||
credential_source: {
|
||||
executable: {
|
||||
/**
|
||||
* The command used to retrieve the 3rd party token.
|
||||
*/
|
||||
command: string;
|
||||
/**
|
||||
* The timeout for executable to run in milliseconds. If none is provided it
|
||||
* will be set to the default timeout of 30 seconds.
|
||||
*/
|
||||
timeout_millis?: number;
|
||||
/**
|
||||
* An optional output file location that will be checked for a cached response
|
||||
* from a previous run of the executable.
|
||||
*/
|
||||
output_file?: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
/**
|
||||
* PluggableAuthClient enables the exchange of workload identity pool external credentials for
|
||||
* Google access tokens by retrieving 3rd party tokens through a user supplied executable. These
|
||||
* scripts/executables are completely independent of the Google Cloud Auth libraries. These
|
||||
* credentials plug into ADC and will call the specified executable to retrieve the 3rd party token
|
||||
* to be exchanged for a Google access token.
|
||||
*
|
||||
* <p>To use these credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable
|
||||
* must be set to '1'. This is for security reasons.
|
||||
*
|
||||
* <p>Both OIDC and SAML are supported. The executable must adhere to a specific response format
|
||||
* defined below.
|
||||
*
|
||||
* <p>The executable must print out the 3rd party token to STDOUT in JSON format. When an
|
||||
* output_file is specified in the credential configuration, the executable must also handle writing the
|
||||
* JSON response to this file.
|
||||
*
|
||||
* <pre>
|
||||
* OIDC response sample:
|
||||
* {
|
||||
* "version": 1,
|
||||
* "success": true,
|
||||
* "token_type": "urn:ietf:params:oauth:token-type:id_token",
|
||||
* "id_token": "HEADER.PAYLOAD.SIGNATURE",
|
||||
* "expiration_time": 1620433341
|
||||
* }
|
||||
*
|
||||
* SAML2 response sample:
|
||||
* {
|
||||
* "version": 1,
|
||||
* "success": true,
|
||||
* "token_type": "urn:ietf:params:oauth:token-type:saml2",
|
||||
* "saml_response": "...",
|
||||
* "expiration_time": 1620433341
|
||||
* }
|
||||
*
|
||||
* Error response sample:
|
||||
* {
|
||||
* "version": 1,
|
||||
* "success": false,
|
||||
* "code": "401",
|
||||
* "message": "Error message."
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <p>The "expiration_time" field in the JSON response is only required for successful
|
||||
* responses when an output file was specified in the credential configuration
|
||||
*
|
||||
* <p>The auth libraries will populate certain environment variables that will be accessible by the
|
||||
* executable, such as: GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE, GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE,
|
||||
* GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE, GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL, and
|
||||
* GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE.
|
||||
*
|
||||
* <p>Please see this repositories README for a complete executable request/response specification.
|
||||
*/
|
||||
export declare class PluggableAuthClient extends BaseExternalAccountClient {
|
||||
/**
|
||||
* The command used to retrieve the third party token.
|
||||
*/
|
||||
private readonly command;
|
||||
/**
|
||||
* The timeout in milliseconds for running executable,
|
||||
* set to default if none provided.
|
||||
*/
|
||||
private readonly timeoutMillis;
|
||||
/**
|
||||
* The path to file to check for cached executable response.
|
||||
*/
|
||||
private readonly outputFile?;
|
||||
/**
|
||||
* Executable and output file handler.
|
||||
*/
|
||||
private readonly handler;
|
||||
/**
|
||||
* Instantiates a PluggableAuthClient instance using the provided JSON
|
||||
* object loaded from an external account credentials file.
|
||||
* An error is thrown if the credential is not a valid pluggable auth credential.
|
||||
* @param options The external account options object typically loaded from
|
||||
* the external account JSON credential file.
|
||||
*/
|
||||
constructor(options: PluggableAuthClientOptions);
|
||||
/**
|
||||
* Triggered when an external subject token is needed to be exchanged for a
|
||||
* GCP access token via GCP STS endpoint.
|
||||
* This uses the `options.credential_source` object to figure out how
|
||||
* to retrieve the token using the current environment. In this case,
|
||||
* this calls a user provided executable which returns the subject token.
|
||||
* The logic is summarized as:
|
||||
* 1. Validated that the executable is allowed to run. The
|
||||
* GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to
|
||||
* 1 for security reasons.
|
||||
* 2. If an output file is specified by the user, check the file location
|
||||
* for a response. If the file exists and contains a valid response,
|
||||
* return the subject token from the file.
|
||||
* 3. Call the provided executable and return response.
|
||||
* @return A promise that resolves with the external subject token.
|
||||
*/
|
||||
retrieveSubjectToken(): Promise<string>;
|
||||
}
|
||||
220
node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js
generated
vendored
Normal file
220
node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js
generated
vendored
Normal file
@@ -0,0 +1,220 @@
|
||||
"use strict";
|
||||
// Copyright 2022 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.PluggableAuthClient = exports.ExecutableError = void 0;
|
||||
const baseexternalclient_1 = require("./baseexternalclient");
|
||||
const executable_response_1 = require("./executable-response");
|
||||
const pluggable_auth_handler_1 = require("./pluggable-auth-handler");
|
||||
var pluggable_auth_handler_2 = require("./pluggable-auth-handler");
|
||||
Object.defineProperty(exports, "ExecutableError", { enumerable: true, get: function () { return pluggable_auth_handler_2.ExecutableError; } });
|
||||
/**
|
||||
* The default executable timeout when none is provided, in milliseconds.
|
||||
*/
|
||||
const DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1000;
|
||||
/**
|
||||
* The minimum allowed executable timeout in milliseconds.
|
||||
*/
|
||||
const MINIMUM_EXECUTABLE_TIMEOUT_MILLIS = 5 * 1000;
|
||||
/**
|
||||
* The maximum allowed executable timeout in milliseconds.
|
||||
*/
|
||||
const MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS = 120 * 1000;
|
||||
/**
|
||||
* The environment variable to check to see if executable can be run.
|
||||
* Value must be set to '1' for the executable to run.
|
||||
*/
|
||||
const GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES = 'GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES';
|
||||
/**
|
||||
* The maximum currently supported executable version.
|
||||
*/
|
||||
const MAXIMUM_EXECUTABLE_VERSION = 1;
|
||||
/**
|
||||
* PluggableAuthClient enables the exchange of workload identity pool external credentials for
|
||||
* Google access tokens by retrieving 3rd party tokens through a user supplied executable. These
|
||||
* scripts/executables are completely independent of the Google Cloud Auth libraries. These
|
||||
* credentials plug into ADC and will call the specified executable to retrieve the 3rd party token
|
||||
* to be exchanged for a Google access token.
|
||||
*
|
||||
* <p>To use these credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable
|
||||
* must be set to '1'. This is for security reasons.
|
||||
*
|
||||
* <p>Both OIDC and SAML are supported. The executable must adhere to a specific response format
|
||||
* defined below.
|
||||
*
|
||||
* <p>The executable must print out the 3rd party token to STDOUT in JSON format. When an
|
||||
* output_file is specified in the credential configuration, the executable must also handle writing the
|
||||
* JSON response to this file.
|
||||
*
|
||||
* <pre>
|
||||
* OIDC response sample:
|
||||
* {
|
||||
* "version": 1,
|
||||
* "success": true,
|
||||
* "token_type": "urn:ietf:params:oauth:token-type:id_token",
|
||||
* "id_token": "HEADER.PAYLOAD.SIGNATURE",
|
||||
* "expiration_time": 1620433341
|
||||
* }
|
||||
*
|
||||
* SAML2 response sample:
|
||||
* {
|
||||
* "version": 1,
|
||||
* "success": true,
|
||||
* "token_type": "urn:ietf:params:oauth:token-type:saml2",
|
||||
* "saml_response": "...",
|
||||
* "expiration_time": 1620433341
|
||||
* }
|
||||
*
|
||||
* Error response sample:
|
||||
* {
|
||||
* "version": 1,
|
||||
* "success": false,
|
||||
* "code": "401",
|
||||
* "message": "Error message."
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <p>The "expiration_time" field in the JSON response is only required for successful
|
||||
* responses when an output file was specified in the credential configuration
|
||||
*
|
||||
* <p>The auth libraries will populate certain environment variables that will be accessible by the
|
||||
* executable, such as: GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE, GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE,
|
||||
* GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE, GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL, and
|
||||
* GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE.
|
||||
*
|
||||
* <p>Please see this repositories README for a complete executable request/response specification.
|
||||
*/
|
||||
class PluggableAuthClient extends baseexternalclient_1.BaseExternalAccountClient {
|
||||
/**
|
||||
* The command used to retrieve the third party token.
|
||||
*/
|
||||
command;
|
||||
/**
|
||||
* The timeout in milliseconds for running executable,
|
||||
* set to default if none provided.
|
||||
*/
|
||||
timeoutMillis;
|
||||
/**
|
||||
* The path to file to check for cached executable response.
|
||||
*/
|
||||
outputFile;
|
||||
/**
|
||||
* Executable and output file handler.
|
||||
*/
|
||||
handler;
|
||||
/**
|
||||
* Instantiates a PluggableAuthClient instance using the provided JSON
|
||||
* object loaded from an external account credentials file.
|
||||
* An error is thrown if the credential is not a valid pluggable auth credential.
|
||||
* @param options The external account options object typically loaded from
|
||||
* the external account JSON credential file.
|
||||
*/
|
||||
constructor(options) {
|
||||
super(options);
|
||||
if (!options.credential_source.executable) {
|
||||
throw new Error('No valid Pluggable Auth "credential_source" provided.');
|
||||
}
|
||||
this.command = options.credential_source.executable.command;
|
||||
if (!this.command) {
|
||||
throw new Error('No valid Pluggable Auth "credential_source" provided.');
|
||||
}
|
||||
// Check if the provided timeout exists and if it is valid.
|
||||
if (options.credential_source.executable.timeout_millis === undefined) {
|
||||
this.timeoutMillis = DEFAULT_EXECUTABLE_TIMEOUT_MILLIS;
|
||||
}
|
||||
else {
|
||||
this.timeoutMillis = options.credential_source.executable.timeout_millis;
|
||||
if (this.timeoutMillis < MINIMUM_EXECUTABLE_TIMEOUT_MILLIS ||
|
||||
this.timeoutMillis > MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS) {
|
||||
throw new Error(`Timeout must be between ${MINIMUM_EXECUTABLE_TIMEOUT_MILLIS} and ` +
|
||||
`${MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS} milliseconds.`);
|
||||
}
|
||||
}
|
||||
this.outputFile = options.credential_source.executable.output_file;
|
||||
this.handler = new pluggable_auth_handler_1.PluggableAuthHandler({
|
||||
command: this.command,
|
||||
timeoutMillis: this.timeoutMillis,
|
||||
outputFile: this.outputFile,
|
||||
});
|
||||
this.credentialSourceType = 'executable';
|
||||
}
|
||||
/**
|
||||
* Triggered when an external subject token is needed to be exchanged for a
|
||||
* GCP access token via GCP STS endpoint.
|
||||
* This uses the `options.credential_source` object to figure out how
|
||||
* to retrieve the token using the current environment. In this case,
|
||||
* this calls a user provided executable which returns the subject token.
|
||||
* The logic is summarized as:
|
||||
* 1. Validated that the executable is allowed to run. The
|
||||
* GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to
|
||||
* 1 for security reasons.
|
||||
* 2. If an output file is specified by the user, check the file location
|
||||
* for a response. If the file exists and contains a valid response,
|
||||
* return the subject token from the file.
|
||||
* 3. Call the provided executable and return response.
|
||||
* @return A promise that resolves with the external subject token.
|
||||
*/
|
||||
async retrieveSubjectToken() {
|
||||
// Check if the executable is allowed to run.
|
||||
if (process.env[GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES] !== '1') {
|
||||
throw new Error('Pluggable Auth executables need to be explicitly allowed to run by ' +
|
||||
'setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment ' +
|
||||
'Variable to 1.');
|
||||
}
|
||||
let executableResponse = undefined;
|
||||
// Try to get cached executable response from output file.
|
||||
if (this.outputFile) {
|
||||
executableResponse = await this.handler.retrieveCachedResponse();
|
||||
}
|
||||
// If no response from output file, call the executable.
|
||||
if (!executableResponse) {
|
||||
// Set up environment map with required values for the executable.
|
||||
const envMap = new Map();
|
||||
envMap.set('GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE', this.audience);
|
||||
envMap.set('GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE', this.subjectTokenType);
|
||||
// Always set to 0 because interactive mode is not supported.
|
||||
envMap.set('GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE', '0');
|
||||
if (this.outputFile) {
|
||||
envMap.set('GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE', this.outputFile);
|
||||
}
|
||||
const serviceAccountEmail = this.getServiceAccountEmail();
|
||||
if (serviceAccountEmail) {
|
||||
envMap.set('GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL', serviceAccountEmail);
|
||||
}
|
||||
executableResponse =
|
||||
await this.handler.retrieveResponseFromExecutable(envMap);
|
||||
}
|
||||
if (executableResponse.version > MAXIMUM_EXECUTABLE_VERSION) {
|
||||
throw new Error(`Version of executable is not currently supported, maximum supported version is ${MAXIMUM_EXECUTABLE_VERSION}.`);
|
||||
}
|
||||
// Check that response was successful.
|
||||
if (!executableResponse.success) {
|
||||
throw new pluggable_auth_handler_1.ExecutableError(executableResponse.errorMessage, executableResponse.errorCode);
|
||||
}
|
||||
// Check that response contains expiration time if output file was specified.
|
||||
if (this.outputFile) {
|
||||
if (!executableResponse.expirationTime) {
|
||||
throw new executable_response_1.InvalidExpirationTimeFieldError('The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.');
|
||||
}
|
||||
}
|
||||
// Check that response is not expired.
|
||||
if (executableResponse.isExpired()) {
|
||||
throw new Error('Executable response is expired.');
|
||||
}
|
||||
// Return subject token from response.
|
||||
return executableResponse.subjectToken;
|
||||
}
|
||||
}
|
||||
exports.PluggableAuthClient = PluggableAuthClient;
|
||||
//# sourceMappingURL=pluggable-auth-client.js.map
|
||||
61
node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.d.ts
generated
vendored
Normal file
61
node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.d.ts
generated
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
import { ExecutableResponse } from './executable-response';
|
||||
/**
|
||||
* Error thrown from the executable run by PluggableAuthClient.
|
||||
*/
|
||||
export declare class ExecutableError extends Error {
|
||||
/**
|
||||
* The exit code returned by the executable.
|
||||
*/
|
||||
readonly code: string;
|
||||
constructor(message: string, code: string);
|
||||
}
|
||||
/**
|
||||
* Defines the options used for the PluggableAuthHandler class.
|
||||
*/
|
||||
export interface PluggableAuthHandlerOptions {
|
||||
/**
|
||||
* The command used to retrieve the third party token.
|
||||
*/
|
||||
command: string;
|
||||
/**
|
||||
* The timeout in milliseconds for running executable,
|
||||
* set to default if none provided.
|
||||
*/
|
||||
timeoutMillis: number;
|
||||
/**
|
||||
* The path to file to check for cached executable response.
|
||||
*/
|
||||
outputFile?: string;
|
||||
}
|
||||
/**
|
||||
* A handler used to retrieve 3rd party token responses from user defined
|
||||
* executables and cached file output for the PluggableAuthClient class.
|
||||
*/
|
||||
export declare class PluggableAuthHandler {
|
||||
private readonly commandComponents;
|
||||
private readonly timeoutMillis;
|
||||
private readonly outputFile?;
|
||||
/**
|
||||
* Instantiates a PluggableAuthHandler instance using the provided
|
||||
* PluggableAuthHandlerOptions object.
|
||||
*/
|
||||
constructor(options: PluggableAuthHandlerOptions);
|
||||
/**
|
||||
* Calls user provided executable to get a 3rd party subject token and
|
||||
* returns the response.
|
||||
* @param envMap a Map of additional Environment Variables required for
|
||||
* the executable.
|
||||
* @return A promise that resolves with the executable response.
|
||||
*/
|
||||
retrieveResponseFromExecutable(envMap: Map<string, string>): Promise<ExecutableResponse>;
|
||||
/**
|
||||
* Checks user provided output file for response from previous run of
|
||||
* executable and return the response if it exists, is formatted correctly, and is not expired.
|
||||
*/
|
||||
retrieveCachedResponse(): Promise<ExecutableResponse | undefined>;
|
||||
/**
|
||||
* Parses given command string into component array, splitting on spaces unless
|
||||
* spaces are between quotation marks.
|
||||
*/
|
||||
private static parseCommand;
|
||||
}
|
||||
174
node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js
generated
vendored
Normal file
174
node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js
generated
vendored
Normal file
@@ -0,0 +1,174 @@
|
||||
"use strict";
|
||||
// Copyright 2022 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.PluggableAuthHandler = exports.ExecutableError = void 0;
|
||||
const executable_response_1 = require("./executable-response");
|
||||
const childProcess = require("child_process");
|
||||
const fs = require("fs");
|
||||
/**
|
||||
* Error thrown from the executable run by PluggableAuthClient.
|
||||
*/
|
||||
class ExecutableError extends Error {
|
||||
/**
|
||||
* The exit code returned by the executable.
|
||||
*/
|
||||
code;
|
||||
constructor(message, code) {
|
||||
super(`The executable failed with exit code: ${code} and error message: ${message}.`);
|
||||
this.code = code;
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
exports.ExecutableError = ExecutableError;
|
||||
/**
|
||||
* A handler used to retrieve 3rd party token responses from user defined
|
||||
* executables and cached file output for the PluggableAuthClient class.
|
||||
*/
|
||||
class PluggableAuthHandler {
|
||||
commandComponents;
|
||||
timeoutMillis;
|
||||
outputFile;
|
||||
/**
|
||||
* Instantiates a PluggableAuthHandler instance using the provided
|
||||
* PluggableAuthHandlerOptions object.
|
||||
*/
|
||||
constructor(options) {
|
||||
if (!options.command) {
|
||||
throw new Error('No command provided.');
|
||||
}
|
||||
this.commandComponents = PluggableAuthHandler.parseCommand(options.command);
|
||||
this.timeoutMillis = options.timeoutMillis;
|
||||
if (!this.timeoutMillis) {
|
||||
throw new Error('No timeoutMillis provided.');
|
||||
}
|
||||
this.outputFile = options.outputFile;
|
||||
}
|
||||
/**
|
||||
* Calls user provided executable to get a 3rd party subject token and
|
||||
* returns the response.
|
||||
* @param envMap a Map of additional Environment Variables required for
|
||||
* the executable.
|
||||
* @return A promise that resolves with the executable response.
|
||||
*/
|
||||
retrieveResponseFromExecutable(envMap) {
|
||||
return new Promise((resolve, reject) => {
|
||||
// Spawn process to run executable using added environment variables.
|
||||
const child = childProcess.spawn(this.commandComponents[0], this.commandComponents.slice(1), {
|
||||
env: { ...process.env, ...Object.fromEntries(envMap) },
|
||||
});
|
||||
let output = '';
|
||||
// Append stdout to output as executable runs.
|
||||
child.stdout.on('data', (data) => {
|
||||
output += data;
|
||||
});
|
||||
// Append stderr as executable runs.
|
||||
child.stderr.on('data', (err) => {
|
||||
output += err;
|
||||
});
|
||||
// Set up a timeout to end the child process and throw an error.
|
||||
const timeout = setTimeout(() => {
|
||||
// Kill child process and remove listeners so 'close' event doesn't get
|
||||
// read after child process is killed.
|
||||
child.removeAllListeners();
|
||||
child.kill();
|
||||
return reject(new Error('The executable failed to finish within the timeout specified.'));
|
||||
}, this.timeoutMillis);
|
||||
child.on('close', (code) => {
|
||||
// Cancel timeout if executable closes before timeout is reached.
|
||||
clearTimeout(timeout);
|
||||
if (code === 0) {
|
||||
// If the executable completed successfully, try to return the parsed response.
|
||||
try {
|
||||
const responseJson = JSON.parse(output);
|
||||
const response = new executable_response_1.ExecutableResponse(responseJson);
|
||||
return resolve(response);
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof executable_response_1.ExecutableResponseError) {
|
||||
return reject(error);
|
||||
}
|
||||
return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`));
|
||||
}
|
||||
}
|
||||
else {
|
||||
return reject(new ExecutableError(output, code.toString()));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Checks user provided output file for response from previous run of
|
||||
* executable and return the response if it exists, is formatted correctly, and is not expired.
|
||||
*/
|
||||
async retrieveCachedResponse() {
|
||||
if (!this.outputFile || this.outputFile.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
let filePath;
|
||||
try {
|
||||
filePath = await fs.promises.realpath(this.outputFile);
|
||||
}
|
||||
catch {
|
||||
// If file path cannot be resolved, return undefined.
|
||||
return undefined;
|
||||
}
|
||||
if (!(await fs.promises.lstat(filePath)).isFile()) {
|
||||
// If path does not lead to file, return undefined.
|
||||
return undefined;
|
||||
}
|
||||
const responseString = await fs.promises.readFile(filePath, {
|
||||
encoding: 'utf8',
|
||||
});
|
||||
if (responseString === '') {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const responseJson = JSON.parse(responseString);
|
||||
const response = new executable_response_1.ExecutableResponse(responseJson);
|
||||
// Check if response is successful and unexpired.
|
||||
if (response.isValid()) {
|
||||
return new executable_response_1.ExecutableResponse(responseJson);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof executable_response_1.ExecutableResponseError) {
|
||||
throw error;
|
||||
}
|
||||
throw new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Parses given command string into component array, splitting on spaces unless
|
||||
* spaces are between quotation marks.
|
||||
*/
|
||||
static parseCommand(command) {
|
||||
// Split the command into components by splitting on spaces,
|
||||
// unless spaces are contained in quotation marks.
|
||||
const components = command.match(/(?:[^\s"]+|"[^"]*")+/g);
|
||||
if (!components) {
|
||||
throw new Error(`Provided command: "${command}" could not be parsed.`);
|
||||
}
|
||||
// Remove quotation marks from the beginning and end of each component if they are present.
|
||||
for (let i = 0; i < components.length; i++) {
|
||||
if (components[i][0] === '"' && components[i].slice(-1) === '"') {
|
||||
components[i] = components[i].slice(1, -1);
|
||||
}
|
||||
}
|
||||
return components;
|
||||
}
|
||||
}
|
||||
exports.PluggableAuthHandler = PluggableAuthHandler;
|
||||
//# sourceMappingURL=pluggable-auth-handler.js.map
|
||||
75
node_modules/google-auth-library/build/src/auth/refreshclient.d.ts
generated
vendored
Normal file
75
node_modules/google-auth-library/build/src/auth/refreshclient.d.ts
generated
vendored
Normal file
@@ -0,0 +1,75 @@
|
||||
import * as stream from 'stream';
|
||||
import { JWTInput } from './credentials';
|
||||
import { GetTokenResponse, OAuth2Client, OAuth2ClientOptions } from './oauth2client';
|
||||
export declare const USER_REFRESH_ACCOUNT_TYPE = "authorized_user";
|
||||
export interface UserRefreshClientOptions extends OAuth2ClientOptions {
|
||||
/**
|
||||
* The authentication client ID.
|
||||
*/
|
||||
clientId?: string;
|
||||
/**
|
||||
* The authentication client secret.
|
||||
*/
|
||||
clientSecret?: string;
|
||||
/**
|
||||
* The authentication refresh token.
|
||||
*/
|
||||
refreshToken?: string;
|
||||
}
|
||||
export declare class UserRefreshClient extends OAuth2Client {
|
||||
_refreshToken?: string | null;
|
||||
/**
|
||||
* The User Refresh Token client.
|
||||
*
|
||||
* @param optionsOrClientId The User Refresh Token client options. Passing an `clientId` directly is **@DEPRECATED**.
|
||||
* @param clientSecret **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
|
||||
* @param refreshToken **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
|
||||
* @param eagerRefreshThresholdMillis **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
|
||||
* @param forceRefreshOnFailure **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
|
||||
*/
|
||||
constructor(optionsOrClientId?: string | UserRefreshClientOptions,
|
||||
/**
|
||||
* @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead
|
||||
*/
|
||||
clientSecret?: UserRefreshClientOptions['clientSecret'],
|
||||
/**
|
||||
* @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead
|
||||
*/
|
||||
refreshToken?: UserRefreshClientOptions['refreshToken'],
|
||||
/**
|
||||
* @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead
|
||||
*/
|
||||
eagerRefreshThresholdMillis?: UserRefreshClientOptions['eagerRefreshThresholdMillis'],
|
||||
/**
|
||||
* @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead
|
||||
*/
|
||||
forceRefreshOnFailure?: UserRefreshClientOptions['forceRefreshOnFailure']);
|
||||
/**
|
||||
* Refreshes the access token.
|
||||
* @param refreshToken An ignored refreshToken..
|
||||
* @param callback Optional callback.
|
||||
*/
|
||||
protected refreshTokenNoCache(): Promise<GetTokenResponse>;
|
||||
fetchIdToken(targetAudience: string): Promise<string>;
|
||||
/**
|
||||
* Create a UserRefreshClient credentials instance using the given input
|
||||
* options.
|
||||
* @param json The input object.
|
||||
*/
|
||||
fromJSON(json: JWTInput): void;
|
||||
/**
|
||||
* Create a UserRefreshClient credentials instance using the given input
|
||||
* stream.
|
||||
* @param inputStream The input stream.
|
||||
* @param callback Optional callback.
|
||||
*/
|
||||
fromStream(inputStream: stream.Readable): Promise<void>;
|
||||
fromStream(inputStream: stream.Readable, callback: (err?: Error) => void): void;
|
||||
private fromStreamAsync;
|
||||
/**
|
||||
* Create a UserRefreshClient credentials instance using the given input
|
||||
* options.
|
||||
* @param json The input object.
|
||||
*/
|
||||
static fromJSON(json: JWTInput): UserRefreshClient;
|
||||
}
|
||||
159
node_modules/google-auth-library/build/src/auth/refreshclient.js
generated
vendored
Normal file
159
node_modules/google-auth-library/build/src/auth/refreshclient.js
generated
vendored
Normal file
@@ -0,0 +1,159 @@
|
||||
"use strict";
|
||||
// Copyright 2015 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.UserRefreshClient = exports.USER_REFRESH_ACCOUNT_TYPE = void 0;
|
||||
const oauth2client_1 = require("./oauth2client");
|
||||
const authclient_1 = require("./authclient");
|
||||
exports.USER_REFRESH_ACCOUNT_TYPE = 'authorized_user';
|
||||
class UserRefreshClient extends oauth2client_1.OAuth2Client {
|
||||
// TODO: refactor tests to make this private
|
||||
// In a future gts release, the _propertyName rule will be lifted.
|
||||
// This is also a hard one because `this.refreshToken` is a function.
|
||||
_refreshToken;
|
||||
/**
|
||||
* The User Refresh Token client.
|
||||
*
|
||||
* @param optionsOrClientId The User Refresh Token client options. Passing an `clientId` directly is **@DEPRECATED**.
|
||||
* @param clientSecret **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
|
||||
* @param refreshToken **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
|
||||
* @param eagerRefreshThresholdMillis **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
|
||||
* @param forceRefreshOnFailure **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.
|
||||
*/
|
||||
constructor(optionsOrClientId,
|
||||
/**
|
||||
* @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead
|
||||
*/
|
||||
clientSecret,
|
||||
/**
|
||||
* @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead
|
||||
*/
|
||||
refreshToken,
|
||||
/**
|
||||
* @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead
|
||||
*/
|
||||
eagerRefreshThresholdMillis,
|
||||
/**
|
||||
* @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead
|
||||
*/
|
||||
forceRefreshOnFailure) {
|
||||
const opts = optionsOrClientId && typeof optionsOrClientId === 'object'
|
||||
? optionsOrClientId
|
||||
: {
|
||||
clientId: optionsOrClientId,
|
||||
clientSecret,
|
||||
refreshToken,
|
||||
eagerRefreshThresholdMillis,
|
||||
forceRefreshOnFailure,
|
||||
};
|
||||
super(opts);
|
||||
this._refreshToken = opts.refreshToken;
|
||||
this.credentials.refresh_token = opts.refreshToken;
|
||||
}
|
||||
/**
|
||||
* Refreshes the access token.
|
||||
* @param refreshToken An ignored refreshToken..
|
||||
* @param callback Optional callback.
|
||||
*/
|
||||
async refreshTokenNoCache() {
|
||||
return super.refreshTokenNoCache(this._refreshToken);
|
||||
}
|
||||
async fetchIdToken(targetAudience) {
|
||||
const opts = {
|
||||
...UserRefreshClient.RETRY_CONFIG,
|
||||
url: this.endpoints.oauth2TokenUrl,
|
||||
method: 'POST',
|
||||
data: new URLSearchParams({
|
||||
client_id: this._clientId,
|
||||
client_secret: this._clientSecret,
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: this._refreshToken,
|
||||
target_audience: targetAudience,
|
||||
}),
|
||||
};
|
||||
authclient_1.AuthClient.setMethodName(opts, 'fetchIdToken');
|
||||
const res = await this.transporter.request(opts);
|
||||
return res.data.id_token;
|
||||
}
|
||||
/**
|
||||
* Create a UserRefreshClient credentials instance using the given input
|
||||
* options.
|
||||
* @param json The input object.
|
||||
*/
|
||||
fromJSON(json) {
|
||||
if (!json) {
|
||||
throw new Error('Must pass in a JSON object containing the user refresh token');
|
||||
}
|
||||
if (json.type !== 'authorized_user') {
|
||||
throw new Error('The incoming JSON object does not have the "authorized_user" type');
|
||||
}
|
||||
if (!json.client_id) {
|
||||
throw new Error('The incoming JSON object does not contain a client_id field');
|
||||
}
|
||||
if (!json.client_secret) {
|
||||
throw new Error('The incoming JSON object does not contain a client_secret field');
|
||||
}
|
||||
if (!json.refresh_token) {
|
||||
throw new Error('The incoming JSON object does not contain a refresh_token field');
|
||||
}
|
||||
this._clientId = json.client_id;
|
||||
this._clientSecret = json.client_secret;
|
||||
this._refreshToken = json.refresh_token;
|
||||
this.credentials.refresh_token = json.refresh_token;
|
||||
this.quotaProjectId = json.quota_project_id;
|
||||
this.universeDomain = json.universe_domain || this.universeDomain;
|
||||
}
|
||||
fromStream(inputStream, callback) {
|
||||
if (callback) {
|
||||
this.fromStreamAsync(inputStream).then(() => callback(), callback);
|
||||
}
|
||||
else {
|
||||
return this.fromStreamAsync(inputStream);
|
||||
}
|
||||
}
|
||||
async fromStreamAsync(inputStream) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!inputStream) {
|
||||
return reject(new Error('Must pass in a stream containing the user refresh token.'));
|
||||
}
|
||||
let s = '';
|
||||
inputStream
|
||||
.setEncoding('utf8')
|
||||
.on('error', reject)
|
||||
.on('data', chunk => (s += chunk))
|
||||
.on('end', () => {
|
||||
try {
|
||||
const data = JSON.parse(s);
|
||||
this.fromJSON(data);
|
||||
return resolve();
|
||||
}
|
||||
catch (err) {
|
||||
return reject(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Create a UserRefreshClient credentials instance using the given input
|
||||
* options.
|
||||
* @param json The input object.
|
||||
*/
|
||||
static fromJSON(json) {
|
||||
const client = new UserRefreshClient();
|
||||
client.fromJSON(json);
|
||||
return client;
|
||||
}
|
||||
}
|
||||
exports.UserRefreshClient = UserRefreshClient;
|
||||
//# sourceMappingURL=refreshclient.js.map
|
||||
125
node_modules/google-auth-library/build/src/auth/stscredentials.d.ts
generated
vendored
Normal file
125
node_modules/google-auth-library/build/src/auth/stscredentials.d.ts
generated
vendored
Normal file
@@ -0,0 +1,125 @@
|
||||
import { GaxiosResponse } from 'gaxios';
|
||||
import { HeadersInit } from './authclient';
|
||||
import { ClientAuthentication, OAuthClientAuthHandler, OAuthClientAuthHandlerOptions } from './oauth2common';
|
||||
/**
|
||||
* Defines the interface needed to initialize an StsCredentials instance.
|
||||
* The interface does not directly map to the spec and instead is converted
|
||||
* to be compliant with the JavaScript style guide. This is because this is
|
||||
* instantiated internally.
|
||||
* StsCredentials implement the OAuth 2.0 token exchange based on
|
||||
* https://tools.ietf.org/html/rfc8693.
|
||||
* Request options are defined in
|
||||
* https://tools.ietf.org/html/rfc8693#section-2.1
|
||||
*/
|
||||
export interface StsCredentialsOptions {
|
||||
/**
|
||||
* REQUIRED. The value "urn:ietf:params:oauth:grant-type:token-exchange"
|
||||
* indicates that a token exchange is being performed.
|
||||
*/
|
||||
grantType: string;
|
||||
/**
|
||||
* OPTIONAL. A URI that indicates the target service or resource where the
|
||||
* client intends to use the requested security token.
|
||||
*/
|
||||
resource?: string;
|
||||
/**
|
||||
* OPTIONAL. The logical name of the target service where the client
|
||||
* intends to use the requested security token. This serves a purpose
|
||||
* similar to the "resource" parameter but with the client providing a
|
||||
* logical name for the target service.
|
||||
*/
|
||||
audience?: string;
|
||||
/**
|
||||
* OPTIONAL. A list of space-delimited, case-sensitive strings, as defined
|
||||
* in Section 3.3 of [RFC6749], that allow the client to specify the desired
|
||||
* scope of the requested security token in the context of the service or
|
||||
* resource where the token will be used.
|
||||
*/
|
||||
scope?: string[];
|
||||
/**
|
||||
* OPTIONAL. An identifier, as described in Section 3 of [RFC8693], eg.
|
||||
* "urn:ietf:params:oauth:token-type:access_token" for the type of the
|
||||
* requested security token.
|
||||
*/
|
||||
requestedTokenType?: string;
|
||||
/**
|
||||
* REQUIRED. A security token that represents the identity of the party on
|
||||
* behalf of whom the request is being made.
|
||||
*/
|
||||
subjectToken: string;
|
||||
/**
|
||||
* REQUIRED. An identifier, as described in Section 3 of [RFC8693], that
|
||||
* indicates the type of the security token in the "subject_token" parameter.
|
||||
*/
|
||||
subjectTokenType: string;
|
||||
actingParty?: {
|
||||
/**
|
||||
* OPTIONAL. A security token that represents the identity of the acting
|
||||
* party. Typically, this will be the party that is authorized to use the
|
||||
* requested security token and act on behalf of the subject.
|
||||
*/
|
||||
actorToken: string;
|
||||
/**
|
||||
* An identifier, as described in Section 3, that indicates the type of the
|
||||
* security token in the "actor_token" parameter. This is REQUIRED when the
|
||||
* "actor_token" parameter is present in the request but MUST NOT be
|
||||
* included otherwise.
|
||||
*/
|
||||
actorTokenType: string;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Defines the OAuth 2.0 token exchange successful response based on
|
||||
* https://tools.ietf.org/html/rfc8693#section-2.2.1
|
||||
*/
|
||||
export interface StsSuccessfulResponse {
|
||||
access_token: string;
|
||||
issued_token_type: string;
|
||||
token_type: string;
|
||||
expires_in?: number;
|
||||
refresh_token?: string;
|
||||
scope?: string;
|
||||
res?: GaxiosResponse | null;
|
||||
}
|
||||
export interface StsCredentialsConstructionOptions extends OAuthClientAuthHandlerOptions {
|
||||
/**
|
||||
* The client authentication credentials if available.
|
||||
*/
|
||||
clientAuthentication?: ClientAuthentication;
|
||||
/**
|
||||
* The token exchange endpoint.
|
||||
*/
|
||||
tokenExchangeEndpoint: string | URL;
|
||||
}
|
||||
/**
|
||||
* Implements the OAuth 2.0 token exchange based on
|
||||
* https://tools.ietf.org/html/rfc8693
|
||||
*/
|
||||
export declare class StsCredentials extends OAuthClientAuthHandler {
|
||||
#private;
|
||||
/**
|
||||
* Initializes an STS credentials instance.
|
||||
*
|
||||
* @param options The STS credentials instance options. Passing an `tokenExchangeEndpoint` directly is **@DEPRECATED**.
|
||||
* @param clientAuthentication **@DEPRECATED**. Provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead.
|
||||
*/
|
||||
constructor(options?: StsCredentialsConstructionOptions | string | URL,
|
||||
/**
|
||||
* @deprecated - provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead
|
||||
*/
|
||||
clientAuthentication?: ClientAuthentication);
|
||||
/**
|
||||
* Exchanges the provided token for another type of token based on the
|
||||
* rfc8693 spec.
|
||||
* @param stsCredentialsOptions The token exchange options used to populate
|
||||
* the token exchange request.
|
||||
* @param additionalHeaders Optional additional headers to pass along the
|
||||
* request.
|
||||
* @param options Optional additional GCP-specific non-spec defined options
|
||||
* to send with the request.
|
||||
* Example: `&options=${encodeUriComponent(JSON.stringified(options))}`
|
||||
* @return A promise that resolves with the token exchange response containing
|
||||
* the requested token and its expiration time.
|
||||
*/
|
||||
exchangeToken(stsCredentialsOptions: StsCredentialsOptions, headers?: HeadersInit, options?: Parameters<JSON['stringify']>[0]): Promise<StsSuccessfulResponse>;
|
||||
}
|
||||
106
node_modules/google-auth-library/build/src/auth/stscredentials.js
generated
vendored
Normal file
106
node_modules/google-auth-library/build/src/auth/stscredentials.js
generated
vendored
Normal file
@@ -0,0 +1,106 @@
|
||||
"use strict";
|
||||
// Copyright 2021 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.StsCredentials = void 0;
|
||||
const gaxios_1 = require("gaxios");
|
||||
const authclient_1 = require("./authclient");
|
||||
const oauth2common_1 = require("./oauth2common");
|
||||
const util_1 = require("../util");
|
||||
/**
|
||||
* Implements the OAuth 2.0 token exchange based on
|
||||
* https://tools.ietf.org/html/rfc8693
|
||||
*/
|
||||
class StsCredentials extends oauth2common_1.OAuthClientAuthHandler {
|
||||
#tokenExchangeEndpoint;
|
||||
/**
|
||||
* Initializes an STS credentials instance.
|
||||
*
|
||||
* @param options The STS credentials instance options. Passing an `tokenExchangeEndpoint` directly is **@DEPRECATED**.
|
||||
* @param clientAuthentication **@DEPRECATED**. Provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead.
|
||||
*/
|
||||
constructor(options = {
|
||||
tokenExchangeEndpoint: '',
|
||||
},
|
||||
/**
|
||||
* @deprecated - provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead
|
||||
*/
|
||||
clientAuthentication) {
|
||||
if (typeof options !== 'object' || options instanceof URL) {
|
||||
options = {
|
||||
tokenExchangeEndpoint: options,
|
||||
clientAuthentication,
|
||||
};
|
||||
}
|
||||
super(options);
|
||||
this.#tokenExchangeEndpoint = options.tokenExchangeEndpoint;
|
||||
}
|
||||
/**
|
||||
* Exchanges the provided token for another type of token based on the
|
||||
* rfc8693 spec.
|
||||
* @param stsCredentialsOptions The token exchange options used to populate
|
||||
* the token exchange request.
|
||||
* @param additionalHeaders Optional additional headers to pass along the
|
||||
* request.
|
||||
* @param options Optional additional GCP-specific non-spec defined options
|
||||
* to send with the request.
|
||||
* Example: `&options=${encodeUriComponent(JSON.stringified(options))}`
|
||||
* @return A promise that resolves with the token exchange response containing
|
||||
* the requested token and its expiration time.
|
||||
*/
|
||||
async exchangeToken(stsCredentialsOptions, headers, options) {
|
||||
const values = {
|
||||
grant_type: stsCredentialsOptions.grantType,
|
||||
resource: stsCredentialsOptions.resource,
|
||||
audience: stsCredentialsOptions.audience,
|
||||
scope: stsCredentialsOptions.scope?.join(' '),
|
||||
requested_token_type: stsCredentialsOptions.requestedTokenType,
|
||||
subject_token: stsCredentialsOptions.subjectToken,
|
||||
subject_token_type: stsCredentialsOptions.subjectTokenType,
|
||||
actor_token: stsCredentialsOptions.actingParty?.actorToken,
|
||||
actor_token_type: stsCredentialsOptions.actingParty?.actorTokenType,
|
||||
// Non-standard GCP-specific options.
|
||||
options: options && JSON.stringify(options),
|
||||
};
|
||||
const opts = {
|
||||
...StsCredentials.RETRY_CONFIG,
|
||||
url: this.#tokenExchangeEndpoint.toString(),
|
||||
method: 'POST',
|
||||
headers,
|
||||
data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)),
|
||||
};
|
||||
authclient_1.AuthClient.setMethodName(opts, 'exchangeToken');
|
||||
// Apply OAuth client authentication.
|
||||
this.applyClientAuthenticationOptions(opts);
|
||||
try {
|
||||
const response = await this.transporter.request(opts);
|
||||
// Successful response.
|
||||
const stsSuccessfulResponse = response.data;
|
||||
stsSuccessfulResponse.res = response;
|
||||
return stsSuccessfulResponse;
|
||||
}
|
||||
catch (error) {
|
||||
// Translate error to OAuthError.
|
||||
if (error instanceof gaxios_1.GaxiosError && error.response) {
|
||||
throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data,
|
||||
// Preserve other fields from the original error.
|
||||
error);
|
||||
}
|
||||
// Request could fail before the server responds.
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.StsCredentials = StsCredentials;
|
||||
//# sourceMappingURL=stscredentials.js.map
|
||||
57
node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.d.ts
generated
vendored
Normal file
57
node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.d.ts
generated
vendored
Normal file
@@ -0,0 +1,57 @@
|
||||
import { ExternalAccountSupplierContext } from './baseexternalclient';
|
||||
import { GaxiosOptions } from 'gaxios';
|
||||
import { SubjectTokenFormatType, SubjectTokenSupplier } from './identitypoolclient';
|
||||
/**
|
||||
* Interface that defines options used to build a {@link UrlSubjectTokenSupplier}
|
||||
*/
|
||||
export interface UrlSubjectTokenSupplierOptions {
|
||||
/**
|
||||
* The URL to call to retrieve the subject token. This is typically a local
|
||||
* metadata server.
|
||||
*/
|
||||
url: string;
|
||||
/**
|
||||
* The token file or URL response type (JSON or text).
|
||||
*/
|
||||
formatType: SubjectTokenFormatType;
|
||||
/**
|
||||
* For JSON response types, this is the subject_token field name. For Azure,
|
||||
* this is access_token. For text response types, this is ignored.
|
||||
*/
|
||||
subjectTokenFieldName?: string;
|
||||
/**
|
||||
* The optional additional headers to send with the request to the metadata
|
||||
* server url.
|
||||
*/
|
||||
headers?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
/**
|
||||
* Additional gaxios options to use for the request to the specified URL.
|
||||
*/
|
||||
additionalGaxiosOptions?: GaxiosOptions;
|
||||
}
|
||||
/**
|
||||
* Internal subject token supplier implementation used when a URL
|
||||
* is configured in the credential configuration used to build an {@link IdentityPoolClient}
|
||||
*/
|
||||
export declare class UrlSubjectTokenSupplier implements SubjectTokenSupplier {
|
||||
private readonly url;
|
||||
private readonly headers?;
|
||||
private readonly formatType;
|
||||
private readonly subjectTokenFieldName?;
|
||||
private readonly additionalGaxiosOptions?;
|
||||
/**
|
||||
* Instantiates a URL subject token supplier.
|
||||
* @param opts The URL subject token supplier options to build the supplier with.
|
||||
*/
|
||||
constructor(opts: UrlSubjectTokenSupplierOptions);
|
||||
/**
|
||||
* Sends a GET request to the URL provided in the constructor and resolves
|
||||
* with the returned external subject token.
|
||||
* @param context {@link ExternalAccountSupplierContext} from the calling
|
||||
* {@link IdentityPoolClient}, contains the requested audience and subject
|
||||
* token type for the external account identity. Not used.
|
||||
*/
|
||||
getSubjectToken(context: ExternalAccountSupplierContext): Promise<string>;
|
||||
}
|
||||
70
node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js
generated
vendored
Normal file
70
node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js
generated
vendored
Normal file
@@ -0,0 +1,70 @@
|
||||
"use strict";
|
||||
// Copyright 2024 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.UrlSubjectTokenSupplier = void 0;
|
||||
const authclient_1 = require("./authclient");
|
||||
/**
|
||||
* Internal subject token supplier implementation used when a URL
|
||||
* is configured in the credential configuration used to build an {@link IdentityPoolClient}
|
||||
*/
|
||||
class UrlSubjectTokenSupplier {
|
||||
url;
|
||||
headers;
|
||||
formatType;
|
||||
subjectTokenFieldName;
|
||||
additionalGaxiosOptions;
|
||||
/**
|
||||
* Instantiates a URL subject token supplier.
|
||||
* @param opts The URL subject token supplier options to build the supplier with.
|
||||
*/
|
||||
constructor(opts) {
|
||||
this.url = opts.url;
|
||||
this.formatType = opts.formatType;
|
||||
this.subjectTokenFieldName = opts.subjectTokenFieldName;
|
||||
this.headers = opts.headers;
|
||||
this.additionalGaxiosOptions = opts.additionalGaxiosOptions;
|
||||
}
|
||||
/**
|
||||
* Sends a GET request to the URL provided in the constructor and resolves
|
||||
* with the returned external subject token.
|
||||
* @param context {@link ExternalAccountSupplierContext} from the calling
|
||||
* {@link IdentityPoolClient}, contains the requested audience and subject
|
||||
* token type for the external account identity. Not used.
|
||||
*/
|
||||
async getSubjectToken(context) {
|
||||
const opts = {
|
||||
...this.additionalGaxiosOptions,
|
||||
url: this.url,
|
||||
method: 'GET',
|
||||
headers: this.headers,
|
||||
};
|
||||
authclient_1.AuthClient.setMethodName(opts, 'getSubjectToken');
|
||||
let subjectToken;
|
||||
if (this.formatType === 'text') {
|
||||
const response = await context.transporter.request(opts);
|
||||
subjectToken = response.data;
|
||||
}
|
||||
else if (this.formatType === 'json' && this.subjectTokenFieldName) {
|
||||
const response = await context.transporter.request(opts);
|
||||
subjectToken = response.data[this.subjectTokenFieldName];
|
||||
}
|
||||
if (!subjectToken) {
|
||||
throw new Error('Unable to parse the subject_token from the credential_source URL');
|
||||
}
|
||||
return subjectToken;
|
||||
}
|
||||
}
|
||||
exports.UrlSubjectTokenSupplier = UrlSubjectTokenSupplier;
|
||||
//# sourceMappingURL=urlsubjecttokensupplier.js.map
|
||||
27
node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts
generated
vendored
Normal file
27
node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts
generated
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
import { Crypto, JwkCertificate } from '../shared';
|
||||
export declare class BrowserCrypto implements Crypto {
|
||||
constructor();
|
||||
sha256DigestBase64(str: string): Promise<string>;
|
||||
randomBytesBase64(count: number): string;
|
||||
private static padBase64;
|
||||
verify(pubkey: JwkCertificate, data: string, signature: string): Promise<boolean>;
|
||||
sign(privateKey: JwkCertificate, data: string): Promise<string>;
|
||||
decodeBase64StringUtf8(base64: string): string;
|
||||
encodeBase64StringUtf8(text: string): string;
|
||||
/**
|
||||
* Computes the SHA-256 hash of the provided string.
|
||||
* @param str The plain text string to hash.
|
||||
* @return A promise that resolves with the SHA-256 hash of the provided
|
||||
* string in hexadecimal encoding.
|
||||
*/
|
||||
sha256DigestHex(str: string): Promise<string>;
|
||||
/**
|
||||
* Computes the HMAC hash of a message using the provided crypto key and the
|
||||
* SHA-256 algorithm.
|
||||
* @param key The secret crypto key in utf-8 or ArrayBuffer format.
|
||||
* @param msg The plain text message.
|
||||
* @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
|
||||
* format.
|
||||
*/
|
||||
signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise<ArrayBuffer>;
|
||||
}
|
||||
127
node_modules/google-auth-library/build/src/crypto/browser/crypto.js
generated
vendored
Normal file
127
node_modules/google-auth-library/build/src/crypto/browser/crypto.js
generated
vendored
Normal file
@@ -0,0 +1,127 @@
|
||||
"use strict";
|
||||
// Copyright 2019 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
/* global window */
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.BrowserCrypto = void 0;
|
||||
// This file implements crypto functions we need using in-browser
|
||||
// SubtleCrypto interface `window.crypto.subtle`.
|
||||
const base64js = require("base64-js");
|
||||
const shared_1 = require("../shared");
|
||||
class BrowserCrypto {
|
||||
constructor() {
|
||||
if (typeof window === 'undefined' ||
|
||||
window.crypto === undefined ||
|
||||
window.crypto.subtle === undefined) {
|
||||
throw new Error("SubtleCrypto not found. Make sure it's an https:// website.");
|
||||
}
|
||||
}
|
||||
async sha256DigestBase64(str) {
|
||||
// SubtleCrypto digest() method is async, so we must make
|
||||
// this method async as well.
|
||||
// To calculate SHA256 digest using SubtleCrypto, we first
|
||||
// need to convert an input string to an ArrayBuffer:
|
||||
const inputBuffer = new TextEncoder().encode(str);
|
||||
// Result is ArrayBuffer as well.
|
||||
const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);
|
||||
return base64js.fromByteArray(new Uint8Array(outputBuffer));
|
||||
}
|
||||
randomBytesBase64(count) {
|
||||
const array = new Uint8Array(count);
|
||||
window.crypto.getRandomValues(array);
|
||||
return base64js.fromByteArray(array);
|
||||
}
|
||||
static padBase64(base64) {
|
||||
// base64js requires padding, so let's add some '='
|
||||
while (base64.length % 4 !== 0) {
|
||||
base64 += '=';
|
||||
}
|
||||
return base64;
|
||||
}
|
||||
async verify(pubkey, data, signature) {
|
||||
const algo = {
|
||||
name: 'RSASSA-PKCS1-v1_5',
|
||||
hash: { name: 'SHA-256' },
|
||||
};
|
||||
const dataArray = new TextEncoder().encode(data);
|
||||
const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature));
|
||||
const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']);
|
||||
// SubtleCrypto's verify method is async so we must make
|
||||
// this method async as well.
|
||||
const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray);
|
||||
return result;
|
||||
}
|
||||
async sign(privateKey, data) {
|
||||
const algo = {
|
||||
name: 'RSASSA-PKCS1-v1_5',
|
||||
hash: { name: 'SHA-256' },
|
||||
};
|
||||
const dataArray = new TextEncoder().encode(data);
|
||||
const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']);
|
||||
// SubtleCrypto's sign method is async so we must make
|
||||
// this method async as well.
|
||||
const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray);
|
||||
return base64js.fromByteArray(new Uint8Array(result));
|
||||
}
|
||||
decodeBase64StringUtf8(base64) {
|
||||
const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64));
|
||||
const result = new TextDecoder().decode(uint8array);
|
||||
return result;
|
||||
}
|
||||
encodeBase64StringUtf8(text) {
|
||||
const uint8array = new TextEncoder().encode(text);
|
||||
const result = base64js.fromByteArray(uint8array);
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Computes the SHA-256 hash of the provided string.
|
||||
* @param str The plain text string to hash.
|
||||
* @return A promise that resolves with the SHA-256 hash of the provided
|
||||
* string in hexadecimal encoding.
|
||||
*/
|
||||
async sha256DigestHex(str) {
|
||||
// SubtleCrypto digest() method is async, so we must make
|
||||
// this method async as well.
|
||||
// To calculate SHA256 digest using SubtleCrypto, we first
|
||||
// need to convert an input string to an ArrayBuffer:
|
||||
const inputBuffer = new TextEncoder().encode(str);
|
||||
// Result is ArrayBuffer as well.
|
||||
const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);
|
||||
return (0, shared_1.fromArrayBufferToHex)(outputBuffer);
|
||||
}
|
||||
/**
|
||||
* Computes the HMAC hash of a message using the provided crypto key and the
|
||||
* SHA-256 algorithm.
|
||||
* @param key The secret crypto key in utf-8 or ArrayBuffer format.
|
||||
* @param msg The plain text message.
|
||||
* @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
|
||||
* format.
|
||||
*/
|
||||
async signWithHmacSha256(key, msg) {
|
||||
// Convert key, if provided in ArrayBuffer format, to string.
|
||||
const rawKey = typeof key === 'string'
|
||||
? key
|
||||
: String.fromCharCode(...new Uint16Array(key));
|
||||
const enc = new TextEncoder();
|
||||
const cryptoKey = await window.crypto.subtle.importKey('raw', enc.encode(rawKey), {
|
||||
name: 'HMAC',
|
||||
hash: {
|
||||
name: 'SHA-256',
|
||||
},
|
||||
}, false, ['sign']);
|
||||
return window.crypto.subtle.sign('HMAC', cryptoKey, enc.encode(msg));
|
||||
}
|
||||
}
|
||||
exports.BrowserCrypto = BrowserCrypto;
|
||||
//# sourceMappingURL=crypto.js.map
|
||||
8
node_modules/google-auth-library/build/src/crypto/crypto.d.ts
generated
vendored
Normal file
8
node_modules/google-auth-library/build/src/crypto/crypto.d.ts
generated
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Crypto } from './shared';
|
||||
export * from './shared';
|
||||
export interface CryptoSigner {
|
||||
update(data: string): void;
|
||||
sign(key: string, outputFormat: string): string;
|
||||
}
|
||||
export declare function createCrypto(): Crypto;
|
||||
export declare function hasBrowserCrypto(): boolean;
|
||||
54
node_modules/google-auth-library/build/src/crypto/crypto.js
generated
vendored
Normal file
54
node_modules/google-auth-library/build/src/crypto/crypto.js
generated
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
"use strict";
|
||||
// Copyright 2019 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
/* global window */
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createCrypto = createCrypto;
|
||||
exports.hasBrowserCrypto = hasBrowserCrypto;
|
||||
const crypto_1 = require("./browser/crypto");
|
||||
const crypto_2 = require("./node/crypto");
|
||||
__exportStar(require("./shared"), exports);
|
||||
// Crypto interface will provide required crypto functions.
|
||||
// Use `createCrypto()` factory function to create an instance
|
||||
// of Crypto. It will either use Node.js `crypto` module, or
|
||||
// use browser's SubtleCrypto interface. Since most of the
|
||||
// SubtleCrypto methods return promises, we must make those
|
||||
// methods return promises here as well, even though in Node.js
|
||||
// they are synchronous.
|
||||
function createCrypto() {
|
||||
if (hasBrowserCrypto()) {
|
||||
return new crypto_1.BrowserCrypto();
|
||||
}
|
||||
return new crypto_2.NodeCrypto();
|
||||
}
|
||||
function hasBrowserCrypto() {
|
||||
return (typeof window !== 'undefined' &&
|
||||
typeof window.crypto !== 'undefined' &&
|
||||
typeof window.crypto.subtle !== 'undefined');
|
||||
}
|
||||
//# sourceMappingURL=crypto.js.map
|
||||
25
node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts
generated
vendored
Normal file
25
node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts
generated
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
import { Crypto } from '../shared';
|
||||
export declare class NodeCrypto implements Crypto {
|
||||
sha256DigestBase64(str: string): Promise<string>;
|
||||
randomBytesBase64(count: number): string;
|
||||
verify(pubkey: string, data: string | Buffer, signature: string): Promise<boolean>;
|
||||
sign(privateKey: string, data: string | Buffer): Promise<string>;
|
||||
decodeBase64StringUtf8(base64: string): string;
|
||||
encodeBase64StringUtf8(text: string): string;
|
||||
/**
|
||||
* Computes the SHA-256 hash of the provided string.
|
||||
* @param str The plain text string to hash.
|
||||
* @return A promise that resolves with the SHA-256 hash of the provided
|
||||
* string in hexadecimal encoding.
|
||||
*/
|
||||
sha256DigestHex(str: string): Promise<string>;
|
||||
/**
|
||||
* Computes the HMAC hash of a message using the provided crypto key and the
|
||||
* SHA-256 algorithm.
|
||||
* @param key The secret crypto key in utf-8 or ArrayBuffer format.
|
||||
* @param msg The plain text message.
|
||||
* @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
|
||||
* format.
|
||||
*/
|
||||
signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise<ArrayBuffer>;
|
||||
}
|
||||
83
node_modules/google-auth-library/build/src/crypto/node/crypto.js
generated
vendored
Normal file
83
node_modules/google-auth-library/build/src/crypto/node/crypto.js
generated
vendored
Normal file
@@ -0,0 +1,83 @@
|
||||
"use strict";
|
||||
// Copyright 2019 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.NodeCrypto = void 0;
|
||||
const crypto = require("crypto");
|
||||
class NodeCrypto {
|
||||
async sha256DigestBase64(str) {
|
||||
return crypto.createHash('sha256').update(str).digest('base64');
|
||||
}
|
||||
randomBytesBase64(count) {
|
||||
return crypto.randomBytes(count).toString('base64');
|
||||
}
|
||||
async verify(pubkey, data, signature) {
|
||||
const verifier = crypto.createVerify('RSA-SHA256');
|
||||
verifier.update(data);
|
||||
verifier.end();
|
||||
return verifier.verify(pubkey, signature, 'base64');
|
||||
}
|
||||
async sign(privateKey, data) {
|
||||
const signer = crypto.createSign('RSA-SHA256');
|
||||
signer.update(data);
|
||||
signer.end();
|
||||
return signer.sign(privateKey, 'base64');
|
||||
}
|
||||
decodeBase64StringUtf8(base64) {
|
||||
return Buffer.from(base64, 'base64').toString('utf-8');
|
||||
}
|
||||
encodeBase64StringUtf8(text) {
|
||||
return Buffer.from(text, 'utf-8').toString('base64');
|
||||
}
|
||||
/**
|
||||
* Computes the SHA-256 hash of the provided string.
|
||||
* @param str The plain text string to hash.
|
||||
* @return A promise that resolves with the SHA-256 hash of the provided
|
||||
* string in hexadecimal encoding.
|
||||
*/
|
||||
async sha256DigestHex(str) {
|
||||
return crypto.createHash('sha256').update(str).digest('hex');
|
||||
}
|
||||
/**
|
||||
* Computes the HMAC hash of a message using the provided crypto key and the
|
||||
* SHA-256 algorithm.
|
||||
* @param key The secret crypto key in utf-8 or ArrayBuffer format.
|
||||
* @param msg The plain text message.
|
||||
* @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
|
||||
* format.
|
||||
*/
|
||||
async signWithHmacSha256(key, msg) {
|
||||
const cryptoKey = typeof key === 'string' ? key : toBuffer(key);
|
||||
return toArrayBuffer(crypto.createHmac('sha256', cryptoKey).update(msg).digest());
|
||||
}
|
||||
}
|
||||
exports.NodeCrypto = NodeCrypto;
|
||||
/**
|
||||
* Converts a Node.js Buffer to an ArrayBuffer.
|
||||
* https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer
|
||||
* @param buffer The Buffer input to covert.
|
||||
* @return The ArrayBuffer representation of the input.
|
||||
*/
|
||||
function toArrayBuffer(buffer) {
|
||||
return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
|
||||
}
|
||||
/**
|
||||
* Converts an ArrayBuffer to a Node.js Buffer.
|
||||
* @param arrayBuffer The ArrayBuffer input to covert.
|
||||
* @return The Buffer representation of the input.
|
||||
*/
|
||||
function toBuffer(arrayBuffer) {
|
||||
return Buffer.from(arrayBuffer);
|
||||
}
|
||||
//# sourceMappingURL=crypto.js.map
|
||||
47
node_modules/google-auth-library/build/src/crypto/shared.d.ts
generated
vendored
Normal file
47
node_modules/google-auth-library/build/src/crypto/shared.d.ts
generated
vendored
Normal file
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Crypto interface will provide required crypto functions.
|
||||
* Use `createCrypto()` factory function to create an instance
|
||||
* of Crypto. It will either use Node.js `crypto` module, or
|
||||
* use browser's SubtleCrypto interface. Since most of the
|
||||
* SubtleCrypto methods return promises, we must make those
|
||||
* methods return promises here as well, even though in Node.js
|
||||
* they are synchronous.
|
||||
*/
|
||||
export interface Crypto {
|
||||
sha256DigestBase64(str: string): Promise<string>;
|
||||
randomBytesBase64(n: number): string;
|
||||
verify(pubkey: string | JwkCertificate, data: string | Buffer, signature: string): Promise<boolean>;
|
||||
sign(privateKey: string | JwkCertificate, data: string | Buffer): Promise<string>;
|
||||
decodeBase64StringUtf8(base64: string): string;
|
||||
encodeBase64StringUtf8(text: string): string;
|
||||
/**
|
||||
* Computes the SHA-256 hash of the provided string.
|
||||
* @param str The plain text string to hash.
|
||||
* @return A promise that resolves with the SHA-256 hash of the provided
|
||||
* string in hexadecimal encoding.
|
||||
*/
|
||||
sha256DigestHex(str: string): Promise<string>;
|
||||
/**
|
||||
* Computes the HMAC hash of a message using the provided crypto key and the
|
||||
* SHA-256 algorithm.
|
||||
* @param key The secret crypto key in utf-8 or ArrayBuffer format.
|
||||
* @param msg The plain text message.
|
||||
* @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
|
||||
* format.
|
||||
*/
|
||||
signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise<ArrayBuffer>;
|
||||
}
|
||||
export interface JwkCertificate {
|
||||
kty: string;
|
||||
alg: string;
|
||||
use?: string;
|
||||
kid: string;
|
||||
n: string;
|
||||
e: string;
|
||||
}
|
||||
/**
|
||||
* Converts an ArrayBuffer to a hexadecimal string.
|
||||
* @param arrayBuffer The ArrayBuffer to convert to hexadecimal string.
|
||||
* @return The hexadecimal encoding of the ArrayBuffer.
|
||||
*/
|
||||
export declare function fromArrayBufferToHex(arrayBuffer: ArrayBuffer): string;
|
||||
32
node_modules/google-auth-library/build/src/crypto/shared.js
generated
vendored
Normal file
32
node_modules/google-auth-library/build/src/crypto/shared.js
generated
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
"use strict";
|
||||
// Copyright 2025 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.fromArrayBufferToHex = fromArrayBufferToHex;
|
||||
/**
|
||||
* Converts an ArrayBuffer to a hexadecimal string.
|
||||
* @param arrayBuffer The ArrayBuffer to convert to hexadecimal string.
|
||||
* @return The hexadecimal encoding of the ArrayBuffer.
|
||||
*/
|
||||
function fromArrayBufferToHex(arrayBuffer) {
|
||||
// Convert buffer to byte array.
|
||||
const byteArray = Array.from(new Uint8Array(arrayBuffer));
|
||||
// Convert bytes to hex string.
|
||||
return byteArray
|
||||
.map(byte => {
|
||||
return byte.toString(16).padStart(2, '0');
|
||||
})
|
||||
.join('');
|
||||
}
|
||||
//# sourceMappingURL=shared.js.map
|
||||
37
node_modules/google-auth-library/build/src/index.d.ts
generated
vendored
Normal file
37
node_modules/google-auth-library/build/src/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
import { GoogleAuth } from './auth/googleauth';
|
||||
export * as gcpMetadata from 'gcp-metadata';
|
||||
export * as gaxios from 'gaxios';
|
||||
import { AuthClient } from './auth/authclient';
|
||||
export { AuthClient, DEFAULT_UNIVERSE } from './auth/authclient';
|
||||
export { Compute, ComputeOptions } from './auth/computeclient';
|
||||
export { CredentialBody, CredentialRequest, Credentials, JWTInput, } from './auth/credentials';
|
||||
export { GCPEnv } from './auth/envDetect';
|
||||
export { GoogleAuthOptions, ProjectIdCallback } from './auth/googleauth';
|
||||
export { IAMAuth, RequestMetadata } from './auth/iam';
|
||||
export { IdTokenClient, IdTokenProvider } from './auth/idtokenclient';
|
||||
export { Claims, JWTAccess } from './auth/jwtaccess';
|
||||
export { JWT, JWTOptions } from './auth/jwtclient';
|
||||
export { Impersonated, ImpersonatedOptions } from './auth/impersonated';
|
||||
export { Certificates, CodeChallengeMethod, CodeVerifierResults, GenerateAuthUrlOpts, GetTokenOptions, OAuth2Client, OAuth2ClientOptions, RefreshOptions, TokenInfo, VerifyIdTokenOptions, ClientAuthentication, } from './auth/oauth2client';
|
||||
export { LoginTicket, TokenPayload } from './auth/loginticket';
|
||||
export { UserRefreshClient, UserRefreshClientOptions, } from './auth/refreshclient';
|
||||
export { AwsClient, AwsClientOptions, AwsSecurityCredentialsSupplier, } from './auth/awsclient';
|
||||
export { AwsSecurityCredentials, AwsRequestSigner, } from './auth/awsrequestsigner';
|
||||
export { IdentityPoolClient, IdentityPoolClientOptions, SubjectTokenSupplier, } from './auth/identitypoolclient';
|
||||
export { ExternalAccountClient, ExternalAccountClientOptions, } from './auth/externalclient';
|
||||
export { BaseExternalAccountClient, BaseExternalAccountClientOptions, SharedExternalAccountClientOptions, ExternalAccountSupplierContext, IamGenerateAccessTokenResponse, } from './auth/baseexternalclient';
|
||||
export { CredentialAccessBoundary, DownscopedClient, } from './auth/downscopedclient';
|
||||
export { PluggableAuthClient, PluggableAuthClientOptions, ExecutableError, } from './auth/pluggable-auth-client';
|
||||
export { EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE, ExternalAccountAuthorizedUserClient, ExternalAccountAuthorizedUserClientOptions, } from './auth/externalAccountAuthorizedUserClient';
|
||||
export { PassThroughClient } from './auth/passthrough';
|
||||
type ALL_EXPORTS = (typeof import('./'))[keyof typeof import('./')];
|
||||
/**
|
||||
* A union type for all {@link AuthClient `AuthClient`} constructors.
|
||||
*/
|
||||
export type AnyAuthClientConstructor = Extract<ALL_EXPORTS, typeof AuthClient>;
|
||||
/**
|
||||
* A union type for all {@link AuthClient `AuthClient`}s.
|
||||
*/
|
||||
export type AnyAuthClient = InstanceType<AnyAuthClientConstructor>;
|
||||
declare const auth: GoogleAuth<AuthClient>;
|
||||
export { auth, GoogleAuth };
|
||||
70
node_modules/google-auth-library/build/src/index.js
generated
vendored
Normal file
70
node_modules/google-auth-library/build/src/index.js
generated
vendored
Normal file
@@ -0,0 +1,70 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.GoogleAuth = exports.auth = exports.PassThroughClient = exports.ExternalAccountAuthorizedUserClient = exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = exports.ExecutableError = exports.PluggableAuthClient = exports.DownscopedClient = exports.BaseExternalAccountClient = exports.ExternalAccountClient = exports.IdentityPoolClient = exports.AwsRequestSigner = exports.AwsClient = exports.UserRefreshClient = exports.LoginTicket = exports.ClientAuthentication = exports.OAuth2Client = exports.CodeChallengeMethod = exports.Impersonated = exports.JWT = exports.JWTAccess = exports.IdTokenClient = exports.IAMAuth = exports.GCPEnv = exports.Compute = exports.DEFAULT_UNIVERSE = exports.AuthClient = exports.gaxios = exports.gcpMetadata = void 0;
|
||||
// Copyright 2017 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
const googleauth_1 = require("./auth/googleauth");
|
||||
Object.defineProperty(exports, "GoogleAuth", { enumerable: true, get: function () { return googleauth_1.GoogleAuth; } });
|
||||
// Export common deps to ensure types/instances are the exact match. Useful
|
||||
// for consistently configuring the library across versions.
|
||||
exports.gcpMetadata = require("gcp-metadata");
|
||||
exports.gaxios = require("gaxios");
|
||||
var authclient_1 = require("./auth/authclient");
|
||||
Object.defineProperty(exports, "AuthClient", { enumerable: true, get: function () { return authclient_1.AuthClient; } });
|
||||
Object.defineProperty(exports, "DEFAULT_UNIVERSE", { enumerable: true, get: function () { return authclient_1.DEFAULT_UNIVERSE; } });
|
||||
var computeclient_1 = require("./auth/computeclient");
|
||||
Object.defineProperty(exports, "Compute", { enumerable: true, get: function () { return computeclient_1.Compute; } });
|
||||
var envDetect_1 = require("./auth/envDetect");
|
||||
Object.defineProperty(exports, "GCPEnv", { enumerable: true, get: function () { return envDetect_1.GCPEnv; } });
|
||||
var iam_1 = require("./auth/iam");
|
||||
Object.defineProperty(exports, "IAMAuth", { enumerable: true, get: function () { return iam_1.IAMAuth; } });
|
||||
var idtokenclient_1 = require("./auth/idtokenclient");
|
||||
Object.defineProperty(exports, "IdTokenClient", { enumerable: true, get: function () { return idtokenclient_1.IdTokenClient; } });
|
||||
var jwtaccess_1 = require("./auth/jwtaccess");
|
||||
Object.defineProperty(exports, "JWTAccess", { enumerable: true, get: function () { return jwtaccess_1.JWTAccess; } });
|
||||
var jwtclient_1 = require("./auth/jwtclient");
|
||||
Object.defineProperty(exports, "JWT", { enumerable: true, get: function () { return jwtclient_1.JWT; } });
|
||||
var impersonated_1 = require("./auth/impersonated");
|
||||
Object.defineProperty(exports, "Impersonated", { enumerable: true, get: function () { return impersonated_1.Impersonated; } });
|
||||
var oauth2client_1 = require("./auth/oauth2client");
|
||||
Object.defineProperty(exports, "CodeChallengeMethod", { enumerable: true, get: function () { return oauth2client_1.CodeChallengeMethod; } });
|
||||
Object.defineProperty(exports, "OAuth2Client", { enumerable: true, get: function () { return oauth2client_1.OAuth2Client; } });
|
||||
Object.defineProperty(exports, "ClientAuthentication", { enumerable: true, get: function () { return oauth2client_1.ClientAuthentication; } });
|
||||
var loginticket_1 = require("./auth/loginticket");
|
||||
Object.defineProperty(exports, "LoginTicket", { enumerable: true, get: function () { return loginticket_1.LoginTicket; } });
|
||||
var refreshclient_1 = require("./auth/refreshclient");
|
||||
Object.defineProperty(exports, "UserRefreshClient", { enumerable: true, get: function () { return refreshclient_1.UserRefreshClient; } });
|
||||
var awsclient_1 = require("./auth/awsclient");
|
||||
Object.defineProperty(exports, "AwsClient", { enumerable: true, get: function () { return awsclient_1.AwsClient; } });
|
||||
var awsrequestsigner_1 = require("./auth/awsrequestsigner");
|
||||
Object.defineProperty(exports, "AwsRequestSigner", { enumerable: true, get: function () { return awsrequestsigner_1.AwsRequestSigner; } });
|
||||
var identitypoolclient_1 = require("./auth/identitypoolclient");
|
||||
Object.defineProperty(exports, "IdentityPoolClient", { enumerable: true, get: function () { return identitypoolclient_1.IdentityPoolClient; } });
|
||||
var externalclient_1 = require("./auth/externalclient");
|
||||
Object.defineProperty(exports, "ExternalAccountClient", { enumerable: true, get: function () { return externalclient_1.ExternalAccountClient; } });
|
||||
var baseexternalclient_1 = require("./auth/baseexternalclient");
|
||||
Object.defineProperty(exports, "BaseExternalAccountClient", { enumerable: true, get: function () { return baseexternalclient_1.BaseExternalAccountClient; } });
|
||||
var downscopedclient_1 = require("./auth/downscopedclient");
|
||||
Object.defineProperty(exports, "DownscopedClient", { enumerable: true, get: function () { return downscopedclient_1.DownscopedClient; } });
|
||||
var pluggable_auth_client_1 = require("./auth/pluggable-auth-client");
|
||||
Object.defineProperty(exports, "PluggableAuthClient", { enumerable: true, get: function () { return pluggable_auth_client_1.PluggableAuthClient; } });
|
||||
Object.defineProperty(exports, "ExecutableError", { enumerable: true, get: function () { return pluggable_auth_client_1.ExecutableError; } });
|
||||
var externalAccountAuthorizedUserClient_1 = require("./auth/externalAccountAuthorizedUserClient");
|
||||
Object.defineProperty(exports, "EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE", { enumerable: true, get: function () { return externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE; } });
|
||||
Object.defineProperty(exports, "ExternalAccountAuthorizedUserClient", { enumerable: true, get: function () { return externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient; } });
|
||||
var passthrough_1 = require("./auth/passthrough");
|
||||
Object.defineProperty(exports, "PassThroughClient", { enumerable: true, get: function () { return passthrough_1.PassThroughClient; } });
|
||||
const auth = new googleauth_1.GoogleAuth();
|
||||
exports.auth = auth;
|
||||
//# sourceMappingURL=index.js.map
|
||||
22
node_modules/google-auth-library/build/src/shared.cjs
generated
vendored
Normal file
22
node_modules/google-auth-library/build/src/shared.cjs
generated
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
"use strict";
|
||||
// Copyright 2023 Google LLC
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.USER_AGENT = exports.PRODUCT_NAME = exports.pkg = void 0;
|
||||
const pkg = require('../../package.json');
|
||||
exports.pkg = pkg;
|
||||
const PRODUCT_NAME = 'google-api-nodejs-client';
|
||||
exports.PRODUCT_NAME = PRODUCT_NAME;
|
||||
const USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`;
|
||||
exports.USER_AGENT = USER_AGENT;
|
||||
//# sourceMappingURL=shared.cjs.map
|
||||
7
node_modules/google-auth-library/build/src/shared.d.cts
generated
vendored
Normal file
7
node_modules/google-auth-library/build/src/shared.d.cts
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
declare const pkg: {
|
||||
name: string;
|
||||
version: string;
|
||||
};
|
||||
declare const PRODUCT_NAME = "google-api-nodejs-client";
|
||||
declare const USER_AGENT: string;
|
||||
export { pkg, PRODUCT_NAME, USER_AGENT };
|
||||
151
node_modules/google-auth-library/build/src/util.d.ts
generated
vendored
Normal file
151
node_modules/google-auth-library/build/src/util.d.ts
generated
vendored
Normal file
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* A utility for converting snake_case to camelCase.
|
||||
*
|
||||
* For, for example `my_snake_string` becomes `mySnakeString`.
|
||||
*/
|
||||
export type SnakeToCamel<S> = S extends `${infer FirstWord}_${infer Remainder}` ? `${FirstWord}${Capitalize<SnakeToCamel<Remainder>>}` : S;
|
||||
/**
|
||||
* A utility for converting an type's keys from snake_case
|
||||
* to camelCase, if the keys are strings.
|
||||
*
|
||||
* For example:
|
||||
*
|
||||
* ```ts
|
||||
* {
|
||||
* my_snake_string: boolean;
|
||||
* myCamelString: string;
|
||||
* my_snake_obj: {
|
||||
* my_snake_obj_string: string;
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* becomes:
|
||||
*
|
||||
* ```ts
|
||||
* {
|
||||
* mySnakeString: boolean;
|
||||
* myCamelString: string;
|
||||
* mySnakeObj: {
|
||||
* mySnakeObjString: string;
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* The generated documentation for the camelCase'd properties won't be available
|
||||
* until {@link https://github.com/microsoft/TypeScript/issues/50715} has been
|
||||
* resolved.
|
||||
*/
|
||||
export type SnakeToCamelObject<T> = {
|
||||
[K in keyof T as SnakeToCamel<K>]: T[K] extends {} ? SnakeToCamelObject<T[K]> : T[K];
|
||||
};
|
||||
/**
|
||||
* A utility for adding camelCase versions of a type's snake_case keys, if the
|
||||
* keys are strings, preserving any existing keys.
|
||||
*
|
||||
* For example:
|
||||
*
|
||||
* ```ts
|
||||
* {
|
||||
* my_snake_boolean: boolean;
|
||||
* myCamelString: string;
|
||||
* my_snake_obj: {
|
||||
* my_snake_obj_string: string;
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* becomes:
|
||||
*
|
||||
* ```ts
|
||||
* {
|
||||
* my_snake_boolean: boolean;
|
||||
* mySnakeBoolean: boolean;
|
||||
* myCamelString: string;
|
||||
* my_snake_obj: {
|
||||
* my_snake_obj_string: string;
|
||||
* };
|
||||
* mySnakeObj: {
|
||||
* mySnakeObjString: string;
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
* @remarks
|
||||
*
|
||||
* The generated documentation for the camelCase'd properties won't be available
|
||||
* until {@link https://github.com/microsoft/TypeScript/issues/50715} has been
|
||||
* resolved.
|
||||
*
|
||||
* Tracking: {@link https://github.com/googleapis/google-auth-library-nodejs/issues/1686}
|
||||
*/
|
||||
export type OriginalAndCamel<T> = {
|
||||
[K in keyof T as K | SnakeToCamel<K>]: T[K] extends {} ? OriginalAndCamel<T[K]> : T[K];
|
||||
};
|
||||
/**
|
||||
* Returns the camel case of a provided string.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* Match any `_` and not `_` pair, then return the uppercase of the not `_`
|
||||
* character.
|
||||
*
|
||||
* @param str the string to convert
|
||||
* @returns the camelCase'd string
|
||||
*/
|
||||
export declare function snakeToCamel<T extends string>(str: T): SnakeToCamel<T>;
|
||||
/**
|
||||
* Get the value of `obj[key]` or `obj[camelCaseKey]`, with a preference
|
||||
* for original, non-camelCase key.
|
||||
*
|
||||
* @param obj object to lookup a value in
|
||||
* @returns a `get` function for getting `obj[key || snakeKey]`, if available
|
||||
*/
|
||||
export declare function originalOrCamelOptions<T extends {}>(obj?: T): {
|
||||
get: <K extends keyof OriginalAndCamel<T> & string>(key: K) => OriginalAndCamel<T>[K];
|
||||
};
|
||||
export interface LRUCacheOptions {
|
||||
/**
|
||||
* The maximum number of items to cache.
|
||||
*/
|
||||
capacity: number;
|
||||
/**
|
||||
* An optional max age for items in milliseconds.
|
||||
*/
|
||||
maxAge?: number;
|
||||
}
|
||||
/**
|
||||
* A simple LRU cache utility.
|
||||
* Not meant for external usage.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
export declare class LRUCache<T> {
|
||||
#private;
|
||||
readonly capacity: number;
|
||||
maxAge?: number;
|
||||
constructor(options: LRUCacheOptions);
|
||||
/**
|
||||
* Add an item to the cache.
|
||||
*
|
||||
* @param key the key to upsert
|
||||
* @param value the value of the key
|
||||
*/
|
||||
set(key: string, value: T): void;
|
||||
/**
|
||||
* Get an item from the cache.
|
||||
*
|
||||
* @param key the key to retrieve
|
||||
*/
|
||||
get(key: string): T | undefined;
|
||||
}
|
||||
export declare function removeUndefinedValuesInObject(object: {
|
||||
[key: string]: unknown;
|
||||
}): {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
/**
|
||||
* Helper to check if a path points to a valid file.
|
||||
*/
|
||||
export declare function isValidFile(filePath: string): Promise<boolean>;
|
||||
176
node_modules/google-auth-library/build/src/util.js
generated
vendored
Normal file
176
node_modules/google-auth-library/build/src/util.js
generated
vendored
Normal file
@@ -0,0 +1,176 @@
|
||||
"use strict";
|
||||
// Copyright 2023 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.LRUCache = void 0;
|
||||
exports.snakeToCamel = snakeToCamel;
|
||||
exports.originalOrCamelOptions = originalOrCamelOptions;
|
||||
exports.removeUndefinedValuesInObject = removeUndefinedValuesInObject;
|
||||
exports.isValidFile = isValidFile;
|
||||
exports.getWellKnownCertificateConfigFileLocation = getWellKnownCertificateConfigFileLocation;
|
||||
const fs = require("fs");
|
||||
const os = require("os");
|
||||
const path = require("path");
|
||||
const WELL_KNOWN_CERTIFICATE_CONFIG_FILE = 'certificate_config.json';
|
||||
const CLOUDSDK_CONFIG_DIRECTORY = 'gcloud';
|
||||
/**
|
||||
* Returns the camel case of a provided string.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* Match any `_` and not `_` pair, then return the uppercase of the not `_`
|
||||
* character.
|
||||
*
|
||||
* @param str the string to convert
|
||||
* @returns the camelCase'd string
|
||||
*/
|
||||
function snakeToCamel(str) {
|
||||
return str.replace(/([_][^_])/g, match => match.slice(1).toUpperCase());
|
||||
}
|
||||
/**
|
||||
* Get the value of `obj[key]` or `obj[camelCaseKey]`, with a preference
|
||||
* for original, non-camelCase key.
|
||||
*
|
||||
* @param obj object to lookup a value in
|
||||
* @returns a `get` function for getting `obj[key || snakeKey]`, if available
|
||||
*/
|
||||
function originalOrCamelOptions(obj) {
|
||||
/**
|
||||
*
|
||||
* @param key an index of object, preferably snake_case
|
||||
* @returns the value `obj[key || snakeKey]`, if available
|
||||
*/
|
||||
function get(key) {
|
||||
const o = (obj || {});
|
||||
return o[key] ?? o[snakeToCamel(key)];
|
||||
}
|
||||
return { get };
|
||||
}
|
||||
/**
|
||||
* A simple LRU cache utility.
|
||||
* Not meant for external usage.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
class LRUCache {
|
||||
capacity;
|
||||
/**
|
||||
* Maps are in order. Thus, the older item is the first item.
|
||||
*
|
||||
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map}
|
||||
*/
|
||||
#cache = new Map();
|
||||
maxAge;
|
||||
constructor(options) {
|
||||
this.capacity = options.capacity;
|
||||
this.maxAge = options.maxAge;
|
||||
}
|
||||
/**
|
||||
* Moves the key to the end of the cache.
|
||||
*
|
||||
* @param key the key to move
|
||||
* @param value the value of the key
|
||||
*/
|
||||
#moveToEnd(key, value) {
|
||||
this.#cache.delete(key);
|
||||
this.#cache.set(key, {
|
||||
value,
|
||||
lastAccessed: Date.now(),
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Add an item to the cache.
|
||||
*
|
||||
* @param key the key to upsert
|
||||
* @param value the value of the key
|
||||
*/
|
||||
set(key, value) {
|
||||
this.#moveToEnd(key, value);
|
||||
this.#evict();
|
||||
}
|
||||
/**
|
||||
* Get an item from the cache.
|
||||
*
|
||||
* @param key the key to retrieve
|
||||
*/
|
||||
get(key) {
|
||||
const item = this.#cache.get(key);
|
||||
if (!item)
|
||||
return;
|
||||
this.#moveToEnd(key, item.value);
|
||||
this.#evict();
|
||||
return item.value;
|
||||
}
|
||||
/**
|
||||
* Maintain the cache based on capacity and TTL.
|
||||
*/
|
||||
#evict() {
|
||||
const cutoffDate = this.maxAge ? Date.now() - this.maxAge : 0;
|
||||
/**
|
||||
* Because we know Maps are in order, this item is both the
|
||||
* last item in the list (capacity) and oldest (maxAge).
|
||||
*/
|
||||
let oldestItem = this.#cache.entries().next();
|
||||
while (!oldestItem.done &&
|
||||
(this.#cache.size > this.capacity || // too many
|
||||
oldestItem.value[1].lastAccessed < cutoffDate) // too old
|
||||
) {
|
||||
this.#cache.delete(oldestItem.value[0]);
|
||||
oldestItem = this.#cache.entries().next();
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.LRUCache = LRUCache;
|
||||
// Given and object remove fields where value is undefined.
|
||||
function removeUndefinedValuesInObject(object) {
|
||||
Object.entries(object).forEach(([key, value]) => {
|
||||
if (value === undefined || value === 'undefined') {
|
||||
delete object[key];
|
||||
}
|
||||
});
|
||||
return object;
|
||||
}
|
||||
/**
|
||||
* Helper to check if a path points to a valid file.
|
||||
*/
|
||||
async function isValidFile(filePath) {
|
||||
try {
|
||||
const stats = await fs.promises.lstat(filePath);
|
||||
return stats.isFile();
|
||||
}
|
||||
catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Determines the well-known gcloud location for the certificate config file.
|
||||
* @returns The platform-specific path to the configuration file.
|
||||
* @internal
|
||||
*/
|
||||
function getWellKnownCertificateConfigFileLocation() {
|
||||
const configDir = process.env.CLOUDSDK_CONFIG ||
|
||||
(_isWindows()
|
||||
? path.join(process.env.APPDATA || '', CLOUDSDK_CONFIG_DIRECTORY)
|
||||
: path.join(process.env.HOME || '', '.config', CLOUDSDK_CONFIG_DIRECTORY));
|
||||
return path.join(configDir, WELL_KNOWN_CERTIFICATE_CONFIG_FILE);
|
||||
}
|
||||
/**
|
||||
* Checks if the current operating system is Windows.
|
||||
* @returns True if the OS is Windows, false otherwise.
|
||||
* @internal
|
||||
*/
|
||||
function _isWindows() {
|
||||
return os.platform().startsWith('win');
|
||||
}
|
||||
//# sourceMappingURL=util.js.map
|
||||
88
node_modules/google-auth-library/package.json
generated
vendored
Normal file
88
node_modules/google-auth-library/package.json
generated
vendored
Normal file
@@ -0,0 +1,88 @@
|
||||
{
|
||||
"name": "google-auth-library",
|
||||
"version": "10.5.0",
|
||||
"author": "Google Inc.",
|
||||
"description": "Google APIs Authentication Client Library for Node.js",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"main": "./build/src/index.js",
|
||||
"types": "./build/src/index.d.ts",
|
||||
"repository": "googleapis/google-auth-library-nodejs.git",
|
||||
"keywords": [
|
||||
"google",
|
||||
"api",
|
||||
"google apis",
|
||||
"client",
|
||||
"client library"
|
||||
],
|
||||
"dependencies": {
|
||||
"base64-js": "^1.3.0",
|
||||
"ecdsa-sig-formatter": "^1.0.11",
|
||||
"gaxios": "^7.0.0",
|
||||
"gcp-metadata": "^8.0.0",
|
||||
"google-logging-utils": "^1.0.0",
|
||||
"gtoken": "^8.0.0",
|
||||
"jws": "^4.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/base64-js": "^1.2.5",
|
||||
"@types/jws": "^3.1.0",
|
||||
"@types/mocha": "^10.0.10",
|
||||
"@types/mv": "^2.1.0",
|
||||
"@types/ncp": "^2.0.1",
|
||||
"@types/node": "^22.0.0",
|
||||
"@types/sinon": "^17.0.0",
|
||||
"assert-rejects": "^1.0.0",
|
||||
"c8": "^10.0.0",
|
||||
"codecov": "^3.0.2",
|
||||
"gts": "^6.0.0",
|
||||
"is-docker": "^3.0.0",
|
||||
"jsdoc": "^4.0.0",
|
||||
"jsdoc-fresh": "^5.0.0",
|
||||
"jsdoc-region-tag": "^4.0.0",
|
||||
"karma": "^6.0.0",
|
||||
"karma-chrome-launcher": "^3.0.0",
|
||||
"karma-coverage": "^2.0.0",
|
||||
"karma-firefox-launcher": "^2.0.0",
|
||||
"karma-mocha": "^2.0.0",
|
||||
"karma-sourcemap-loader": "^0.4.0",
|
||||
"karma-webpack": "^5.0.1",
|
||||
"keypair": "^1.0.4",
|
||||
"mocha": "^11.1.0",
|
||||
"mv": "^2.1.1",
|
||||
"ncp": "^2.0.0",
|
||||
"nock": "^14.0.5",
|
||||
"null-loader": "^4.0.0",
|
||||
"puppeteer": "^24.0.0",
|
||||
"sinon": "^21.0.0",
|
||||
"ts-loader": "^8.0.0",
|
||||
"typescript": "5.8.2",
|
||||
"webpack": "^5.21.2",
|
||||
"webpack-cli": "^4.0.0"
|
||||
},
|
||||
"files": [
|
||||
"build/src",
|
||||
"!build/src/**/*.map"
|
||||
],
|
||||
"scripts": {
|
||||
"test": "c8 mocha build/test",
|
||||
"clean": "gts clean",
|
||||
"prepare": "npm run compile",
|
||||
"lint": "gts check --no-inline-config",
|
||||
"compile": "tsc -p .",
|
||||
"fix": "gts fix",
|
||||
"pretest": "npm run compile -- --sourceMap",
|
||||
"docs": "jsdoc -c .jsdoc.js",
|
||||
"samples-setup": "cd samples/ && npm link ../ && npm run setup && cd ../",
|
||||
"samples-test": "cd samples/ && npm link ../ && npm test && cd ../",
|
||||
"system-test": "mocha build/system-test --timeout 60000",
|
||||
"presystem-test": "npm run compile -- --sourceMap",
|
||||
"webpack": "webpack",
|
||||
"browser-test": "karma start",
|
||||
"docs-test": "echo 'disabled until linkinator is fixed'",
|
||||
"predocs-test": "npm run docs",
|
||||
"prelint": "cd samples; npm link ../; npm install"
|
||||
},
|
||||
"license": "Apache-2.0"
|
||||
}
|
||||
Reference in New Issue
Block a user