/*! firebase-admin v9.10.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.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_HOUR_IN_SECONDS = 60 * 60;
// 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.
     *
     * @return 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) {
        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.');
        }
        return this.signer.getAccountId().then(function (account) {
            var header = {
                alg: _this.signer.algorithm,
                typ: 'JWT',
            };
            var iat = Math.floor(Date.now() / 1000);
            var body = {
                iss: account,
                sub: account,
                // eslint-disable-next-line @typescript-eslint/camelcase
                app_id: appId,
                aud: FIREBASE_APP_CHECK_AUDIENCE,
                exp: iat + ONE_HOUR_IN_SECONDS,
                iat: iat,
            };
            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(/=+$/, '');
    };
    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
 * @return 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 siging 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';
    }
}
