UNPKG

firebase-tools

Version:
294 lines (293 loc) • 11 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getDebugTokenValidationError = getDebugTokenValidationError; exports.validateDebugTokenUuid = validateDebugTokenUuid; exports.getDisplayNameValidationError = getDisplayNameValidationError; exports.validateDisplayName = validateDisplayName; exports.getDefaultDisplayName = getDefaultDisplayName; exports.isWebAppId = isWebAppId; exports.formatLocalTokenStatus = formatLocalTokenStatus; exports.ensureCanCreateOrOverwriteDebugToken = ensureCanCreateOrOverwriteDebugToken; exports.provisionDebugToken = provisionDebugToken; exports.inspectLocalDebugTokens = inspectLocalDebugTokens; exports.findStaleLocalDebugTokens = findStaleLocalDebugTokens; exports.deleteDebugTokenAndCleanLocal = deleteDebugTokenAndCleanLocal; const clc = require("colorette"); const os = require("os"); const error_1 = require("../error"); const logger_1 = require("../logger"); const apps_1 = require("../management/apps"); const projectUtils_1 = require("../projectUtils"); const requireAuth_1 = require("../requireAuth"); const utils_1 = require("../utils"); const api_1 = require("./api"); const localConfig_1 = require("./localConfig"); const MAX_DEBUG_TOKENS_PER_APP = 20; const MAX_DISPLAY_NAME_LENGTH = 50; const MASK_PREFIX_LENGTH = 8; const UUID_V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; const GMP_APP_ID_PROJECT_NUMBER_REGEX = /^\d+:(\d+):/; function extractProjectNumberFromAppId(appId) { const match = GMP_APP_ID_PROJECT_NUMBER_REGEX.exec(appId); return match ? match[1] : undefined; } function maskDebugToken(token) { if (token.length <= MASK_PREFIX_LENGTH) { return "********"; } const prefix = token.slice(0, MASK_PREFIX_LENGTH); return token[MASK_PREFIX_LENGTH] === "-" ? `${prefix}-...` : `${prefix}...`; } async function deleteServerTokensIgnoringNotFound(tokens) { for (const existing of tokens) { try { await (0, api_1.deleteDebugToken)(existing.name); } catch (err) { if ((0, error_1.getErrStatus)(err) !== 404) { throw err; } } } } async function checkAppServerTokenStatus(projectNumber, appId, recordedResourceName) { let serverTokens; try { serverTokens = await (0, api_1.listDebugTokens)(projectNumber, appId); } catch (err) { const status = (0, error_1.getErrStatus)(err); if (status === 404 || status === 409) { return "APP_DELETED"; } throw err; } if (serverTokens.length === 0) { return "REVOKED"; } if (recordedResourceName) { return serverTokens.some((t) => t.name === recordedResourceName) ? "ACTIVE" : "REVOKED"; } return "UNCHECKED"; } async function resolveProjectTokenStatuses(params) { const { projectId, projectNumber, candidateAppIds, tokenNames } = params; const statuses = {}; if (candidateAppIds.length === 0) { return statuses; } const apps = await (0, apps_1.listFirebaseApps)(projectId, apps_1.AppPlatform.ANY); const activeProjectAppIds = new Set(apps.map((app) => app.appId)); await Promise.all(candidateAppIds.map(async (appId) => { if (!activeProjectAppIds.has(appId)) { statuses[appId] = "APP_DELETED"; return; } try { statuses[appId] = await checkAppServerTokenStatus(projectNumber, appId, tokenNames[appId]); } catch (err) { logger_1.logger.debug(`Failed to check server token status for app ${appId}: ${(0, error_1.getErrMsg)(err)}`); statuses[appId] = "UNCHECKED"; } })); return statuses; } function buildLocalTokenEntry(params) { const { appId, token, status, resourceName } = params; const entry = { appId, tokenPrefix: maskDebugToken(token), status, }; if (resourceName) { entry.name = resourceName; } return entry; } function getDebugTokenValidationError(raw) { const trimmed = raw.trim(); if (!trimmed) { return "Debug token cannot be empty."; } if (!UUID_V4_REGEX.test(trimmed)) { return (`Invalid debug token "${trimmed}". Expected a UUID v4 string ` + `(for example, xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx). To specify a Firebase App ID, pass --app <appId>.`); } return undefined; } function validateDebugTokenUuid(raw) { const error = getDebugTokenValidationError(raw); if (error) { throw new error_1.FirebaseError(error, { exit: 1 }); } return raw.trim(); } function getDisplayNameValidationError(raw) { const trimmed = raw.trim(); if (!trimmed) { return "Display name cannot be empty."; } if (trimmed.length > MAX_DISPLAY_NAME_LENGTH) { return (`Display name "${trimmed}" exceeds the maximum length of ${MAX_DISPLAY_NAME_LENGTH} characters ` + `(got ${trimmed.length}). Pass a shorter --display-name.`); } return undefined; } function validateDisplayName(raw) { const error = getDisplayNameValidationError(raw); if (error) { throw new error_1.FirebaseError(error, { exit: 1 }); } return raw.trim(); } function getDefaultDisplayName(saveLocal = true) { const fullHost = os.hostname() || "unknown-host"; const shortHost = fullHost.split(".")[0] || fullHost; if (!saveLocal) { return `CLI Debug Token (${shortHost})`.slice(0, MAX_DISPLAY_NAME_LENGTH); } let username = "user"; try { const info = os.userInfo(); if (info.username) { username = info.username; } } catch { } const fullCandidate = `${username}@${fullHost}`; if (fullCandidate.length <= MAX_DISPLAY_NAME_LENGTH) { return fullCandidate; } return `${username}@${shortHost}`.slice(0, MAX_DISPLAY_NAME_LENGTH); } function isWebAppId(appId) { return appId.toLowerCase().includes(":web:"); } function formatLocalTokenStatus(status) { switch (status) { case "ACTIVE": return clc.green("Active"); case "REVOKED": return clc.yellow("Revoked"); case "APP_DELETED": return clc.red("App Deleted"); case "UNCHECKED": return clc.gray("Unchecked"); } } function ensureCanCreateOrOverwriteDebugToken(params) { const { appId, existingTokens, matchingTokens } = params; if (matchingTokens.length === 0 && existingTokens.length >= MAX_DEBUG_TOKENS_PER_APP) { throw new error_1.FirebaseError(`App ${appId} already has the maximum of ${MAX_DEBUG_TOKENS_PER_APP} debug tokens. ` + `View existing tokens with "firebase appcheck:debugtokens:list --app ${appId}" and ` + `revoke unused tokens with "firebase appcheck:debugtokens:delete <debugTokenId>".`, { exit: 1 }); } } async function provisionDebugToken(params) { const { projectNumber, appId, displayName, token, existingTokens, matchingTokens, saveLocal } = params; ensureCanCreateOrOverwriteDebugToken({ appId, existingTokens, matchingTokens }); const mustDeleteBeforeCreate = matchingTokens.length > 0 && existingTokens.length >= MAX_DEBUG_TOKENS_PER_APP; if (mustDeleteBeforeCreate) { await deleteServerTokensIgnoringNotFound(matchingTokens); } const created = await (0, api_1.createDebugToken)(projectNumber, appId, displayName, token); if (matchingTokens.length > 0 && !mustDeleteBeforeCreate) { await deleteServerTokensIgnoringNotFound(matchingTokens); } const finalToken = created.token || token; const hydrated = { ...created, token: finalToken, }; if (saveLocal) { (0, localConfig_1.saveLocalToken)(appId, finalToken, hydrated.name); } return hydrated; } async function inspectLocalDebugTokens(options) { let tokens; if (options.app) { const single = (0, localConfig_1.getLocalToken)(options.app); tokens = single ? { [options.app]: single } : {}; } else { tokens = (0, localConfig_1.getAllLocalTokens)(); } const appIds = Object.keys(tokens); if (appIds.length === 0) { return []; } const tokenNames = (0, localConfig_1.getAllLocalTokenNames)(); const statusByAppId = {}; for (const appId of appIds) { statusByAppId[appId] = "UNCHECKED"; } if ((0, projectUtils_1.getProjectId)(options) || options.projectNumber) { try { await (0, requireAuth_1.requireAuth)(options); const projectId = (0, projectUtils_1.needProjectId)(options); const projectNumber = await (0, projectUtils_1.needProjectNumber)(options); const candidateAppIds = appIds.filter((appId) => extractProjectNumberFromAppId(appId) === projectNumber); const resolvedStatuses = await resolveProjectTokenStatuses({ projectId, projectNumber, candidateAppIds, tokenNames, }); Object.assign(statusByAppId, resolvedStatuses); } catch (err) { logger_1.logger.debug(`Skipping server status check for local App Check debug tokens: ${(0, error_1.getErrMsg)(err)}`); } } return appIds.map((appId) => buildLocalTokenEntry({ appId, token: tokens[appId], status: statusByAppId[appId], resourceName: tokenNames[appId], })); } async function findStaleLocalDebugTokens(params) { const { projectId, projectNumber } = params; const tokens = (0, localConfig_1.getAllLocalTokens)(); const candidateAppIds = Object.keys(tokens).filter((appId) => extractProjectNumberFromAppId(appId) === projectNumber); if (candidateAppIds.length === 0) { return []; } const tokenNames = (0, localConfig_1.getAllLocalTokenNames)(); const statuses = await resolveProjectTokenStatuses({ projectId, projectNumber, candidateAppIds, tokenNames, }); const stale = []; for (const appId of candidateAppIds) { const status = statuses[appId]; if (status === "APP_DELETED" || status === "REVOKED") { stale.push(buildLocalTokenEntry({ appId, token: tokens[appId], status, resourceName: tokenNames[appId], })); } } return stale; } async function deleteDebugTokenAndCleanLocal(params) { const { appId, debugTokenName } = params; await (0, api_1.deleteDebugToken)(debugTokenName); try { if ((0, localConfig_1.getLocalTokenName)(appId) === debugTokenName) { (0, localConfig_1.removeLocalTokens)([appId]); return true; } } catch (err) { (0, utils_1.logWarning)(`Deleted server debug token, but failed to clean up local App Check config: ${(0, error_1.getErrMsg)(err)}`); } return false; }