push all website files

This commit is contained in:
Jacob Levine
2019-01-06 13:14:45 -06:00
parent d7301e26c3
commit d2d5d4c04e
15662 changed files with 2166516 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
/**
* 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 { AxiosPromise, AxiosRequestConfig } from 'axios';
import { EventEmitter } from 'events';
import { DefaultTransporter } from '../transporters';
import { Credentials } from './credentials';
export declare interface AuthClient {
on(event: 'tokens', listener: (tokens: Credentials) => void): this;
}
export declare abstract class AuthClient extends EventEmitter {
transporter: DefaultTransporter;
credentials: Credentials;
/**
* Provides an alternative Axios request implementation with auth credentials
*/
abstract request<T>(opts: AxiosRequestConfig): AxiosPromise<T>;
/**
* Sets the auth credentials.
*/
setCredentials(credentials: Credentials): void;
}

View File

@@ -0,0 +1,47 @@
"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.
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var events_1 = require("events");
var transporters_1 = require("../transporters");
var AuthClient = /** @class */ (function (_super) {
__extends(AuthClient, _super);
function AuthClient() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.transporter = new transporters_1.DefaultTransporter();
_this.credentials = {};
return _this;
}
/**
* Sets the auth credentials.
*/
AuthClient.prototype.setCredentials = function (credentials) {
this.credentials = credentials;
};
return AuthClient;
}(events_1.EventEmitter));
exports.AuthClient = AuthClient;
//# sourceMappingURL=authclient.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"authclient.js","sourceRoot":"","sources":["../../../src/auth/authclient.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;AAGH,iCAAoC;AAEpC,gDAAmD;AAQnD;IAAyC,8BAAY;IAArD;QAAA,qEAeC;QAdC,iBAAW,GAAG,IAAI,iCAAkB,EAAE,CAAC;QACvC,iBAAW,GAAgB,EAAE,CAAC;;IAahC,CAAC;IANC;;OAEG;IACH,mCAAc,GAAd,UAAe,WAAwB;QACrC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;IACH,iBAAC;AAAD,CAAC,AAfD,CAAyC,qBAAY,GAepD;AAfqB,gCAAU"}

View File

@@ -0,0 +1,46 @@
/**
* 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 { AxiosPromise, AxiosRequestConfig } from 'axios';
import { GetTokenResponse, OAuth2Client, RefreshOptions } from './oauth2client';
export interface ComputeOptions extends RefreshOptions {
/**
* The service account email to use, or 'default'. A Compute Engine instance
* may have multiple service accounts.
*/
serviceAccountEmail?: string;
}
export declare class Compute extends OAuth2Client {
private serviceAccountEmail;
/**
* Google Compute Engine service account credentials.
*
* Retrieve access token from the metadata server.
* 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.
* @return Boolean indicating if scope is required.
*/
createScopedRequired(): boolean;
/**
* Refreshes the access token.
* @param refreshToken Unused parameter
*/
protected refreshTokenNoCache(refreshToken?: string | null): Promise<GetTokenResponse>;
protected requestAsync<T>(opts: AxiosRequestConfig, retry?: boolean): AxiosPromise<T>;
}

View File

@@ -0,0 +1,187 @@
"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.
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var axios_1 = __importDefault(require("axios"));
var gcpMetadata = __importStar(require("gcp-metadata"));
var rax = __importStar(require("retry-axios"));
var oauth2client_1 = require("./oauth2client");
// Create a scoped axios instance that will retry 3 times by default
var ax = axios_1.default.create();
rax.attach(ax);
var Compute = /** @class */ (function (_super) {
__extends(Compute, _super);
/**
* Google Compute Engine service account credentials.
*
* Retrieve access token from the metadata server.
* See: https://developers.google.com/compute/docs/authentication
*/
function Compute(options) {
if (options === void 0) { options = {}; }
var _this = _super.call(this, options) || this;
// Start with an expired refresh token, which will automatically be
// refreshed before the first API call is made.
_this.credentials = { expiry_date: 1, refresh_token: 'compute-placeholder' };
_this.serviceAccountEmail = options.serviceAccountEmail || 'default';
return _this;
}
/**
* Indicates whether the credential requires scopes to be created by calling
* createdScoped before use.
* @return Boolean indicating if scope is required.
*/
Compute.prototype.createScopedRequired = function () {
// On compute engine, scopes are specified at the compute instance's
// creation time, and cannot be changed. For this reason, always return
// false.
return false;
};
/**
* Refreshes the access token.
* @param refreshToken Unused parameter
*/
Compute.prototype.refreshTokenNoCache = function (refreshToken) {
return __awaiter(this, void 0, void 0, function () {
var _a, url, res, e_1, tokens;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
url = this.tokenUrl ||
"" + gcpMetadata.HOST_ADDRESS + gcpMetadata.BASE_PATH + "/instance/service-accounts/" + this.serviceAccountEmail + "/token";
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, ax.request({
url: url,
headers: (_a = {}, _a[gcpMetadata.HEADER_NAME] = 'Google', _a),
raxConfig: { noResponseRetries: 3, retry: 3, instance: ax }
})];
case 2:
// TODO: In 2.0, we should remove the ability to configure the tokenUrl,
// and switch this over to use the gcp-metadata package instead.
res = _b.sent();
return [3 /*break*/, 4];
case 3:
e_1 = _b.sent();
e_1.message = 'Could not refresh access token.';
throw e_1;
case 4:
tokens = res.data;
if (res.data && res.data.expires_in) {
tokens.expiry_date =
((new Date()).getTime() + (res.data.expires_in * 1000));
delete tokens.expires_in;
}
this.emit('tokens', tokens);
return [2 /*return*/, { tokens: tokens, res: res }];
}
});
});
};
Compute.prototype.requestAsync = function (opts, retry) {
if (retry === void 0) { retry = false; }
return _super.prototype.requestAsync.call(this, opts, retry).catch(function (e) {
var res = e.response;
if (res && res.status) {
var helpfulMessage = null;
if (res.status === 403) {
helpfulMessage =
'A Forbidden error was returned while attempting to retrieve an access ' +
'token for the Compute Engine built-in service account. This may be because the Compute ' +
'Engine instance does not have the correct permission scopes specified.';
}
else if (res.status === 404) {
helpfulMessage =
'A Not Found error was returned while attempting to retrieve an access' +
'token for the Compute Engine built-in service account. This may be because the Compute ' +
'Engine instance does not have any permission scopes specified.';
}
if (helpfulMessage) {
if (e && e.message && !retry) {
helpfulMessage += ' ' + e.message;
}
if (e) {
e.message = helpfulMessage;
}
else {
e = new Error(helpfulMessage);
e.code = res.status.toString();
}
}
}
throw e;
});
};
return Compute;
}(oauth2client_1.OAuth2Client));
exports.Compute = Compute;
//# sourceMappingURL=computeclient.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"computeclient.js","sourceRoot":"","sources":["../../../src/auth/computeclient.ts"],"names":[],"mappings":"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"}

View File

@@ -0,0 +1,42 @@
/**
* 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 {
refresh_token?: string | null;
expiry_date?: number | null;
access_token?: string | null;
token_type?: string | null;
id_token?: string | null;
}
export interface CredentialRequest {
refresh_token?: string;
access_token?: string;
token_type?: string;
expires_in?: number;
id_token?: string;
}
export interface JWTInput {
type?: string;
client_email?: string;
private_key?: string;
project_id?: string;
client_id?: string;
client_secret?: string;
refresh_token?: string;
}
export interface CredentialBody {
client_email?: string;
private_key?: string;
}

View File

@@ -0,0 +1,18 @@
"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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=credentials.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"credentials.js","sourceRoot":"","sources":["../../../src/auth/credentials.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG"}

View File

@@ -0,0 +1,24 @@
/**
* 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",
CLOUD_FUNCTIONS = "CLOUD_FUNCTIONS",
COMPUTE_ENGINE = "COMPUTE_ENGINE",
NONE = "NONE"
}
export declare function clear(): void;
export declare function getEnv(): Promise<GCPEnv>;

View File

@@ -0,0 +1,139 @@
"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.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var gcpMetadata = __importStar(require("gcp-metadata"));
var GCPEnv;
(function (GCPEnv) {
GCPEnv["APP_ENGINE"] = "APP_ENGINE";
GCPEnv["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE";
GCPEnv["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS";
GCPEnv["COMPUTE_ENGINE"] = "COMPUTE_ENGINE";
GCPEnv["NONE"] = "NONE";
})(GCPEnv = exports.GCPEnv || (exports.GCPEnv = {}));
var env;
function clear() {
env = undefined;
}
exports.clear = clear;
function getEnv() {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!!env) return [3 /*break*/, 6];
if (!isAppEngine()) return [3 /*break*/, 1];
env = GCPEnv.APP_ENGINE;
return [3 /*break*/, 6];
case 1:
if (!isCloudFunction()) return [3 /*break*/, 2];
env = GCPEnv.CLOUD_FUNCTIONS;
return [3 /*break*/, 6];
case 2: return [4 /*yield*/, isKubernetesEngine()];
case 3:
if (!_a.sent()) return [3 /*break*/, 4];
env = GCPEnv.KUBERNETES_ENGINE;
return [3 /*break*/, 6];
case 4: return [4 /*yield*/, isComputeEngine()];
case 5:
if (_a.sent()) {
env = GCPEnv.COMPUTE_ENGINE;
}
else {
env = GCPEnv.NONE;
}
_a.label = 6;
case 6: return [2 /*return*/, env];
}
});
});
}
exports.getEnv = getEnv;
function isAppEngine() {
return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME);
}
function isCloudFunction() {
return !!process.env.FUNCTION_NAME;
}
function isKubernetesEngine() {
return __awaiter(this, void 0, void 0, function () {
var e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, gcpMetadata.instance('attributes/cluster-name')];
case 1:
_a.sent();
return [2 /*return*/, true];
case 2:
e_1 = _a.sent();
return [2 /*return*/, false];
case 3: return [2 /*return*/];
}
});
});
}
function isComputeEngine() {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, gcpMetadata.isAvailable()];
});
});
}
//# sourceMappingURL=envDetect.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"envDetect.js","sourceRoot":"","sources":["../../../src/auth/envDetect.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,wDAA4C;AAE5C,IAAY,MAMX;AAND,WAAY,MAAM;IAChB,mCAAyB,CAAA;IACzB,iDAAuC,CAAA;IACvC,6CAAmC,CAAA;IACnC,2CAAiC,CAAA;IACjC,uBAAa,CAAA;AACf,CAAC,EANW,MAAM,GAAN,cAAM,KAAN,cAAM,QAMjB;AAED,IAAI,GAAqB,CAAC;AAE1B;IACE,GAAG,GAAG,SAAS,CAAC;AAClB,CAAC;AAFD,sBAEC;AAED;;;;;yBACM,CAAC,GAAG,EAAJ,wBAAI;yBACF,WAAW,EAAE,EAAb,wBAAa;oBACf,GAAG,GAAG,MAAM,CAAC,UAAU,CAAC;;;yBACf,eAAe,EAAE,EAAjB,wBAAiB;oBAC1B,GAAG,GAAG,MAAM,CAAC,eAAe,CAAC;;wBACpB,qBAAM,kBAAkB,EAAE,EAAA;;yBAA1B,SAA0B,EAA1B,wBAA0B;oBACnC,GAAG,GAAG,MAAM,CAAC,iBAAiB,CAAC;;wBACtB,qBAAM,eAAe,EAAE,EAAA;;oBAA3B,IAAI,SAAuB,EAAE;wBAClC,GAAG,GAAG,MAAM,CAAC,cAAc,CAAC;qBAC7B;yBAAM;wBACL,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC;qBACnB;;wBAEH,sBAAO,GAAG,EAAC;;;;CACZ;AAfD,wBAeC;AAED;IACE,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;AACpE,CAAC;AAED;IACE,OAAO,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC;AACrC,CAAC;AAED;;;;;;;oBAEI,qBAAM,WAAW,CAAC,QAAQ,CAAC,yBAAyB,CAAC,EAAA;;oBAArD,SAAqD,CAAC;oBACtD,sBAAO,IAAI,EAAC;;;oBAEZ,sBAAO,KAAK,EAAC;;;;;CAEhB;AAED;;;YACE,sBAAO,WAAW,CAAC,WAAW,EAAE,EAAC;;;CAClC"}

View File

@@ -0,0 +1,264 @@
/**
* 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.
*/
/// <reference types="node" />
import { AxiosRequestConfig, AxiosResponse } from 'axios';
import * as fs from 'fs';
import * as http from 'http';
import * as stream from 'stream';
import { DefaultTransporter, Transporter } from '../transporters';
import { Compute } from './computeclient';
import { CredentialBody, JWTInput } from './credentials';
import { GCPEnv } from './envDetect';
import { JWT } from './jwtclient';
import { OAuth2Client, RefreshOptions } from './oauth2client';
import { UserRefreshClient } from './refreshclient';
export interface ProjectIdCallback {
(err?: Error | null, projectId?: string | null): void;
}
export interface CredentialCallback {
(err: Error | null, result?: UserRefreshClient | JWT): void;
}
export interface ADCCallback {
(err: Error | null, credential?: OAuth2Client, projectId?: string | null): void;
}
export interface ADCResponse {
credential: OAuth2Client;
projectId: string | null;
}
export interface GoogleAuthOptions {
/**
* Path to a .json, .pem, or .p12 key file
*/
keyFilename?: string;
/**
* Path to a .json, .pem, or .p12 key file
*/
keyFile?: string;
/**
* Object containing client_email and private_key properties
*/
credentials?: CredentialBody;
/**
* Required scopes for the desired API request
*/
scopes?: string | string[];
/**
* Your project ID.
*/
projectId?: string;
}
export declare class GoogleAuth {
transporter?: Transporter;
getProjectId: {
(): Promise<string>;
(callback: ProjectIdCallback): void;
};
/**
* Caches a value indicating whether the auth layer is running on Google
* Compute Engine.
* @private
*/
private checkIsGCE?;
readonly isGCE: boolean | undefined;
private _getDefaultProjectIdPromise?;
private _cachedProjectId?;
jsonContent: JWTInput | null;
cachedCredential: JWT | UserRefreshClient | Compute | null;
private keyFilename?;
private scopes?;
/**
* Export DefaultTransporter as a static property of the class.
*/
static DefaultTransporter: typeof DefaultTransporter;
constructor(opts?: GoogleAuthOptions);
/**
* Obtains the default project ID for the application.
* @param callback Optional callback
* @returns Promise that resolves with project Id (if used without callback)
*/
getDefaultProjectId(): Promise<string>;
getDefaultProjectId(callback: ProjectIdCallback): void;
private getDefaultProjectIdAsync;
/**
* Obtains the default service-level credentials for the application.
* @param callback Optional callback.
* @returns Promise that resolves with the ADCResponse (if no callback was
* passed).
*/
getApplicationDefault(): Promise<ADCResponse>;
getApplicationDefault(callback: ADCCallback): void;
getApplicationDefault(options: RefreshOptions): Promise<ADCResponse>;
getApplicationDefault(options: RefreshOptions, callback: ADCCallback): void;
private getApplicationDefaultAsync;
/**
* Determines whether the auth layer is running on Google Compute Engine.
* @returns A promise that resolves with the boolean.
* @api private
*/
_checkIsGCE(): Promise<boolean>;
/**
* Attempts to load default credentials from the environment variable path..
* @returns Promise that resolves with the OAuth2Client or null.
* @api private
*/
_tryGetApplicationCredentialsFromEnvironmentVariable(options?: RefreshOptions): Promise<JWT | UserRefreshClient | null>;
/**
* Attempts to load default credentials from a well-known file location
* @return Promise that resolves with the OAuth2Client or null.
* @api private
*/
_tryGetApplicationCredentialsFromWellKnownFile(options?: RefreshOptions): Promise<JWT | UserRefreshClient | null>;
/**
* Attempts to load default credentials from a file at the given path..
* @param filePath The path to the file to read.
* @returns Promise that resolves with the OAuth2Client
* @api private
*/
_getApplicationCredentialsFromFilePath(filePath: string, options?: RefreshOptions): Promise<JWT | UserRefreshClient>;
/**
* Create a credentials instance using the given input options.
* @param json The input object.
* @returns JWT or UserRefresh Client with data
*/
fromJSON(json: JWTInput, options?: RefreshOptions): JWT | UserRefreshClient;
/**
* Create a credentials instance using the given input stream.
* @param inputStream The input stream.
* @param callback Optional callback.
*/
fromStream(inputStream: stream.Readable): Promise<JWT | UserRefreshClient>;
fromStream(inputStream: stream.Readable, callback: CredentialCallback): void;
fromStream(inputStream: stream.Readable, options: RefreshOptions): Promise<JWT | UserRefreshClient>;
fromStream(inputStream: stream.Readable, options: RefreshOptions, callback: CredentialCallback): void;
private fromStreamAsync;
/**
* Create a credentials instance using the given API key string.
* @param apiKey The API key string
* @param options An optional options object.
* @returns A JWT loaded from the key
*/
fromAPIKey(apiKey: string, options?: RefreshOptions): JWT;
/**
* Determines whether the current operating system is Windows.
* @api private
*/
private _isWindows;
/**
* Creates a file stream. Allows mocking.
* @api private
*/
_createReadStream(filePath: string): fs.ReadStream;
/**
* Gets the current operating system platform. Allows mocking.
* @api private
*/
_osPlatform(): NodeJS.Platform;
/**
* Determines whether a file exists. Allows mocking.
* @api private
*/
_fileExists(filePath: string): boolean;
/**
* Joins two parts of a path. Allows mocking.
* @api private
*/
_pathJoin(item1: string, item2: string): string;
/**
* Allows mocking of the path to a well-known file.
* @api private
*/
_mockWellKnownFilePath(filePath: string): string;
private createError;
/**
* Run the Google Cloud SDK command that prints the default project ID
*/
private getDefaultServiceProjectId;
/**
* Loads the project id from environment variables.
* @api private
*/
private getProductionProjectId;
/**
* Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file.
* @api private
*/
private getFileProjectId;
/**
* Gets the Compute Engine project ID if it can be inferred.
*/
private getGCEProjectId;
/**
* The callback function handles a credential object that contains the
* client_email and private_key (if exists).
* getCredentials checks for these values from the user JSON at first.
* If it doesn't exist, and the environment is on GCE, it gets the
* client_email from the cloud metadata server.
* @param callback Callback that handles the credential object that contains
* a client_email and optional private key, or the error.
* returned
*/
getCredentials(): Promise<CredentialBody>;
getCredentials(callback: (err: Error | null, credentials?: CredentialBody) => void): void;
private getCredentialsAsync;
/**
* Automatically obtain a client based on the provided configuration. If no
* options were passed, use Application Default Credentials.
*/
getClient(options?: GoogleAuthOptions): Promise<Compute | JWT | UserRefreshClient>;
/**
* Automatically obtain application default credentials, and return
* an access token for making requests.
*/
getAccessToken(): Promise<string | null | undefined>;
/**
* Obtain the HTTP headers that will provide authorization for a given
* request.
*/
getRequestHeaders(url?: string): Promise<http.IncomingHttpHeaders>;
/**
* Obtain credentials for a request, then attach the appropriate headers to
* the request options.
* @param opts Axios or Request options on which to attach the headers
*/
authorizeRequest(opts: {
url?: string;
uri?: string;
headers?: http.IncomingHttpHeaders;
}): Promise<{
url?: string | undefined;
uri?: string | undefined;
headers?: http.IncomingHttpHeaders | undefined;
}>;
/**
* Automatically obtain application default credentials, and make an
* HTTP request using the given options.
* @param opts Axios request options for the HTTP request.
*/
request<T = any>(opts: AxiosRequestConfig): Promise<AxiosResponse<T>>;
/**
* Determine the compute environment in which the code is running.
*/
getEnv(): Promise<GCPEnv>;
/**
* Sign the given data with the current private key, or go out
* to the IAM API to sign it.
* @param data The data to be signed.
*/
sign(data: string): Promise<string>;
}
export interface SignBlobResponse {
signature: string;
}

View File

@@ -0,0 +1,815 @@
"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.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var child_process_1 = require("child_process");
var crypto_1 = __importDefault(require("crypto"));
var fs = __importStar(require("fs"));
var gcpMetadata = __importStar(require("gcp-metadata"));
var os_1 = __importDefault(require("os"));
var path_1 = __importDefault(require("path"));
var util_1 = __importDefault(require("util"));
var transporters_1 = require("../transporters");
var computeclient_1 = require("./computeclient");
var envDetect_1 = require("./envDetect");
var jwtclient_1 = require("./jwtclient");
var refreshclient_1 = require("./refreshclient");
var GoogleAuth = /** @class */ (function () {
function GoogleAuth(opts) {
// This shim is in place for compatibility with google-auto-auth.
this.getProjectId = this.getDefaultProjectId;
/**
* Caches a value indicating whether the auth layer is running on Google
* Compute Engine.
* @private
*/
this.checkIsGCE = undefined;
// To save the contents of the JSON credential file
this.jsonContent = null;
this.cachedCredential = null;
opts = opts || {};
this._cachedProjectId = opts.projectId || null;
this.keyFilename = opts.keyFilename || opts.keyFile;
this.scopes = opts.scopes;
this.jsonContent = opts.credentials || null;
}
Object.defineProperty(GoogleAuth.prototype, "isGCE", {
// Note: this properly is only public to satisify unit tests.
// https://github.com/Microsoft/TypeScript/issues/5228
get: function () {
return this.checkIsGCE;
},
enumerable: true,
configurable: true
});
GoogleAuth.prototype.getDefaultProjectId = function (callback) {
if (callback) {
this.getDefaultProjectIdAsync()
.then(function (r) { return callback(null, r); })
.catch(callback);
}
else {
return this.getDefaultProjectIdAsync();
}
};
GoogleAuth.prototype.getDefaultProjectIdAsync = function () {
var _this = this;
if (this._cachedProjectId) {
return Promise.resolve(this._cachedProjectId);
}
// In implicit case, supports three environments. In order of precedence,
// the implicit environments are:
// - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable
// - GOOGLE_APPLICATION_CREDENTIALS JSON file
// - Cloud SDK: `gcloud config config-helper --format json`
// - GCE project ID from metadata server)
if (!this._getDefaultProjectIdPromise) {
this._getDefaultProjectIdPromise =
new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
var projectId, _a, _b, _c, e_1;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
_d.trys.push([0, 7, , 8]);
_c = this.getProductionProjectId();
if (_c) return [3 /*break*/, 2];
return [4 /*yield*/, this.getFileProjectId()];
case 1:
_c = (_d.sent());
_d.label = 2;
case 2:
_b = _c;
if (_b) return [3 /*break*/, 4];
return [4 /*yield*/, this.getDefaultServiceProjectId()];
case 3:
_b = (_d.sent());
_d.label = 4;
case 4:
_a = _b;
if (_a) return [3 /*break*/, 6];
return [4 /*yield*/, this.getGCEProjectId()];
case 5:
_a = (_d.sent());
_d.label = 6;
case 6:
projectId = _a;
this._cachedProjectId = projectId;
resolve(projectId);
return [3 /*break*/, 8];
case 7:
e_1 = _d.sent();
reject(e_1);
return [3 /*break*/, 8];
case 8: return [2 /*return*/];
}
});
}); });
}
return this._getDefaultProjectIdPromise;
};
GoogleAuth.prototype.getApplicationDefault = function (optionsOrCallback, callback) {
if (optionsOrCallback === void 0) { optionsOrCallback = {}; }
var options;
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
}
else {
options = optionsOrCallback;
}
if (callback) {
this.getApplicationDefaultAsync(options)
.then(function (r) { return callback(null, r.credential, r.projectId); })
.catch(callback);
}
else {
return this.getApplicationDefaultAsync(options);
}
};
GoogleAuth.prototype.getApplicationDefaultAsync = function (options) {
return __awaiter(this, void 0, void 0, function () {
var _a, credential, projectId, gce, e_2;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!this.cachedCredential) return [3 /*break*/, 2];
_a = {
credential: this.cachedCredential
};
return [4 /*yield*/, this.getDefaultProjectIdAsync()];
case 1: return [2 /*return*/, (_a.projectId = _b.sent(),
_a)];
case 2: return [4 /*yield*/, this._tryGetApplicationCredentialsFromEnvironmentVariable(options)];
case 3:
// Check for the existence of a local environment variable pointing to the
// location of the credential file. This is typically used in local
// developer scenarios.
credential =
_b.sent();
if (!credential) return [3 /*break*/, 5];
if (credential instanceof jwtclient_1.JWT) {
credential.scopes = this.scopes;
}
this.cachedCredential = credential;
return [4 /*yield*/, this.getDefaultProjectId()];
case 4:
projectId = _b.sent();
return [2 /*return*/, { credential: credential, projectId: projectId }];
case 5: return [4 /*yield*/, this._tryGetApplicationCredentialsFromWellKnownFile(options)];
case 6:
// Look in the well-known credential file location.
credential =
_b.sent();
if (!credential) return [3 /*break*/, 8];
if (credential instanceof jwtclient_1.JWT) {
credential.scopes = this.scopes;
}
this.cachedCredential = credential;
return [4 /*yield*/, this.getDefaultProjectId()];
case 7:
projectId = _b.sent();
return [2 /*return*/, { credential: credential, projectId: projectId }];
case 8:
_b.trys.push([8, 13, , 14]);
return [4 /*yield*/, this._checkIsGCE()];
case 9:
gce = _b.sent();
if (!gce) return [3 /*break*/, 11];
// For GCE, just return a default ComputeClient. It will take care of
// the rest.
this.cachedCredential = new computeclient_1.Compute(options);
return [4 /*yield*/, this.getDefaultProjectId()];
case 10:
projectId = _b.sent();
return [2 /*return*/, { projectId: projectId, credential: this.cachedCredential }];
case 11:
// We failed to find the default credentials. Bail out with an error.
throw new Error('Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information.');
case 12: return [3 /*break*/, 14];
case 13:
e_2 = _b.sent();
throw new Error('Unexpected error while acquiring application default credentials: ' +
e_2.message);
case 14: return [2 /*return*/];
}
});
});
};
/**
* Determines whether the auth layer is running on Google Compute Engine.
* @returns A promise that resolves with the boolean.
* @api private
*/
GoogleAuth.prototype._checkIsGCE = function () {
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!(this.checkIsGCE === undefined)) return [3 /*break*/, 2];
_a = this;
return [4 /*yield*/, gcpMetadata.isAvailable()];
case 1:
_a.checkIsGCE = _b.sent();
_b.label = 2;
case 2: return [2 /*return*/, this.checkIsGCE];
}
});
});
};
/**
* Attempts to load default credentials from the environment variable path..
* @returns Promise that resolves with the OAuth2Client or null.
* @api private
*/
GoogleAuth.prototype._tryGetApplicationCredentialsFromEnvironmentVariable = function (options) {
return __awaiter(this, void 0, void 0, function () {
var credentialsPath;
return __generator(this, function (_a) {
credentialsPath = process.env['GOOGLE_APPLICATION_CREDENTIALS'];
if (!credentialsPath || credentialsPath.length === 0) {
return [2 /*return*/, null];
}
try {
return [2 /*return*/, this._getApplicationCredentialsFromFilePath(credentialsPath, options)];
}
catch (e) {
throw this.createError('Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable.', e);
}
return [2 /*return*/];
});
});
};
/**
* Attempts to load default credentials from a well-known file location
* @return Promise that resolves with the OAuth2Client or null.
* @api private
*/
GoogleAuth.prototype._tryGetApplicationCredentialsFromWellKnownFile = function (options) {
return __awaiter(this, void 0, void 0, function () {
var location, home;
return __generator(this, function (_a) {
location = null;
if (this._isWindows()) {
// Windows
location = process.env['APPDATA'];
}
else {
home = process.env['HOME'];
if (home) {
location = this._pathJoin(home, '.config');
}
}
// If we found the root path, expand it.
if (location) {
location = this._pathJoin(location, 'gcloud');
location =
this._pathJoin(location, 'application_default_credentials.json');
location = this._mockWellKnownFilePath(location);
// Check whether the file exists.
if (!this._fileExists(location)) {
location = null;
}
}
// The file does not exist.
if (!location) {
return [2 /*return*/, null];
}
// The file seems to exist. Try to use it.
return [2 /*return*/, this._getApplicationCredentialsFromFilePath(location, options)];
});
});
};
/**
* Attempts to load default credentials from a file at the given path..
* @param filePath The path to the file to read.
* @returns Promise that resolves with the OAuth2Client
* @api private
*/
GoogleAuth.prototype._getApplicationCredentialsFromFilePath = function (filePath, options) {
if (options === void 0) { options = {}; }
return __awaiter(this, void 0, void 0, function () {
var readStream;
return __generator(this, function (_a) {
// Make sure the path looks like a string.
if (!filePath || filePath.length === 0) {
throw new Error('The file path is invalid.');
}
// Make sure there is a file at the path. lstatSync will throw if there is
// nothing there.
try {
// Resolve path to actual file in case of symlink. Expect a thrown error
// if not resolvable.
filePath = fs.realpathSync(filePath);
if (!fs.lstatSync(filePath).isFile()) {
throw new Error();
}
}
catch (err) {
throw this.createError(util_1.default.format('The file at %s does not exist, or it is not a file.', filePath), err);
}
// Now open a read stream on the file, and parse it.
try {
readStream = this._createReadStream(filePath);
return [2 /*return*/, this.fromStream(readStream, options)];
}
catch (err) {
throw this.createError(util_1.default.format('Unable to read the file at %s.', filePath), err);
}
return [2 /*return*/];
});
});
};
/**
* Create a credentials instance using the given input options.
* @param json The input object.
* @returns JWT or UserRefresh Client with data
*/
GoogleAuth.prototype.fromJSON = function (json, options) {
var client;
if (!json) {
throw new Error('Must pass in a JSON object containing the Google auth settings.');
}
this.jsonContent = json;
options = options || {};
if (json.type === 'authorized_user') {
client = new refreshclient_1.UserRefreshClient(options);
}
else {
options.scopes = this.scopes;
client = new jwtclient_1.JWT(options);
}
client.fromJSON(json);
return client;
};
GoogleAuth.prototype.fromStream = function (inputStream, optionsOrCallback, callback) {
if (optionsOrCallback === void 0) { optionsOrCallback = {}; }
var options = {};
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
}
else {
options = optionsOrCallback;
}
if (callback) {
this.fromStreamAsync(inputStream, options)
.then(function (r) { return callback(null, r); })
.catch(callback);
}
else {
return this.fromStreamAsync(inputStream, options);
}
};
GoogleAuth.prototype.fromStreamAsync = function (inputStream, options) {
var _this = this;
return new Promise(function (resolve, reject) {
if (!inputStream) {
throw new Error('Must pass in a stream containing the Google auth settings.');
}
var s = '';
inputStream.setEncoding('utf8');
inputStream.on('data', function (chunk) {
s += chunk;
});
inputStream.on('end', function () {
try {
var data = JSON.parse(s);
var r = _this.fromJSON(data, options);
return resolve(r);
}
catch (err) {
return reject(err);
}
});
});
};
/**
* Create a credentials instance using the given API key string.
* @param apiKey The API key string
* @param options An optional options object.
* @returns A JWT loaded from the key
*/
GoogleAuth.prototype.fromAPIKey = function (apiKey, options) {
options = options || {};
var client = new jwtclient_1.JWT(options);
client.fromAPIKey(apiKey);
return client;
};
/**
* Determines whether the current operating system is Windows.
* @api private
*/
GoogleAuth.prototype._isWindows = function () {
var sys = this._osPlatform();
if (sys && sys.length >= 3) {
if (sys.substring(0, 3).toLowerCase() === 'win') {
return true;
}
}
return false;
};
/**
* Creates a file stream. Allows mocking.
* @api private
*/
GoogleAuth.prototype._createReadStream = function (filePath) {
return fs.createReadStream(filePath);
};
/**
* Gets the current operating system platform. Allows mocking.
* @api private
*/
GoogleAuth.prototype._osPlatform = function () {
return os_1.default.platform();
};
/**
* Determines whether a file exists. Allows mocking.
* @api private
*/
GoogleAuth.prototype._fileExists = function (filePath) {
return fs.existsSync(filePath);
};
/**
* Joins two parts of a path. Allows mocking.
* @api private
*/
GoogleAuth.prototype._pathJoin = function (item1, item2) {
return path_1.default.join(item1, item2);
};
/**
* Allows mocking of the path to a well-known file.
* @api private
*/
GoogleAuth.prototype._mockWellKnownFilePath = function (filePath) {
return filePath;
};
// Creates an Error containing the given message, and includes the message
// from the optional err passed in.
GoogleAuth.prototype.createError = function (message, err) {
var s = message || '';
if (err) {
var errorMessage = String(err);
if (errorMessage && errorMessage.length > 0) {
if (s.length > 0) {
s += ' ';
}
s += errorMessage;
}
}
return Error(s);
};
/**
* Run the Google Cloud SDK command that prints the default project ID
*/
GoogleAuth.prototype.getDefaultServiceProjectId = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve) {
child_process_1.exec('gcloud config config-helper --format json', function (err, stdout, stderr) {
if (!err && stdout) {
try {
var projectId = JSON.parse(stdout).configuration.properties.core.project;
resolve(projectId);
return;
}
catch (e) {
// ignore errors
}
}
resolve(null);
});
})];
});
});
};
/**
* Loads the project id from environment variables.
* @api private
*/
GoogleAuth.prototype.getProductionProjectId = function () {
return process.env['GCLOUD_PROJECT'] || process.env['GOOGLE_CLOUD_PROJECT'];
};
/**
* Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file.
* @api private
*/
GoogleAuth.prototype.getFileProjectId = function () {
return __awaiter(this, void 0, void 0, function () {
var r;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.cachedCredential) {
// Try to read the project ID from the cached credentials file
return [2 /*return*/, this.cachedCredential.projectId];
}
return [4 /*yield*/, this._tryGetApplicationCredentialsFromEnvironmentVariable()];
case 1:
r = _a.sent();
if (r) {
return [2 /*return*/, r.projectId];
}
else {
return [2 /*return*/, null];
}
return [2 /*return*/];
}
});
});
};
/**
* Gets the Compute Engine project ID if it can be inferred.
*/
GoogleAuth.prototype.getGCEProjectId = function () {
return __awaiter(this, void 0, void 0, function () {
var r, e_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, gcpMetadata.project('project-id')];
case 1:
r = _a.sent();
return [2 /*return*/, r.data];
case 2:
e_3 = _a.sent();
// Ignore any errors
return [2 /*return*/, null];
case 3: return [2 /*return*/];
}
});
});
};
GoogleAuth.prototype.getCredentials = function (callback) {
if (callback) {
this.getCredentialsAsync().then(function (r) { return callback(null, r); }).catch(callback);
}
else {
return this.getCredentialsAsync();
}
};
GoogleAuth.prototype.getCredentialsAsync = function () {
return __awaiter(this, void 0, void 0, function () {
var credential, isGCE, data;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.jsonContent) {
credential = {
client_email: this.jsonContent.client_email,
private_key: this.jsonContent.private_key
};
return [2 /*return*/, credential];
}
return [4 /*yield*/, this._checkIsGCE()];
case 1:
isGCE = _a.sent();
if (!isGCE) {
throw new Error('Unknown error.');
}
return [4 /*yield*/, gcpMetadata.instance({ property: 'service-accounts/', params: { recursive: true } })];
case 2:
data = (_a.sent()).data;
if (!data || !data.default || !data.default.email) {
throw new Error('Failure from metadata server.');
}
return [2 /*return*/, { client_email: data.default.email }];
}
});
});
};
/**
* Automatically obtain a client based on the provided configuration. If no
* options were passed, use Application Default Credentials.
*/
GoogleAuth.prototype.getClient = function (options) {
return __awaiter(this, void 0, void 0, function () {
var _a, filePath, stream_1, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
if (options) {
this.keyFilename =
options.keyFilename || options.keyFile || this.keyFilename;
this.scopes = options.scopes || this.scopes;
this.jsonContent = options.credentials || this.jsonContent;
}
if (!!this.cachedCredential) return [3 /*break*/, 6];
if (!this.jsonContent) return [3 /*break*/, 2];
_a = this;
return [4 /*yield*/, this.fromJSON(this.jsonContent)];
case 1:
_a.cachedCredential = _c.sent();
return [3 /*break*/, 6];
case 2:
if (!this.keyFilename) return [3 /*break*/, 4];
filePath = path_1.default.resolve(this.keyFilename);
stream_1 = fs.createReadStream(filePath);
_b = this;
return [4 /*yield*/, this.fromStreamAsync(stream_1)];
case 3:
_b.cachedCredential = _c.sent();
return [3 /*break*/, 6];
case 4: return [4 /*yield*/, this.getApplicationDefaultAsync()];
case 5:
_c.sent();
_c.label = 6;
case 6: return [2 /*return*/, this.cachedCredential];
}
});
});
};
/**
* Automatically obtain application default credentials, and return
* an access token for making requests.
*/
GoogleAuth.prototype.getAccessToken = function () {
return __awaiter(this, void 0, void 0, function () {
var client;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getClient()];
case 1:
client = _a.sent();
return [4 /*yield*/, client.getAccessToken()];
case 2: return [2 /*return*/, (_a.sent()).token];
}
});
});
};
/**
* Obtain the HTTP headers that will provide authorization for a given
* request.
*/
GoogleAuth.prototype.getRequestHeaders = function (url) {
return __awaiter(this, void 0, void 0, function () {
var client;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getClient()];
case 1:
client = _a.sent();
return [4 /*yield*/, client.getRequestMetadata(url)];
case 2: return [2 /*return*/, (_a.sent()).headers];
}
});
});
};
/**
* Obtain credentials for a request, then attach the appropriate headers to
* the request options.
* @param opts Axios or Request options on which to attach the headers
*/
GoogleAuth.prototype.authorizeRequest = function (opts) {
return __awaiter(this, void 0, void 0, function () {
var url, client, headers;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
opts = opts || {};
url = opts.url || opts.uri;
return [4 /*yield*/, this.getClient()];
case 1:
client = _a.sent();
return [4 /*yield*/, client.getRequestMetadata(url)];
case 2:
headers = (_a.sent()).headers;
opts.headers = Object.assign(opts.headers || {}, headers);
return [2 /*return*/, opts];
}
});
});
};
/**
* Automatically obtain application default credentials, and make an
* HTTP request using the given options.
* @param opts Axios request options for the HTTP request.
*/
// tslint:disable-next-line no-any
GoogleAuth.prototype.request = function (opts) {
return __awaiter(this, void 0, void 0, function () {
var client;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getClient()];
case 1:
client = _a.sent();
return [2 /*return*/, client.request(opts)];
}
});
});
};
/**
* Determine the compute environment in which the code is running.
*/
GoogleAuth.prototype.getEnv = function () {
return envDetect_1.getEnv();
};
/**
* Sign the given data with the current private key, or go out
* to the IAM API to sign it.
* @param data The data to be signed.
*/
GoogleAuth.prototype.sign = function (data) {
return __awaiter(this, void 0, void 0, function () {
var client, sign, projectId, creds, id, res;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getClient()];
case 1:
client = _a.sent();
if (client instanceof jwtclient_1.JWT && client.key) {
sign = crypto_1.default.createSign('RSA-SHA256');
sign.update(data);
return [2 /*return*/, sign.sign(client.key, 'base64')];
}
return [4 /*yield*/, this.getProjectId()];
case 2:
projectId = _a.sent();
if (!projectId) {
throw new Error('Cannot sign data without a project ID.');
}
return [4 /*yield*/, this.getCredentials()];
case 3:
creds = _a.sent();
if (!creds.client_email) {
throw new Error('Cannot sign data without `client_email`.');
}
id = "projects/" + projectId + "/serviceAccounts/" + creds.client_email;
return [4 /*yield*/, this.request({
method: 'POST',
url: "https://iam.googleapis.com/v1/" + id + ":signBlob",
data: { bytesToSign: Buffer.from(data).toString('base64') }
})];
case 4:
res = _a.sent();
return [2 /*return*/, res.data.signature];
}
});
});
};
/**
* Export DefaultTransporter as a static property of the class.
*/
GoogleAuth.DefaultTransporter = transporters_1.DefaultTransporter;
return GoogleAuth;
}());
exports.GoogleAuth = GoogleAuth;
//# sourceMappingURL=googleauth.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,46 @@
/**
* 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;
}
export declare class IAMAuth {
selector: string;
token: string;
/**
* IAM credentials.
*
* @param selector the iam authority selector
* @param token the token
* @constructor
*/
constructor(selector: string, token: string);
/**
* Indicates whether the credential requires scopes to be created by calling
* createdScoped before use.
*
* @return always false
*/
createScopedRequired(): boolean;
/**
* Pass the selector and token to the metadataFn callback.
*
* @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;
}

View File

@@ -0,0 +1,58 @@
"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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var IAMAuth = /** @class */ (function () {
/**
* IAM credentials.
*
* @param selector the iam authority selector
* @param token the token
* @constructor
*/
function IAMAuth(selector, token) {
this.selector = selector;
this.token = token;
this.selector = selector;
this.token = token;
}
/**
* Indicates whether the credential requires scopes to be created by calling
* createdScoped before use.
*
* @return always false
*/
IAMAuth.prototype.createScopedRequired = function () {
// IAM authorization does not use scopes.
return false;
};
/**
* Pass the selector and token to the metadataFn callback.
*
* @param unused_uri is required of the credentials interface
* @param metadataFn a callback invoked with object
* containing request metadata.
*/
IAMAuth.prototype.getRequestMetadata = function (unusedUri, metadataFn) {
metadataFn(null, {
'x-goog-iam-authority-selector': this.selector,
'x-goog-iam-authorization-token': this.token
});
};
return IAMAuth;
}());
exports.IAMAuth = IAMAuth;
//# sourceMappingURL=iam.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"iam.js","sourceRoot":"","sources":["../../../src/auth/iam.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAOH;IACE;;;;;;OAMG;IACH,iBAAmB,QAAgB,EAAS,KAAa;QAAtC,aAAQ,GAAR,QAAQ,CAAQ;QAAS,UAAK,GAAL,KAAK,CAAQ;QACvD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAED;;;;;OAKG;IACH,sCAAoB,GAApB;QACE,yCAAyC;QACzC,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;;;;;OAMG;IACH,oCAAkB,GAAlB,UACI,SAAsB,EACtB,UAAiE;QACnE,UAAU,CAAC,IAAI,EAAE;YACf,+BAA+B,EAAE,IAAI,CAAC,QAAQ;YAC9C,gCAAgC,EAAE,IAAI,CAAC,KAAK;SAC7C,CAAC,CAAC;IACL,CAAC;IACH,cAAC;AAAD,CAAC,AAvCD,IAuCC;AAvCY,0BAAO"}

View File

@@ -0,0 +1,66 @@
/**
* 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 { RequestMetadataResponse } from './oauth2client';
export declare class JWTAccess {
email?: string | null;
key?: string | null;
projectId?: string;
private cache;
/**
* JWTAccess service account credentials.
*
* Create a new access token by using the credential to create a new JWT token
* that's recognized as the access token.
*
* @param email the service account email address.
* @param key the private key that will be used to sign the token.
*/
constructor(email?: string | null, key?: string | null);
/**
* Indicates whether the credential requires scopes to be created by calling
* createdScoped before use.
*
* @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.
* @returns An object that includes the authorization header.
*/
getRequestMetadata(authURI: string, additionalClaims?: {
[index: string]: string;
}): RequestMetadataResponse;
/**
* Create a JWTAccess credentials instance using the given input options.
* @param json The input object.
*/
fromJSON(json: JWTInput): void;
/**
* Create a JWTAccess credentials instance using the given input stream.
* @param inputStream The input stream.
* @param callback Optional callback.
*/
fromStream(inputStream: stream.Readable): Promise<void>;
fromStream(inputStream: stream.Readable, callback: (err?: Error) => void): void;
private fromStreamAsync;
}

View File

@@ -0,0 +1,136 @@
"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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var jws_1 = __importDefault(require("jws"));
var lru_cache_1 = __importDefault(require("lru-cache"));
var JWTAccess = /** @class */ (function () {
/**
* JWTAccess service account credentials.
*
* Create a new access token by using the credential to create a new JWT token
* that's recognized as the access token.
*
* @param email the service account email address.
* @param key the private key that will be used to sign the token.
*/
function JWTAccess(email, key) {
this.cache = lru_cache_1.default({ max: 500, maxAge: 60 * 60 * 1000 });
this.email = email;
this.key = key;
}
/**
* Indicates whether the credential requires scopes to be created by calling
* createdScoped before use.
*
* @return always false
*/
JWTAccess.prototype.createScopedRequired = function () {
// JWT Header authentication does not use scopes.
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.
* @returns An object that includes the authorization header.
*/
JWTAccess.prototype.getRequestMetadata = function (authURI, additionalClaims) {
var cachedToken = this.cache.get(authURI);
if (cachedToken) {
return cachedToken;
}
var iat = Math.floor(new Date().getTime() / 1000);
var exp = iat + 3600; // 3600 seconds = 1 hour
// The payload used for signed JWT headers has:
// iss == sub == <client email>
// aud == <the authorization uri>
var defaultClaims = { iss: this.email, sub: this.email, aud: authURI, exp: exp, iat: iat };
// if additionalClaims are provided, ensure they do not collide with
// other required claims.
if (additionalClaims) {
for (var claim in defaultClaims) {
if (additionalClaims[claim]) {
throw new Error("The '" + claim + "' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.");
}
}
}
var payload = Object.assign(defaultClaims, additionalClaims);
// Sign the jwt and add it to the cache
var signedJWT = jws_1.default.sign({ header: { alg: 'RS256' }, payload: payload, secret: this.key });
var res = { headers: { Authorization: "Bearer " + signedJWT } };
this.cache.set(authURI, res);
return res;
};
/**
* Create a JWTAccess credentials instance using the given input options.
* @param json The input object.
*/
JWTAccess.prototype.fromJSON = function (json) {
if (!json) {
throw new Error('Must pass in a JSON object containing the service account auth settings.');
}
if (!json.client_email) {
throw new Error('The incoming JSON object does not contain a client_email field');
}
if (!json.private_key) {
throw new Error('The incoming JSON object does not contain a private_key field');
}
// Extract the relevant information from the json key file.
this.email = json.client_email;
this.key = json.private_key;
this.projectId = json.project_id;
};
JWTAccess.prototype.fromStream = function (inputStream, callback) {
if (callback) {
this.fromStreamAsync(inputStream).then(function (r) { return callback(); }).catch(callback);
}
else {
return this.fromStreamAsync(inputStream);
}
};
JWTAccess.prototype.fromStreamAsync = function (inputStream) {
var _this = this;
return new Promise(function (resolve, reject) {
if (!inputStream) {
reject(new Error('Must pass in a stream containing the service account auth settings.'));
}
var s = '';
inputStream.setEncoding('utf8');
inputStream.on('data', function (chunk) {
s += chunk;
});
inputStream.on('end', function () {
try {
var data = JSON.parse(s);
_this.fromJSON(data);
resolve();
}
catch (err) {
reject(err);
}
});
});
};
return JWTAccess;
}());
exports.JWTAccess = JWTAccess;
//# sourceMappingURL=jwtaccess.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"jwtaccess.js","sourceRoot":"","sources":["../../../src/auth/jwtaccess.ts"],"names":[],"mappings":"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"}

View File

@@ -0,0 +1,111 @@
/**
* 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 { GetTokenResponse, OAuth2Client, RefreshOptions, RequestMetadataResponse } from './oauth2client';
export interface JWTOptions extends RefreshOptions {
email?: string;
keyFile?: string;
key?: string;
scopes?: string | string[];
subject?: string;
additionalClaims?: {};
}
export declare class JWT extends OAuth2Client {
email?: string;
keyFile?: string;
key?: string;
scopes?: string | string[];
scope?: string;
subject?: string;
gtoken?: GoogleToken;
additionalClaims?: {};
private access?;
/**
* JWT service account credentials.
*
* Retrieve access token using gtoken.
*
* @param email service account email address.
* @param keyFile path to private key file.
* @param key value of key
* @param scopes list of requested scopes or a single scope.
* @param subject impersonated account's email address.
*/
constructor(options: JWTOptions);
constructor(email?: string, keyFile?: string, key?: string, scopes?: string | string[], subject?: string);
/**
* Creates a copy of the credential with the specified scopes.
* @param scopes List of requested scopes or a single scope.
* @return The cloned instance.
*/
createScoped(scopes?: string | string[]): JWT;
/**
* Obtains the metadata to be sent with the request.
*
* @param url the URI being authorized.
*/
protected getRequestMetadataAsync(url?: string | null): Promise<RequestMetadataResponse>;
/**
* Indicates whether the credential requires scopes to be created by calling
* createScoped before use.
* @return false if createScoped does not need to be called.
*/
createScopedRequired(): boolean;
/**
* Get the initial access token using gToken.
* @param callback Optional callback.
* @returns Promise that resolves with credentials
*/
authorize(): Promise<Credentials>;
authorize(callback: (err: Error | null, result?: Credentials) => void): void;
private authorizeAsync;
/**
* Refreshes the access token.
* @param refreshToken ignored
* @private
*/
protected refreshTokenNoCache(refreshToken?: string | null): Promise<GetTokenResponse>;
/**
* Create a gToken if it doesn't already exist.
*/
private createGToken;
/**
* Create a JWT credentials instance using the given input options.
* @param json The input object.
*/
fromJSON(json: JWTInput): void;
/**
* Create a JWT credentials instance using the given input stream.
* @param inputStream The input stream.
* @param callback Optional callback.
*/
fromStream(inputStream: stream.Readable): Promise<void>;
fromStream(inputStream: stream.Readable, callback: (err?: Error | null) => void): void;
private fromStreamAsync;
/**
* Creates a JWT credentials instance using an API Key for authentication.
* @param apiKey The API Key in string form.
*/
fromAPIKey(apiKey: string): void;
/**
* Using the key or keyFile on the JWT client, obtain an object that contains
* the key and the client email.
*/
getCredentials(): Promise<CredentialBody>;
}

View File

@@ -0,0 +1,306 @@
"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.
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var gtoken_1 = require("gtoken");
var jwtaccess_1 = require("./jwtaccess");
var oauth2client_1 = require("./oauth2client");
var isString = require('lodash.isstring');
var JWT = /** @class */ (function (_super) {
__extends(JWT, _super);
function JWT(optionsOrEmail, keyFile, key, scopes, subject) {
var _this = this;
var opts = (optionsOrEmail && typeof optionsOrEmail === 'object') ?
optionsOrEmail :
{ email: optionsOrEmail, keyFile: keyFile, key: key, scopes: scopes, subject: subject };
_this = _super.call(this, { eagerRefreshThresholdMillis: opts.eagerRefreshThresholdMillis }) || this;
_this.email = opts.email;
_this.keyFile = opts.keyFile;
_this.key = opts.key;
_this.scopes = opts.scopes;
_this.subject = opts.subject;
_this.additionalClaims = opts.additionalClaims;
_this.credentials = { refresh_token: 'jwt-placeholder', expiry_date: 1 };
return _this;
}
/**
* Creates a copy of the credential with the specified scopes.
* @param scopes List of requested scopes or a single scope.
* @return The cloned instance.
*/
JWT.prototype.createScoped = function (scopes) {
return new JWT({
email: this.email,
keyFile: this.keyFile,
key: this.key,
scopes: scopes,
subject: this.subject,
additionalClaims: this.additionalClaims
});
};
/**
* Obtains the metadata to be sent with the request.
*
* @param url the URI being authorized.
*/
JWT.prototype.getRequestMetadataAsync = function (url) {
return __awaiter(this, void 0, void 0, function () {
var tokens;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(!this.apiKey && this.createScopedRequired() && url)) return [3 /*break*/, 4];
if (!(this.additionalClaims && this.additionalClaims.target_audience)) return [3 /*break*/, 2];
return [4 /*yield*/, this.refreshToken()];
case 1:
tokens = (_a.sent()).tokens;
return [2 /*return*/, { headers: { Authorization: "Bearer " + tokens.id_token } }];
case 2:
// 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);
}
return [2 /*return*/, this.access.getRequestMetadata(url, this.additionalClaims)];
case 3: return [3 /*break*/, 5];
case 4: return [2 /*return*/, _super.prototype.getRequestMetadataAsync.call(this, url)];
case 5: return [2 /*return*/];
}
});
});
};
/**
* Indicates whether the credential requires scopes to be created by calling
* createScoped before use.
* @return false if createScoped does not need to be called.
*/
JWT.prototype.createScopedRequired = function () {
// If scopes is null, always return true.
if (this.scopes) {
// 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 true;
};
JWT.prototype.authorize = function (callback) {
if (callback) {
this.authorizeAsync().then(function (r) { return callback(null, r); }).catch(callback);
}
else {
return this.authorizeAsync();
}
};
JWT.prototype.authorizeAsync = function () {
return __awaiter(this, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.refreshToken()];
case 1:
result = _a.sent();
if (!result) {
throw new Error('No result returned');
}
this.credentials = result.tokens;
this.credentials.refresh_token = 'jwt-placeholder';
this.key = this.gtoken.key;
this.email = this.gtoken.iss;
return [2 /*return*/, result.tokens];
}
});
});
};
/**
* Refreshes the access token.
* @param refreshToken ignored
* @private
*/
JWT.prototype.refreshTokenNoCache = function (refreshToken) {
return __awaiter(this, void 0, void 0, function () {
var gtoken, token, tokens;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
gtoken = this.createGToken();
return [4 /*yield*/, gtoken.getToken()];
case 1:
token = _a.sent();
tokens = {
access_token: token,
token_type: 'Bearer',
expiry_date: gtoken.expiresAt,
// tslint:disable-next-line no-any
id_token: gtoken.rawToken.id_token
};
this.emit('tokens', tokens);
return [2 /*return*/, { res: null, tokens: tokens }];
}
});
});
};
/**
* Create a gToken if it doesn't already exist.
*/
JWT.prototype.createGToken = function () {
if (!this.gtoken) {
this.gtoken = new gtoken_1.GoogleToken({
iss: this.email,
sub: this.subject,
scope: this.scopes,
keyFile: this.keyFile,
key: this.key,
additionalClaims: this.additionalClaims
});
}
return this.gtoken;
};
/**
* Create a JWT credentials instance using the given input options.
* @param json The input object.
*/
JWT.prototype.fromJSON = function (json) {
if (!json) {
throw new Error('Must pass in a JSON object containing the service account auth settings.');
}
if (!json.client_email) {
throw new Error('The incoming JSON object does not contain a client_email field');
}
if (!json.private_key) {
throw new Error('The incoming JSON object does not contain a private_key field');
}
// Extract the relevant information from the json key file.
this.email = json.client_email;
this.key = json.private_key;
this.projectId = json.project_id;
};
JWT.prototype.fromStream = function (inputStream, callback) {
if (callback) {
this.fromStreamAsync(inputStream).then(function (r) { return callback(); }).catch(callback);
}
else {
return this.fromStreamAsync(inputStream);
}
};
JWT.prototype.fromStreamAsync = function (inputStream) {
var _this = this;
return new Promise(function (resolve, reject) {
if (!inputStream) {
throw new Error('Must pass in a stream containing the service account auth settings.');
}
var s = '';
inputStream.setEncoding('utf8');
inputStream.on('data', function (chunk) {
s += chunk;
});
inputStream.on('end', function () {
try {
var data = JSON.parse(s);
_this.fromJSON(data);
resolve();
}
catch (e) {
reject(e);
}
});
});
};
/**
* Creates a JWT credentials instance using an API Key for authentication.
* @param apiKey The API Key in string form.
*/
JWT.prototype.fromAPIKey = function (apiKey) {
if (!isString(apiKey)) {
throw new Error('Must provide an API Key string.');
}
this.apiKey = apiKey;
};
/**
* Using the key or keyFile on the JWT client, obtain an object that contains
* the key and the client email.
*/
JWT.prototype.getCredentials = function () {
return __awaiter(this, void 0, void 0, function () {
var gtoken, creds;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.key) return [3 /*break*/, 1];
return [2 /*return*/, { private_key: this.key, client_email: this.email }];
case 1:
if (!this.keyFile) return [3 /*break*/, 3];
gtoken = this.createGToken();
return [4 /*yield*/, gtoken.getCredentials(this.keyFile)];
case 2:
creds = _a.sent();
return [2 /*return*/, { private_key: creds.privateKey, client_email: creds.clientEmail }];
case 3: throw new Error('A key or a keyFile must be provided to getCredentials.');
}
});
});
};
return JWT;
}(oauth2client_1.OAuth2Client));
exports.JWT = JWT;
//# sourceMappingURL=jwtclient.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,150 @@
/**
* 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?;
/**
* Create a simple class to extract user ID from an ID Token
*
* @param {string} env Envelope of the jwt
* @param {TokenPayload} pay Payload of the jwt
* @constructor
*/
constructor(env?: string, pay?: TokenPayload);
getEnvelope(): string | undefined;
getPayload(): TokenPayload | undefined;
/**
* Create a simple class to extract user ID from an ID Token
*
* @return The user ID
*/
getUserId(): string | null;
/**
* Returns attributes from the login ticket. This can contain
* various information about the user session.
*
* @return The envelope and payload
*/
getAttributes(): {
envelope: string | undefined;
payload: TokenPayload | undefined;
};
}
export interface TokenPayload {
/**
* The Issuer Identifier for the Issuer of the response. Always
* https://accounts.google.com or accounts.google.com for Google ID tokens.
*/
iss: string;
/**
* Access token hash. Provides validation that the access token is tied to the
* identity token. If the ID token is issued with an access token in the
* server flow, this is always included. This can be used as an alternate
* mechanism to protect against cross-site request forgery attacks, but if you
* follow Step 1 and Step 3 it is not necessary to verify the access token.
*/
at_hash?: string;
/**
* True if the user's e-mail address has been verified; otherwise false.
*/
email_verified?: boolean;
/**
* An identifier for the user, unique among all Google accounts and never
* reused. A Google account can have multiple emails at different points in
* time, but the sub value is never changed. Use sub within your application
* as the unique-identifier key for the user.
*/
sub: string;
/**
* The client_id of the authorized presenter. This claim is only needed when
* the party requesting the ID token is not the same as the audience of the ID
* token. This may be the case at Google for hybrid apps where a web
* application and Android app have a different client_id but share the same
* project.
*/
azp?: string;
/**
* The user's email address. This may not be unique and is not suitable for
* use as a primary key. Provided only if your scope included the string
* "email".
*/
email?: string;
/**
* The URL of the user's profile page. Might be provided when:
* - The request scope included the string "profile"
* - The ID token is returned from a token refresh
* - When profile claims are present, you can use them to update your app's
* user records. Note that this claim is never guaranteed to be present.
*/
profile?: string;
/**
* The URL of the user's profile picture. Might be provided when:
* - The request scope included the string "profile"
* - The ID token is returned from a token refresh
* - When picture claims are present, you can use them to update your app's
* user records. Note that this claim is never guaranteed to be present.
*/
picture?: string;
/**
* The user's full name, in a displayable form. Might be provided when:
* - The request scope included the string "profile"
* - The ID token is returned from a token refresh
* - When name claims are present, you can use them to update your app's user
* records. Note that this claim is never guaranteed to be present.
*/
name?: string;
/**
* The user's given name, in a displayable form. Might be provided when:
* - The request scope included the string "profile"
* - The ID token is returned from a token refresh
* - When name claims are present, you can use them to update your app's user
* records. Note that this claim is never guaranteed to be present.
*/
given_name?: string;
/**
* The user's family name, in a displayable form. Might be provided when:
* - The request scope included the string "profile"
* - The ID token is returned from a token refresh
* - When name claims are present, you can use them to update your app's user
* records. Note that this claim is never guaranteed to be present.
*/
family_name?: string;
/**
* Identifies the audience that this ID token is intended for. It must be one
* of the OAuth 2.0 client IDs of your application.
*/
aud: string;
/**
* The time the ID token was issued, represented in Unix time (integer
* seconds).
*/
iat: number;
/**
* The time the ID token expires, represented in Unix time (integer seconds).
*/
exp: number;
/**
* The value of the nonce supplied by your app in the authentication request.
* You should enforce protection against replay attacks by ensuring it is
* presented only once.
*/
nonce?: string;
/**
* The hosted G Suite domain of the user. Provided only if the user belongs to
* a hosted domain.
*/
hd?: string;
}

View File

@@ -0,0 +1,60 @@
"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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var LoginTicket = /** @class */ (function () {
/**
* Create a simple class to extract user ID from an ID Token
*
* @param {string} env Envelope of the jwt
* @param {TokenPayload} pay Payload of the jwt
* @constructor
*/
function LoginTicket(env, pay) {
this.envelope = env;
this.payload = pay;
}
LoginTicket.prototype.getEnvelope = function () {
return this.envelope;
};
LoginTicket.prototype.getPayload = function () {
return this.payload;
};
/**
* Create a simple class to extract user ID from an ID Token
*
* @return The user ID
*/
LoginTicket.prototype.getUserId = function () {
var payload = this.getPayload();
if (payload && payload.sub) {
return payload.sub;
}
return null;
};
/**
* Returns attributes from the login ticket. This can contain
* various information about the user session.
*
* @return The envelope and payload
*/
LoginTicket.prototype.getAttributes = function () {
return { envelope: this.getEnvelope(), payload: this.getPayload() };
};
return LoginTicket;
}());
exports.LoginTicket = LoginTicket;
//# sourceMappingURL=loginticket.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"loginticket.js","sourceRoot":"","sources":["../../../src/auth/loginticket.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAEH;IAIE;;;;;;OAMG;IACH,qBAAY,GAAY,EAAE,GAAkB;QAC1C,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC;IACrB,CAAC;IAED,iCAAW,GAAX;QACE,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED,gCAAU,GAAV;QACE,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED;;;;OAIG;IACH,+BAAS,GAAT;QACE,IAAM,OAAO,GAAG,IAAI,CAAC,UAAU,EAAE,CAAC;QAClC,IAAI,OAAO,IAAI,OAAO,CAAC,GAAG,EAAE;YAC1B,OAAO,OAAO,CAAC,GAAG,CAAC;SACpB;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;;;;OAKG;IACH,mCAAa,GAAb;QACE,OAAO,EAAC,QAAQ,EAAE,IAAI,CAAC,WAAW,EAAE,EAAE,OAAO,EAAE,IAAI,CAAC,UAAU,EAAE,EAAC,CAAC;IACpE,CAAC;IACH,kBAAC;AAAD,CAAC,AA9CD,IA8CC;AA9CY,kCAAW"}

View File

@@ -0,0 +1,461 @@
/**
* 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 { AxiosError, AxiosPromise, AxiosRequestConfig, AxiosResponse } from 'axios';
import * as http from 'http';
import { BodyResponseCallback } from './../transporters';
import { AuthClient } from './authclient';
import { Credentials } from './credentials';
import { LoginTicket } from './loginticket';
export declare enum CodeChallengeMethod {
Plain = "plain",
S256 = "S256"
}
export interface GetTokenOptions {
code: string;
codeVerifier?: string;
/**
* The client ID for your application. The value passed into the constructor
* will be used if not provided. Must match any client_id option passed to
* a corresponding call to generateAuthUrl.
*/
client_id?: string;
/**
* Determines where the API server redirects the user after the user
* completes the authorization flow. The value passed into the constructor
* will be used if not provided. Must match any redirect_uri option passed to
* a corresponding call to generateAuthUrl.
*/
redirect_uri?: string;
}
export interface TokenInfo {
/**
* The application that is the intended user of the access token.
*/
aud: string;
/**
* This value lets you correlate profile information from multiple Google
* APIs. It is only present in the response if you included the profile scope
* in your request in step 1. The field value is an immutable identifier for
* the logged-in user that can be used to create and manage user sessions in
* your application. The identifier is the same regardless of which client ID
* is used to retrieve it. This enables multiple applications in the same
* organization to correlate profile information.
*/
user_id?: string;
/**
* An array of scopes that the user granted access to.
*/
scopes: string[];
/**
* The datetime when the token becomes invalid.
*/
expiry_date: number;
/**
* An identifier for the user, unique among all Google accounts and never
* reused. A Google account can have multiple emails at different points in
* time, but the sub value is never changed. Use sub within your application
* as the unique-identifier key for the user.
*/
sub?: string;
/**
* The client_id of the authorized presenter. This claim is only needed when
* the party requesting the ID token is not the same as the audience of the ID
* token. This may be the case at Google for hybrid apps where a web
* application and Android app have a different client_id but share the same
* project.
*/
azp?: string;
/**
* Indicates whether your application can refresh access tokens
* when the user is not present at the browser. Valid parameter values are
* 'online', which is the default value, and 'offline'. Set the value to
* 'offline' if your application needs to refresh access tokens when the user
* is not present at the browser. This value instructs the Google
* authorization server to return a refresh token and an access token the
* first time that your application exchanges an authorization code for
* tokens.
*/
access_type?: string;
}
export interface TokenInfoRequest {
aud: string;
user_id?: string;
scope: string;
expires_in: number;
azp?: string;
sub?: string;
exp?: number;
access_type?: string;
}
export interface GenerateAuthUrlOpts {
/**
* Recommended. Indicates whether your application can refresh access tokens
* when the user is not present at the browser. Valid parameter values are
* 'online', which is the default value, and 'offline'. Set the value to
* 'offline' if your application needs to refresh access tokens when the user
* is not present at the browser. This value instructs the Google
* authorization server to return a refresh token and an access token the
* first time that your application exchanges an authorization code for
* tokens.
*/
access_type?: string;
/**
* The 'response_type' will always be set to 'CODE'.
*/
response_type?: string;
/**
* The client ID for your application. The value passed into the constructor
* will be used if not provided. You can find this value in the API Console.
*/
client_id?: string;
/**
* Determines where the API server redirects the user after the user
* completes the authorization flow. The value must exactly match one of the
* 'redirect_uri' values listed for your project in the API Console. Note that
* the http or https scheme, case, and trailing slash ('/') must all match.
* The value passed into the constructor will be used if not provided.
*/
redirect_uri?: string;
/**
* Required. A space-delimited list of scopes that identify the resources that
* your application could access on the user's behalf. These values inform the
* consent screen that Google displays to the user. Scopes enable your
* application to only request access to the resources that it needs while
* also enabling users to control the amount of access that they grant to your
* application. Thus, there is an inverse relationship between the number of
* scopes requested and the likelihood of obtaining user consent. The
* OAuth 2.0 API Scopes document provides a full list of scopes that you might
* use to access Google APIs. We recommend that your application request
* access to authorization scopes in context whenever possible. By requesting
* access to user data in context, via incremental authorization, you help
* users to more easily understand why your application needs the access it is
* requesting.
*/
scope?: string[] | string;
/**
* Recommended. Specifies any string value that your application uses to
* maintain state between your authorization request and the authorization
* server's response. The server returns the exact value that you send as a
* name=value pair in the hash (#) fragment of the 'redirect_uri' after the
* user consents to or denies your application's access request. You can use
* this parameter for several purposes, such as directing the user to the
* correct resource in your application, sending nonces, and mitigating
* cross-site request forgery. Since your redirect_uri can be guessed, using a
* state value can increase your assurance that an incoming connection is the
* result of an authentication request. If you generate a random string or
* encode the hash of a cookie or another value that captures the client's
* state, you can validate the response to additionally ensure that the
* request and response originated in the same browser, providing protection
* against attacks such as cross-site request forgery. See the OpenID Connect
* documentation for an example of how to create and confirm a state token.
*/
state?: string;
/**
* Optional. Enables applications to use incremental authorization to request
* access to additional scopes in context. If you set this parameter's value
* to true and the authorization request is granted, then the new access token
* will also cover any scopes to which the user previously granted the
* application access. See the incremental authorization section for examples.
*/
include_granted_scopes?: boolean;
/**
* Optional. If your application knows which user is trying to authenticate,
* it can use this parameter to provide a hint to the Google Authentication
* Server. The server uses the hint to simplify the login flow either by
* prefilling the email field in the sign-in form or by selecting the
* appropriate multi-login session. Set the parameter value to an email
* address or sub identifier, which is equivalent to the user's Google ID.
*/
login_hint?: string;
/**
* Optional. A space-delimited, case-sensitive list of prompts to present the
* user. If you don't specify this parameter, the user will be prompted only
* the first time your app requests access. Possible values are:
*
* 'none' - Donot display any authentication or consent screens. Must not be
* specified with other values.
* 'consent' - Prompt the user for consent.
* 'select_account' - Prompt the user to select an account.
*/
prompt?: string;
/**
* Recommended. Specifies what method was used to encode a 'code_verifier'
* that will be used during authorization code exchange. This parameter must
* be used with the 'code_challenge' parameter. The value of the
* 'code_challenge_method' defaults to "plain" if not present in the request
* that includes a 'code_challenge'. The only supported values for this
* parameter are "S256" or "plain".
*/
code_challenge_method?: CodeChallengeMethod;
/**
* Recommended. Specifies an encoded 'code_verifier' that will be used as a
* server-side challenge during authorization code exchange. This parameter
* must be used with the 'code_challenge' parameter described above.
*/
code_challenge?: string;
}
export interface AuthClientOpts {
authBaseUrl?: string;
tokenUrl?: string;
}
export interface GetTokenCallback {
(err: AxiosError | null, token?: Credentials | null, res?: AxiosResponse | null): void;
}
export interface GetTokenResponse {
tokens: Credentials;
res: AxiosResponse | null;
}
export interface GetAccessTokenCallback {
(err: AxiosError | null, token?: string | null, res?: AxiosResponse | null): void;
}
export interface GetAccessTokenResponse {
token?: string | null;
res?: AxiosResponse | null;
}
export interface RefreshAccessTokenCallback {
(err: AxiosError | null, credentials?: Credentials | null, res?: AxiosResponse | null): void;
}
export interface RefreshAccessTokenResponse {
credentials: Credentials;
res: AxiosResponse | null;
}
export interface RequestMetadataResponse {
headers: http.IncomingHttpHeaders;
res?: AxiosResponse<void> | null;
}
export interface RequestMetadataCallback {
(err: AxiosError | null, headers?: http.IncomingHttpHeaders, res?: AxiosResponse<void> | null): void;
}
export interface GetFederatedSignonCertsCallback {
(err: AxiosError | null, certs?: any, response?: AxiosResponse<void> | null): void;
}
export interface FederatedSignonCertsResponse {
certs: any;
res?: AxiosResponse<void> | null;
}
export interface RevokeCredentialsResult {
success: boolean;
}
export interface VerifyIdTokenOptions {
idToken: string;
audience: string | string[];
maxExpiry?: number;
}
export interface OAuth2ClientOptions extends RefreshOptions {
clientId?: string;
clientSecret?: string;
redirectUri?: string;
authBaseUrl?: string;
tokenUrl?: string;
}
export interface RefreshOptions {
eagerRefreshThresholdMillis?: number;
}
export declare class OAuth2Client extends AuthClient {
private redirectUri?;
private certificateCache;
private certificateExpiry;
protected refreshTokenPromises: Map<string, Promise<GetTokenResponse>>;
protected authBaseUrl?: string;
protected tokenUrl?: string;
_clientId?: string;
_clientSecret?: string;
apiKey?: string;
projectId?: string;
eagerRefreshThresholdMillis: number;
/**
* Handles OAuth2 flow for Google APIs.
*
* @param clientId The authentication client ID.
* @param clientSecret The authentication client secret.
* @param redirectUri The URI to redirect to after completing the auth
* request.
* @param opts optional options for overriding the given parameters.
* @constructor
*/
constructor(options?: OAuth2ClientOptions);
constructor(clientId?: string, clientSecret?: string, redirectUri?: string, opts?: AuthClientOpts);
protected static readonly GOOGLE_TOKEN_INFO_URL: string;
/**
* The base URL for auth endpoints.
*/
private static readonly GOOGLE_OAUTH2_AUTH_BASE_URL_;
/**
* The base endpoint for token retrieval.
*/
private static readonly GOOGLE_OAUTH2_TOKEN_URL_;
/**
* The base endpoint to revoke tokens.
*/
private static readonly GOOGLE_OAUTH2_REVOKE_URL_;
/**
* Google Sign on certificates.
*/
private static readonly GOOGLE_OAUTH2_FEDERATED_SIGNON_CERTS_URL_;
/**
* Clock skew - five minutes in seconds
*/
private static readonly CLOCK_SKEW_SECS_;
/**
* Max Token Lifetime is one day in seconds
*/
private static readonly MAX_TOKEN_LIFETIME_SECS_;
/**
* The allowed oauth token issuers.
*/
private static readonly ISSUERS_;
/**
* Generates URL for consent page landing.
* @param opts Options.
* @return URL to consent page.
*/
generateAuthUrl(opts?: GenerateAuthUrlOpts): string;
/**
* Convenience method to automatically generate a code_verifier, and it's
* resulting SHA256. If used, this must be paired with a S256
* code_challenge_method.
*/
generateCodeVerifier(): {
codeVerifier: string;
codeChallenge: string;
};
/**
* Gets the access token for the given code.
* @param code The authorization code.
* @param callback Optional callback fn.
*/
getToken(code: string): Promise<GetTokenResponse>;
getToken(options: GetTokenOptions): Promise<GetTokenResponse>;
getToken(code: string, callback: GetTokenCallback): void;
getToken(options: GetTokenOptions, callback: GetTokenCallback): void;
private getTokenAsync;
/**
* Refreshes the access token.
* @param refresh_token Existing refresh token.
* @private
*/
protected refreshToken(refreshToken?: string | null): Promise<GetTokenResponse>;
protected refreshTokenNoCache(refreshToken?: string | null): Promise<GetTokenResponse>;
/**
* Retrieves the access token using refresh token
*
* @deprecated use getRequestMetadata instead.
* @param callback callback
*/
refreshAccessToken(): Promise<RefreshAccessTokenResponse>;
refreshAccessToken(callback: RefreshAccessTokenCallback): void;
private refreshAccessTokenAsync;
/**
* Get a non-expired access token, after refreshing if necessary
*
* @param callback Callback to call with the access token
*/
getAccessToken(): Promise<GetAccessTokenResponse>;
getAccessToken(callback: GetAccessTokenCallback): void;
private getAccessTokenAsync;
/**
* getRequestMetadata obtains auth metadata to be used by requests.
*
* getRequestMetadata is the main authentication interface. It takes an
* optional uri which when present is the endpoint being accessed, and a
* callback func(err, metadata_obj, response) where metadata_obj contains
* authorization metadata fields and response is an optional response object.
*
* In OAuth2Client, metadata_obj has the form.
*
* {Authorization: 'Bearer <access_token_value>'}
*
* @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;
protected getRequestMetadataAsync(url?: string | null): Promise<RequestMetadataResponse>;
/**
* Revokes the access given to token.
* @param token The existing token to be revoked.
* @param callback Optional callback fn.
*/
revokeToken(token: string): AxiosPromise<RevokeCredentialsResult>;
revokeToken(token: string, callback: BodyResponseCallback<RevokeCredentialsResult>): void;
/**
* Revokes access token and clears the credentials object
* @param callback callback
*/
revokeCredentials(): AxiosPromise<RevokeCredentialsResult>;
revokeCredentials(callback: BodyResponseCallback<RevokeCredentialsResult>): void;
private revokeCredentialsAsync;
/**
* Provides a request implementation with OAuth 2.0 flow. If credentials have
* a refresh_token, in cases of HTTP 401 and 403 responses, it automatically
* asks for a new access token and replays the unsuccessful request.
* @param opts Request options.
* @param callback callback.
* @return Request object
*/
request<T>(opts: AxiosRequestConfig): AxiosPromise<T>;
request<T>(opts: AxiosRequestConfig, callback: BodyResponseCallback<T>): void;
protected requestAsync<T>(opts: AxiosRequestConfig, retry?: boolean): Promise<AxiosResponse<T>>;
/**
* Verify id token is token by checking the certs and audience
* @param options that contains all options.
* @param callback Callback supplying GoogleLogin if successful
*/
verifyIdToken(options: VerifyIdTokenOptions): Promise<LoginTicket | null>;
verifyIdToken(options: VerifyIdTokenOptions, callback: (err: Error | null, login?: LoginTicket | null) => void): void;
private verifyIdTokenAsync;
/**
* Obtains information about the provisioned access token. Especially useful
* if you want to check the scopes that were provisioned to a given token.
*
* @param accessToken Required. The Access Token for which you want to get
* user info.
*/
getTokenInfo(accessToken: string): Promise<TokenInfo>;
/**
* Gets federated sign-on certificates to use for verifying identity tokens.
* Returns certs as array structure, where keys are key ids, and values
* are PEM encoded certificates.
* @param callback Callback supplying the certificates
*/
getFederatedSignonCerts(): Promise<FederatedSignonCertsResponse>;
getFederatedSignonCerts(callback: GetFederatedSignonCertsCallback): void;
getFederatedSignonCertsAsync(): Promise<FederatedSignonCertsResponse>;
/**
* Verify the id token is signed with the correct certificate
* and is from the correct audience.
* @param jwt The jwt to verify (The ID Token in this case).
* @param certs The array of certs to test the jwt against.
* @param requiredAudience The audience to test the jwt against.
* @param issuers The allowed issuers of the jwt (Optional).
* @param maxExpiry The max expiry the certificate can be (Optional).
* @return Returns a LoginTicket on verification.
*/
verifySignedJwtWithCerts(jwt: string, certs: {}, requiredAudience: string | string[], issuers?: string[], maxExpiry?: number): LoginTicket;
/**
* This is a utils method to decode a base64 string
* @param b64String The string to base64 decode
* @return The decoded string
*/
decodeBase64(b64String: string): string;
/**
* Returns true if a token is expired or will expire within
* eagerRefreshThresholdMillismilliseconds.
* If there is no expiry time, assumes the token is not expired or expiring.
*/
protected isTokenExpiring(): boolean;
}

View File

@@ -0,0 +1,753 @@
"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.
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var crypto_1 = __importDefault(require("crypto"));
var querystring_1 = __importDefault(require("querystring"));
var stream = __importStar(require("stream"));
var pemverifier_1 = require("./../pemverifier");
var authclient_1 = require("./authclient");
var loginticket_1 = require("./loginticket");
var CodeChallengeMethod;
(function (CodeChallengeMethod) {
CodeChallengeMethod["Plain"] = "plain";
CodeChallengeMethod["S256"] = "S256";
})(CodeChallengeMethod = exports.CodeChallengeMethod || (exports.CodeChallengeMethod = {}));
var OAuth2Client = /** @class */ (function (_super) {
__extends(OAuth2Client, _super);
function OAuth2Client(optionsOrClientId, clientSecret, redirectUri, authClientOpts) {
if (authClientOpts === void 0) { authClientOpts = {}; }
var _this = _super.call(this) || this;
_this.certificateCache = null;
_this.certificateExpiry = null;
_this.refreshTokenPromises = new Map();
var opts = (optionsOrClientId && typeof optionsOrClientId === 'object') ?
optionsOrClientId :
{
clientId: optionsOrClientId,
clientSecret: clientSecret,
redirectUri: redirectUri,
tokenUrl: authClientOpts.tokenUrl,
authBaseUrl: authClientOpts.authBaseUrl
};
_this._clientId = opts.clientId;
_this._clientSecret = opts.clientSecret;
_this.redirectUri = opts.redirectUri;
_this.authBaseUrl = opts.authBaseUrl;
_this.tokenUrl = opts.tokenUrl;
_this.eagerRefreshThresholdMillis =
opts.eagerRefreshThresholdMillis || 5 * 60 * 1000;
return _this;
}
/**
* Generates URL for consent page landing.
* @param opts Options.
* @return URL to consent page.
*/
OAuth2Client.prototype.generateAuthUrl = function (opts) {
if (opts === void 0) { opts = {}; }
if (opts.code_challenge_method && !opts.code_challenge) {
throw new Error('If a code_challenge_method is provided, code_challenge must be included.');
}
opts.response_type = opts.response_type || 'code';
opts.client_id = opts.client_id || this._clientId;
opts.redirect_uri = opts.redirect_uri || this.redirectUri;
// Allow scopes to be passed either as array or a string
if (opts.scope instanceof Array) {
opts.scope = opts.scope.join(' ');
}
var rootUrl = this.authBaseUrl || OAuth2Client.GOOGLE_OAUTH2_AUTH_BASE_URL_;
return rootUrl + '?' + querystring_1.default.stringify(opts);
};
/**
* Convenience method to automatically generate a code_verifier, and it's
* resulting SHA256. If used, this must be paired with a S256
* code_challenge_method.
*/
OAuth2Client.prototype.generateCodeVerifier = function () {
// base64 encoding uses 6 bits per character, and we want to generate128
// characters. 6*128/8 = 96.
var randomString = crypto_1.default.randomBytes(96).toString('base64');
// The valid characters in the code_verifier are [A-Z]/[a-z]/[0-9]/
// "-"/"."/"_"/"~". Base64 encoded strings are pretty close, so we're just
// swapping out a few chars.
var codeVerifier = randomString.replace(/\+/g, '~').replace(/=/g, '_').replace(/\//g, '-');
// Generate the base64 encoded SHA256
var unencodedCodeChallenge = crypto_1.default.createHash('sha256').update(codeVerifier).digest('base64');
// We need to use base64UrlEncoding instead of standard base64
var codeChallenge = unencodedCodeChallenge.split('=')[0]
.replace(/\+/g, '-')
.replace(/\//g, '_');
return { codeVerifier: codeVerifier, codeChallenge: codeChallenge };
};
OAuth2Client.prototype.getToken = function (codeOrOptions, callback) {
var options = (typeof codeOrOptions === 'string') ?
{ code: codeOrOptions } :
codeOrOptions;
if (callback) {
this.getTokenAsync(options)
.then(function (r) { return callback(null, r.tokens, r.res); })
.catch(function (e) { return callback(e, null, e.response); });
}
else {
return this.getTokenAsync(options);
}
};
OAuth2Client.prototype.getTokenAsync = function (options) {
return __awaiter(this, void 0, void 0, function () {
var url, values, res, tokens;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
url = this.tokenUrl || OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_;
values = {
code: options.code,
client_id: options.client_id || this._clientId,
client_secret: this._clientSecret,
redirect_uri: options.redirect_uri || this.redirectUri,
grant_type: 'authorization_code',
code_verifier: options.codeVerifier
};
return [4 /*yield*/, this.transporter.request({
method: 'POST',
url: url,
data: querystring_1.default.stringify(values),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})];
case 1:
res = _a.sent();
tokens = res.data;
if (res.data && res.data.expires_in) {
tokens.expiry_date =
((new Date()).getTime() + (res.data.expires_in * 1000));
delete tokens.expires_in;
}
this.emit('tokens', tokens);
return [2 /*return*/, { tokens: tokens, res: res }];
}
});
});
};
/**
* Refreshes the access token.
* @param refresh_token Existing refresh token.
* @private
*/
OAuth2Client.prototype.refreshToken = function (refreshToken) {
return __awaiter(this, void 0, void 0, function () {
var p;
var _this = this;
return __generator(this, function (_a) {
if (!refreshToken) {
return [2 /*return*/, this.refreshTokenNoCache(refreshToken)];
}
// If a request to refresh using the same token has started,
// return the same promise.
if (this.refreshTokenPromises.has(refreshToken)) {
return [2 /*return*/, this.refreshTokenPromises.get(refreshToken)];
}
p = this.refreshTokenNoCache(refreshToken)
.then(function (r) {
_this.refreshTokenPromises.delete(refreshToken);
return r;
})
.catch(function (e) {
_this.refreshTokenPromises.delete(refreshToken);
throw e;
});
this.refreshTokenPromises.set(refreshToken, p);
return [2 /*return*/, p];
});
});
};
OAuth2Client.prototype.refreshTokenNoCache = function (refreshToken) {
return __awaiter(this, void 0, void 0, function () {
var url, data, res, tokens;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
url = this.tokenUrl || OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_;
data = {
refresh_token: refreshToken,
client_id: this._clientId,
client_secret: this._clientSecret,
grant_type: 'refresh_token'
};
return [4 /*yield*/, this.transporter.request({
method: 'POST',
url: url,
data: querystring_1.default.stringify(data),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})];
case 1:
res = _a.sent();
tokens = res.data;
// TODO: de-duplicate this code from a few spots
if (res.data && res.data.expires_in) {
tokens.expiry_date =
((new Date()).getTime() + (res.data.expires_in * 1000));
delete tokens.expires_in;
}
this.emit('tokens', tokens);
return [2 /*return*/, { tokens: tokens, res: res }];
}
});
});
};
OAuth2Client.prototype.refreshAccessToken = function (callback) {
if (callback) {
this.refreshAccessTokenAsync()
.then(function (r) { return callback(null, r.credentials, r.res); })
.catch(callback);
}
else {
return this.refreshAccessTokenAsync();
}
};
OAuth2Client.prototype.refreshAccessTokenAsync = function () {
return __awaiter(this, void 0, void 0, function () {
var r, tokens;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.credentials.refresh_token) {
throw new Error('No refresh token is set.');
}
return [4 /*yield*/, this.refreshToken(this.credentials.refresh_token)];
case 1:
r = _a.sent();
tokens = r.tokens;
tokens.refresh_token = this.credentials.refresh_token;
this.credentials = tokens;
return [2 /*return*/, { credentials: this.credentials, res: r.res }];
}
});
});
};
OAuth2Client.prototype.getAccessToken = function (callback) {
if (callback) {
this.getAccessTokenAsync()
.then(function (r) { return callback(null, r.token, r.res); })
.catch(callback);
}
else {
return this.getAccessTokenAsync();
}
};
OAuth2Client.prototype.getAccessTokenAsync = function () {
return __awaiter(this, void 0, void 0, function () {
var shouldRefresh, r;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
shouldRefresh = !this.credentials.access_token || this.isTokenExpiring();
if (!(shouldRefresh && this.credentials.refresh_token)) return [3 /*break*/, 2];
if (!this.credentials.refresh_token) {
throw new Error('No refresh token is set.');
}
return [4 /*yield*/, this.refreshAccessToken()];
case 1:
r = _a.sent();
if (!r.credentials || (r.credentials && !r.credentials.access_token)) {
throw new Error('Could not refresh access token.');
}
return [2 /*return*/, { token: r.credentials.access_token, res: r.res }];
case 2: return [2 /*return*/, { token: this.credentials.access_token }];
}
});
});
};
OAuth2Client.prototype.getRequestMetadata = function (url, callback) {
if (callback) {
this.getRequestMetadataAsync(url)
.then(function (r) { return callback(null, r.headers, r.res); })
.catch(callback);
}
else {
return this.getRequestMetadataAsync(url);
}
};
OAuth2Client.prototype.getRequestMetadataAsync = function (url) {
return __awaiter(this, void 0, void 0, function () {
var thisCreds, headers_1, r, tokens, err_1, e, credentials, headers;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
thisCreds = this.credentials;
if (!thisCreds.access_token && !thisCreds.refresh_token && !this.apiKey) {
throw new Error('No access, refresh token or API key is set.');
}
if (thisCreds.access_token && !this.isTokenExpiring()) {
thisCreds.token_type = thisCreds.token_type || 'Bearer';
headers_1 = {
Authorization: thisCreds.token_type + ' ' + thisCreds.access_token
};
return [2 /*return*/, { headers: headers_1 }];
}
if (this.apiKey) {
return [2 /*return*/, { headers: {} }];
}
r = null;
tokens = null;
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.refreshToken(thisCreds.refresh_token)];
case 2:
r = _a.sent();
tokens = r.tokens;
return [3 /*break*/, 4];
case 3:
err_1 = _a.sent();
e = err_1;
if (e.response &&
(e.response.status === 403 || e.response.status === 404)) {
e.message = 'Could not refresh access token.';
}
throw e;
case 4:
credentials = this.credentials;
credentials.token_type = credentials.token_type || 'Bearer';
tokens.refresh_token = credentials.refresh_token;
this.credentials = tokens;
headers = {
Authorization: credentials.token_type + ' ' + tokens.access_token
};
return [2 /*return*/, { headers: headers, res: r.res }];
}
});
});
};
OAuth2Client.prototype.revokeToken = function (token, callback) {
var opts = {
url: OAuth2Client.GOOGLE_OAUTH2_REVOKE_URL_ + '?' +
querystring_1.default.stringify({ token: token })
};
if (callback) {
this.transporter.request(opts)
.then(function (res) {
callback(null, res);
})
.catch(callback);
}
else {
return this.transporter.request(opts);
}
};
OAuth2Client.prototype.revokeCredentials = function (callback) {
if (callback) {
this.revokeCredentialsAsync()
.then(function (res) { return callback(null, res); })
.catch(callback);
}
else {
return this.revokeCredentialsAsync();
}
};
OAuth2Client.prototype.revokeCredentialsAsync = function () {
return __awaiter(this, void 0, void 0, function () {
var token;
return __generator(this, function (_a) {
token = this.credentials.access_token;
this.credentials = {};
if (token) {
return [2 /*return*/, this.revokeToken(token)];
}
else {
throw new Error('No access token to revoke.');
}
return [2 /*return*/];
});
});
};
OAuth2Client.prototype.request = function (opts, callback) {
if (callback) {
this.requestAsync(opts).then(function (r) { return callback(null, r); }).catch(function (e) {
var err = e;
var body = err.response ? err.response.data : null;
return callback(e, err.response);
});
}
else {
return this.requestAsync(opts);
}
};
OAuth2Client.prototype.requestAsync = function (opts, retry) {
if (retry === void 0) { retry = false; }
return __awaiter(this, void 0, void 0, function () {
var r2, r, e_1, res, statusCode, mayRequireRefresh, isReadableStream, isAuthErr;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 3, , 6]);
return [4 /*yield*/, this.getRequestMetadataAsync(opts.url)];
case 1:
r = _a.sent();
if (r.headers && r.headers.Authorization) {
opts.headers = opts.headers || {};
opts.headers.Authorization = r.headers.Authorization;
}
if (this.apiKey) {
opts.params = Object.assign(opts.params || {}, { key: this.apiKey });
}
return [4 /*yield*/, this.transporter.request(opts)];
case 2:
r2 = _a.sent();
return [3 /*break*/, 6];
case 3:
e_1 = _a.sent();
res = e_1.response;
if (!res) return [3 /*break*/, 5];
statusCode = res.status;
mayRequireRefresh = this.credentials &&
this.credentials.access_token && this.credentials.refresh_token &&
!this.credentials.expiry_date;
isReadableStream = res.config.data instanceof stream.Readable;
isAuthErr = statusCode === 401 || statusCode === 403;
if (!(!retry && isAuthErr && !isReadableStream && mayRequireRefresh)) return [3 /*break*/, 5];
return [4 /*yield*/, this.refreshAccessTokenAsync()];
case 4:
_a.sent();
return [2 /*return*/, this.requestAsync(opts, true)];
case 5: throw e_1;
case 6: return [2 /*return*/, r2];
}
});
});
};
OAuth2Client.prototype.verifyIdToken = function (options, callback) {
// This function used to accept two arguments instead of an options object.
// Check the types to help users upgrade with less pain.
// This check can be removed after a 2.0 release.
if (callback && typeof callback !== 'function') {
throw new Error('This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.');
}
if (callback) {
this.verifyIdTokenAsync(options)
.then(function (r) { return callback(null, r); })
.catch(callback);
}
else {
return this.verifyIdTokenAsync(options);
}
};
OAuth2Client.prototype.verifyIdTokenAsync = function (options) {
return __awaiter(this, void 0, void 0, function () {
var response, login;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!options.idToken) {
throw new Error('The verifyIdToken method requires an ID Token');
}
return [4 /*yield*/, this.getFederatedSignonCertsAsync()];
case 1:
response = _a.sent();
login = this.verifySignedJwtWithCerts(options.idToken, response.certs, options.audience, OAuth2Client.ISSUERS_, options.maxExpiry);
return [2 /*return*/, login];
}
});
});
};
/**
* Obtains information about the provisioned access token. Especially useful
* if you want to check the scopes that were provisioned to a given token.
*
* @param accessToken Required. The Access Token for which you want to get
* user info.
*/
OAuth2Client.prototype.getTokenInfo = function (accessToken) {
return __awaiter(this, void 0, void 0, function () {
var data, info;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.transporter.request({
method: 'GET',
url: OAuth2Client.GOOGLE_TOKEN_INFO_URL,
params: { access_token: accessToken }
})];
case 1:
data = (_a.sent()).data;
info = Object.assign({
expiry_date: ((new Date()).getTime() + (data.expires_in * 1000)),
scopes: data.scope.split(' ')
}, data);
delete info.expires_in;
delete info.scope;
return [2 /*return*/, info];
}
});
});
};
OAuth2Client.prototype.getFederatedSignonCerts = function (callback) {
if (callback) {
this.getFederatedSignonCertsAsync()
.then(function (r) { return callback(null, r.certs, r.res); })
.catch(callback);
}
else {
return this.getFederatedSignonCertsAsync();
}
};
OAuth2Client.prototype.getFederatedSignonCertsAsync = function () {
return __awaiter(this, void 0, void 0, function () {
var nowTime, res, e_2, cacheControl, cacheAge, pattern, regexResult, now;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
nowTime = (new Date()).getTime();
if (this.certificateExpiry &&
(nowTime < this.certificateExpiry.getTime())) {
return [2 /*return*/, { certs: this.certificateCache }];
}
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.transporter.request({ url: OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_CERTS_URL_ })];
case 2:
res = _a.sent();
return [3 /*break*/, 4];
case 3:
e_2 = _a.sent();
throw new Error('Failed to retrieve verification certificates: ' + e_2);
case 4:
cacheControl = res ? res.headers['cache-control'] : undefined;
cacheAge = -1;
if (cacheControl) {
pattern = new RegExp('max-age=([0-9]*)');
regexResult = pattern.exec(cacheControl);
if (regexResult && regexResult.length === 2) {
// Cache results with max-age (in seconds)
cacheAge = Number(regexResult[1]) * 1000; // milliseconds
}
}
now = new Date();
this.certificateExpiry =
cacheAge === -1 ? null : new Date(now.getTime() + cacheAge);
this.certificateCache = res.data;
return [2 /*return*/, { certs: res.data, res: res }];
}
});
});
};
/**
* Verify the id token is signed with the correct certificate
* and is from the correct audience.
* @param jwt The jwt to verify (The ID Token in this case).
* @param certs The array of certs to test the jwt against.
* @param requiredAudience The audience to test the jwt against.
* @param issuers The allowed issuers of the jwt (Optional).
* @param maxExpiry The max expiry the certificate can be (Optional).
* @return Returns a LoginTicket on verification.
*/
OAuth2Client.prototype.verifySignedJwtWithCerts = function (jwt, certs, requiredAudience, issuers, maxExpiry) {
if (!maxExpiry) {
maxExpiry = OAuth2Client.MAX_TOKEN_LIFETIME_SECS_;
}
var segments = jwt.split('.');
if (segments.length !== 3) {
throw new Error('Wrong number of segments in token: ' + jwt);
}
var signed = segments[0] + '.' + segments[1];
var signature = segments[2];
var envelope;
var payload;
try {
envelope = JSON.parse(this.decodeBase64(segments[0]));
}
catch (err) {
throw new Error('Can\'t parse token envelope: ' + segments[0]);
}
if (!envelope) {
throw new Error('Can\'t parse token envelope: ' + segments[0]);
}
try {
payload = JSON.parse(this.decodeBase64(segments[1]));
}
catch (err) {
throw new Error('Can\'t parse token payload: ' + segments[0]);
}
if (!payload) {
throw new Error('Can\'t parse token payload: ' + segments[1]);
}
if (!certs.hasOwnProperty(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));
}
// certs is a legit dynamic object
// tslint:disable-next-line no-any
var pem = certs[envelope.kid];
var pemVerifier = new pemverifier_1.PemVerifier();
var verified = pemVerifier.verify(pem, signed, signature, 'base64');
if (!verified) {
throw new Error('Invalid token signature: ' + jwt);
}
if (!payload.iat) {
throw new Error('No issue time in token: ' + JSON.stringify(payload));
}
if (!payload.exp) {
throw new Error('No expiration time in token: ' + JSON.stringify(payload));
}
var iat = Number(payload.iat);
if (isNaN(iat))
throw new Error('iat field using invalid format');
var exp = Number(payload.exp);
if (isNaN(exp))
throw new Error('exp field using invalid format');
var now = new Date().getTime() / 1000;
if (exp >= now + maxExpiry) {
throw new Error('Expiration time too far in future: ' + JSON.stringify(payload));
}
var earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_;
var latest = exp + OAuth2Client.CLOCK_SKEW_SECS_;
if (now < earliest) {
throw new Error('Token used too early, ' + now + ' < ' + earliest + ': ' +
JSON.stringify(payload));
}
if (now > latest) {
throw new Error('Token used too late, ' + now + ' > ' + latest + ': ' +
JSON.stringify(payload));
}
if (issuers && issuers.indexOf(payload.iss) < 0) {
throw new Error('Invalid issuer, expected one of [' + issuers + '], but got ' +
payload.iss);
}
// Check the audience matches if we have one
if (typeof requiredAudience !== 'undefined' && requiredAudience !== null) {
var aud = payload.aud;
var audVerified = false;
// If the requiredAudience is an array, check if it contains token
// audience
if (requiredAudience.constructor === Array) {
audVerified = (requiredAudience.indexOf(aud) > -1);
}
else {
audVerified = (aud === requiredAudience);
}
if (!audVerified) {
throw new Error('Wrong recipient, payload audience != requiredAudience');
}
}
return new loginticket_1.LoginTicket(envelope, payload);
};
/**
* This is a utils method to decode a base64 string
* @param b64String The string to base64 decode
* @return The decoded string
*/
OAuth2Client.prototype.decodeBase64 = function (b64String) {
var buffer = new Buffer(b64String, 'base64');
return buffer.toString('utf8');
};
/**
* Returns true if a token is expired or will expire within
* eagerRefreshThresholdMillismilliseconds.
* If there is no expiry time, assumes the token is not expired or expiring.
*/
OAuth2Client.prototype.isTokenExpiring = function () {
var expiryDate = this.credentials.expiry_date;
return expiryDate ? expiryDate <=
((new Date()).getTime() + this.eagerRefreshThresholdMillis) :
false;
};
OAuth2Client.GOOGLE_TOKEN_INFO_URL = 'https://www.googleapis.com/oauth2/v3/tokeninfo';
/**
* The base URL for auth endpoints.
*/
OAuth2Client.GOOGLE_OAUTH2_AUTH_BASE_URL_ = 'https://accounts.google.com/o/oauth2/v2/auth';
/**
* The base endpoint for token retrieval.
*/
OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_ = 'https://www.googleapis.com/oauth2/v4/token';
/**
* The base endpoint to revoke tokens.
*/
OAuth2Client.GOOGLE_OAUTH2_REVOKE_URL_ = 'https://accounts.google.com/o/oauth2/revoke';
/**
* Google Sign on certificates.
*/
OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_CERTS_URL_ = 'https://www.googleapis.com/oauth2/v1/certs';
/**
* Clock skew - five minutes in seconds
*/
OAuth2Client.CLOCK_SKEW_SECS_ = 300;
/**
* Max Token Lifetime is one day in seconds
*/
OAuth2Client.MAX_TOKEN_LIFETIME_SECS_ = 86400;
/**
* The allowed oauth token issuers.
*/
OAuth2Client.ISSUERS_ = ['accounts.google.com', 'https://accounts.google.com'];
return OAuth2Client;
}(authclient_1.AuthClient));
exports.OAuth2Client = OAuth2Client;
//# sourceMappingURL=oauth2client.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,58 @@
/**
* 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 { GetTokenResponse, OAuth2Client, RefreshOptions } from './oauth2client';
export interface UserRefreshClientOptions extends RefreshOptions {
clientId?: string;
clientSecret?: string;
refreshToken?: string;
}
export declare class UserRefreshClient extends OAuth2Client {
_refreshToken?: string | null;
/**
* User Refresh Token credentials.
*
* @param clientId The authentication client ID.
* @param clientSecret The authentication client secret.
* @param refreshToken The authentication refresh token.
*/
constructor(clientId?: string, clientSecret?: string, refreshToken?: string);
constructor(options: UserRefreshClientOptions);
constructor(clientId?: string, clientSecret?: string, refreshToken?: string);
/**
* Refreshes the access token.
* @param refreshToken An ignored refreshToken..
* @param callback Optional callback.
*/
protected refreshTokenNoCache(refreshToken?: string | null): Promise<GetTokenResponse>;
/**
* Create a UserRefreshClient credentials instance using the given input
* options.
* @param json The input object.
*/
fromJSON(json: JWTInput): void;
/**
* Create a UserRefreshClient credentials instance using the given input
* stream.
* @param inputStream The input stream.
* @param callback Optional callback.
*/
fromStream(inputStream: stream.Readable): Promise<void>;
fromStream(inputStream: stream.Readable, callback: (err?: Error) => void): void;
private fromStreamAsync;
}

View File

@@ -0,0 +1,160 @@
"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.
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var oauth2client_1 = require("./oauth2client");
var UserRefreshClient = /** @class */ (function (_super) {
__extends(UserRefreshClient, _super);
function UserRefreshClient(optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis) {
var _this = this;
var opts = (optionsOrClientId && typeof optionsOrClientId === 'object') ?
optionsOrClientId :
{
clientId: optionsOrClientId,
clientSecret: clientSecret,
refreshToken: refreshToken,
eagerRefreshThresholdMillis: eagerRefreshThresholdMillis
};
_this = _super.call(this, {
clientId: opts.clientId,
clientSecret: opts.clientSecret,
eagerRefreshThresholdMillis: opts.eagerRefreshThresholdMillis
}) || this;
_this._refreshToken = opts.refreshToken;
return _this;
}
/**
* Refreshes the access token.
* @param refreshToken An ignored refreshToken..
* @param callback Optional callback.
*/
UserRefreshClient.prototype.refreshTokenNoCache = function (refreshToken) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, _super.prototype.refreshTokenNoCache.call(this, this._refreshToken)];
});
});
};
/**
* Create a UserRefreshClient credentials instance using the given input
* options.
* @param json The input object.
*/
UserRefreshClient.prototype.fromJSON = function (json) {
if (!json) {
throw new Error('Must pass in a JSON object containing the user refresh token');
}
if (json.type !== 'authorized_user') {
throw new Error('The incoming JSON object does not have the "authorized_user" type');
}
if (!json.client_id) {
throw new Error('The incoming JSON object does not contain a client_id field');
}
if (!json.client_secret) {
throw new Error('The incoming JSON object does not contain a client_secret field');
}
if (!json.refresh_token) {
throw new Error('The incoming JSON object does not contain a refresh_token field');
}
this._clientId = json.client_id;
this._clientSecret = json.client_secret;
this._refreshToken = json.refresh_token;
this.credentials.refresh_token = json.refresh_token;
};
UserRefreshClient.prototype.fromStream = function (inputStream, callback) {
if (callback) {
this.fromStreamAsync(inputStream).then(function (r) { return callback(); }).catch(callback);
}
else {
return this.fromStreamAsync(inputStream);
}
};
UserRefreshClient.prototype.fromStreamAsync = function (inputStream) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) {
if (!inputStream) {
return reject(new Error('Must pass in a stream containing the user refresh token.'));
}
var s = '';
inputStream.setEncoding('utf8');
inputStream.on('data', function (chunk) {
s += chunk;
});
inputStream.on('end', function () {
try {
var data = JSON.parse(s);
_this.fromJSON(data);
return resolve();
}
catch (err) {
return reject(err);
}
});
})];
});
});
};
return UserRefreshClient;
}(oauth2client_1.OAuth2Client));
exports.UserRefreshClient = UserRefreshClient;
//# sourceMappingURL=refreshclient.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"refreshclient.js","sourceRoot":"","sources":["../../../src/auth/refreshclient.ts"],"names":[],"mappings":"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"}

View File

@@ -0,0 +1,26 @@
/**
* 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 } from './auth/computeclient';
export { GoogleAuthOptions } from './auth/googleauth';
export { IAMAuth } from './auth/iam';
export { JWTAccess } from './auth/jwtaccess';
export { JWT } from './auth/jwtclient';
export { CodeChallengeMethod, OAuth2Client } from './auth/oauth2client';
export { UserRefreshClient } from './auth/refreshclient';
export { DefaultTransporter } from './transporters';
declare const auth: GoogleAuth;
export { auth, GoogleAuth };

View File

@@ -0,0 +1,37 @@
"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.
*/
var googleauth_1 = require("./auth/googleauth");
exports.GoogleAuth = googleauth_1.GoogleAuth;
var computeclient_1 = require("./auth/computeclient");
exports.Compute = computeclient_1.Compute;
var iam_1 = require("./auth/iam");
exports.IAMAuth = iam_1.IAMAuth;
var jwtaccess_1 = require("./auth/jwtaccess");
exports.JWTAccess = jwtaccess_1.JWTAccess;
var jwtclient_1 = require("./auth/jwtclient");
exports.JWT = jwtclient_1.JWT;
var oauth2client_1 = require("./auth/oauth2client");
exports.CodeChallengeMethod = oauth2client_1.CodeChallengeMethod;
exports.OAuth2Client = oauth2client_1.OAuth2Client;
var refreshclient_1 = require("./auth/refreshclient");
exports.UserRefreshClient = refreshclient_1.UserRefreshClient;
var transporters_1 = require("./transporters");
exports.DefaultTransporter = transporters_1.DefaultTransporter;
var auth = new googleauth_1.GoogleAuth();
exports.auth = auth;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;AAAA;;;;;;;;;;;;;;GAcG;AACH,gDAA6C;AAY/B,qBAZN,uBAAU,CAYM;AAVxB,sDAA6C;AAArC,kCAAA,OAAO,CAAA;AAEf,kCAAmC;AAA3B,wBAAA,OAAO,CAAA;AACf,8CAA2C;AAAnC,gCAAA,SAAS,CAAA;AACjB,8CAAqC;AAA7B,0BAAA,GAAG,CAAA;AACX,oDAAsE;AAA9D,6CAAA,mBAAmB,CAAA;AAAE,sCAAA,YAAY,CAAA;AACzC,sDAAuD;AAA/C,4CAAA,iBAAiB,CAAA;AACzB,+CAAkD;AAA1C,4CAAA,kBAAkB,CAAA;AAE1B,IAAM,IAAI,GAAG,IAAI,uBAAU,EAAE,CAAC;AACtB,oBAAI"}

View File

@@ -0,0 +1,16 @@
/**
* 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

@@ -0,0 +1,37 @@
"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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
// 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
function validate(options) {
var vpairs = [
{ invalid: 'uri', expected: 'url' }, { invalid: 'json', expected: 'data' },
{ invalid: 'qs', expected: 'params' }
];
for (var _i = 0, vpairs_1 = vpairs; _i < vpairs_1.length; _i++) {
var pair = vpairs_1[_i];
if (options[pair.invalid]) {
var e = "'" + pair.invalid + "' is not a valid configuration option. Please use '" + pair.expected + "' instead. This library is using Axios for requests. Please see https://github.com/axios/axios to learn more about the valid request options.";
throw new Error(e);
}
}
}
exports.validate = validate;
//# sourceMappingURL=options.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"options.js","sourceRoot":"","sources":["../../src/options.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAEH,qEAAqE;AACrE,0EAA0E;AAC1E,yEAAyE;AACzE,6EAA6E;AAC7E,kCAAkC;AAClC,kBAAyB,OAAY;IACnC,IAAM,MAAM,GAAG;QACb,EAAC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAC,EAAE,EAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAC;QACtE,EAAC,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAC;KACpC,CAAC;IACF,KAAmB,UAAM,EAAN,iBAAM,EAAN,oBAAM,EAAN,IAAM,EAAE;QAAtB,IAAM,IAAI,eAAA;QACb,IAAI,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE;YACzB,IAAM,CAAC,GAAG,MACN,IAAI,CAAC,OAAO,2DACZ,IAAI,CAAC,QAAQ,kJAA+I,CAAC;YACjK,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC;SACpB;KACF;AACH,CAAC;AAbD,4BAaC"}

View File

@@ -0,0 +1,20 @@
/**
* 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.
*/
/// <reference types="node" />
import crypto from 'crypto';
export declare class PemVerifier {
verify(pubkey: string, data: string | Buffer, signature: string, encoding: crypto.HexBase64Latin1Encoding): boolean;
}

View File

@@ -0,0 +1,33 @@
"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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var crypto_1 = __importDefault(require("crypto"));
var PemVerifier = /** @class */ (function () {
function PemVerifier() {
}
PemVerifier.prototype.verify = function (pubkey, data, signature, encoding) {
var verifier = crypto_1.default.createVerify('sha256');
verifier.update(data);
return verifier.verify(pubkey, signature, encoding);
};
return PemVerifier;
}());
exports.PemVerifier = PemVerifier;
//# sourceMappingURL=pemverifier.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"pemverifier.js","sourceRoot":"","sources":["../../src/pemverifier.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;AAEH,kDAA4B;AAE5B;IAAA;IAQA,CAAC;IAPC,4BAAM,GAAN,UACI,MAAc,EAAE,IAAmB,EAAE,SAAiB,EACtD,QAAwC;QAC1C,IAAM,QAAQ,GAAG,gBAAM,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;QAC/C,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACtB,OAAO,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;IACtD,CAAC;IACH,kBAAC;AAAD,CAAC,AARD,IAQC;AARY,kCAAW"}

View File

@@ -0,0 +1,51 @@
/**
* 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.
*/
import { AxiosError, AxiosPromise, AxiosRequestConfig, AxiosResponse } from 'axios';
export interface Transporter {
request<T>(opts: AxiosRequestConfig): AxiosPromise<T>;
request<T>(opts: AxiosRequestConfig, callback?: BodyResponseCallback<T>): void;
request<T>(opts: AxiosRequestConfig, callback?: BodyResponseCallback<T>): AxiosPromise | void;
}
export interface BodyResponseCallback<T> {
(err: Error | null, res?: AxiosResponse<T> | null): void;
}
export interface RequestError extends AxiosError {
errors: Error[];
}
export declare class DefaultTransporter {
/**
* Default user agent.
*/
static readonly USER_AGENT: string;
/**
* Configures request options before making a request.
* @param opts AxiosRequestConfig options.
* @return Configured options.
*/
configure(opts?: AxiosRequestConfig): AxiosRequestConfig;
/**
* Makes a request using Axios with given options.
* @param opts AxiosRequestConfig options.
* @param callback optional callback that contains AxiosResponse object.
* @return AxiosPromise, assuming no callback is passed.
*/
request<T>(opts: AxiosRequestConfig): AxiosPromise<T>;
request<T>(opts: AxiosRequestConfig, callback?: BodyResponseCallback<T>): void;
/**
* Changes the error to include details from the body.
*/
private processError;
}

View File

@@ -0,0 +1,123 @@
"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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var axios_1 = __importDefault(require("axios"));
var options_1 = require("./options");
// tslint:disable-next-line no-var-requires
var pkg = require('../../package.json');
var PRODUCT_NAME = 'google-api-nodejs-client';
/**
* Axios will use XHR if it is available. In the case of Electron,
* since XHR is there it will try to use that. This leads to OPTIONS
* preflight requests which googleapis DOES NOT like. This line of
* code pins the adapter to ensure it uses node.
* https://github.com/google/google-api-nodejs-client/issues/1083
*/
axios_1.default.defaults.adapter = require('axios/lib/adapters/http');
var DefaultTransporter = /** @class */ (function () {
function DefaultTransporter() {
}
/**
* Configures request options before making a request.
* @param opts AxiosRequestConfig options.
* @return Configured options.
*/
DefaultTransporter.prototype.configure = function (opts) {
if (opts === void 0) { opts = {}; }
// set transporter user agent
opts.headers = opts.headers || {};
var uaValue = opts.headers['User-Agent'];
if (!uaValue) {
opts.headers['User-Agent'] = DefaultTransporter.USER_AGENT;
}
else if (!uaValue.includes(PRODUCT_NAME + "/")) {
opts.headers['User-Agent'] =
uaValue + " " + DefaultTransporter.USER_AGENT;
}
return opts;
};
DefaultTransporter.prototype.request = function (opts, callback) {
var _this = this;
// ensure the user isn't passing in request-style options
opts = this.configure(opts);
try {
options_1.validate(opts);
}
catch (e) {
if (callback) {
return callback(e);
}
else {
throw e;
}
}
if (callback) {
axios_1.default(opts)
.then(function (r) {
callback(null, r);
})
.catch(function (e) {
callback(_this.processError(e));
});
}
else {
return axios_1.default(opts).catch(function (e) {
throw _this.processError(e);
});
}
};
/**
* Changes the error to include details from the body.
*/
DefaultTransporter.prototype.processError = function (e) {
var res = e.response;
var err = e;
var body = res ? res.data : null;
if (res && body && body.error && res.status !== 200) {
if (typeof body.error === 'string') {
err.message = body.error;
err.code = res.status.toString();
}
else if (Array.isArray(body.error.errors)) {
err.message =
body.error.errors.map(function (err2) { return err2.message; }).join('\n');
err.code = body.error.code;
err.errors = body.error.errors;
}
else {
err.message = body.error.message;
err.code = body.error.code || res.status;
}
}
else if (res && res.status >= 400) {
// Consider all 4xx and 5xx responses errors.
err.message = body;
err.code = res.status.toString();
}
return err;
};
/**
* Default user agent.
*/
DefaultTransporter.USER_AGENT = PRODUCT_NAME + "/" + pkg.version;
return DefaultTransporter;
}());
exports.DefaultTransporter = DefaultTransporter;
//# sourceMappingURL=transporters.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"transporters.js","sourceRoot":"","sources":["../../src/transporters.ts"],"names":[],"mappings":"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"}