Initial commit

This commit is contained in:
talksik
2021-12-29 01:57:42 -08:00
commit ce39a60b42
4634 changed files with 997667 additions and 0 deletions
@@ -0,0 +1,32 @@
/*! firebase-admin v10.0.1 */
/*!
* @license
* Copyright 2021 Google Inc.
*
* 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 { PrefixedFirebaseError } from '../utils/error';
export declare const APP_CHECK_ERROR_CODE_MAPPING: {
[key: string]: AppCheckErrorCode;
};
export declare type AppCheckErrorCode = 'aborted' | 'invalid-argument' | 'invalid-credential' | 'internal-error' | 'permission-denied' | 'unauthenticated' | 'not-found' | 'app-check-token-expired' | 'unknown-error';
/**
* Firebase App Check error code structure. This extends PrefixedFirebaseError.
*
* @param code - The error code.
* @param message - The error message.
* @constructor
*/
export declare class FirebaseAppCheckError extends PrefixedFirebaseError {
constructor(code: AppCheckErrorCode, message: string);
}
@@ -0,0 +1,197 @@
/*! firebase-admin v10.0.1 */
"use strict";
/*!
* @license
* Copyright 2021 Google Inc.
*
* 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 = function (d, b) {
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 extendStatics(d, b);
};
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 });
exports.FirebaseAppCheckError = exports.APP_CHECK_ERROR_CODE_MAPPING = exports.AppCheckApiClient = void 0;
var api_request_1 = require("../utils/api-request");
var error_1 = require("../utils/error");
var utils = require("../utils/index");
var validator = require("../utils/validator");
// App Check backend constants
var FIREBASE_APP_CHECK_V1_API_URL_FORMAT = 'https://firebaseappcheck.googleapis.com/v1beta/projects/{projectId}/apps/{appId}:exchangeCustomToken';
var FIREBASE_APP_CHECK_CONFIG_HEADERS = {
'X-Firebase-Client': "fire-admin-node/" + utils.getSdkVersion()
};
/**
* Class that facilitates sending requests to the Firebase App Check backend API.
*
* @internal
*/
var AppCheckApiClient = /** @class */ (function () {
function AppCheckApiClient(app) {
this.app = app;
if (!validator.isNonNullObject(app) || !('options' in app)) {
throw new FirebaseAppCheckError('invalid-argument', 'First argument passed to admin.appCheck() must be a valid Firebase app instance.');
}
this.httpClient = new api_request_1.AuthorizedHttpClient(app);
}
/**
* Exchange a signed custom token to App Check token
*
* @param customToken - The custom token to be exchanged.
* @param appId - The mobile App ID.
* @returns A promise that fulfills with a `AppCheckToken`.
*/
AppCheckApiClient.prototype.exchangeToken = function (customToken, appId) {
var _this = this;
if (!validator.isNonEmptyString(appId)) {
throw new FirebaseAppCheckError('invalid-argument', '`appId` must be a non-empty string.');
}
if (!validator.isNonEmptyString(customToken)) {
throw new FirebaseAppCheckError('invalid-argument', '`customToken` must be a non-empty string.');
}
return this.getUrl(appId)
.then(function (url) {
var request = {
method: 'POST',
url: url,
headers: FIREBASE_APP_CHECK_CONFIG_HEADERS,
data: { customToken: customToken }
};
return _this.httpClient.send(request);
})
.then(function (resp) {
return _this.toAppCheckToken(resp);
})
.catch(function (err) {
throw _this.toFirebaseError(err);
});
};
AppCheckApiClient.prototype.getUrl = function (appId) {
return this.getProjectId()
.then(function (projectId) {
var urlParams = {
projectId: projectId,
appId: appId,
};
var baseUrl = utils.formatString(FIREBASE_APP_CHECK_V1_API_URL_FORMAT, urlParams);
return utils.formatString(baseUrl);
});
};
AppCheckApiClient.prototype.getProjectId = function () {
var _this = this;
if (this.projectId) {
return Promise.resolve(this.projectId);
}
return utils.findProjectId(this.app)
.then(function (projectId) {
if (!validator.isNonEmptyString(projectId)) {
throw new FirebaseAppCheckError('unknown-error', 'Failed to determine project ID. Initialize the '
+ 'SDK with service account credentials or set project ID as an app option. '
+ 'Alternatively, set the GOOGLE_CLOUD_PROJECT environment variable.');
}
_this.projectId = projectId;
return projectId;
});
};
AppCheckApiClient.prototype.toFirebaseError = function (err) {
if (err instanceof error_1.PrefixedFirebaseError) {
return err;
}
var response = err.response;
if (!response.isJson()) {
return new FirebaseAppCheckError('unknown-error', "Unexpected response with status: " + response.status + " and body: " + response.text);
}
var error = response.data.error || {};
var code = 'unknown-error';
if (error.status && error.status in exports.APP_CHECK_ERROR_CODE_MAPPING) {
code = exports.APP_CHECK_ERROR_CODE_MAPPING[error.status];
}
var message = error.message || "Unknown server error: " + response.text;
return new FirebaseAppCheckError(code, message);
};
/**
* Creates an AppCheckToken from the API response.
*
* @param resp - API response object.
* @returns An AppCheckToken instance.
*/
AppCheckApiClient.prototype.toAppCheckToken = function (resp) {
var token = resp.data.attestationToken;
// `ttl` is a string with the suffix "s" preceded by the number of seconds,
// with nanoseconds expressed as fractional seconds.
var ttlMillis = this.stringToMilliseconds(resp.data.ttl);
return {
token: token,
ttlMillis: ttlMillis
};
};
/**
* Converts a duration string with the suffix `s` to milliseconds.
*
* @param duration - The duration as a string with the suffix "s" preceded by the
* number of seconds, with fractional seconds. For example, 3 seconds with 0 nanoseconds
* is expressed as "3s", while 3 seconds and 1 nanosecond is expressed as "3.000000001s",
* and 3 seconds and 1 microsecond is expressed as "3.000001s".
*
* @returns The duration in milliseconds.
*/
AppCheckApiClient.prototype.stringToMilliseconds = function (duration) {
if (!validator.isNonEmptyString(duration) || !duration.endsWith('s')) {
throw new FirebaseAppCheckError('invalid-argument', '`ttl` must be a valid duration string with the suffix `s`.');
}
var seconds = duration.slice(0, -1);
return Math.floor(Number(seconds) * 1000);
};
return AppCheckApiClient;
}());
exports.AppCheckApiClient = AppCheckApiClient;
exports.APP_CHECK_ERROR_CODE_MAPPING = {
ABORTED: 'aborted',
INVALID_ARGUMENT: 'invalid-argument',
INVALID_CREDENTIAL: 'invalid-credential',
INTERNAL: 'internal-error',
PERMISSION_DENIED: 'permission-denied',
UNAUTHENTICATED: 'unauthenticated',
NOT_FOUND: 'not-found',
UNKNOWN: 'unknown-error',
};
/**
* Firebase App Check error code structure. This extends PrefixedFirebaseError.
*
* @param code - The error code.
* @param message - The error message.
* @constructor
*/
var FirebaseAppCheckError = /** @class */ (function (_super) {
__extends(FirebaseAppCheckError, _super);
function FirebaseAppCheckError(code, message) {
var _this = _super.call(this, 'app-check', code, message) || this;
/* tslint:disable:max-line-length */
// Set the prototype explicitly. See the following link for more details:
// https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
/* tslint:enable:max-line-length */
_this.__proto__ = FirebaseAppCheckError.prototype;
return _this;
}
return FirebaseAppCheckError;
}(error_1.PrefixedFirebaseError));
exports.FirebaseAppCheckError = FirebaseAppCheckError;
+95
View File
@@ -0,0 +1,95 @@
/*! firebase-admin v10.0.1 */
/*!
* @license
* Copyright 2021 Google Inc.
*
* 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.
*/
/**
* Interface representing an App Check token.
*/
export interface AppCheckToken {
/**
* The Firebase App Check token.
*/
token: string;
/**
* The time-to-live duration of the token in milliseconds.
*/
ttlMillis: number;
}
/**
* Interface representing App Check token options.
*/
export interface AppCheckTokenOptions {
/**
* The length of time, in milliseconds, for which the App Check token will
* be valid. This value must be between 30 minutes and 7 days, inclusive.
*/
ttlMillis?: number;
}
/**
* Interface representing a decoded Firebase App Check token, returned from the
* {@link AppCheck.verifyToken} method.
*/
export interface DecodedAppCheckToken {
/**
* The issuer identifier for the issuer of the response.
* This value is a URL with the format
* `https://firebaseappcheck.googleapis.com/<PROJECT_NUMBER>`, where `<PROJECT_NUMBER>` is the
* same project number specified in the {@link DecodedAppCheckToken.aud | aud} property.
*/
iss: string;
/**
* The Firebase App ID corresponding to the app the token belonged to.
* As a convenience, this value is copied over to the {@link DecodedAppCheckToken.app_id | app_id} property.
*/
sub: string;
/**
* The audience for which this token is intended.
* This value is a JSON array of two strings, the first is the project number of your
* Firebase project, and the second is the project ID of the same project.
*/
aud: string[];
/**
* The App Check token's expiration time, in seconds since the Unix epoch. That is, the
* time at which this App Check token expires and should no longer be considered valid.
*/
exp: number;
/**
* The App Check token's issued-at time, in seconds since the Unix epoch. That is, the
* time at which this App Check token was issued and should start to be considered
* valid.
*/
iat: number;
/**
* The App ID corresponding to the App the App Check token belonged to.
* This value is not actually one of the JWT token claims. It is added as a
* convenience, and is set as the value of the {@link DecodedAppCheckToken.sub | sub} property.
*/
app_id: string;
[key: string]: any;
}
/**
* Interface representing a verified App Check token response.
*/
export interface VerifyAppCheckTokenResponse {
/**
* The App ID corresponding to the App the App Check token belonged to.
*/
appId: string;
/**
* The decoded Firebase App Check token.
*/
token: DecodedAppCheckToken;
}
+19
View File
@@ -0,0 +1,19 @@
/*! firebase-admin v10.0.1 */
"use strict";
/*!
* @license
* Copyright 2021 Google Inc.
*
* 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 });
+65
View File
@@ -0,0 +1,65 @@
/*! firebase-admin v10.0.1 */
/*!
* Copyright 2021 Google Inc.
*
* 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 { App } from '../app';
import { AppCheckToken as TAppCheckToken, AppCheckTokenOptions as TAppCheckTokenOptions, DecodedAppCheckToken as TDecodedAppCheckToken, VerifyAppCheckTokenResponse as TVerifyAppCheckTokenResponse } from './app-check-api';
import { AppCheck as TAppCheck } from './app-check';
/**
* Gets the {@link firebase-admin.app-check#AppCheck} service for the default app or a given app.
*
* `admin.appCheck()` can be called with no arguments to access the default
* app's `AppCheck` service or as `admin.appCheck(app)` to access the
* `AppCheck` service associated with a specific app.
*
* @example
* ```javascript
* // Get the `AppCheck` service for the default app
* var defaultAppCheck = admin.appCheck();
* ```
*
* @example
* ```javascript
* // Get the `AppCheck` service for a given app
* var otherAppCheck = admin.appCheck(otherApp);
* ```
*
* @param app - Optional app for which to return the `AppCheck` service.
* If not provided, the default `AppCheck` service is returned.
*
* @returns The default `AppCheck` service if no
* app is provided, or the `AppCheck` service associated with the provided
* app.
*/
export declare function appCheck(app?: App): appCheck.AppCheck;
export declare namespace appCheck {
/**
* Type alias to {@link firebase-admin.app-check#AppCheck}.
*/
type AppCheck = TAppCheck;
/**
* Type alias to {@link firebase-admin.app-check#AppCheckToken}.
*/
type AppCheckToken = TAppCheckToken;
/**
* Type alias to {@link firebase-admin.app-check#DecodedAppCheckToken}.
*/
type DecodedAppCheckToken = TDecodedAppCheckToken;
/**
* Type alias to {@link firebase-admin.app-check#VerifyAppCheckTokenResponse}.
*/
type VerifyAppCheckTokenResponse = TVerifyAppCheckTokenResponse;
type AppCheckTokenOptions = TAppCheckTokenOptions;
}
+18
View File
@@ -0,0 +1,18 @@
/*! firebase-admin v10.0.1 */
"use strict";
/*!
* Copyright 2021 Google Inc.
*
* 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 });
+49
View File
@@ -0,0 +1,49 @@
/*! firebase-admin v10.0.1 */
/*!
* @license
* Copyright 2021 Google Inc.
*
* 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 { App } from '../app';
import { AppCheckToken, AppCheckTokenOptions, VerifyAppCheckTokenResponse } from './app-check-api';
/**
* The Firebase `AppCheck` service interface.
*/
export declare class AppCheck {
readonly app: App;
private readonly client;
private readonly tokenGenerator;
private readonly appCheckTokenVerifier;
/**
* Creates a new {@link AppCheckToken} that can be sent
* back to a client.
*
* @param appId - The app ID to use as the JWT app_id.
* @param options - Optional options object when creating a new App Check Token.
*
* @returns A promise that fulfills with a `AppCheckToken`.
*/
createToken(appId: string, options?: AppCheckTokenOptions): Promise<AppCheckToken>;
/**
* Verifies a Firebase App Check token (JWT). If the token is valid, the promise is
* fulfilled with the token's decoded claims; otherwise, the promise is
* rejected.
*
* @param appCheckToken - The App Check token to verify.
*
* @returns A promise fulfilled with the token's decoded claims
* if the App Check token is valid; otherwise, a rejected promise.
*/
verifyToken(appCheckToken: string): Promise<VerifyAppCheckTokenResponse>;
}
+82
View File
@@ -0,0 +1,82 @@
/*! firebase-admin v10.0.1 */
"use strict";
/*!
* @license
* Copyright 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AppCheck = void 0;
var app_check_api_client_internal_1 = require("./app-check-api-client-internal");
var token_generator_1 = require("./token-generator");
var token_verifier_1 = require("./token-verifier");
var crypto_signer_1 = require("../utils/crypto-signer");
/**
* The Firebase `AppCheck` service interface.
*/
var AppCheck = /** @class */ (function () {
/**
* @param app - The app for this AppCheck service.
* @constructor
* @internal
*/
function AppCheck(app) {
this.app = app;
this.client = new app_check_api_client_internal_1.AppCheckApiClient(app);
try {
this.tokenGenerator = new token_generator_1.AppCheckTokenGenerator(crypto_signer_1.cryptoSignerFromApp(app));
}
catch (err) {
throw token_generator_1.appCheckErrorFromCryptoSignerError(err);
}
this.appCheckTokenVerifier = new token_verifier_1.AppCheckTokenVerifier(app);
}
/**
* Creates a new {@link AppCheckToken} that can be sent
* back to a client.
*
* @param appId - The app ID to use as the JWT app_id.
* @param options - Optional options object when creating a new App Check Token.
*
* @returns A promise that fulfills with a `AppCheckToken`.
*/
AppCheck.prototype.createToken = function (appId, options) {
var _this = this;
return this.tokenGenerator.createCustomToken(appId, options)
.then(function (customToken) {
return _this.client.exchangeToken(customToken, appId);
});
};
/**
* Verifies a Firebase App Check token (JWT). If the token is valid, the promise is
* fulfilled with the token's decoded claims; otherwise, the promise is
* rejected.
*
* @param appCheckToken - The App Check token to verify.
*
* @returns A promise fulfilled with the token's decoded claims
* if the App Check token is valid; otherwise, a rejected promise.
*/
AppCheck.prototype.verifyToken = function (appCheckToken) {
return this.appCheckTokenVerifier.verifyToken(appCheckToken)
.then(function (decodedToken) {
return {
appId: decodedToken.app_id,
token: decodedToken,
};
});
};
return AppCheck;
}());
exports.AppCheck = AppCheck;
+53
View File
@@ -0,0 +1,53 @@
/*! firebase-admin v10.0.1 */
/*!
* @license
* Copyright 2021 Google Inc.
*
* 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.
*/
/**
* Firebase App Check.
*
* @packageDocumentation
*/
import { App } from '../app';
import { AppCheck } from './app-check';
export { AppCheckToken, AppCheckTokenOptions, DecodedAppCheckToken, VerifyAppCheckTokenResponse, } from './app-check-api';
export { AppCheck } from './app-check';
/**
* Gets the {@link AppCheck} service for the default app or a given app.
*
* `getAppCheck()` can be called with no arguments to access the default
* app's `AppCheck` service or as `getAppCheck(app)` to access the
* `AppCheck` service associated with a specific app.
*
* @example
* ```javascript
* // Get the `AppCheck` service for the default app
* const defaultAppCheck = getAppCheck();
* ```
*
* @example
* ```javascript
* // Get the `AppCheck` service for a given app
* const otherAppCheck = getAppCheck(otherApp);
* ```
*
* @param app - Optional app for which to return the `AppCheck` service.
* If not provided, the default `AppCheck` service is returned.
*
* @returns The default `AppCheck` service if no
* app is provided, or the `AppCheck` service associated with the provided
* app.
*/
export declare function getAppCheck(app?: App): AppCheck;
+63
View File
@@ -0,0 +1,63 @@
/*! firebase-admin v10.0.1 */
"use strict";
/*!
* @license
* Copyright 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAppCheck = void 0;
/**
* Firebase App Check.
*
* @packageDocumentation
*/
var app_1 = require("../app");
var app_check_1 = require("./app-check");
var app_check_2 = require("./app-check");
Object.defineProperty(exports, "AppCheck", { enumerable: true, get: function () { return app_check_2.AppCheck; } });
/**
* Gets the {@link AppCheck} service for the default app or a given app.
*
* `getAppCheck()` can be called with no arguments to access the default
* app's `AppCheck` service or as `getAppCheck(app)` to access the
* `AppCheck` service associated with a specific app.
*
* @example
* ```javascript
* // Get the `AppCheck` service for the default app
* const defaultAppCheck = getAppCheck();
* ```
*
* @example
* ```javascript
* // Get the `AppCheck` service for a given app
* const otherAppCheck = getAppCheck(otherApp);
* ```
*
* @param app - Optional app for which to return the `AppCheck` service.
* If not provided, the default `AppCheck` service is returned.
*
* @returns The default `AppCheck` service if no
* app is provided, or the `AppCheck` service associated with the provided
* app.
*/
function getAppCheck(app) {
if (typeof app === 'undefined') {
app = app_1.getApp();
}
var firebaseApp = app;
return firebaseApp.getOrInitService('appCheck', function (app) { return new app_check_1.AppCheck(app); });
}
exports.getAppCheck = getAppCheck;
+25
View File
@@ -0,0 +1,25 @@
/*! firebase-admin v10.0.1 */
/*!
* @license
* Copyright 2021 Google Inc.
*
* 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.
*/
/**
* Creates a new `FirebaseAppCheckError` by extracting the error code, message and other relevant
* details from a `CryptoSignerError`.
*
* @param err - The Error to convert into a `FirebaseAppCheckError` error
* @returns A Firebase App Check error that can be returned to the user.
*/
export declare function appCheckErrorFromCryptoSignerError(err: Error): Error;
+161
View File
@@ -0,0 +1,161 @@
/*! firebase-admin v10.0.1 */
"use strict";
/*!
* @license
* Copyright 2021 Google Inc.
*
* 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 __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.appCheckErrorFromCryptoSignerError = exports.AppCheckTokenGenerator = void 0;
var validator = require("../utils/validator");
var utils_1 = require("../utils");
var crypto_signer_1 = require("../utils/crypto-signer");
var app_check_api_client_internal_1 = require("./app-check-api-client-internal");
var ONE_MINUTE_IN_SECONDS = 60;
var ONE_MINUTE_IN_MILLIS = ONE_MINUTE_IN_SECONDS * 1000;
var ONE_DAY_IN_MILLIS = 24 * 60 * 60 * 1000;
// Audience to use for Firebase App Check Custom tokens
var FIREBASE_APP_CHECK_AUDIENCE = 'https://firebaseappcheck.googleapis.com/google.firebase.appcheck.v1beta.TokenExchangeService';
/**
* Class for generating Firebase App Check tokens.
*
* @internal
*/
var AppCheckTokenGenerator = /** @class */ (function () {
/**
* The AppCheckTokenGenerator class constructor.
*
* @param signer - The CryptoSigner instance for this token generator.
* @constructor
*/
function AppCheckTokenGenerator(signer) {
if (!validator.isNonNullObject(signer)) {
throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', 'INTERNAL ASSERT: Must provide a CryptoSigner to use AppCheckTokenGenerator.');
}
this.signer = signer;
}
/**
* Creates a new custom token that can be exchanged to an App Check token.
*
* @param appId - The Application ID to use for the generated token.
*
* @returns A Promise fulfilled with a custom token signed with a service account key
* that can be exchanged to an App Check token.
*/
AppCheckTokenGenerator.prototype.createCustomToken = function (appId, options) {
var _this = this;
if (!validator.isNonEmptyString(appId)) {
throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', '`appId` must be a non-empty string.');
}
var customOptions = {};
if (typeof options !== 'undefined') {
customOptions = this.validateTokenOptions(options);
}
return this.signer.getAccountId().then(function (account) {
var header = {
alg: _this.signer.algorithm,
typ: 'JWT',
};
var iat = Math.floor(Date.now() / 1000);
var body = __assign({ iss: account, sub: account,
// eslint-disable-next-line @typescript-eslint/camelcase
app_id: appId, aud: FIREBASE_APP_CHECK_AUDIENCE, exp: iat + (ONE_MINUTE_IN_SECONDS * 5), iat: iat }, customOptions);
var token = _this.encodeSegment(header) + "." + _this.encodeSegment(body);
return _this.signer.sign(Buffer.from(token))
.then(function (signature) {
return token + "." + _this.encodeSegment(signature);
});
}).catch(function (err) {
throw appCheckErrorFromCryptoSignerError(err);
});
};
AppCheckTokenGenerator.prototype.encodeSegment = function (segment) {
var buffer = (segment instanceof Buffer) ? segment : Buffer.from(JSON.stringify(segment));
return utils_1.toWebSafeBase64(buffer).replace(/=+$/, '');
};
/**
* Checks if a given `AppCheckTokenOptions` object is valid. If successful, returns an object with
* custom properties.
*
* @param options - An options object to be validated.
* @returns A custom object with ttl converted to protobuf Duration string format.
*/
AppCheckTokenGenerator.prototype.validateTokenOptions = function (options) {
if (!validator.isNonNullObject(options)) {
throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', 'AppCheckTokenOptions must be a non-null object.');
}
if (typeof options.ttlMillis !== 'undefined') {
if (!validator.isNumber(options.ttlMillis)) {
throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', 'ttlMillis must be a duration in milliseconds.');
}
// ttlMillis must be between 30 minutes and 7 days (inclusive)
if (options.ttlMillis < (ONE_MINUTE_IN_MILLIS * 30) || options.ttlMillis > (ONE_DAY_IN_MILLIS * 7)) {
throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', 'ttlMillis must be a duration in milliseconds between 30 minutes and 7 days (inclusive).');
}
return { ttl: utils_1.transformMillisecondsToSecondsString(options.ttlMillis) };
}
return {};
};
return AppCheckTokenGenerator;
}());
exports.AppCheckTokenGenerator = AppCheckTokenGenerator;
/**
* Creates a new `FirebaseAppCheckError` by extracting the error code, message and other relevant
* details from a `CryptoSignerError`.
*
* @param err - The Error to convert into a `FirebaseAppCheckError` error
* @returns A Firebase App Check error that can be returned to the user.
*/
function appCheckErrorFromCryptoSignerError(err) {
if (!(err instanceof crypto_signer_1.CryptoSignerError)) {
return err;
}
if (err.code === crypto_signer_1.CryptoSignerErrorCode.SERVER_ERROR && validator.isNonNullObject(err.cause)) {
var httpError = err.cause;
var errorResponse = httpError.response.data;
if (errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse.error) {
var status = errorResponse.error.status;
var description = errorResponse.error.message || JSON.stringify(httpError.response);
var code = 'unknown-error';
if (status && status in app_check_api_client_internal_1.APP_CHECK_ERROR_CODE_MAPPING) {
code = app_check_api_client_internal_1.APP_CHECK_ERROR_CODE_MAPPING[status];
}
return new app_check_api_client_internal_1.FirebaseAppCheckError(code, "Error returned from server while signing a custom token: " + description);
}
return new app_check_api_client_internal_1.FirebaseAppCheckError('internal-error', 'Error returned from server: ' + JSON.stringify(errorResponse) + '.');
}
return new app_check_api_client_internal_1.FirebaseAppCheckError(mapToAppCheckErrorCode(err.code), err.message);
}
exports.appCheckErrorFromCryptoSignerError = appCheckErrorFromCryptoSignerError;
function mapToAppCheckErrorCode(code) {
switch (code) {
case crypto_signer_1.CryptoSignerErrorCode.INVALID_CREDENTIAL:
return 'invalid-credential';
case crypto_signer_1.CryptoSignerErrorCode.INVALID_ARGUMENT:
return 'invalid-argument';
default:
return 'internal-error';
}
}
+17
View File
@@ -0,0 +1,17 @@
/*! firebase-admin v10.0.1 */
/*!
* Copyright 2021 Google Inc.
*
* 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 {};
+152
View File
@@ -0,0 +1,152 @@
/*! firebase-admin v10.0.1 */
"use strict";
/*!
* Copyright 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AppCheckTokenVerifier = void 0;
var validator = require("../utils/validator");
var util = require("../utils/index");
var app_check_api_client_internal_1 = require("./app-check-api-client-internal");
var jwt_1 = require("../utils/jwt");
var APP_CHECK_ISSUER = 'https://firebaseappcheck.googleapis.com/';
var JWKS_URL = 'https://firebaseappcheck.googleapis.com/v1beta/jwks';
/**
* Class for verifying Firebase App Check tokens.
*
* @internal
*/
var AppCheckTokenVerifier = /** @class */ (function () {
function AppCheckTokenVerifier(app) {
this.app = app;
this.signatureVerifier = jwt_1.PublicKeySignatureVerifier.withJwksUrl(JWKS_URL);
}
/**
* Verifies the format and signature of a Firebase App Check token.
*
* @param token - The Firebase Auth JWT token to verify.
* @returns A promise fulfilled with the decoded claims of the Firebase App Check token.
*/
AppCheckTokenVerifier.prototype.verifyToken = function (token) {
var _this = this;
if (!validator.isString(token)) {
throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', 'App check token must be a non-null string.');
}
return this.ensureProjectId()
.then(function (projectId) {
return _this.decodeAndVerify(token, projectId);
})
.then(function (decoded) {
var decodedAppCheckToken = decoded.payload;
// eslint-disable-next-line @typescript-eslint/camelcase
decodedAppCheckToken.app_id = decodedAppCheckToken.sub;
return decodedAppCheckToken;
});
};
AppCheckTokenVerifier.prototype.ensureProjectId = function () {
return util.findProjectId(this.app)
.then(function (projectId) {
if (!validator.isNonEmptyString(projectId)) {
throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-credential', 'Must initialize app with a cert credential or set your Firebase project ID as the ' +
'GOOGLE_CLOUD_PROJECT environment variable to verify an App Check token.');
}
return projectId;
});
};
AppCheckTokenVerifier.prototype.decodeAndVerify = function (token, projectId) {
var _this = this;
return this.safeDecode(token)
.then(function (decodedToken) {
_this.verifyContent(decodedToken, projectId);
return _this.verifySignature(token)
.then(function () { return decodedToken; });
});
};
AppCheckTokenVerifier.prototype.safeDecode = function (jwtToken) {
return jwt_1.decodeJwt(jwtToken)
.catch(function () {
var errorMessage = 'Decoding App Check token failed. Make sure you passed ' +
'the entire string JWT which represents the Firebase App Check token.';
throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', errorMessage);
});
};
/**
* Verifies the content of a Firebase App Check JWT.
*
* @param fullDecodedToken - The decoded JWT.
* @param projectId - The Firebase Project Id.
*/
AppCheckTokenVerifier.prototype.verifyContent = function (fullDecodedToken, projectId) {
var header = fullDecodedToken.header;
var payload = fullDecodedToken.payload;
var projectIdMatchMessage = ' Make sure the App Check token comes from the same ' +
'Firebase project as the service account used to authenticate this SDK.';
var scopedProjectId = "projects/" + projectId;
var errorMessage;
if (header.alg !== jwt_1.ALGORITHM_RS256) {
errorMessage = 'The provided App Check token has incorrect algorithm. Expected "' +
jwt_1.ALGORITHM_RS256 + '" but got ' + '"' + header.alg + '".';
}
else if (!validator.isNonEmptyArray(payload.aud) || !payload.aud.includes(scopedProjectId)) {
errorMessage = 'The provided App Check token has incorrect "aud" (audience) claim. Expected "' +
scopedProjectId + '" but got "' + payload.aud + '".' + projectIdMatchMessage;
}
else if (typeof payload.iss !== 'string' || !payload.iss.startsWith(APP_CHECK_ISSUER)) {
errorMessage = 'The provided App Check token has incorrect "iss" (issuer) claim.';
}
else if (typeof payload.sub !== 'string') {
errorMessage = 'The provided App Check token has no "sub" (subject) claim.';
}
else if (payload.sub === '') {
errorMessage = 'The provided App Check token has an empty string "sub" (subject) claim.';
}
if (errorMessage) {
throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', errorMessage);
}
};
AppCheckTokenVerifier.prototype.verifySignature = function (jwtToken) {
var _this = this;
return this.signatureVerifier.verify(jwtToken)
.catch(function (error) {
throw _this.mapJwtErrorToAppCheckError(error);
});
};
/**
* Maps JwtError to FirebaseAppCheckError
*
* @param error - JwtError to be mapped.
* @returns FirebaseAppCheckError instance.
*/
AppCheckTokenVerifier.prototype.mapJwtErrorToAppCheckError = function (error) {
if (error.code === jwt_1.JwtErrorCode.TOKEN_EXPIRED) {
var errorMessage = 'The provided App Check token has expired. Get a fresh App Check token' +
' from your client app and try again.';
return new app_check_api_client_internal_1.FirebaseAppCheckError('app-check-token-expired', errorMessage);
}
else if (error.code === jwt_1.JwtErrorCode.INVALID_SIGNATURE) {
var errorMessage = 'The provided App Check token has invalid signature.';
return new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', errorMessage);
}
else if (error.code === jwt_1.JwtErrorCode.NO_MATCHING_KID) {
var errorMessage = 'The provided App Check token has "kid" claim which does not ' +
'correspond to a known public key. Most likely the provided App Check token ' +
'is expired, so get a fresh token from your client app and try again.';
return new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', errorMessage);
}
return new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', error.message);
};
return AppCheckTokenVerifier;
}());
exports.AppCheckTokenVerifier = AppCheckTokenVerifier;