Updating NPM dependencies

This commit is contained in:
Drew Heavner
2020-11-11 13:30:52 +00:00
committed by GitHub
parent 7a6fb66c63
commit bd487ef324
9068 changed files with 1400893 additions and 587661 deletions

View File

@@ -1,27 +1,14 @@
/**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* 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.
*/
/// <reference types="node" />
import { EventEmitter } from 'events';
import { GaxiosOptions, GaxiosPromise } from 'gaxios';
import { DefaultTransporter } from '../transporters';
import { Credentials } from './credentials';
import { Headers } from './oauth2client';
export declare interface AuthClient {
on(event: 'tokens', listener: (tokens: Credentials) => void): this;
}
export declare abstract class AuthClient extends EventEmitter {
protected quotaProjectId?: string;
transporter: DefaultTransporter;
credentials: Credentials;
/**
@@ -32,4 +19,13 @@ export declare abstract class AuthClient extends EventEmitter {
* 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 objedcdt to append additional headers to.
*/
protected addSharedMetadataHeaders(headers: Headers): Headers;
}

View File

@@ -1,20 +1,19 @@
"use strict";
/**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* 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.
*/
// 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 = void 0;
const events_1 = require("events");
const transporters_1 = require("../transporters");
class AuthClient extends events_1.EventEmitter {
@@ -29,6 +28,24 @@ class AuthClient extends events_1.EventEmitter {
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 objedcdt 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['x-goog-user-project'] && // don't override a value the user sets.
this.quotaProjectId) {
headers['x-goog-user-project'] = this.quotaProjectId;
}
return headers;
}
}
exports.AuthClient = AuthClient;
//# sourceMappingURL=authclient.js.map

View File

@@ -1,18 +1,3 @@
/**
* Copyright 2013 Google Inc. All Rights Reserved.
*
* 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 { GaxiosError } from 'gaxios';
import { GetTokenResponse, OAuth2Client, RefreshOptions } from './oauth2client';
export interface ComputeOptions extends RefreshOptions {
@@ -38,17 +23,15 @@ export declare class Compute extends OAuth2Client {
* See: https://developers.google.com/compute/docs/authentication
*/
constructor(options?: ComputeOptions);
/**
* Indicates whether the credential requires scopes to be created by calling
* createdScoped before use.
* @deprecated
* @return Boolean indicating if scope is required.
*/
createScopedRequired(): boolean;
/**
* Refreshes the access token.
* @param refreshToken Unused parameter
*/
protected refreshTokenNoCache(refreshToken?: string | null): 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;
}

View File

@@ -1,23 +1,21 @@
"use strict";
/**
* Copyright 2013 Google Inc. All Rights Reserved.
*
* 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.
*/
// 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 arrify = require("arrify");
const gcpMetadata = require("gcp-metadata");
const messages = require("../messages");
const oauth2client_1 = require("./oauth2client");
class Compute extends oauth2client_1.OAuth2Client {
/**
@@ -34,24 +32,13 @@ class Compute extends oauth2client_1.OAuth2Client {
this.serviceAccountEmail = options.serviceAccountEmail || 'default';
this.scopes = arrify(options.scopes);
}
/**
* Indicates whether the credential requires scopes to be created by calling
* createdScoped before use.
* @deprecated
* @return Boolean indicating if scope is required.
*/
createScopedRequired() {
// On compute engine, scopes are specified at the compute instance's
// creation time, and cannot be changed. For this reason, always return
// false.
messages.warn(messages.COMPUTE_CREATE_SCOPED_DEPRECATED);
return false;
}
/**
* Refreshes the access token.
* @param refreshToken Unused parameter
*/
async refreshTokenNoCache(refreshToken) {
async refreshTokenNoCache(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
refreshToken) {
const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`;
let data;
try {
@@ -78,6 +65,26 @@ class Compute extends oauth2client_1.OAuth2Client {
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) {
e.message = `Could not fetch ID token: ${e.message}`;
throw e;
}
return idToken;
}
wrapError(e) {
const res = e.response;
if (res && res.status) {

View File

@@ -1,31 +1,54 @@
/**
* Copyright 2014 Google Inc. All Rights Reserved.
*
* 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.
*/
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;
@@ -36,6 +59,7 @@ export interface JWTInput {
client_id?: string;
client_secret?: string;
refresh_token?: string;
quota_project_id?: string;
}
export interface CredentialBody {
client_email?: string;

View File

@@ -1,18 +1,16 @@
"use strict";
/**
* Copyright 2014 Google Inc. All Rights Reserved.
*
* 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.
*/
// 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

View File

@@ -1,18 +1,3 @@
/**
* Copyright 2018 Google LLC. All Rights Reserved.
*
* 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.
*/
export declare enum GCPEnv {
APP_ENGINE = "APP_ENGINE",
KUBERNETES_ENGINE = "KUBERNETES_ENGINE",

View File

@@ -1,20 +1,19 @@
"use strict";
/**
* Copyright 2018 Google LLC. All Rights Reserved.
*
* 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.
*/
// 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.getEnv = exports.clear = exports.GCPEnv = void 0;
const gcpMetadata = require("gcp-metadata");
var GCPEnv;
(function (GCPEnv) {
@@ -24,34 +23,40 @@ var GCPEnv;
GCPEnv["COMPUTE_ENGINE"] = "COMPUTE_ENGINE";
GCPEnv["NONE"] = "NONE";
})(GCPEnv = exports.GCPEnv || (exports.GCPEnv = {}));
let env;
let envPromise;
function clear() {
env = undefined;
envPromise = undefined;
}
exports.clear = clear;
async function getEnv() {
if (!env) {
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 {
env = GCPEnv.COMPUTE_ENGINE;
}
if (envPromise) {
return envPromise;
}
envPromise = getEnvMemoized();
return envPromise;
}
exports.getEnv = getEnv;
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 {
env = GCPEnv.NONE;
env = GCPEnv.COMPUTE_ENGINE;
}
}
else {
env = GCPEnv.NONE;
}
return env;
}
exports.getEnv = getEnv;
function isAppEngine() {
return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME);
}

View File

@@ -1,24 +1,10 @@
/**
* Copyright 2019 Google LLC. All Rights Reserved.
*
* 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.
*/
/// <reference types="node" />
import { GaxiosOptions, GaxiosResponse } from 'gaxios';
import * as stream from 'stream';
import { DefaultTransporter, Transporter } from '../transporters';
import { Compute } from './computeclient';
import { CredentialBody, JWTInput } from './credentials';
import { IdTokenClient } from './idtokenclient';
import { GCPEnv } from './envDetect';
import { JWT, JWTOptions } from './jwtclient';
import { Headers, OAuth2Client, OAuth2ClientOptions, RefreshOptions } from './oauth2client';
@@ -73,11 +59,16 @@ export declare class GoogleAuth {
* @private
*/
private checkIsGCE?;
readonly isGCE: boolean | undefined;
get isGCE(): boolean | undefined;
private _getDefaultProjectIdPromise?;
private _cachedProjectId?;
jsonContent: JWTInput | null;
cachedCredential: JWT | UserRefreshClient | Compute | 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?;
@@ -86,12 +77,6 @@ export declare class GoogleAuth {
*/
static DefaultTransporter: typeof DefaultTransporter;
constructor(opts?: GoogleAuthOptions);
/**
* THIS METHOD HAS BEEN DEPRECATED.
* It will be removed in 3.0. Please use getProjectId instead.
*/
getDefaultProjectId(): Promise<string>;
getDefaultProjectId(callback: ProjectIdCallback): void;
/**
* Obtains the default project ID for the application.
* @param callback Optional callback
@@ -136,12 +121,6 @@ export declare class GoogleAuth {
* @api private
*/
_getApplicationCredentialsFromFilePath(filePath: string, options?: RefreshOptions): Promise<JWT | UserRefreshClient>;
/**
* Credentials from the Cloud SDK that are associated with Cloud SDK's project
* are problematic because they may not have APIs enabled and have limited
* quota. If this is the case, warn about it.
*/
protected warnOnProblematicCredentials(client: JWT): void;
/**
* Create a credentials instance using the given input options.
* @param json The input object.
@@ -215,6 +194,12 @@ export declare class GoogleAuth {
* options were passed, use Application Default Credentials.
*/
getClient(options?: DeprecatedGetClientOptions): Promise<Compute | JWT | UserRefreshClient>;
/**
* 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.
@@ -257,6 +242,7 @@ export declare class GoogleAuth {
sign(data: string): Promise<string>;
}
export interface SignBlobResponse {
signature: string;
keyId: string;
signedBlob: string;
}
export {};

View File

@@ -1,29 +1,28 @@
"use strict";
/**
* Copyright 2019 Google LLC. All Rights Reserved.
*
* 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.
*/
// 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.CLOUD_SDK_CLIENT_ID = void 0;
const child_process_1 = require("child_process");
const fs = require("fs");
const gcpMetadata = require("gcp-metadata");
const os = require("os");
const path = require("path");
const crypto_1 = require("../crypto/crypto");
const messages = require("../messages");
const transporters_1 = require("../transporters");
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");
@@ -51,15 +50,6 @@ class GoogleAuth {
get isGCE() {
return this.checkIsGCE;
}
getDefaultProjectId(callback) {
messages.warn(messages.DEFAULT_PROJECT_ID_DEPRECATED);
if (callback) {
this.getProjectIdAsync().then(r => callback(null, r), callback);
}
else {
return this.getProjectIdAsync();
}
}
getProjectId(callback) {
if (callback) {
this.getProjectIdAsync().then(r => callback(null, r), callback);
@@ -79,7 +69,11 @@ class GoogleAuth {
// - Cloud SDK: `gcloud config config-helper --format json`
// - GCE project ID from metadata server)
if (!this._getDefaultProjectIdPromise) {
this._getDefaultProjectIdPromise = new Promise(async (resolve, reject) => {
// TODO: refactor the below code so that it doesn't mix and match
// promises and async/await.
this._getDefaultProjectIdPromise = new Promise(
// eslint-disable-next-line no-async-promise-executor
async (resolve, reject) => {
try {
const projectId = this.getProductionProjectId() ||
(await this.getFileProjectId()) ||
@@ -131,6 +125,7 @@ class GoogleAuth {
credential = await this._tryGetApplicationCredentialsFromEnvironmentVariable(options);
if (credential) {
if (credential instanceof jwtclient_1.JWT) {
credential.defaultScopes = this.defaultScopes;
credential.scopes = this.scopes;
}
this.cachedCredential = credential;
@@ -141,6 +136,7 @@ class GoogleAuth {
credential = await this._tryGetApplicationCredentialsFromWellKnownFile(options);
if (credential) {
if (credential instanceof jwtclient_1.JWT) {
credential.defaultScopes = this.defaultScopes;
credential.scopes = this.scopes;
}
this.cachedCredential = credential;
@@ -162,7 +158,7 @@ class GoogleAuth {
}
// For GCE, just return a default ComputeClient. It will take care of
// the rest.
options.scopes = this.scopes;
options.scopes = this.scopes || this.defaultScopes;
this.cachedCredential = new computeclient_1.Compute(options);
projectId = await this.getProjectId();
return { projectId, credential: this.cachedCredential };
@@ -229,7 +225,6 @@ class GoogleAuth {
}
// The file seems to exist. Try to use it.
const client = await this._getApplicationCredentialsFromFilePath(location, options);
this.warnOnProblematicCredentials(client);
return client;
}
/**
@@ -261,16 +256,6 @@ class GoogleAuth {
const readStream = fs.createReadStream(filePath);
return this.fromStream(readStream, options);
}
/**
* Credentials from the Cloud SDK that are associated with Cloud SDK's project
* are problematic because they may not have APIs enabled and have limited
* quota. If this is the case, warn about it.
*/
warnOnProblematicCredentials(client) {
if (client.email === exports.CLOUD_SDK_CLIENT_ID) {
messages.warn(messages.PROBLEMATIC_CREDENTIALS_WARNING);
}
}
/**
* Create a credentials instance using the given input options.
* @param json The input object.
@@ -289,6 +274,7 @@ class GoogleAuth {
else {
options.scopes = this.scopes;
client = new jwtclient_1.JWT(options);
client.defaultScopes = this.defaultScopes;
}
client.fromJSON(json);
return client;
@@ -310,6 +296,7 @@ class GoogleAuth {
else {
options.scopes = this.scopes;
client = new jwtclient_1.JWT(options);
client.defaultScopes = this.defaultScopes;
}
client.fromJSON(json);
// cache both raw data used to instantiate client and client itself.
@@ -384,7 +371,7 @@ class GoogleAuth {
*/
async getDefaultServiceProjectId() {
return new Promise(resolve => {
child_process_1.exec('gcloud config config-helper --format json', (err, stdout, stderr) => {
child_process_1.exec('gcloud config config-helper --format json', (err, stdout) => {
if (!err && stdout) {
try {
const projectId = JSON.parse(stdout).configuration.properties.core
@@ -505,6 +492,18 @@ class GoogleAuth {
}
return this.cachedCredential;
}
/**
* 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.
@@ -539,7 +538,7 @@ class GoogleAuth {
* HTTP request using the given options.
* @param opts Axios request options for the HTTP request.
*/
// tslint:disable-next-line no-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async request(opts) {
const client = await this.getClient();
return client.request(opts);
@@ -570,13 +569,15 @@ class GoogleAuth {
if (!creds.client_email) {
throw new Error('Cannot sign data without `client_email`.');
}
const id = `projects/${projectId}/serviceAccounts/${creds.client_email}`;
const url = `https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${creds.client_email}:signBlob`;
const res = await this.request({
method: 'POST',
url: `https://iam.googleapis.com/v1/${id}:signBlob`,
data: { bytesToSign: crypto.encodeBase64StringUtf8(data) },
url,
data: {
payload: crypto.encodeBase64StringUtf8(data),
},
});
return res.data.signature;
return res.data.signedBlob;
}
}
exports.GoogleAuth = GoogleAuth;

View File

@@ -1,18 +1,3 @@
/**
* Copyright 2014 Google Inc. All Rights Reserved.
*
* 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.
*/
export interface RequestMetadata {
'x-goog-iam-authority-selector': string;
'x-goog-iam-authorization-token': string;
@@ -28,21 +13,6 @@ export declare class IAMAuth {
* @constructor
*/
constructor(selector: string, token: string);
/**
* Indicates whether the credential requires scopes to be created by calling
* createdScoped before use.
* @deprecated
* @return always false
*/
createScopedRequired(): boolean;
/**
* Pass the selector and token to the metadataFn callback.
* @deprecated
* @param unused_uri is required of the credentials interface
* @param metadataFn a callback invoked with object containing request
* metadata.
*/
getRequestMetadata(unusedUri: string | null, metadataFn: (err: Error | null, metadata?: RequestMetadata) => void): void;
/**
* Acquire the HTTP headers required to make an authenticated request.
*/

View File

@@ -1,21 +1,19 @@
"use strict";
/**
* Copyright 2014 Google Inc. All Rights Reserved.
*
* 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.
*/
// 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 });
const messages = require("../messages");
exports.IAMAuth = void 0;
class IAMAuth {
/**
* IAM credentials.
@@ -30,28 +28,6 @@ class IAMAuth {
this.selector = selector;
this.token = token;
}
/**
* Indicates whether the credential requires scopes to be created by calling
* createdScoped before use.
* @deprecated
* @return always false
*/
createScopedRequired() {
// IAM authorization does not use scopes.
messages.warn(messages.IAM_CREATE_SCOPED_DEPRECATED);
return false;
}
/**
* Pass the selector and token to the metadataFn callback.
* @deprecated
* @param unused_uri is required of the credentials interface
* @param metadataFn a callback invoked with object containing request
* metadata.
*/
getRequestMetadata(unusedUri, metadataFn) {
messages.warn(messages.IAM_GET_REQUEST_METADATA_DEPRECATED);
metadataFn(null, this.getRequestHeaders());
}
/**
* Acquire the HTTP headers required to make an authenticated request.
*/

View File

@@ -0,0 +1,27 @@
import { OAuth2Client, RequestMetadataResponse } from './oauth2client';
export interface IdTokenOptions {
/**
* 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 access token from the metadata server.
* See: https://developers.google.com/compute/docs/authentication
*/
constructor(options: IdTokenOptions);
protected getRequestMetadataAsync(url?: string | null): Promise<RequestMetadataResponse>;
private getIdTokenExpiryDate;
}

View File

@@ -0,0 +1,55 @@
"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 {
/**
* Google ID Token client
*
* Retrieve access token from the metadata server.
* See: https://developers.google.com/compute/docs/authentication
*/
constructor(options) {
super();
this.targetAudience = options.targetAudience;
this.idTokenProvider = options.idTokenProvider;
}
async getRequestMetadataAsync(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
url) {
if (!this.credentials.id_token ||
(this.credentials.expiry_date || 0) < Date.now()) {
const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience);
this.credentials = {
id_token: idToken,
expiry_date: this.getIdTokenExpiryDate(idToken),
};
}
const 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

View File

@@ -1,22 +1,7 @@
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.
*/
/// <reference types="node" />
import * as stream from 'stream';
import { JWTInput } from './credentials';
import { Headers, RequestMetadataResponse } from './oauth2client';
import { Headers } from './oauth2client';
export interface Claims {
[index: string]: string;
}
@@ -25,6 +10,7 @@ export declare class JWTAccess {
key?: string | null;
keyId?: string | null;
projectId?: string;
eagerRefreshThresholdMillis: number;
private cache;
/**
* JWTAccess service account credentials.
@@ -36,24 +22,7 @@ export declare class JWTAccess {
* @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);
/**
* Indicates whether the credential requires scopes to be created by calling
* createdScoped before use.
* @deprecated
* @return always false
*/
createScopedRequired(): boolean;
/**
* Get a non-expired access token, after refreshing if necessary.
*
* @param authURI The URI being authorized.
* @param additionalClaims An object with a set of additional claims to
* include in the payload.
* @deprecated Please use `getRequestHeaders` instead.
* @returns An object that includes the authorization header.
*/
getRequestMetadata(url: string, additionalClaims?: Claims): RequestMetadataResponse;
constructor(email?: string | null, key?: string | null, keyId?: string | null, eagerRefreshThresholdMillis?: number);
/**
* Get a non-expired access token, after refreshing if necessary.
*
@@ -63,6 +32,13 @@ export declare class JWTAccess {
* @returns An object that includes the authorization header.
*/
getRequestHeaders(url: string, additionalClaims?: Claims): 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.

View File

@@ -1,23 +1,21 @@
"use strict";
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.
*/
// 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 LRU = require("lru-cache");
const messages = require("../messages");
const DEFAULT_HEADER = {
alg: 'RS256',
typ: 'JWT',
@@ -33,35 +31,15 @@ class JWTAccess {
* @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) {
this.cache = new LRU({ max: 500, maxAge: 60 * 60 * 1000 });
constructor(email, key, keyId, eagerRefreshThresholdMillis) {
this.cache = new LRU({
max: 500,
maxAge: 60 * 60 * 1000,
});
this.email = email;
this.key = key;
this.keyId = keyId;
}
/**
* Indicates whether the credential requires scopes to be created by calling
* createdScoped before use.
* @deprecated
* @return always false
*/
createScopedRequired() {
// JWT Header authentication does not use scopes.
messages.warn(messages.JWT_ACCESS_CREATE_SCOPED_DEPRECATED);
return false;
}
/**
* Get a non-expired access token, after refreshing if necessary.
*
* @param authURI The URI being authorized.
* @param additionalClaims An object with a set of additional claims to
* include in the payload.
* @deprecated Please use `getRequestHeaders` instead.
* @returns An object that includes the authorization header.
*/
getRequestMetadata(url, additionalClaims) {
messages.warn(messages.JWT_ACCESS_GET_REQUEST_METADATA_DEPRECATED);
return { headers: this.getRequestHeaders(url, additionalClaims) };
this.eagerRefreshThresholdMillis = eagerRefreshThresholdMillis !== null && eagerRefreshThresholdMillis !== void 0 ? eagerRefreshThresholdMillis : 5 * 60 * 1000;
}
/**
* Get a non-expired access token, after refreshing if necessary.
@@ -72,12 +50,16 @@ class JWTAccess {
* @returns An object that includes the authorization header.
*/
getRequestHeaders(url, additionalClaims) {
// Return cached authorization headers, unless we are within
// eagerRefreshThresholdMillis ms of them expiring:
const cachedToken = this.cache.get(url);
if (cachedToken) {
return cachedToken;
const now = Date.now();
if (cachedToken &&
cachedToken.expiration - now > this.eagerRefreshThresholdMillis) {
return cachedToken.headers;
}
const iat = Math.floor(new Date().getTime() / 1000);
const exp = iat + 3600; // 3600 seconds = 1 hour
const iat = Math.floor(Date.now() / 1000);
const exp = JWTAccess.getExpirationTime(iat);
// The payload used for signed JWT headers has:
// iss == sub == <client email>
// aud == <the authorization uri>
@@ -98,14 +80,28 @@ class JWTAccess {
}
}
const header = this.keyId
? Object.assign(Object.assign({}, DEFAULT_HEADER), { kid: this.keyId }) : DEFAULT_HEADER;
? { ...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 = { Authorization: `Bearer ${signedJWT}` };
this.cache.set(url, headers);
this.cache.set(url, {
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.
@@ -128,7 +124,7 @@ class JWTAccess {
}
fromStream(inputStream, callback) {
if (callback) {
this.fromStreamAsync(inputStream).then(r => callback(), callback);
this.fromStreamAsync(inputStream).then(() => callback(), callback);
}
else {
return this.fromStreamAsync(inputStream);

View File

@@ -1,22 +1,8 @@
/**
* Copyright 2013 Google Inc. All Rights Reserved.
*
* 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.
*/
/// <reference types="node" />
import { GoogleToken } from 'gtoken';
import * as stream from 'stream';
import { CredentialBody, Credentials, JWTInput } from './credentials';
import { IdTokenProvider } from './idtokenclient';
import { GetTokenResponse, OAuth2Client, RefreshOptions, RequestMetadataResponse } from './oauth2client';
export interface JWTOptions extends RefreshOptions {
email?: string;
@@ -27,11 +13,12 @@ export interface JWTOptions extends RefreshOptions {
subject?: string;
additionalClaims?: {};
}
export declare class JWT extends OAuth2Client {
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;
@@ -65,16 +52,18 @@ export declare class JWT extends OAuth2Client {
*/
protected getRequestMetadataAsync(url?: string | null): Promise<RequestMetadataResponse>;
/**
* Indicates whether the credential requires scopes to be created by calling
* createScoped before use.
* @deprecated
* @return false if createScoped does not need to be called.
* Fetches an ID token.
* @param targetAudience the audience for the fetched ID token.
*/
createScopedRequired(): boolean;
fetchIdToken(targetAudience: string): Promise<string>;
/**
* Determine if there are currently scopes available.
*/
private hasScopes;
private hasUserScopes;
/**
* Are there any default or user scopes defined.
*/
private hasAnyScopes;
/**
* Get the initial access token using gToken.
* @param callback Optional callback.

View File

@@ -1,22 +1,20 @@
"use strict";
/**
* Copyright 2013 Google Inc. All Rights Reserved.
*
* 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.
*/
// 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 messages = require("../messages");
const jwtaccess_1 = require("./jwtaccess");
const oauth2client_1 = require("./oauth2client");
class JWT extends oauth2client_1.OAuth2Client {
@@ -59,49 +57,75 @@ class JWT extends oauth2client_1.OAuth2Client {
* @param url the URI being authorized.
*/
async getRequestMetadataAsync(url) {
if (!this.apiKey && !this.hasScopes() && url) {
if (!this.apiKey && !this.hasUserScopes() && url) {
if (this.additionalClaims &&
this.additionalClaims.target_audience) {
const { tokens } = await this.refreshToken();
return { headers: { Authorization: `Bearer ${tokens.id_token}` } };
return {
headers: this.addSharedMetadataHeaders({
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.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis);
}
const headers = await this.access.getRequestHeaders(url, this.additionalClaims);
return { headers };
return { headers: this.addSharedMetadataHeaders(headers) };
}
}
else {
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: {} };
}
}
/**
* Indicates whether the credential requires scopes to be created by calling
* createScoped before use.
* @deprecated
* @return false if createScoped does not need to be called.
* Fetches an ID token.
* @param targetAudience the audience for the fetched ID token.
*/
createScopedRequired() {
messages.warn(messages.JWT_CREATE_SCOPED_DEPRECATED);
return !this.hasScopes();
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 },
});
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.
*/
hasScopes() {
hasUserScopes() {
if (!this.scopes) {
return false;
}
// For arrays, check the array length.
if (this.scopes instanceof Array) {
return this.scopes.length > 0;
}
// For others, convert to a string and check the length.
return String(this.scopes).length > 0;
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) {
@@ -127,7 +151,9 @@ class JWT extends oauth2client_1.OAuth2Client {
* @param refreshToken ignored
* @private
*/
async refreshTokenNoCache(refreshToken) {
async refreshTokenNoCache(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
refreshToken) {
const gtoken = this.createGToken();
const token = await gtoken.getToken({
forceRefresh: this.isTokenExpiring(),
@@ -149,7 +175,7 @@ class JWT extends oauth2client_1.OAuth2Client {
this.gtoken = new gtoken_1.GoogleToken({
iss: this.email,
sub: this.subject,
scope: this.scopes,
scope: this.scopes || this.defaultScopes,
keyFile: this.keyFile,
key: this.key,
additionalClaims: this.additionalClaims,
@@ -176,10 +202,11 @@ class JWT extends oauth2client_1.OAuth2Client {
this.key = json.private_key;
this.keyId = json.private_key_id;
this.projectId = json.project_id;
this.quotaProjectId = json.quota_project_id;
}
fromStream(inputStream, callback) {
if (callback) {
this.fromStreamAsync(inputStream).then(r => callback(), callback);
this.fromStreamAsync(inputStream).then(() => callback(), callback);
}
else {
return this.fromStreamAsync(inputStream);

View File

@@ -1,18 +1,3 @@
/**
* Copyright 2014 Google Inc. All Rights Reserved.
*
* 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.
*/
export declare class LoginTicket {
private envelope?;
private payload?;
@@ -147,4 +132,9 @@ export interface TokenPayload {
* 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;
}

View File

@@ -1,20 +1,19 @@
"use strict";
/**
* Copyright 2014 Google Inc. All Rights Reserved.
*
* 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.
*/
// 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 {
/**
* Create a simple class to extract user ID from an ID Token

View File

@@ -1,27 +1,32 @@
/**
* Copyright 2019 Google LLC. All Rights Reserved.
*
* 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 { GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios';
import { JwkCertificate } from '../crypto/crypto';
import { BodyResponseCallback } from '../transporters';
import { AuthClient } 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/master/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 interface Headers {
[index: string]: string;
}
@@ -99,6 +104,16 @@ export interface TokenInfo {
* 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 {
/**
@@ -256,12 +271,19 @@ export interface FederatedSignonCertsResponse {
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[];
audience?: string | string[];
maxExpiry?: number;
}
export interface OAuth2ClientOptions extends RefreshOptions {
@@ -318,6 +340,10 @@ export declare class OAuth2Client extends AuthClient {
* Google Sign on certificates in JWK format.
*/
private static readonly GOOGLE_OAUTH2_FEDERATED_SIGNON_JWK_CERTS_URL_;
/**
* Google Sign on certificates in JWK format.
*/
private static readonly GOOGLE_OAUTH2_IAP_PUBLIC_KEY_URL_;
/**
* Clock skew - five minutes in seconds
*/
@@ -338,14 +364,14 @@ export declare class OAuth2Client extends AuthClient {
generateAuthUrl(opts?: GenerateAuthUrlOpts): string;
generateCodeVerifier(): void;
/**
* Convenience method to automatically generate a code_verifier, and it's
* 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/master/samples/oauth2-codeVerifier.js
*/
generateCodeVerifierAsync(): Promise<{
codeVerifier: string;
codeChallenge: string;
}>;
generateCodeVerifierAsync(): Promise<CodeVerifierResults>;
/**
* Gets the access token for the given code.
* @param code The authorization code.
@@ -380,15 +406,6 @@ export declare class OAuth2Client extends AuthClient {
getAccessToken(): Promise<GetAccessTokenResponse>;
getAccessToken(callback: GetAccessTokenCallback): void;
private getAccessTokenAsync;
/**
* Obtain the set of headers required to authenticate a request.
*
* @deprecated Use getRequestHeaders instead.
* @param url the Uri being authorized
* @param callback the func described above
*/
getRequestMetadata(url?: string | null): Promise<RequestMetadataResponse>;
getRequestMetadata(url: string | null, callback: RequestMetadataCallback): void;
/**
* The main authentication interface. It takes an optional url which when
* present is the endpoint being accessed, and returns a Promise which
@@ -455,6 +472,15 @@ export declare class OAuth2Client extends AuthClient {
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
@@ -466,7 +492,7 @@ export declare class OAuth2Client extends AuthClient {
* @param maxExpiry The max expiry the certificate can be (Optional).
* @return Returns a promise resolving to LoginTicket on verification.
*/
verifySignedJwtWithCertsAsync(jwt: string, certs: Certificates, requiredAudience: string | string[], issuers?: string[], maxExpiry?: number): Promise<LoginTicket>;
verifySignedJwtWithCertsAsync(jwt: string, certs: Certificates | PublicKeys, requiredAudience?: string | string[], issuers?: string[], maxExpiry?: number): Promise<LoginTicket>;
/**
* Returns true if a token is expired or will expire within
* eagerRefreshThresholdMillismilliseconds.

View File

@@ -1,24 +1,23 @@
"use strict";
/**
* Copyright 2019 Google LLC. All Rights Reserved.
*
* 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.
*/
// 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.CertificateFormat = exports.CodeChallengeMethod = void 0;
const querystring = require("querystring");
const stream = require("stream");
const formatEcdsa = require("ecdsa-sig-formatter");
const crypto_1 = require("../crypto/crypto");
const messages = require("../messages");
const authclient_1 = require("./authclient");
const loginticket_1 = require("./loginticket");
var CodeChallengeMethod;
@@ -73,9 +72,12 @@ class OAuth2Client extends authclient_1.AuthClient {
throw new Error('generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.');
}
/**
* Convenience method to automatically generate a code_verifier, and it's
* 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/master/samples/oauth2-codeVerifier.js
*/
async generateCodeVerifierAsync() {
// base64 encoding uses 6 bits per character, and we want to generate128
@@ -221,15 +223,6 @@ class OAuth2Client extends authclient_1.AuthClient {
return { token: this.credentials.access_token };
}
}
getRequestMetadata(url, callback) {
messages.warn(messages.OAUTH_GET_REQUEST_METADATA_DEPRECATED);
if (callback) {
this.getRequestMetadataAsync(url).then(r => callback(null, r.headers, r.res), callback);
}
else {
return this.getRequestMetadataAsync();
}
}
/**
* The main authentication interface. It takes an optional url which when
* present is the endpoint being accessed, and returns a Promise which
@@ -240,10 +233,12 @@ class OAuth2Client extends authclient_1.AuthClient {
* @param url The optional url being authorized
*/
async getRequestHeaders(url) {
const res = await this.getRequestMetadataAsync(url);
return res.headers;
const headers = (await this.getRequestMetadataAsync(url)).headers;
return headers;
}
async getRequestMetadataAsync(url) {
async getRequestMetadataAsync(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
url) {
const thisCreds = this.credentials;
if (!thisCreds.access_token && !thisCreds.refresh_token && !this.apiKey) {
throw new Error('No access, refresh token or API key is set.');
@@ -279,7 +274,7 @@ class OAuth2Client extends authclient_1.AuthClient {
const headers = {
Authorization: credentials.token_type + ' ' + tokens.access_token,
};
return { headers, res: r.res };
return { headers: this.addSharedMetadataHeaders(headers), res: r.res };
}
/**
* Generates an URL to revoke the given token.
@@ -335,12 +330,14 @@ class OAuth2Client extends authclient_1.AuthClient {
let r2;
try {
const r = await this.getRequestMetadataAsync(opts.url);
opts.headers = opts.headers || {};
if (r.headers && r.headers['x-goog-user-project']) {
opts.headers['x-goog-user-project'] = r.headers['x-goog-user-project'];
}
if (r.headers && r.headers.Authorization) {
opts.headers = opts.headers || {};
opts.headers.Authorization = r.headers.Authorization;
}
if (this.apiKey) {
opts.headers = opts.headers || {};
opts.headers['X-Goog-Api-Key'] = this.apiKey;
}
r2 = await this.transporter.request(opts);
@@ -406,9 +403,12 @@ class OAuth2Client extends authclient_1.AuthClient {
*/
async getTokenInfo(accessToken) {
const { data } = await this.transporter.request({
method: 'GET',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
url: OAuth2Client.GOOGLE_TOKEN_INFO_URL,
params: { access_token: accessToken },
data: querystring.stringify({ access_token: accessToken }),
});
const info = Object.assign({
expiry_date: new Date().getTime() + data.expires_in * 1000,
@@ -485,6 +485,26 @@ class OAuth2Client extends authclient_1.AuthClient {
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 = OAuth2Client.GOOGLE_OAUTH2_IAP_PUBLIC_KEY_URL_;
try {
res = await this.transporter.request({ url });
}
catch (e) {
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.
@@ -510,7 +530,7 @@ class OAuth2Client extends authclient_1.AuthClient {
throw new Error('Wrong number of segments in token: ' + jwt);
}
const signed = segments[0] + '.' + segments[1];
const signature = segments[2];
let signature = segments[2];
let envelope;
let payload;
try {
@@ -533,11 +553,14 @@ class OAuth2Client extends authclient_1.AuthClient {
if (!payload) {
throw new Error("Can't parse token payload: " + segments[1]);
}
if (!certs.hasOwnProperty(envelope.kid)) {
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);
@@ -634,6 +657,10 @@ OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_PEM_CERTS_URL_ = 'https://www.google
* Google Sign on certificates in JWK format.
*/
OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_JWK_CERTS_URL_ = 'https://www.googleapis.com/oauth2/v3/certs';
/**
* Google Sign on certificates in JWK format.
*/
OAuth2Client.GOOGLE_OAUTH2_IAP_PUBLIC_KEY_URL_ = 'https://www.gstatic.com/iap/verify/public_key';
/**
* Clock skew - five minutes in seconds
*/

View File

@@ -1,18 +1,3 @@
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.
*/
/// <reference types="node" />
import * as stream from 'stream';
import { JWTInput } from './credentials';

View File

@@ -1,20 +1,19 @@
"use strict";
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.
*/
// 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 = void 0;
const oauth2client_1 = require("./oauth2client");
class UserRefreshClient extends oauth2client_1.OAuth2Client {
constructor(optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure) {
@@ -34,13 +33,16 @@ class UserRefreshClient extends oauth2client_1.OAuth2Client {
forceRefreshOnFailure: opts.forceRefreshOnFailure,
});
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(refreshToken) {
async refreshTokenNoCache(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
refreshToken) {
return super.refreshTokenNoCache(this._refreshToken);
}
/**
@@ -68,10 +70,11 @@ class UserRefreshClient extends oauth2client_1.OAuth2Client {
this._clientSecret = json.client_secret;
this._refreshToken = json.refresh_token;
this.credentials.refresh_token = json.refresh_token;
this.quotaProjectId = json.quota_project_id;
}
fromStream(inputStream, callback) {
if (callback) {
this.fromStreamAsync(inputStream).then(r => callback(), callback);
this.fromStreamAsync(inputStream).then(() => callback(), callback);
}
else {
return this.fromStreamAsync(inputStream);

View File

@@ -1,18 +1,3 @@
/**
* Copyright 2019 Google LLC. All Rights Reserved.
*
* 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 { Crypto, JwkCertificate } from '../crypto';
export declare class BrowserCrypto implements Crypto {
constructor();

View File

@@ -1,26 +1,27 @@
"use strict";
/**
* Copyright 2019 Google LLC. All Rights Reserved.
*
* 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.
*/
// 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");
// Not all browsers support `TextEncoder`. The following `require` will
// provide a fast UTF8-only replacement for those browsers that don't support
// text encoding natively.
// eslint-disable-next-line node/no-unsupported-features/node-builtins
if (typeof process === 'undefined' && typeof TextEncoder === 'undefined') {
require('fast-text-encoding');
}
@@ -37,6 +38,7 @@ class BrowserCrypto {
// this method async as well.
// To calculate SHA256 digest using SubtleCrypto, we first
// need to convert an input string to an ArrayBuffer:
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const inputBuffer = new TextEncoder().encode(str);
// Result is ArrayBuffer as well.
const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);
@@ -59,6 +61,7 @@ class BrowserCrypto {
name: 'RSASSA-PKCS1-v1_5',
hash: { name: 'SHA-256' },
};
// eslint-disable-next-line node/no-unsupported-features/node-builtins
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']);
@@ -72,6 +75,7 @@ class BrowserCrypto {
name: 'RSASSA-PKCS1-v1_5',
hash: { name: 'SHA-256' },
};
// eslint-disable-next-line node/no-unsupported-features/node-builtins
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
@@ -81,10 +85,12 @@ class BrowserCrypto {
}
decodeBase64StringUtf8(base64) {
const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64));
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const result = new TextDecoder().decode(uint8array);
return result;
}
encodeBase64StringUtf8(text) {
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const uint8array = new TextEncoder().encode(text);
const result = base64js.fromByteArray(uint8array);
return result;

View File

@@ -1,18 +1,3 @@
/**
* Copyright 2019 Google LLC. All Rights Reserved.
*
* 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.
*/
/// <reference types="node" />
export interface JwkCertificate {
kty: string;

View File

@@ -1,20 +1,20 @@
"use strict";
/**
* Copyright 2019 Google LLC. All Rights Reserved.
*
* 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.
*/
// 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.hasBrowserCrypto = exports.createCrypto = void 0;
const crypto_1 = require("./browser/crypto");
const crypto_2 = require("./node/crypto");
function createCrypto() {

View File

@@ -1,18 +1,3 @@
/**
* Copyright 2019 Google LLC. All Rights Reserved.
*
* 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.
*/
/// <reference types="node" />
import { Crypto } from '../crypto';
export declare class NodeCrypto implements Crypto {

View File

@@ -1,27 +1,23 @@
"use strict";
/**
* Copyright 2019 Google LLC. All Rights Reserved.
*
* 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.
*/
// 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');
return crypto.createHash('sha256').update(str).digest('base64');
}
randomBytesBase64(count) {
return crypto.randomBytes(count).toString('base64');

View File

@@ -1,27 +1,14 @@
/**
* Copyright 2017 Google Inc. All Rights Reserved.
*
* 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 { GoogleAuth } from './auth/googleauth';
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 { Certificates, CodeChallengeMethod, GenerateAuthUrlOpts, GetTokenOptions, OAuth2Client, OAuth2ClientOptions, RefreshOptions, TokenInfo, VerifyIdTokenOptions, } from './auth/oauth2client';
export { Certificates, CodeChallengeMethod, CodeVerifierResults, GenerateAuthUrlOpts, GetTokenOptions, OAuth2Client, OAuth2ClientOptions, RefreshOptions, TokenInfo, VerifyIdTokenOptions, } from './auth/oauth2client';
export { LoginTicket, TokenPayload } from './auth/loginticket';
export { UserRefreshClient, UserRefreshClientOptions, } from './auth/refreshclient';
export { DefaultTransporter } from './transporters';
declare const auth: GoogleAuth;

View File

@@ -1,39 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Copyright 2017 Google Inc. All Rights Reserved.
*
* 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.
*/
exports.GoogleAuth = exports.auth = 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");
exports.GoogleAuth = googleauth_1.GoogleAuth;
Object.defineProperty(exports, "GoogleAuth", { enumerable: true, get: function () { return googleauth_1.GoogleAuth; } });
var computeclient_1 = require("./auth/computeclient");
exports.Compute = computeclient_1.Compute;
Object.defineProperty(exports, "Compute", { enumerable: true, get: function () { return computeclient_1.Compute; } });
var envDetect_1 = require("./auth/envDetect");
exports.GCPEnv = envDetect_1.GCPEnv;
Object.defineProperty(exports, "GCPEnv", { enumerable: true, get: function () { return envDetect_1.GCPEnv; } });
var iam_1 = require("./auth/iam");
exports.IAMAuth = iam_1.IAMAuth;
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");
exports.JWTAccess = jwtaccess_1.JWTAccess;
Object.defineProperty(exports, "JWTAccess", { enumerable: true, get: function () { return jwtaccess_1.JWTAccess; } });
var jwtclient_1 = require("./auth/jwtclient");
exports.JWT = jwtclient_1.JWT;
Object.defineProperty(exports, "JWT", { enumerable: true, get: function () { return jwtclient_1.JWT; } });
var oauth2client_1 = require("./auth/oauth2client");
exports.CodeChallengeMethod = oauth2client_1.CodeChallengeMethod;
exports.OAuth2Client = oauth2client_1.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; } });
var loginticket_1 = require("./auth/loginticket");
Object.defineProperty(exports, "LoginTicket", { enumerable: true, get: function () { return loginticket_1.LoginTicket; } });
var refreshclient_1 = require("./auth/refreshclient");
exports.UserRefreshClient = refreshclient_1.UserRefreshClient;
Object.defineProperty(exports, "UserRefreshClient", { enumerable: true, get: function () { return refreshclient_1.UserRefreshClient; } });
var transporters_1 = require("./transporters");
exports.DefaultTransporter = transporters_1.DefaultTransporter;
Object.defineProperty(exports, "DefaultTransporter", { enumerable: true, get: function () { return transporters_1.DefaultTransporter; } });
const auth = new googleauth_1.GoogleAuth();
exports.auth = auth;
//# sourceMappingURL=index.js.map

View File

@@ -1,18 +1,3 @@
/**
* Copyright 2018 Google LLC. All Rights Reserved.
*
* 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.
*/
export declare enum WarningTypes {
WARNING = "Warning",
DEPRECATION = "DeprecationWarning"
@@ -24,48 +9,3 @@ export interface Warning {
message: string;
warned?: boolean;
}
export declare const PROBLEMATIC_CREDENTIALS_WARNING: {
code: string;
type: WarningTypes;
message: string;
};
export declare const DEFAULT_PROJECT_ID_DEPRECATED: {
code: string;
type: WarningTypes;
message: string;
};
export declare const COMPUTE_CREATE_SCOPED_DEPRECATED: {
code: string;
type: WarningTypes;
message: string;
};
export declare const JWT_CREATE_SCOPED_DEPRECATED: {
code: string;
type: WarningTypes;
message: string;
};
export declare const IAM_CREATE_SCOPED_DEPRECATED: {
code: string;
type: WarningTypes;
message: string;
};
export declare const JWT_ACCESS_CREATE_SCOPED_DEPRECATED: {
code: string;
type: WarningTypes;
message: string;
};
export declare const OAUTH_GET_REQUEST_METADATA_DEPRECATED: {
code: string;
type: WarningTypes;
message: string;
};
export declare const IAM_GET_REQUEST_METADATA_DEPRECATED: {
code: string;
type: WarningTypes;
message: string;
};
export declare const JWT_ACCESS_GET_REQUEST_METADATA_DEPRECATED: {
code: string;
type: WarningTypes;
message: string;
};

View File

@@ -1,20 +1,19 @@
"use strict";
/**
* Copyright 2018 Google LLC. All Rights Reserved.
*
* 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.
*/
// 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.warn = exports.WarningTypes = void 0;
var WarningTypes;
(function (WarningTypes) {
WarningTypes["WARNING"] = "Warning";
@@ -30,7 +29,7 @@ function warn(warning) {
// @types/node doesn't recognize the emitWarning syntax which
// accepts a config object, so `as any` it is
// https://nodejs.org/docs/latest-v8.x/api/process.html#process_process_emitwarning_warning_options
// tslint:disable-next-line no-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
process.emitWarning(warning.message, warning);
}
else {
@@ -38,84 +37,4 @@ function warn(warning) {
}
}
exports.warn = warn;
exports.PROBLEMATIC_CREDENTIALS_WARNING = {
code: 'google-auth-library:00001',
type: WarningTypes.WARNING,
message: [
'Your application has authenticated using end user credentials from Google',
'Cloud SDK. We recommend that most server applications use service accounts',
'instead. If your application continues to use end user credentials from',
'Cloud SDK, you might receive a "quota exceeded" or "API not enabled" error.',
'For more information about service accounts, see',
'https://cloud.google.com/docs/authentication/.',
].join(' '),
};
exports.DEFAULT_PROJECT_ID_DEPRECATED = {
code: 'google-auth-library:DEP002',
type: WarningTypes.DEPRECATION,
message: [
'The `getDefaultProjectId` method has been deprecated, and will be removed',
'in the 3.0 release of google-auth-library. Please use the `getProjectId`',
'method instead.',
].join(' '),
};
exports.COMPUTE_CREATE_SCOPED_DEPRECATED = {
code: 'google-auth-library:DEP003',
type: WarningTypes.DEPRECATION,
message: [
'The `createScopedRequired` method on the `Compute` class has been deprecated,',
'and will be removed in the 3.0 release of google-auth-library.',
].join(' '),
};
exports.JWT_CREATE_SCOPED_DEPRECATED = {
code: 'google-auth-library:DEP004',
type: WarningTypes.DEPRECATION,
message: [
'The `createScopedRequired` method on the `JWT` class has been deprecated,',
'and will be removed in the 3.0 release of google-auth-library.',
].join(' '),
};
exports.IAM_CREATE_SCOPED_DEPRECATED = {
code: 'google-auth-library:DEP005',
type: WarningTypes.DEPRECATION,
message: [
'The `createScopedRequired` method on the `IAM` class has been deprecated,',
'and will be removed in the 3.0 release of google-auth-library.',
].join(' '),
};
exports.JWT_ACCESS_CREATE_SCOPED_DEPRECATED = {
code: 'google-auth-library:DEP006',
type: WarningTypes.DEPRECATION,
message: [
'The `createScopedRequired` method on the `JWTAccess` class has been deprecated,',
'and will be removed in the 3.0 release of google-auth-library.',
].join(' '),
};
exports.OAUTH_GET_REQUEST_METADATA_DEPRECATED = {
code: 'google-auth-library:DEP004',
type: WarningTypes.DEPRECATION,
message: [
'The `getRequestMetadata` method on the `OAuth2` class has been deprecated,',
'and will be removed in the 3.0 release of google-auth-library. Please use',
'the `getRequestHeaders` method instead.',
].join(' '),
};
exports.IAM_GET_REQUEST_METADATA_DEPRECATED = {
code: 'google-auth-library:DEP005',
type: WarningTypes.DEPRECATION,
message: [
'The `getRequestMetadata` method on the `IAM` class has been deprecated,',
'and will be removed in the 3.0 release of google-auth-library. Please use',
'the `getRequestHeaders` method instead.',
].join(' '),
};
exports.JWT_ACCESS_GET_REQUEST_METADATA_DEPRECATED = {
code: 'google-auth-library:DEP006',
type: WarningTypes.DEPRECATION,
message: [
'The `getRequestMetadata` method on the `JWTAccess` class has been deprecated,',
'and will be removed in the 3.0 release of google-auth-library. Please use',
'the `getRequestHeaders` method instead.',
].join(' '),
};
//# sourceMappingURL=messages.js.map

View File

@@ -1,16 +1 @@
/**
* Copyright 2017 Google Inc. All Rights Reserved.
*
* 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.
*/
export declare function validate(options: any): void;

View File

@@ -1,25 +1,24 @@
"use strict";
/**
* Copyright 2017 Google Inc. All Rights Reserved.
*
* 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.
*/
// 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.
Object.defineProperty(exports, "__esModule", { value: true });
exports.validate = void 0;
// Accepts an options object passed from the user to the API. In the
// previous version of the API, it referred to a `Request` options object.
// Now it refers to an Axiox Request Config object. This is here to help
// ensure users don't pass invalid options when they upgrade from 0.x to 1.x.
// tslint:disable-next-line no-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function validate(options) {
const vpairs = [
{ invalid: 'uri', expected: 'url' },

View File

@@ -1,18 +1,3 @@
/**
* Copyright 2019 Google LLC. All Rights Reserved.
*
* 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 { GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios';
export interface Transporter {
request<T>(opts: GaxiosOptions): GaxiosPromise<T>;

View File

@@ -1,23 +1,22 @@
"use strict";
/**
* Copyright 2019 Google LLC. All Rights Reserved.
*
* 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.
*/
// 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.DefaultTransporter = void 0;
const gaxios_1 = require("gaxios");
const options_1 = require("./options");
// tslint:disable-next-line no-var-requires
// eslint-disable-next-line @typescript-eslint/no-var-requires
const pkg = require('../../package.json');
const PRODUCT_NAME = 'google-api-nodejs-client';
class DefaultTransporter {