Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

google-auth-library

Package Overview
Dependencies
Maintainers
7
Versions
150
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

google-auth-library - npm Package Compare versions

Comparing version 1.3.2 to 1.4.0

7

build/src/auth/authclient.d.ts

@@ -0,1 +1,2 @@

/// <reference types="node" />
/**

@@ -17,5 +18,9 @@ * Copyright 2012 Google Inc. All Rights Reserved.

import { AxiosPromise, AxiosRequestConfig } from 'axios';
import { EventEmitter } from 'events';
import { DefaultTransporter } from '../transporters';
import { Credentials } from './credentials';
export declare abstract class AuthClient {
export interface AuthClient {
on(event: 'tokens', listener: (tokens: Credentials) => void): this;
}
export declare abstract class AuthClient extends EventEmitter {
transporter: DefaultTransporter;

@@ -22,0 +27,0 @@ credentials: Credentials;

@@ -17,8 +17,22 @@ "use strict";

*/
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 () {
var AuthClient = /** @class */ (function (_super) {
__extends(AuthClient, _super);
function AuthClient() {
this.transporter = new transporters_1.DefaultTransporter();
this.credentials = {};
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.transporter = new transporters_1.DefaultTransporter();
_this.credentials = {};
return _this;
}

@@ -32,4 +46,4 @@ /**

return AuthClient;
}());
}(events_1.EventEmitter));
exports.AuthClient = AuthClient;
//# sourceMappingURL=authclient.js.map

2

build/src/auth/computeclient.d.ts

@@ -42,4 +42,4 @@ /**

*/
protected refreshToken(refreshToken?: string | null): Promise<GetTokenResponse>;
protected refreshTokenNoCache(refreshToken?: string | null): Promise<GetTokenResponse>;
protected requestAsync<T>(opts: AxiosRequestConfig, retry?: boolean): AxiosPromise<T>;
}

@@ -100,3 +100,3 @@ "use strict";

*/
Compute.prototype.refreshToken = function (refreshToken) {
Compute.prototype.refreshTokenNoCache = function (refreshToken) {
return __awaiter(this, void 0, void 0, function () {

@@ -134,2 +134,3 @@ var url, res, e_1, tokens, _a;

}
this.emit('tokens', tokens);
return [2 /*return*/, { tokens: tokens, res: res }];

@@ -136,0 +137,0 @@ }

@@ -28,2 +28,3 @@ /**

expires_in?: number;
id_token?: string;
}

@@ -39,1 +40,5 @@ export interface JWTInput {

}
export interface CredentialBody {
client_email?: string;
private_key?: string;
}
/// <reference types="node" />
/**
* 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.
*/
import { AxiosRequestConfig, AxiosResponse } from 'axios';
import * as fs from 'fs';

@@ -7,3 +23,3 @@ import * as http from 'http';

import { Compute } from './computeclient';
import { JWTInput } from './credentials';
import { CredentialBody, JWTInput } from './credentials';
import { GCPEnv } from './envDetect';

@@ -26,6 +42,2 @@ import { JWT } from './jwtclient';

}
export interface CredentialBody {
client_email?: string;
private_key?: string;
}
export interface GoogleAuthOptions {

@@ -206,3 +218,3 @@ /**

*/
getClient(): Promise<Compute | JWT | UserRefreshClient>;
getClient(options?: GoogleAuthOptions): Promise<Compute | JWT | UserRefreshClient>;
/**

@@ -233,2 +245,8 @@ * Automatically obtain application default credentials, and return

/**
* Automatically obtain application default credentials, and make an
* HTTP request using the given options.
* @param opts Axios request options for the HTTP request.
*/
request(opts: AxiosRequestConfig): Promise<AxiosResponse>;
/**
* Determine the compute environment in which the code is running.

@@ -235,0 +253,0 @@ */

@@ -194,2 +194,5 @@ "use strict";

if (!credential) return [3 /*break*/, 5];
if (credential instanceof jwtclient_1.JWT) {
credential.scopes = this.scopes;
}
this.cachedCredential = credential;

@@ -206,2 +209,5 @@ return [4 /*yield*/, this.getDefaultProjectId()];

if (!credential) return [3 /*break*/, 8];
if (credential instanceof jwtclient_1.JWT) {
credential.scopes = this.scopes;
}
this.cachedCredential = credential;

@@ -625,3 +631,3 @@ return [4 /*yield*/, this.getDefaultProjectId()];

*/
GoogleAuth.prototype.getClient = function () {
GoogleAuth.prototype.getClient = function (options) {
return __awaiter(this, void 0, void 0, function () {

@@ -632,2 +638,8 @@ var filePath, stream_1, _a, _b;

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];

@@ -720,2 +732,20 @@ if (!this.keyFilename) return [3 /*break*/, 2];

/**
* Automatically obtain application default credentials, and make an
* HTTP request using the given options.
* @param opts Axios request options for the HTTP request.
*/
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.

@@ -722,0 +752,0 @@ */

@@ -19,3 +19,3 @@ /// <reference types="node" />

import * as stream from 'stream';
import { Credentials, JWTInput } from './credentials';
import { CredentialBody, Credentials, JWTInput } from './credentials';
import { GetTokenResponse, OAuth2Client, RefreshOptions, RequestMetadataResponse } from './oauth2client';

@@ -84,4 +84,8 @@ export interface JWTOptions extends RefreshOptions {

*/
refreshToken(refreshToken?: string | null): Promise<GetTokenResponse>;
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.

@@ -104,2 +108,7 @@ * @param json The input object.

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>;
}

@@ -115,3 +115,3 @@ "use strict";

tokens = (_a.sent()).tokens;
return [2 /*return*/, { headers: { Authorization: "Bearer " + tokens.access_token } }];
return [2 /*return*/, { headers: { Authorization: "Bearer " + tokens.id_token } }];
case 2:

@@ -181,19 +181,10 @@ // no scopes have been set, but a uri has been provided. Use JWTAccess

*/
JWT.prototype.refreshToken = function (refreshToken) {
JWT.prototype.refreshTokenNoCache = function (refreshToken) {
return __awaiter(this, void 0, void 0, function () {
var token, tokens;
var gtoken, token, tokens;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
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 [4 /*yield*/, this.gtoken.getToken()];
gtoken = this.createGToken();
return [4 /*yield*/, gtoken.getToken()];
case 1:

@@ -204,4 +195,7 @@ token = _a.sent();

token_type: 'Bearer',
expiry_date: this.gtoken.expiresAt
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 }];

@@ -213,2 +207,18 @@ }

/**
* 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.

@@ -273,2 +283,26 @@ * @param json The input object.

};
/**
* 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;

@@ -275,0 +309,0 @@ }(oauth2client_1.OAuth2Client));

@@ -31,2 +31,62 @@ /// <reference types="node" />

}
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 {

@@ -200,2 +260,3 @@ /**

private certificateExpiry;
protected refreshTokenPromises: Map<string, Promise<GetTokenResponse>>;
protected authBaseUrl?: string;

@@ -220,2 +281,3 @@ protected tokenUrl?: string;

constructor(clientId?: string, clientSecret?: string, redirectUri?: string, opts?: AuthClientOpts);
protected static readonly GOOGLE_TOKEN_INFO_URL: string;
/**

@@ -280,2 +342,3 @@ * The base URL for auth endpoints.

protected refreshToken(refreshToken?: string | null): Promise<GetTokenResponse>;
protected refreshTokenNoCache(refreshToken?: string | null): Promise<GetTokenResponse>;
/**

@@ -350,2 +413,10 @@ * Retrieves the access token using refresh token

/**
* 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.

@@ -352,0 +423,0 @@ * Returns certs as array structure, where keys are key ids, and values

@@ -81,2 +81,3 @@ "use strict";

_this.certificateExpiry = null;
_this.refreshTokenPromises = new Map();
var opts = (optionsOrClientId && typeof optionsOrClientId === 'object') ?

@@ -183,2 +184,3 @@ optionsOrClientId :

}
this.emit('tokens', tokens);
return [2 /*return*/, { tokens: tokens, res: res }];

@@ -196,2 +198,29 @@ }

return __awaiter(this, void 0, void 0, function () {
var _this = this;
var p;
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;

@@ -223,2 +252,3 @@ return __generator(this, function (_a) {

}
this.emit('tokens', tokens);
return [2 /*return*/, { tokens: tokens, res: res }];

@@ -489,2 +519,32 @@ }

};
/**
* 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) {

@@ -661,2 +721,3 @@ if (callback) {

};
OAuth2Client.GOOGLE_TOKEN_INFO_URL = 'https://www.googleapis.com/oauth2/v3/tokeninfo';
/**

@@ -663,0 +724,0 @@ * The base URL for auth endpoints.

@@ -42,3 +42,3 @@ /// <reference types="node" />

*/
protected refreshToken(refreshToken?: string | null): Promise<GetTokenResponse>;
protected refreshTokenNoCache(refreshToken?: string | null): Promise<GetTokenResponse>;
/**

@@ -45,0 +45,0 @@ * Create a UserRefreshClient credentials instance using the given input

@@ -89,6 +89,6 @@ "use strict";

*/
UserRefreshClient.prototype.refreshToken = function (refreshToken) {
UserRefreshClient.prototype.refreshTokenNoCache = function (refreshToken) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, _super.prototype.refreshToken.call(this, this._refreshToken)];
return [2 /*return*/, _super.prototype.refreshTokenNoCache.call(this, this._refreshToken)];
});

@@ -95,0 +95,0 @@ });

@@ -18,2 +18,3 @@ /**

export { Compute } from './auth/computeclient';
export { GoogleAuthOptions } from './auth/googleauth';
export { IAMAuth } from './auth/iam';

@@ -20,0 +21,0 @@ export { JWTAccess } from './auth/jwtaccess';

@@ -22,2 +22,11 @@ "use strict";

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 () {

@@ -35,9 +44,9 @@ function DefaultTransporter() {

opts.headers = opts.headers || {};
if (!opts.headers['User-Agent']) {
var uaValue = opts.headers['User-Agent'];
if (!uaValue) {
opts.headers['User-Agent'] = DefaultTransporter.USER_AGENT;
}
else if (opts.headers['User-Agent'].indexOf(DefaultTransporter.USER_AGENT) ===
-1) {
else if (!uaValue.includes(PRODUCT_NAME + "/")) {
opts.headers['User-Agent'] =
opts.headers['User-Agent'] + ' ' + DefaultTransporter.USER_AGENT;
uaValue + " " + DefaultTransporter.USER_AGENT;
}

@@ -109,3 +118,3 @@ return opts;

*/
DefaultTransporter.USER_AGENT = 'google-api-nodejs-client/' + pkg.version;
DefaultTransporter.USER_AGENT = PRODUCT_NAME + "/" + pkg.version;
return DefaultTransporter;

@@ -112,0 +121,0 @@ }());

{
"name": "google-auth-library",
"version": "1.3.2",
"version": "1.4.0",
"author": "Google Inc.",

@@ -24,3 +24,3 @@ "description": "Google APIs Authentication Client Library for Node.js",

"axios": "^0.18.0",
"gtoken": "^2.1.1",
"gtoken": "^2.2.0",
"jws": "^3.1.4",

@@ -37,3 +37,3 @@ "lodash.isstring": "^4.0.1",

"@types/lru-cache": "^4.1.0",
"@types/mocha": "^2.2.48",
"@types/mocha": "^5.0.0",
"@types/ncp": "^2.0.1",

@@ -58,3 +58,3 @@ "@types/nock": "^9.1.2",

"prettier": "^1.11.1",
"sinon": "^4.4.2",
"sinon": "^4.5.0",
"source-map-support": "^0.5.3",

@@ -61,0 +61,0 @@ "tmp": "^0.0.33",

@@ -53,5 +53,5 @@ <img src="https://avatars0.githubusercontent.com/u/1342004?v=3&s=96" alt="Google Inc. logo" title="Google" align="right" height="96" width="96"/>

For example, a JWT auth client will be created when your code is running on your local developer machine, and a Compute client will be created when the same code is running on Google Cloud Platform.
For example, a JWT auth client will be created when your code is running on your local developer machine, and a Compute client will be created when the same code is running on Google Cloud Platform. If you need a specific set of scopes, you can pass those in the form of a string or an array into the `auth.getClient` method.
The code below shows how to retrieve a default credential type, depending upon the runtime environment. The createScopedRequired must be called to determine when you need to pass in the scopes manually, and when they have been set for you automatically based on the configured runtime environment.
The code below shows how to retrieve a default credential type, depending upon the runtime environment.

@@ -65,5 +65,8 @@ ```js

async function main() {
const adc = await getADC();
const url = `https://www.googleapis.com/dns/v1/projects/${adc.projectId}`;
const res = await adc.client.request({url});
const client = await auth.getClient({
scopes: 'https://www.googleapis.com/auth/cloud-platform'
});
const projectId = await auth.getDefaultProjectId();
const url = `https://www.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({ url });
console.log(res.data);

@@ -186,7 +189,21 @@ }

##### IMPORTANT NOTE
`refresh_token` is only returned on the first authorization.
More details [here](https://github.com/google/google-api-nodejs-client/issues/750#issuecomment-304521450)
##### Handling token events
This library will automatically obtain an `access_token`, and automatically refresh the `access_token` if a `refresh_token` is present. The `refresh_token` is only returned on the [first authorization]((https://github.com/google/google-api-nodejs-client/issues/750#issuecomment-304521450), so if you want to make sure you store it safely. An easy way to make sure you always store the most recent tokens is to use the `tokens` event:
```js
const client = await auth.getClient();
client.on('tokens', (tokens) => {
if (tokens.refresh_token) {
// store the refresh_token in my database!
console.log(tokens.refresh_token);
}
console.log(tokens.access_token);
});
const url = `https://www.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({ url });
// The `tokens` event would now be raised if this was the first request
```
##### Retrieve access token

@@ -227,2 +244,16 @@ With the code returned, you can ask for an access token as shown below:

##### Checking `access_token` information
After obtaining and storing an `access_token`, at a later time you may want to go check the expiration date,
original scopes, or audience for the token. To get the token info, you can use the `getTokenInfo` method:
```js
// after acquiring an oAuth2Client...
const tokenInfo = await oAuth2client.getTokenInfo('my-access-token');
// take a look at the scopes originally provisioned for the access token
console.log(tokenInfo.scopes);
```
This method will throw if the token is invalid.
##### OAuth2 with Installed Apps (Electron)

@@ -229,0 +260,0 @@ If you're authenticating with OAuth2 from an installed application (like Electron), you may not want to embed your `client_secret` inside of the application sources. To work around this restriction, you can choose the `iOS` application type when creating your OAuth2 credentials in the [Google Developers console][devconsole]:

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc