initial commit

This commit is contained in:
2025-09-01 22:12:29 +02:00
parent b1873f9c1d
commit 02a54f61c0
5598 changed files with 903558 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
/*! firebase-admin v13.5.0 */
/*!
* @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 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);
}

View File

@@ -0,0 +1,214 @@
/*! firebase-admin v13.5.0 */
"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.FirebaseAppCheckError = exports.APP_CHECK_ERROR_CODE_MAPPING = exports.AppCheckApiClient = void 0;
const api_request_1 = require("../utils/api-request");
const error_1 = require("../utils/error");
const utils = require("../utils/index");
const validator = require("../utils/validator");
// App Check backend constants
const FIREBASE_APP_CHECK_V1_API_URL_FORMAT = 'https://firebaseappcheck.googleapis.com/v1/projects/{projectId}/apps/{appId}:exchangeCustomToken';
const ONE_TIME_USE_TOKEN_VERIFICATION_URL_FORMAT = 'https://firebaseappcheck.googleapis.com/v1beta/projects/{projectId}:verifyAppCheckToken';
const 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
*/
class AppCheckApiClient {
constructor(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`.
*/
exchangeToken(customToken, appId) {
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((url) => {
const request = {
method: 'POST',
url,
headers: FIREBASE_APP_CHECK_CONFIG_HEADERS,
data: { customToken }
};
return this.httpClient.send(request);
})
.then((resp) => {
return this.toAppCheckToken(resp);
})
.catch((err) => {
throw this.toFirebaseError(err);
});
}
verifyReplayProtection(token) {
if (!validator.isNonEmptyString(token)) {
throw new FirebaseAppCheckError('invalid-argument', '`token` must be a non-empty string.');
}
return this.getVerifyTokenUrl()
.then((url) => {
const request = {
method: 'POST',
url,
headers: FIREBASE_APP_CHECK_CONFIG_HEADERS,
data: { app_check_token: token }
};
return this.httpClient.send(request);
})
.then((resp) => {
if (typeof resp.data.alreadyConsumed !== 'undefined'
&& !validator.isBoolean(resp.data?.alreadyConsumed)) {
throw new FirebaseAppCheckError('invalid-argument', '`alreadyConsumed` must be a boolean value.');
}
return resp.data.alreadyConsumed || false;
})
.catch((err) => {
throw this.toFirebaseError(err);
});
}
getUrl(appId) {
return this.getProjectId()
.then((projectId) => {
const urlParams = {
projectId,
appId,
};
const baseUrl = utils.formatString(FIREBASE_APP_CHECK_V1_API_URL_FORMAT, urlParams);
return utils.formatString(baseUrl);
});
}
getVerifyTokenUrl() {
return this.getProjectId()
.then((projectId) => {
const urlParams = {
projectId
};
const baseUrl = utils.formatString(ONE_TIME_USE_TOKEN_VERIFICATION_URL_FORMAT, urlParams);
return utils.formatString(baseUrl);
});
}
getProjectId() {
if (this.projectId) {
return Promise.resolve(this.projectId);
}
return utils.findProjectId(this.app)
.then((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;
});
}
toFirebaseError(err) {
if (err instanceof error_1.PrefixedFirebaseError) {
return err;
}
const response = err.response;
if (!response.isJson()) {
return new FirebaseAppCheckError('unknown-error', `Unexpected response with status: ${response.status} and body: ${response.text}`);
}
const error = response.data.error || {};
let code = 'unknown-error';
if (error.status && error.status in exports.APP_CHECK_ERROR_CODE_MAPPING) {
code = exports.APP_CHECK_ERROR_CODE_MAPPING[error.status];
}
const 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.
*/
toAppCheckToken(resp) {
const token = resp.data.token;
// `ttl` is a string with the suffix "s" preceded by the number of seconds,
// with nanoseconds expressed as fractional seconds.
const ttlMillis = this.stringToMilliseconds(resp.data.ttl);
return {
token,
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.
*/
stringToMilliseconds(duration) {
if (!validator.isNonEmptyString(duration) || !duration.endsWith('s')) {
throw new FirebaseAppCheckError('invalid-argument', '`ttl` must be a valid duration string with the suffix `s`.');
}
const seconds = duration.slice(0, -1);
return Math.floor(Number(seconds) * 1000);
}
}
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
*/
class FirebaseAppCheckError extends error_1.PrefixedFirebaseError {
constructor(code, message) {
super('app-check', code, message);
/* 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;
}
}
exports.FirebaseAppCheckError = FirebaseAppCheckError;

View File

@@ -0,0 +1,129 @@
/*! firebase-admin v13.5.0 */
/*!
* @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 options for the {@link AppCheck.verifyToken} method.
*/
export interface VerifyAppCheckTokenOptions {
/**
* To use the replay protection feature, set this to `true`. The {@link AppCheck.verifyToken}
* method will mark the token as consumed after verifying it.
*
* Tokens that are found to be already consumed will be marked as such in the response.
*
* Tokens are only considered to be consumed if it is sent to App Check backend by calling the
* {@link AppCheck.verifyToken} method with this field set to `true`; other uses of the token
* do not consume it.
*
* This replay protection feature requires an additional network call to the App Check backend
* and forces your clients to obtain a fresh attestation from your chosen attestation providers.
* This can therefore negatively impact performance and can potentially deplete your attestation
* providers' quotas faster. We recommend that you use this feature only for protecting
* low volume, security critical, or expensive operations.
*/
consume?: boolean;
}
/**
* 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;
/**
* Indicates weather this token was already consumed.
* If this is the first time {@link AppCheck.verifyToken} method has seen this token,
* this field will contain the value `false`. The given token will then be
* marked as `already_consumed` for all future invocations of this {@link AppCheck.verifyToken}
* method for this token.
*
* When this field is `true`, the caller is attempting to reuse a previously consumed token.
* You should take precautions against such a caller; for example, you can take actions such as
* rejecting the request or ask the caller to pass additional layers of security checks.
*/
alreadyConsumed?: boolean;
}

View File

@@ -0,0 +1,19 @@
/*! firebase-admin v13.5.0 */
"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 });

View File

@@ -0,0 +1,72 @@
/*! firebase-admin v13.5.0 */
/*!
* 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, VerifyAppCheckTokenOptions as TVerifyAppCheckTokenOptions, 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 alias to {@link firebase-admin.app-check#AppCheckTokenOptions}.
*/
type AppCheckTokenOptions = TAppCheckTokenOptions;
/**
* Type alias to {@link firebase-admin.app-check#VerifyAppCheckTokenOptions}.
*/
type VerifyAppCheckTokenOptions = TVerifyAppCheckTokenOptions;
}

View File

@@ -0,0 +1,18 @@
/*! firebase-admin v13.5.0 */
"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 });

View File

@@ -0,0 +1,51 @@
/*! firebase-admin v13.5.0 */
/*!
* @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, VerifyAppCheckTokenOptions, 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.
* @param options - Optional {@link VerifyAppCheckTokenOptions} object when verifying an App Check Token.
*
* @returns A promise fulfilled with the token's decoded claims
* if the App Check token is valid; otherwise, a rejected promise.
*/
verifyToken(appCheckToken: string, options?: VerifyAppCheckTokenOptions): Promise<VerifyAppCheckTokenResponse>;
private validateVerifyAppCheckTokenOptions;
}

View File

@@ -0,0 +1,101 @@
/*! firebase-admin v13.5.0 */
"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;
const validator = require("../utils/validator");
const app_check_api_client_internal_1 = require("./app-check-api-client-internal");
const token_generator_1 = require("./token-generator");
const token_verifier_1 = require("./token-verifier");
const crypto_signer_1 = require("../utils/crypto-signer");
/**
* The Firebase `AppCheck` service interface.
*/
class AppCheck {
/**
* @param app - The app for this AppCheck service.
* @constructor
* @internal
*/
constructor(app) {
this.app = app;
this.client = new app_check_api_client_internal_1.AppCheckApiClient(app);
try {
this.tokenGenerator = new token_generator_1.AppCheckTokenGenerator((0, crypto_signer_1.cryptoSignerFromApp)(app));
}
catch (err) {
throw (0, 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`.
*/
createToken(appId, options) {
return this.tokenGenerator.createCustomToken(appId, options)
.then((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.
* @param options - Optional {@link VerifyAppCheckTokenOptions} object when verifying an App Check Token.
*
* @returns A promise fulfilled with the token's decoded claims
* if the App Check token is valid; otherwise, a rejected promise.
*/
verifyToken(appCheckToken, options) {
this.validateVerifyAppCheckTokenOptions(options);
return this.appCheckTokenVerifier.verifyToken(appCheckToken)
.then((decodedToken) => {
if (options?.consume) {
return this.client.verifyReplayProtection(appCheckToken)
.then((alreadyConsumed) => {
return {
alreadyConsumed,
appId: decodedToken.app_id,
token: decodedToken,
};
});
}
return {
appId: decodedToken.app_id,
token: decodedToken,
};
});
}
validateVerifyAppCheckTokenOptions(options) {
if (typeof options === 'undefined') {
return;
}
if (!validator.isNonNullObject(options)) {
throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', 'VerifyAppCheckTokenOptions must be a non-null object.');
}
}
}
exports.AppCheck = AppCheck;

View File

@@ -0,0 +1,53 @@
/*! firebase-admin v13.5.0 */
/*!
* @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, VerifyAppCheckTokenOptions, 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;

View File

@@ -0,0 +1,63 @@
/*! firebase-admin v13.5.0 */
"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;
exports.getAppCheck = getAppCheck;
/**
* Firebase App Check.
*
* @packageDocumentation
*/
const app_1 = require("../app");
const 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 = (0, app_1.getApp)();
}
const firebaseApp = app;
return firebaseApp.getOrInitService('appCheck', (app) => new app_check_1.AppCheck(app));
}

View File

@@ -0,0 +1,25 @@
/*! firebase-admin v13.5.0 */
/*!
* @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;

View File

@@ -0,0 +1,154 @@
/*! firebase-admin v13.5.0 */
"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.AppCheckTokenGenerator = void 0;
exports.appCheckErrorFromCryptoSignerError = appCheckErrorFromCryptoSignerError;
const validator = require("../utils/validator");
const utils_1 = require("../utils");
const crypto_signer_1 = require("../utils/crypto-signer");
const app_check_api_client_internal_1 = require("./app-check-api-client-internal");
const ONE_MINUTE_IN_SECONDS = 60;
const ONE_MINUTE_IN_MILLIS = ONE_MINUTE_IN_SECONDS * 1000;
const ONE_DAY_IN_MILLIS = 24 * 60 * 60 * 1000;
// Audience to use for Firebase App Check Custom tokens
const FIREBASE_APP_CHECK_AUDIENCE = 'https://firebaseappcheck.googleapis.com/google.firebase.appcheck.v1.TokenExchangeService';
/**
* Class for generating Firebase App Check tokens.
*
* @internal
*/
class AppCheckTokenGenerator {
/**
* The AppCheckTokenGenerator class constructor.
*
* @param signer - The CryptoSigner instance for this token generator.
* @constructor
*/
constructor(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.
*/
createCustomToken(appId, options) {
if (!validator.isNonEmptyString(appId)) {
throw new app_check_api_client_internal_1.FirebaseAppCheckError('invalid-argument', '`appId` must be a non-empty string.');
}
let customOptions = {};
if (typeof options !== 'undefined') {
customOptions = this.validateTokenOptions(options);
}
return this.signer.getAccountId().then((account) => {
const header = {
alg: this.signer.algorithm,
typ: 'JWT',
};
const iat = Math.floor(Date.now() / 1000);
const body = {
iss: account,
sub: account,
app_id: appId,
aud: FIREBASE_APP_CHECK_AUDIENCE,
exp: iat + (ONE_MINUTE_IN_SECONDS * 5),
iat,
...customOptions,
};
const token = `${this.encodeSegment(header)}.${this.encodeSegment(body)}`;
return this.signer.sign(Buffer.from(token))
.then((signature) => {
return `${token}.${this.encodeSegment(signature)}`;
});
}).catch((err) => {
throw appCheckErrorFromCryptoSignerError(err);
});
}
encodeSegment(segment) {
const buffer = (segment instanceof Buffer) ? segment : Buffer.from(JSON.stringify(segment));
return (0, 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.
*/
validateTokenOptions(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: (0, utils_1.transformMillisecondsToSecondsString)(options.ttlMillis) };
}
return {};
}
}
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)) {
const httpError = err.cause;
const errorResponse = httpError.response.data;
if (errorResponse?.error) {
const status = errorResponse.error.status;
const description = errorResponse.error.message || JSON.stringify(httpError.response);
let 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);
}
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';
}
}

View File

@@ -0,0 +1,17 @@
/*! firebase-admin v13.5.0 */
/*!
* 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 {};

View File

@@ -0,0 +1,147 @@
/*! firebase-admin v13.5.0 */
"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;
const validator = require("../utils/validator");
const util = require("../utils/index");
const app_check_api_client_internal_1 = require("./app-check-api-client-internal");
const jwt_1 = require("../utils/jwt");
const APP_CHECK_ISSUER = 'https://firebaseappcheck.googleapis.com/';
const JWKS_URL = 'https://firebaseappcheck.googleapis.com/v1/jwks';
/**
* Class for verifying Firebase App Check tokens.
*
* @internal
*/
class AppCheckTokenVerifier {
constructor(app) {
this.app = app;
this.signatureVerifier = jwt_1.PublicKeySignatureVerifier.withJwksUrl(JWKS_URL, app.options.httpAgent);
}
/**
* 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.
*/
verifyToken(token) {
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((projectId) => {
return this.decodeAndVerify(token, projectId);
})
.then((decoded) => {
const decodedAppCheckToken = decoded.payload;
decodedAppCheckToken.app_id = decodedAppCheckToken.sub;
return decodedAppCheckToken;
});
}
ensureProjectId() {
return util.findProjectId(this.app)
.then((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;
});
}
decodeAndVerify(token, projectId) {
return this.safeDecode(token)
.then((decodedToken) => {
this.verifyContent(decodedToken, projectId);
return this.verifySignature(token)
.then(() => decodedToken);
});
}
safeDecode(jwtToken) {
return (0, jwt_1.decodeJwt)(jwtToken)
.catch(() => {
const 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.
*/
verifyContent(fullDecodedToken, projectId) {
const header = fullDecodedToken.header;
const payload = fullDecodedToken.payload;
const projectIdMatchMessage = ' Make sure the App Check token comes from the same ' +
'Firebase project as the service account used to authenticate this SDK.';
const scopedProjectId = `projects/${projectId}`;
let 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);
}
}
verifySignature(jwtToken) {
return this.signatureVerifier.verify(jwtToken)
.catch((error) => {
throw this.mapJwtErrorToAppCheckError(error);
});
}
/**
* Maps JwtError to FirebaseAppCheckError
*
* @param error - JwtError to be mapped.
* @returns FirebaseAppCheckError instance.
*/
mapJwtErrorToAppCheckError(error) {
if (error.code === jwt_1.JwtErrorCode.TOKEN_EXPIRED) {
const 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) {
const 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) {
const 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);
}
}
exports.AppCheckTokenVerifier = AppCheckTokenVerifier;