firebase-tools
Version:
Command-Line Interface for Firebase
121 lines (119 loc) • 6.83 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.command = void 0;
const clc = require("colorette");
const node_crypto_1 = require("node:crypto");
const command_1 = require("../command");
const projectUtils_1 = require("../projectUtils");
const api_1 = require("../appcheck/api");
const debugTokens_1 = require("../appcheck/debugTokens");
const localConfig_1 = require("../appcheck/localConfig");
const appcheck_prompts_1 = require("./appcheck-prompts");
const requireAuth_1 = require("../requireAuth");
const utils_1 = require("../utils");
const error_1 = require("../error");
const prompt_1 = require("../prompt");
const logger_1 = require("../logger");
exports.command = new command_1.Command("appcheck:debugtokens:create [debugToken]")
.description("generate and register an App Check debug token for an app")
.help(`generates or registers a Firebase App Check debug token for an app and saves it to the local machine configuration (~/.config/configstore/firebase-appcheck.json) so local SDKs can discover it automatically.
Pass an optional \`[debugToken]\` UUID v4 to register a specific token, or omit it to generate a new UUID v4 token. Use \`--no-save-local\` when provisioning tokens for remote CI environments to avoid modifying the local config file.`)
.option("--app <appId>", "the app id of your Firebase app")
.option("--display-name <displayName>", "display name for the debug token (max 50 characters)")
.option("--no-save-local", "do not save the debug token to the local machine config")
.withForce("accept default prompts and overwrite any existing debug token with the same display name")
.before((options) => (0, requireAuth_1.requireAuth)(options))
.action(async (debugToken, options) => {
const validatedTokenArg = debugToken !== undefined ? (0, debugTokens_1.validateDebugTokenUuid)(debugToken) : undefined;
const validatedDisplayNameOpt = options.displayName !== undefined ? (0, debugTokens_1.validateDisplayName)(options.displayName) : undefined;
const saveLocal = options.saveLocal !== false;
const { appId } = await (0, appcheck_prompts_1.getOrPromptProjectAndAppId)(options);
const projectNumber = await (0, projectUtils_1.needProjectNumber)(options);
let token = validatedTokenArg;
if (!token) {
if (!options.nonInteractive && !options.force) {
const action = await (0, prompt_1.select)({
message: "Would you like to register a token generated by the SDK, or create a new one?",
choices: [
{ name: "Create a new debug token", value: "generate" },
{ name: "Register a token generated by the SDK", value: "sdk" },
],
});
if (action === "sdk") {
const entered = await (0, prompt_1.password)({
message: "Enter the debug token generated by the SDK:",
validate: (val) => (0, debugTokens_1.getDebugTokenValidationError)(val) ?? true,
});
token = (0, debugTokens_1.validateDebugTokenUuid)(entered);
}
else {
token = (0, node_crypto_1.randomUUID)();
}
}
else {
token = (0, node_crypto_1.randomUUID)();
}
}
let displayName = validatedDisplayNameOpt;
if (!displayName) {
const defaultName = (0, debugTokens_1.getDefaultDisplayName)(saveLocal);
if (!options.nonInteractive && !options.force) {
const entered = await (0, prompt_1.input)({
message: "What would you like to call this debug token?",
default: defaultName,
validate: (val) => (0, debugTokens_1.getDisplayNameValidationError)(val) ?? true,
});
displayName = (0, debugTokens_1.validateDisplayName)(entered);
}
else {
displayName = defaultName;
}
}
const existingTokens = await (0, api_1.listDebugTokens)(projectNumber, appId);
const matchingTokens = existingTokens.filter((t) => t.displayName === displayName);
(0, debugTokens_1.ensureCanCreateOrOverwriteDebugToken)({ appId, existingTokens, matchingTokens });
if (matchingTokens.length > 0 && !options.force) {
if (options.nonInteractive) {
throw new error_1.FirebaseError(`A token with the display name "${displayName}" already exists. Must pass --force to overwrite in non-interactive mode.`, { exit: 1 });
}
const shouldOverwrite = await (0, prompt_1.confirm)({
message: `A token with the display name "${displayName}" already exists. Replace the existing token(s)?`,
default: true,
});
if (!shouldOverwrite) {
throw new error_1.FirebaseError("Registration canceled.", { exit: 1 });
}
}
const result = await (0, utils_1.promiseWithSpinner)(() => (0, debugTokens_1.provisionDebugToken)({
projectNumber,
appId,
displayName,
token,
existingTokens,
matchingTokens,
saveLocal,
}), `Registering App Check debug token with Firebase for app ${clc.bold(appId)}`);
const finalToken = result.token || token;
(0, utils_1.logSuccess)(`Successfully registered App Check debug token:
- Display Name: ${clc.bold(result.displayName)}
- Resource Name: ${clc.cyan(result.name)}
- Token: ${clc.bold(clc.green(finalToken))}`);
if (saveLocal) {
logger_1.logger.info(`Saved debug token to local config: ${clc.bold((0, localConfig_1.getLocalConfigPath)())}`);
}
if ((0, debugTokens_1.isWebAppId)(appId)) {
logger_1.logger.info(`\nWeb Framework Instructions:\n` +
`Copy and paste the relevant variable into your local environment file (${clc.bold(".env.local")}), or export the debug token as a shell environment variable:\n` +
` # Vite\n` +
` VITE_FIREBASE_APPCHECK_DEBUG_TOKEN=${finalToken}\n` +
` # Next.js\n` +
` NEXT_PUBLIC_FIREBASE_APPCHECK_DEBUG_TOKEN=${finalToken}\n` +
` # Create React App\n` +
` REACT_APP_FIREBASE_APPCHECK_DEBUG_TOKEN=${finalToken}\n` +
`Assign this variable to ${clc.bold("self.FIREBASE_APPCHECK_DEBUG_TOKEN")} in your app initialization code before initializing App Check.\n` +
`Ensure ${clc.bold(".env.local")} is in your ${clc.bold(".gitignore")} so debug tokens are never committed.`);
}
logger_1.logger.info(clc.yellow(clc.bold("Warning: ") +
"App Check debug tokens grant access to backend resources and are secrets. Do NOT commit debug tokens or .env.local to source repositories. Revoke unused tokens with 'firebase appcheck:debugtokens:delete'."));
return finalToken;
});