diff --git a/CHANGELOG.md b/CHANGELOG.md index 289e959769f..7b47368dc11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1 +1,2 @@ - Fixed a race condition across a second boundary during `accounts:signUp` in the Auth emulator where `validSince` could exceed `auth_time`. (#11413) +- Added local machine config persistence to `appcheck:debugtokens:create` so local SDKs can discover App Check debug tokens automatically, along with a `--no-save-local` flag. diff --git a/src/appcheck/debugTokens.spec.ts b/src/appcheck/debugTokens.spec.ts new file mode 100644 index 00000000000..426ff23226b --- /dev/null +++ b/src/appcheck/debugTokens.spec.ts @@ -0,0 +1,226 @@ +import { expect } from "chai"; +import * as fs from "fs-extra"; +import * as nock from "nock"; +import * as os from "os"; +import * as path from "path"; +import * as sinon from "sinon"; + +import { appCheckOrigin } from "../api"; +import { FirebaseError } from "../error"; +import { + ensureCanCreateOrOverwriteDebugToken, + getDefaultDisplayName, + isWebAppId, + provisionDebugToken, + validateDebugTokenUuid, + validateDisplayName, +} from "./debugTokens"; +import { getLocalToken, getLocalTokenName } from "./localConfig"; +import { DebugToken } from "./types"; + +describe("appcheck debugTokens helpers", () => { + const projectNumber = "1234567890"; + const iosAppId = `1:${projectNumber}:ios:0a1b2c3d4e5f6a7b8c9d0e`; + const webAppId = `1:${projectNumber}:web:9f8e7d6c5b4a3f2e1d0c`; + const validUuid = "e3d9b1a0-cf48-4389-8d19-482a177ffec8"; + + let sandbox: sinon.SinonSandbox; + let tempRoot: string; + let originalXdgConfigHome: string | undefined; + + beforeEach(() => { + sandbox = sinon.createSandbox(); + originalXdgConfigHome = process.env.XDG_CONFIG_HOME; + delete process.env.XDG_CONFIG_HOME; + tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "firebase-debugtokens-helper-test-")); + sandbox.stub(os, "homedir").returns(tempRoot); + }); + + afterEach(() => { + if (originalXdgConfigHome === undefined) { + delete process.env.XDG_CONFIG_HOME; + } else { + process.env.XDG_CONFIG_HOME = originalXdgConfigHome; + } + sandbox.restore(); + nock.cleanAll(); + fs.removeSync(tempRoot); + }); + + describe("validation & display names", () => { + it("trims and accepts valid UUID v4 tokens case-insensitively", () => { + const upper = ` ${validUuid.toUpperCase()} `; + expect(validateDebugTokenUuid(upper)).to.equal(validUuid.toUpperCase()); + }); + + it("rejects empty, non-UUID, or non-v4 UUID strings with actionable guidance", () => { + expect(() => validateDebugTokenUuid(" ")).to.throw(FirebaseError, /cannot be empty/); + expect(() => validateDebugTokenUuid(iosAppId)).to.throw(FirebaseError, /pass --app /); + // Version 1 UUID (13th hex char is 1 instead of 4) + expect(() => validateDebugTokenUuid("e3d9b1a0-cf48-1389-8d19-482a177ffec8")).to.throw( + FirebaseError, + /UUID v4/, + ); + }); + + it("enforces 1..50 character display names", () => { + expect(validateDisplayName(" alice@macbook ")).to.equal("alice@macbook"); + expect(() => validateDisplayName(" ")).to.throw(FirebaseError, /cannot be empty/); + expect(() => validateDisplayName("a".repeat(51))).to.throw( + FirebaseError, + /maximum length of 50 characters/, + ); + }); + + it("bounds getDefaultDisplayName to <= 50 chars and avoids host collision when saveLocal is false", () => { + sandbox.stub(os, "userInfo").returns({ + username: "austinbenoit", + uid: 1000, + gid: 1000, + shell: "/bin/bash", + homedir: tempRoot, + }); + sandbox.stub(os, "hostname").returns("austinbenoit-long-cloudtop-instance.c.googlers.com"); + + const localDefault = getDefaultDisplayName(true); + expect(localDefault).to.equal("austinbenoit@austinbenoit-long-cloudtop-instance"); + expect(localDefault.length).to.be.at.most(50); + + const remoteDefault = getDefaultDisplayName(false); + expect(remoteDefault).to.equal( + "CLI Debug Token (austinbenoit-long-cloudtop-instance)".slice(0, 50), + ); + expect(remoteDefault).to.not.equal(localDefault); + expect(remoteDefault.length).to.be.at.most(50); + }); + + it("falls back to user@ when os.userInfo throws", () => { + sandbox.stub(os, "userInfo").throws(new Error("ENOENT")); + sandbox.stub(os, "hostname").returns("dev-box"); + + expect(getDefaultDisplayName(true)).to.equal("user@dev-box"); + }); + + it("detects Web App IDs accurately", () => { + expect(isWebAppId(webAppId)).to.be.true; + expect(isWebAppId(iosAppId)).to.be.false; + }); + }); + + describe("provisionDebugToken", () => { + it("creates replacement token BEFORE deleting matching token when below 20-token quota", async () => { + const callOrder: string[] = []; + const oldResourceName = `projects/${projectNumber}/apps/${iosAppId}/debugTokens/old-id`; + const newResourceName = `projects/${projectNumber}/apps/${iosAppId}/debugTokens/new-id`; + const existing: DebugToken = { name: oldResourceName, displayName: "alice@mac", token: "" }; + + nock(appCheckOrigin()) + .post(`/v1/projects/${projectNumber}/apps/${iosAppId}/debugTokens`, { + displayName: "alice@mac", + token: validUuid, + }) + .reply(200, () => { + callOrder.push("create"); + // Real backend omits/clears `token` in CreateDebugToken response. + return { name: newResourceName, displayName: "alice@mac" }; + }); + + nock(appCheckOrigin()) + .delete(`/v1/${oldResourceName}`) + .reply(200, () => { + callOrder.push("delete"); + return {}; + }); + + const hydrated = await provisionDebugToken({ + projectNumber, + appId: iosAppId, + displayName: "alice@mac", + token: validUuid, + existingTokens: [existing], + matchingTokens: [existing], + saveLocal: true, + }); + + expect(callOrder).to.deep.equal(["create", "delete"]); + expect(hydrated).to.deep.equal({ + name: newResourceName, + displayName: "alice@mac", + token: validUuid, + }); + expect(getLocalToken(iosAppId)).to.equal(validUuid); + expect(getLocalTokenName(iosAppId)).to.equal(newResourceName); + expect(nock.isDone()).to.be.true; + }); + + it("preserves existing server token if createDebugToken fails when below 20-token quota", async () => { + const oldResourceName = `projects/${projectNumber}/apps/${iosAppId}/debugTokens/old-id`; + const existing: DebugToken = { name: oldResourceName, displayName: "alice@mac", token: "" }; + const deleteScope = nock(appCheckOrigin()).delete(`/v1/${oldResourceName}`).reply(200, {}); + + nock(appCheckOrigin()) + .post(`/v1/projects/${projectNumber}/apps/${iosAppId}/debugTokens`) + .reply(500, { error: { message: "Internal backend failure" } }); + + await expect( + provisionDebugToken({ + projectNumber, + appId: iosAppId, + displayName: "alice@mac", + token: validUuid, + existingTokens: [existing], + matchingTokens: [existing], + saveLocal: true, + }), + ).to.be.rejectedWith(FirebaseError); + + expect(deleteScope.isDone()).to.be.false; + }); + + it("deletes matching token before creating when app is at the 20-token limit, and throws when 20 unrelated tokens exist", async () => { + const twentyTokens: DebugToken[] = Array.from({ length: 20 }, (_, idx) => ({ + name: `projects/${projectNumber}/apps/${iosAppId}/debugTokens/tok-${idx}`, + displayName: `token-${idx}`, + token: "", + })); + + expect(() => + ensureCanCreateOrOverwriteDebugToken({ + appId: iosAppId, + existingTokens: twentyTokens, + matchingTokens: [], + }), + ).to.throw(FirebaseError, /maximum of 20 debug tokens/); + + const callOrder: string[] = []; + nock(appCheckOrigin()) + .delete(`/v1/${twentyTokens[0].name}`) + .reply(200, () => { + callOrder.push("delete"); + return {}; + }); + nock(appCheckOrigin()) + .post(`/v1/projects/${projectNumber}/apps/${iosAppId}/debugTokens`) + .reply(200, () => { + callOrder.push("create"); + return { + name: `projects/${projectNumber}/apps/${iosAppId}/debugTokens/new-id`, + displayName: "token-0", + }; + }); + + await provisionDebugToken({ + projectNumber, + appId: iosAppId, + displayName: "token-0", + token: validUuid, + existingTokens: twentyTokens, + matchingTokens: [twentyTokens[0]], + saveLocal: false, + }); + + expect(callOrder).to.deep.equal(["delete", "create"]); + expect(nock.isDone()).to.be.true; + }); + }); +}); diff --git a/src/appcheck/debugTokens.ts b/src/appcheck/debugTokens.ts new file mode 100644 index 00000000000..e67fc0e3ba5 --- /dev/null +++ b/src/appcheck/debugTokens.ts @@ -0,0 +1,181 @@ +import * as os from "os"; + +import { FirebaseError, getErrStatus } from "../error"; +import { createDebugToken, deleteDebugToken } from "./api"; +import { saveLocalToken } from "./localConfig"; +import { DebugToken } from "./types"; + +const MAX_DEBUG_TOKENS_PER_APP = 20; +const MAX_DISPLAY_NAME_LENGTH = 50; +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; + +async function deleteServerTokensIgnoringNotFound(tokens: readonly DebugToken[]): Promise { + for (const existing of tokens) { + try { + await deleteDebugToken(existing.name); + } catch (err: unknown) { + if (getErrStatus(err) !== 404) { + throw err; + } + } + } +} + +/** + * Returns an error message when `raw` is not a valid UUID v4 debug token, or `undefined` if valid. + */ +export function getDebugTokenValidationError(raw: string): string | undefined { + 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 .` + ); + } + return undefined; +} + +/** + * Trims and validates a UUID v4 debug token, throwing a `FirebaseError` if invalid. + */ +export function validateDebugTokenUuid(raw: string): string { + const error = getDebugTokenValidationError(raw); + if (error) { + throw new FirebaseError(error, { exit: 1 }); + } + return raw.trim(); +} + +/** + * Returns an error message when `raw` is not a valid debug token display name (`1..50` chars), or `undefined` if valid. + */ +export function getDisplayNameValidationError(raw: string): string | undefined { + 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; +} + +/** + * Trims and validates a debug token display name against backend length constraints (`<= 50` chars). + */ +export function validateDisplayName(raw: string): string { + const error = getDisplayNameValidationError(raw); + if (error) { + throw new FirebaseError(error, { exit: 1 }); + } + return raw.trim(); +} + +/** + * Builds the default display name for a debug token, bounded to the backend's 50-character limit. + * + * When `saveLocal` is `true`, uses `@` (falling back to the short hostname if + * the FQDN would exceed 50 characters). When `saveLocal` is `false` (`--no-save-local`), uses + * `CLI Debug Token ()` so provisioning a remote/CI token never collides with and revokes + * the host machine's own local token. + */ +export function getDefaultDisplayName(saveLocal = true): string { + 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 { + // os.userInfo() can throw a SystemError in restricted container environments without a passwd entry. + } + + const fullCandidate = `${username}@${fullHost}`; + if (fullCandidate.length <= MAX_DISPLAY_NAME_LENGTH) { + return fullCandidate; + } + return `${username}@${shortHost}`.slice(0, MAX_DISPLAY_NAME_LENGTH); +} + +/** + * Returns whether a Firebase GMP App ID targets the Web platform. + */ +export function isWebAppId(appId: string): boolean { + return appId.toLowerCase().includes(":web:"); +} + +/** + * Verifies that creating (or overwriting) a debug token will not exceed the 20-token per-app backend limit. + */ +export function ensureCanCreateOrOverwriteDebugToken(params: { + appId: string; + existingTokens: readonly DebugToken[]; + matchingTokens: readonly DebugToken[]; +}): void { + const { appId, existingTokens, matchingTokens } = params; + if (matchingTokens.length === 0 && existingTokens.length >= MAX_DEBUG_TOKENS_PER_APP) { + throw new 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 ".`, + { exit: 1 }, + ); + } +} + +/** + * Registers a debug token on the App Check backend, safely replacing any `matchingTokens` + * and optionally persisting the token and its resource name to `~/.config/configstore/firebase-appcheck.json`. + */ +export async function provisionDebugToken(params: { + projectNumber: string; + appId: string; + displayName: string; + token: string; + existingTokens: readonly DebugToken[]; + matchingTokens: readonly DebugToken[]; + saveLocal: boolean; +}): Promise { + 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 createDebugToken(projectNumber, appId, displayName, token); + + if (matchingTokens.length > 0 && !mustDeleteBeforeCreate) { + await deleteServerTokensIgnoringNotFound(matchingTokens); + } + + // The App Check CreateDebugToken API clears the secret `token` field in its response; + // re-attach the registered UUID so `--json` callers receive it. + const finalToken = created.token || token; + const hydrated: DebugToken = { + ...created, + token: finalToken, + }; + + if (saveLocal) { + saveLocalToken(appId, finalToken, hydrated.name); + } + + return hydrated; +} diff --git a/src/appcheck/localConfig.spec.ts b/src/appcheck/localConfig.spec.ts new file mode 100644 index 00000000000..1ea7078da06 --- /dev/null +++ b/src/appcheck/localConfig.spec.ts @@ -0,0 +1,251 @@ +import { expect } from "chai"; +import * as fs from "fs-extra"; +import * as os from "os"; +import * as path from "path"; +import * as sinon from "sinon"; + +import { FirebaseError } from "../error"; +import { + getAllLocalTokenNames, + getAllLocalTokens, + getLocalConfigPath, + getLocalToken, + getLocalTokenName, + removeLocalTokens, + saveLocalToken, +} from "./localConfig"; + +const EXPECTED_COMMENT = + "This file contains secrets and should not be committed to source repositories"; + +describe("appcheck localConfig", () => { + const iosAppId = "1:1234567890:ios:0a1b2c3d4e5f6a7b8c9d0e"; + const webAppId = "1:1234567890:web:abcdef1234567890"; + const dottedAppId = "1:1234567890:android:com.example.app"; + const token1 = "e3d9b1a0-cf48-4389-8d19-482a177ffec8"; + const token2 = "f4e8c2b1-da59-4490-9e20-593b288ffed9"; + const resourceName1 = `projects/1234567890/apps/${iosAppId}/debugTokens/tok-1`; + const resourceName2 = `projects/1234567890/apps/${webAppId}/debugTokens/tok-2`; + + let sandbox: sinon.SinonSandbox; + let tempRoot: string; + let originalXdgConfigHome: string | undefined; + + beforeEach(() => { + sandbox = sinon.createSandbox(); + originalXdgConfigHome = process.env.XDG_CONFIG_HOME; + delete process.env.XDG_CONFIG_HOME; + + tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "firebase-appcheck-test-")); + sandbox.stub(os, "homedir").returns(tempRoot); + }); + + afterEach(() => { + if (originalXdgConfigHome === undefined) { + delete process.env.XDG_CONFIG_HOME; + } else { + process.env.XDG_CONFIG_HOME = originalXdgConfigHome; + } + sandbox.restore(); + fs.removeSync(tempRoot); + }); + + it("resolves getLocalConfigPath under ~/.config/configstore/firebase-appcheck.json", () => { + expect(getLocalConfigPath()).to.equal( + path.join(tempRoot, ".config", "configstore", "firebase-appcheck.json"), + ); + }); + + it("returns empty maps and undefined entries without creating file when none exists", () => { + expect(getAllLocalTokens()).to.deep.equal({}); + expect(getAllLocalTokenNames()).to.deep.equal({}); + expect(getLocalToken(iosAppId)).to.be.undefined; + expect(getLocalTokenName(iosAppId)).to.be.undefined; + expect(fs.existsSync(getLocalConfigPath())).to.be.false; + }); + + it("saves and reads tokens including appIds with dots without dot-prop splitting", () => { + saveLocalToken(iosAppId, token1); + saveLocalToken(dottedAppId, token2); + + expect(getLocalToken(iosAppId)).to.equal(token1); + expect(getLocalToken(dottedAppId)).to.equal(token2); + expect(getAllLocalTokens()).to.deep.equal({ + [iosAppId]: token1, + [dottedAppId]: token2, + }); + + const rawDisk = JSON.parse(fs.readFileSync(getLocalConfigPath(), "utf8")) as Record< + string, + unknown + >; + expect(rawDisk).to.deep.equal({ + _comment: EXPECTED_COMMENT, + tokens: { + [iosAppId]: token1, + [dottedAppId]: token2, + }, + }); + }); + + it("persists optional server resource names in tokenNames and cleans them up on overwrite or removal", () => { + saveLocalToken(iosAppId, token1, resourceName1); + saveLocalToken(webAppId, token2, resourceName2); + + expect(getLocalTokenName(iosAppId)).to.equal(resourceName1); + expect(getAllLocalTokenNames()).to.deep.equal({ + [iosAppId]: resourceName1, + [webAppId]: resourceName2, + }); + + // Overwriting without resourceName clears stale tokenNames entry for that appId. + saveLocalToken(iosAppId, token2); + expect(getLocalToken(iosAppId)).to.equal(token2); + expect(getLocalTokenName(iosAppId)).to.be.undefined; + + // Removing webAppId removes both tokens[webAppId] and tokenNames[webAppId] (omitting empty tokenNames). + removeLocalTokens([webAppId]); + expect(getLocalTokenName(webAppId)).to.be.undefined; + const rawDisk = JSON.parse(fs.readFileSync(getLocalConfigPath(), "utf8")) as Record< + string, + unknown + >; + expect(rawDisk).to.deep.equal({ + _comment: EXPECTED_COMMENT, + tokens: { + [iosAppId]: token2, + }, + }); + }); + + it("preserves unknown top-level fields for forward compatibility when updating tokens", () => { + const configPath = getLocalConfigPath(); + fs.ensureDirSync(path.dirname(configPath)); + fs.writeFileSync( + configPath, + JSON.stringify({ + _comment: EXPECTED_COMMENT, + tokens: { [iosAppId]: token1 }, + futureSdkMetadata: { schemaVersion: 2 }, + }), + "utf8", + ); + + saveLocalToken(webAppId, token2); + + const rawDisk = JSON.parse(fs.readFileSync(configPath, "utf8")) as Record; + expect(rawDisk.futureSdkMetadata).to.deep.equal({ schemaVersion: 2 }); + expect(rawDisk.tokens).to.deep.equal({ + [iosAppId]: token1, + [webAppId]: token2, + }); + }); + + it("does not write to disk when removeLocalTokens is called with empty or unknown appIds", () => { + removeLocalTokens([]); + removeLocalTokens([iosAppId]); + + expect(fs.existsSync(getLocalConfigPath())).to.be.false; + }); + + it("mirrors writes and removals to absolute XDG_CONFIG_HOME when distinct from ~/.config", () => { + const xdgDir = path.join(tempRoot, "custom-xdg"); + process.env.XDG_CONFIG_HOME = xdgDir; + const xdgConfigPath = path.join(xdgDir, "configstore", "firebase-appcheck.json"); + + saveLocalToken(iosAppId, token1, resourceName1); + saveLocalToken(webAppId, token2); + + expect(fs.existsSync(getLocalConfigPath())).to.be.true; + expect(fs.existsSync(xdgConfigPath)).to.be.true; + + const canonicalJson = JSON.parse(fs.readFileSync(getLocalConfigPath(), "utf8")) as Record< + string, + unknown + >; + const xdgJson = JSON.parse(fs.readFileSync(xdgConfigPath, "utf8")) as Record; + expect(canonicalJson).to.deep.equal(xdgJson); + + removeLocalTokens([iosAppId]); + + const updatedXdgJson = JSON.parse(fs.readFileSync(xdgConfigPath, "utf8")) as Record< + string, + unknown + >; + expect(updatedXdgJson).to.deep.equal({ + _comment: EXPECTED_COMMENT, + tokens: { + [webAppId]: token2, + }, + }); + }); + + it("ignores relative XDG_CONFIG_HOME paths so secrets are never written into cwd", () => { + const repoCwd = path.join(tempRoot, "project-repo"); + fs.ensureDirSync(repoCwd); + const originalCwd = process.cwd(); + process.chdir(repoCwd); + try { + process.env.XDG_CONFIG_HOME = ".config"; + saveLocalToken(iosAppId, token1); + + expect(fs.existsSync(getLocalConfigPath())).to.be.true; + expect(fs.existsSync(path.join(repoCwd, ".config"))).to.be.false; + } finally { + process.chdir(originalCwd); + } + }); + + it("throws FirebaseError without wiping file on invalid JSON instead of truncating to 0 bytes", () => { + const configPath = getLocalConfigPath(); + fs.ensureDirSync(path.dirname(configPath)); + const corruptContent = `{"tokens": {"${iosAppId}": "${token1}",}}`; + fs.writeFileSync(configPath, corruptContent, "utf8"); + + expect(() => getAllLocalTokens()).to.throw( + FirebaseError, + /Failed to parse local App Check config/, + ); + expect(() => saveLocalToken(webAppId, token2)).to.throw( + FirebaseError, + /Failed to parse local App Check config/, + ); + // File on disk must remain intact for user recovery, never wiped to 0 bytes. + expect(fs.readFileSync(configPath, "utf8")).to.equal(corruptContent); + }); + + it("handles 0-byte or whitespace-only config files gracefully and enforces 0o600 permissions on write", () => { + const configPath = getLocalConfigPath(); + fs.ensureDirSync(path.dirname(configPath)); + fs.writeFileSync(configPath, " \n", { encoding: "utf8", mode: 0o644 }); + + expect(getAllLocalTokens()).to.deep.equal({}); + + saveLocalToken(iosAppId, token1); + expect(getLocalToken(iosAppId)).to.equal(token1); + if (process.platform !== "win32") { + expect(fs.statSync(configPath).mode & 0o777).to.equal(0o600); + } + }); + + it("guards against Object.prototype keys in lookups and malformed config files", () => { + const configPath = getLocalConfigPath(); + fs.ensureDirSync(path.dirname(configPath)); + fs.writeFileSync( + configPath, + `{"_comment":"test","tokens":{"${iosAppId}":"${token1}","__proto__":"polluted","constructor":"bad","invalidNum":123,"empty":""}}`, + "utf8", + ); + + expect(getAllLocalTokens()).to.deep.equal({ + [iosAppId]: token1, + }); + expect(getLocalToken("toString")).to.be.undefined; + expect(getLocalToken("constructor")).to.be.undefined; + expect(getLocalToken("__proto__")).to.be.undefined; + expect(() => saveLocalToken("__proto__", token1)).to.throw( + FirebaseError, + /Invalid Firebase App ID/, + ); + }); +}); diff --git a/src/appcheck/localConfig.ts b/src/appcheck/localConfig.ts new file mode 100644 index 00000000000..6a75059b144 --- /dev/null +++ b/src/appcheck/localConfig.ts @@ -0,0 +1,253 @@ +import * as Configstore from "configstore"; +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; + +import { FirebaseError, getErrMsg, isObject } from "../error"; + +const CONFIGSTORE_ID = "firebase-appcheck"; +const WARNING_COMMENT = + "This file contains secrets and should not be committed to source repositories"; +const FORBIDDEN_KEYS: ReadonlySet = new Set(["__proto__", "constructor", "prototype"]); +const MANAGED_TOP_LEVEL_KEYS: ReadonlySet = new Set(["_comment", "tokens", "tokenNames"]); + +interface ParsedLocalConfig { + tokens: Record; + tokenNames: Record; + extraFields: Record; +} + +function getCanonicalConfigDir(): string { + return path.join(os.homedir(), ".config"); +} + +function areSameDirectory(dirA: string, dirB: string): boolean { + const resolvedA = path.resolve(dirA); + const resolvedB = path.resolve(dirB); + const caseInsensitive = process.platform === "win32" || process.platform === "darwin"; + if ( + caseInsensitive ? resolvedA.toLowerCase() === resolvedB.toLowerCase() : resolvedA === resolvedB + ) { + return true; + } + try { + if (fs.existsSync(resolvedA) && fs.existsSync(resolvedB)) { + return fs.realpathSync(resolvedA) === fs.realpathSync(resolvedB); + } + } catch { + // Ignore transient filesystem errors when probing realpath equivalence. + } + return false; +} + +function getConfigStorePaths(): string[] { + const canonicalDir = getCanonicalConfigDir(); + const canonicalPath = path.join(canonicalDir, "configstore", `${CONFIGSTORE_ID}.json`); + const xdgConfigHome = process.env.XDG_CONFIG_HOME?.trim(); + // Per the XDG Base Directory Specification, relative paths in XDG_CONFIG_HOME + // must be ignored so secrets are never written into the current working directory. + if ( + xdgConfigHome && + path.isAbsolute(xdgConfigHome) && + !areSameDirectory(xdgConfigHome, canonicalDir) + ) { + const xdgPath = path.join(xdgConfigHome, "configstore", `${CONFIGSTORE_ID}.json`); + return [canonicalPath, xdgPath]; + } + return [canonicalPath]; +} + +function extractStringRecord(raw: unknown): Record { + if (!isObject(raw) || Array.isArray(raw)) { + return {}; + } + const result: Record = {}; + for (const [key, value] of Object.entries(raw)) { + if (FORBIDDEN_KEYS.has(key)) { + continue; + } + if (typeof value === "string" && value.length > 0) { + result[key] = value; + } + } + return result; +} + +/** + * Reads and parses a config file directly rather than via `Configstore.all`, + * because `Configstore`'s getter overwrites files with 0 bytes on JSON `SyntaxError`. + */ +function readConfigFile(configPath: string): Record | undefined { + let content: string; + try { + content = fs.readFileSync(configPath, "utf8"); + } catch (err: unknown) { + if ((err as NodeJS.ErrnoException)?.code === "ENOENT") { + return undefined; + } + throw new FirebaseError( + `Failed to read local App Check config at ${configPath}: ${getErrMsg(err)}`, + { exit: 1, original: err instanceof Error ? err : undefined }, + ); + } + + if (!content.trim()) { + return undefined; + } + + let parsed: unknown; + try { + parsed = JSON.parse(content); + } catch (err: unknown) { + throw new FirebaseError( + `Failed to parse local App Check config at ${configPath}: ${getErrMsg(err)}. Fix or delete the file and try again.`, + { exit: 1, original: err instanceof Error ? err : undefined }, + ); + } + + if (!isObject(parsed) || Array.isArray(parsed)) { + throw new FirebaseError( + `Invalid local App Check config at ${configPath}: expected a top-level JSON object.`, + { exit: 1 }, + ); + } + return parsed; +} + +function readMergedConfig(): ParsedLocalConfig { + const tokens: Record = {}; + const tokenNames: Record = {}; + const extraFields: Record = {}; + const paths = getConfigStorePaths(); + + // `~/.config` is the primary location that SDKs and build plugins read (the iOS Simulator via + // SIMULATOR_HOST_HOME, Gradle via user.home), and `$XDG_CONFIG_HOME` is a mirror of it. Read in + // reverse order so the primary `~/.config` copy wins if the two files diverge. + for (let i = paths.length - 1; i >= 0; i--) { + const raw = readConfigFile(paths[i]); + if (!raw) { + continue; + } + for (const [key, value] of Object.entries(raw)) { + if (!MANAGED_TOP_LEVEL_KEYS.has(key) && !FORBIDDEN_KEYS.has(key)) { + extraFields[key] = value; + } + } + Object.assign(tokens, extractStringRecord(raw.tokens)); + Object.assign(tokenNames, extractStringRecord(raw.tokenNames)); + } + + for (const appId of Object.keys(tokenNames)) { + if (!Object.prototype.hasOwnProperty.call(tokens, appId)) { + delete tokenNames[appId]; + } + } + + return { tokens, tokenNames, extraFields }; +} + +function writeLocalConfig(config: ParsedLocalConfig): void { + const payload: Record = { + ...config.extraFields, + _comment: WARNING_COMMENT, + tokens: config.tokens, + }; + if (Object.keys(config.tokenNames).length > 0) { + payload.tokenNames = config.tokenNames; + } + + for (const configPath of getConfigStorePaths()) { + const store = new Configstore(CONFIGSTORE_ID, undefined, { configPath }); + store.all = payload; + try { + fs.chmodSync(configPath, 0o600); + } catch { + // Ignore on filesystems/platforms that do not support POSIX file modes. + } + } +} + +/** + * Returns the canonical path to `~/.config/configstore/firebase-appcheck.json`. + */ +export function getLocalConfigPath(): string { + return path.join(getCanonicalConfigDir(), "configstore", `${CONFIGSTORE_ID}.json`); +} + +/** + * Reads all App Check debug tokens stored locally on this machine. + */ +export function getAllLocalTokens(): Record { + return readMergedConfig().tokens; +} + +/** + * Reads all server DebugToken resource names recorded for locally stored App IDs. + */ +export function getAllLocalTokenNames(): Record { + return readMergedConfig().tokenNames; +} + +/** + * Returns the locally stored debug token for `appId`, or `undefined` if not present. + */ +export function getLocalToken(appId: string): string | undefined { + if (FORBIDDEN_KEYS.has(appId)) { + return undefined; + } + const tokens = getAllLocalTokens(); + return Object.prototype.hasOwnProperty.call(tokens, appId) ? tokens[appId] : undefined; +} + +/** + * Returns the recorded server DebugToken resource name for `appId`, or `undefined` if not recorded. + */ +export function getLocalTokenName(appId: string): string | undefined { + if (FORBIDDEN_KEYS.has(appId)) { + return undefined; + } + const tokenNames = getAllLocalTokenNames(); + return Object.prototype.hasOwnProperty.call(tokenNames, appId) ? tokenNames[appId] : undefined; +} + +/** + * Saves an App Check debug token (and optional server resource name) for `appId` + * to the local machine config, mirroring to `$XDG_CONFIG_HOME` when distinct from `~/.config`. + */ +export function saveLocalToken(appId: string, token: string, resourceName?: string): void { + if (!appId || FORBIDDEN_KEYS.has(appId)) { + throw new FirebaseError(`Invalid Firebase App ID "${appId}".`, { exit: 1 }); + } + const config = readMergedConfig(); + config.tokens[appId] = token; + if (resourceName) { + config.tokenNames[appId] = resourceName; + } else { + delete config.tokenNames[appId]; + } + writeLocalConfig(config); +} + +/** + * Removes locally stored debug tokens (and any recorded resource names) for the specified `appIds`. + */ +export function removeLocalTokens(appIds: readonly string[]): void { + if (appIds.length === 0) { + return; + } + const config = readMergedConfig(); + let modified = false; + for (const appId of appIds) { + if (FORBIDDEN_KEYS.has(appId)) { + continue; + } + if (Object.prototype.hasOwnProperty.call(config.tokens, appId)) { + delete config.tokens[appId]; + delete config.tokenNames[appId]; + modified = true; + } + } + if (modified) { + writeLocalConfig(config); + } +} diff --git a/src/appcheck/types.ts b/src/appcheck/types.ts index b537f1d4829..762dd0cd9c0 100644 --- a/src/appcheck/types.ts +++ b/src/appcheck/types.ts @@ -15,6 +15,7 @@ export interface ListDebugTokensResponse { export interface AppCheckDebugOptions extends Options { app?: string; displayName?: string; + saveLocal?: boolean; } /** How App Check treats requests to a service. */ diff --git a/src/commands/appcheck-debugtokens-create.spec.ts b/src/commands/appcheck-debugtokens-create.spec.ts index 921ca156bed..0ee2a83a9c4 100644 --- a/src/commands/appcheck-debugtokens-create.spec.ts +++ b/src/commands/appcheck-debugtokens-create.spec.ts @@ -1,191 +1,252 @@ import { expect } from "chai"; +import * as fs from "fs-extra"; import * as nock from "nock"; +import * as os from "os"; +import * as path from "path"; import * as sinon from "sinon"; -import { command as createCmd } from "./appcheck-debugtokens-create"; -import { command as listCmd } from "./appcheck-debugtokens-list"; -import { command as deleteCmd } from "./appcheck-debugtokens-delete"; -import * as requireAuthModule from "../requireAuth"; import { appCheckOrigin } from "../api"; +import { getDefaultDisplayName } from "../appcheck/debugTokens"; +import { getLocalToken, getLocalTokenName, saveLocalToken } from "../appcheck/localConfig"; import { DebugToken } from "../appcheck/types"; +import { FirebaseError } from "../error"; +import { logger } from "../logger"; +import * as promptModule from "../prompt"; +import * as requireAuthModule from "../requireAuth"; +import { command as createCmd } from "./appcheck-debugtokens-create"; -describe("appcheck:debugtokens commands", () => { +describe("appcheck:debugtokens:create", () => { + const project = "my-ai-project"; const projectNumber = "1234567890"; const appId = "1:1234567890:ios:0a1b2c3d4e5f6a7b8c9d0e"; + const webAppId = "1:1234567890:web:9f8e7d6c5b4a3f2e1d0c"; const parent = `projects/${projectNumber}/apps/${appId}`; const tokenId = "7890-abcd"; const tokenName = `${parent}/debugTokens/${tokenId}`; const tokenValue = "e3d9b1a0-cf48-4389-8d19-482a177ffec8"; const displayName = "CI Runner Token"; - const dummyToken: DebugToken = { + // Matches real App Check v1 CreateDebugToken wire response, where `token` is cleared/omitted. + const serverResponseToken = { name: tokenName, displayName, - token: tokenValue, updateTime: "2026-07-06T16:20:00Z", }; let sandbox: sinon.SinonSandbox; - let requireAuthStub: sinon.SinonStub; + let tempRoot: string; + let originalXdgConfigHome: string | undefined; beforeEach(() => { sandbox = sinon.createSandbox(); - requireAuthStub = sandbox.stub(requireAuthModule, "requireAuth"); - requireAuthStub.resolves("a@b.com"); - (createCmd as unknown as { befores: unknown[] }).befores = []; - (listCmd as unknown as { befores: unknown[] }).befores = []; - (deleteCmd as unknown as { befores: unknown[] }).befores = []; + originalXdgConfigHome = process.env.XDG_CONFIG_HOME; + delete process.env.XDG_CONFIG_HOME; + tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "firebase-debugtokens-create-test-")); + sandbox.stub(os, "homedir").returns(tempRoot); + sandbox.stub(requireAuthModule, "requireAuth").resolves("a@b.com"); }); afterEach(() => { + if (originalXdgConfigHome === undefined) { + delete process.env.XDG_CONFIG_HOME; + } else { + process.env.XDG_CONFIG_HOME = originalXdgConfigHome; + } sandbox.restore(); nock.cleanAll(); + fs.removeSync(tempRoot); }); - describe("appcheck:debugtokens:create", () => { - it("should register a debug token when appId and debugToken are passed", async () => { - nock(appCheckOrigin()) - .get(/.*debugTokens.*/) - .reply(200, { debugTokens: [] }); - - nock(appCheckOrigin()) - .post(/.*debugTokens.*/, { - displayName, - token: tokenValue, - }) - .reply(200, dummyToken); - - const options = { - project: "my-ai-project", - projectNumber, + it("registers a debug token, returns the token string, and saves token + resource name locally", async () => { + nock(appCheckOrigin()).get(`/v1/${parent}/debugTokens`).reply(200, { debugTokens: [] }); + + nock(appCheckOrigin()) + .post(`/v1/${parent}/debugTokens`, { displayName, - app: appId, - nonInteractive: true, - }; + token: tokenValue, + }) + .reply(200, serverResponseToken); + + const result = (await createCmd.runner()(tokenValue, { + project, + projectNumber, + displayName, + app: appId, + nonInteractive: true, + })) as string; + + expect(result).to.equal(tokenValue); + expect(getLocalToken(appId)).to.equal(tokenValue); + expect(getLocalTokenName(appId)).to.equal(tokenName); + expect(nock.isDone()).to.be.true; + }); - const result = (await createCmd.runner()(tokenValue, options)) as DebugToken; - expect(result).to.deep.equal(dummyToken); - expect(nock.isDone()).to.be.true; - }); + it("does not save locally or collide with host @ when --no-save-local is passed", async () => { + const hostDisplayName = getDefaultDisplayName(true); + const ciDefaultDisplayName = getDefaultDisplayName(false); + expect(ciDefaultDisplayName).to.not.equal(hostDisplayName); + + const activeLocalToken = "a1b2c3d4-e5f6-4789-89ab-cdef01234567"; + const activeLocalResource = `${parent}/debugTokens/host-id`; + saveLocalToken(appId, activeLocalToken, activeLocalResource); + + // Host machine's active token exists on the server; --no-save-local must NOT delete it! + nock(appCheckOrigin()) + .get(`/v1/${parent}/debugTokens`) + .reply(200, { + debugTokens: [{ name: activeLocalResource, displayName: hostDisplayName }], + }); + + nock(appCheckOrigin()) + .post(`/v1/${parent}/debugTokens`, { + displayName: ciDefaultDisplayName, + token: tokenValue, + }) + .reply(200, { + name: tokenName, + displayName: ciDefaultDisplayName, + }); + + const result = (await createCmd.runner()(tokenValue, { + project, + projectNumber, + app: appId, + saveLocal: false, + force: true, + nonInteractive: true, + })) as string; + + expect(result).to.equal(tokenValue); + expect(getLocalToken(appId)).to.equal(activeLocalToken); + expect(getLocalTokenName(appId)).to.equal(activeLocalResource); + expect(nock.isDone()).to.be.true; + }); - it("should overwrite matching tokens if existing token found", async () => { - const existingToken: DebugToken = { - ...dummyToken, - name: `${parent}/debugTokens/old-id`, - }; - - nock(appCheckOrigin()) - .get(/.*debugTokens.*/) - .reply(200, { debugTokens: [existingToken] }); - - nock(appCheckOrigin()) - .delete(/.*debugTokens\/old-id/) - .reply(200, {}); - - nock(appCheckOrigin()) - .post(/.*debugTokens.*/, { - displayName, - token: tokenValue, - }) - .reply(200, dummyToken); - - const options = { - project: "my-ai-project", + it("validates UUID v4 and displayName length upfront before making any network requests", async () => { + await expect( + createCmd.runner()(appId, { + project, projectNumber, - displayName, app: appId, - force: true, nonInteractive: true, - }; - - const result = (await createCmd.runner()(tokenValue, options)) as DebugToken; - expect(result).to.deep.equal(dummyToken); - }); + }), + ).to.be.rejectedWith(FirebaseError, /Expected a UUID v4 string/); - it("should throw error if nonInteractive is true and force is false when matching token found", async () => { - const existingToken: DebugToken = { - ...dummyToken, - name: `${parent}/debugTokens/old-id`, - }; - - nock(appCheckOrigin()) - .get(/.*debugTokens.*/) - .reply(200, { debugTokens: [existingToken] }); - - const options = { - project: "my-ai-project", + await expect( + createCmd.runner()(tokenValue, { + project, projectNumber, - displayName, app: appId, + displayName: "x".repeat(51), nonInteractive: true, - }; - - await expect(createCmd.runner()(tokenValue, options)).to.be.rejectedWith( - "Must pass --force to overwrite in non-interactive mode.", - ); - }); + }), + ).to.be.rejectedWith(FirebaseError, /maximum length of 50 characters/); }); - describe("appcheck:debugtokens:list", () => { - it("should list debug tokens for an app", async () => { - nock(appCheckOrigin()) - .get(/.*debugTokens.*/) - .reply(200, { debugTokens: [dummyToken] }); + it("logs Web framework env instructions (.env.local and shell env var + self.FIREBASE_APPCHECK_DEBUG_TOKEN) for Web apps", async () => { + const loggerInfoSpy = sandbox.spy(logger, "info"); - const options = { - project: "my-ai-project", - projectNumber, - app: appId, - }; + nock(appCheckOrigin()) + .get(`/v1/projects/${projectNumber}/apps/${webAppId}/debugTokens`) + .reply(200, { debugTokens: [] }); - const result = (await listCmd.runner()(options)) as DebugToken[]; - expect(result).to.deep.equal([dummyToken]); - expect(nock.isDone()).to.be.true; + nock(appCheckOrigin()) + .post(`/v1/projects/${projectNumber}/apps/${webAppId}/debugTokens`, { + displayName, + token: tokenValue, + }) + .reply(200, { + ...serverResponseToken, + name: `projects/${projectNumber}/apps/${webAppId}/debugTokens/${tokenId}`, + }); + + await createCmd.runner()(tokenValue, { + project, + projectNumber, + displayName, + app: webAppId, + nonInteractive: true, }); - }); - - describe("appcheck:debugtokens:delete", () => { - it("should delete debug token with --force flag", async () => { - nock(appCheckOrigin()) - .delete(/.*debugTokens.*/) - .reply(200, {}); - - const options = { - project: "my-ai-project", - projectNumber, - app: appId, - force: true, - }; - await deleteCmd.runner()(tokenId, options); - expect(nock.isDone()).to.be.true; - }); + const loggedText = loggerInfoSpy.args.map((a) => a.join(" ")).join("\n"); + expect(loggedText).to.include(`VITE_FIREBASE_APPCHECK_DEBUG_TOKEN=${tokenValue}`); + expect(loggedText).to.include(`NEXT_PUBLIC_FIREBASE_APPCHECK_DEBUG_TOKEN=${tokenValue}`); + expect(loggedText).to.include(`REACT_APP_FIREBASE_APPCHECK_DEBUG_TOKEN=${tokenValue}`); + expect(loggedText).to.include("shell environment variable"); + expect(loggedText).to.include("self.FIREBASE_APPCHECK_DEBUG_TOKEN"); + expect(loggedText).to.include(".gitignore"); + expect(nock.isDone()).to.be.true; + }); - it("should throw error if full resource name does not match app and project", async () => { - const mismatchedResource = `projects/${projectNumber}/apps/other-app-id/debugTokens/${tokenId}`; - const options = { - project: "my-ai-project", - projectNumber, - app: appId, - force: true, - }; + it("replaces matching tokens when --force is passed and errors in non-interactive mode without --force", async () => { + const existingToken: DebugToken = { + name: `${parent}/debugTokens/old-id`, + displayName, + token: "", + }; - await expect(deleteCmd.runner()(mismatchedResource, options)).to.be.rejectedWith( - "does not belong to app", - ); - }); + nock(appCheckOrigin()) + .get(`/v1/${parent}/debugTokens`) + .reply(200, { debugTokens: [existingToken] }); - it("should throw error in non-interactive mode if --force is missing", async () => { - const options = { - project: "my-ai-project", + await expect( + createCmd.runner()(tokenValue, { + project, projectNumber, + displayName, app: appId, nonInteractive: true, - }; + }), + ).to.be.rejectedWith(FirebaseError, /Must pass --force to overwrite in non-interactive mode/); + expect(nock.isDone()).to.be.true; + + nock(appCheckOrigin()) + .get(`/v1/${parent}/debugTokens`) + .reply(200, { debugTokens: [existingToken] }); + nock(appCheckOrigin()) + .post(`/v1/${parent}/debugTokens`, { displayName, token: tokenValue }) + .reply(200, serverResponseToken); + nock(appCheckOrigin()).delete(`/v1/${parent}/debugTokens/old-id`).reply(200, {}); + + const result = (await createCmd.runner()(tokenValue, { + project, + projectNumber, + displayName, + app: appId, + force: true, + nonInteractive: true, + })) as string; + + expect(result).to.equal(tokenValue); + expect(getLocalToken(appId)).to.equal(tokenValue); + expect(nock.isDone()).to.be.true; + }); - await expect(deleteCmd.runner()(tokenId, options)).to.be.rejectedWith( - "Must pass --force to delete in non-interactive mode.", - ); - }); + it("supports interactive SDK token and display name prompts", async () => { + sandbox.stub(promptModule, "select").resolves("sdk"); + sandbox.stub(promptModule, "password").resolves(` ${tokenValue} `); + sandbox.stub(promptModule, "input").resolves(" Interactive Token "); + + nock(appCheckOrigin()).get(`/v1/${parent}/debugTokens`).reply(200, { debugTokens: [] }); + + nock(appCheckOrigin()) + .post(`/v1/${parent}/debugTokens`, { + displayName: "Interactive Token", + token: tokenValue, + }) + .reply(200, { + name: tokenName, + displayName: "Interactive Token", + }); + + const result = (await createCmd.runner()(undefined, { + project, + projectNumber, + app: appId, + interactive: true, + })) as string; + + expect(result).to.equal(tokenValue); + expect(nock.isDone()).to.be.true; }); }); diff --git a/src/commands/appcheck-debugtokens-create.ts b/src/commands/appcheck-debugtokens-create.ts index c36c4f37baa..2669a376408 100644 --- a/src/commands/appcheck-debugtokens-create.ts +++ b/src/commands/appcheck-debugtokens-create.ts @@ -16,11 +16,21 @@ import * as clc from "colorette"; import { randomUUID } from "node:crypto"; -import * as os from "os"; import { Command } from "../command"; import { needProjectNumber } from "../projectUtils"; -import { createDebugToken, listDebugTokens, deleteDebugToken } from "../appcheck/api"; +import { listDebugTokens } from "../appcheck/api"; +import { + ensureCanCreateOrOverwriteDebugToken, + getDebugTokenValidationError, + getDefaultDisplayName, + getDisplayNameValidationError, + isWebAppId, + provisionDebugToken, + validateDebugTokenUuid, + validateDisplayName, +} from "../appcheck/debugTokens"; +import { getLocalConfigPath } from "../appcheck/localConfig"; import { DebugToken, AppCheckDebugOptions } from "../appcheck/types"; import { getOrPromptProjectAndAppId } from "./appcheck-prompts"; import { requireAuth } from "../requireAuth"; @@ -31,25 +41,32 @@ import { logger } from "../logger"; export const command = new 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 ", "the app id of your Firebase app") - .option("--display-name ", "display name for the debug token") - .option( - "--force", - "overwrite existing debug token if it has the same display name without prompting", + .option("--display-name ", "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(requireAuth) + .before((options: AppCheckDebugOptions) => requireAuth(options)) .action( - async ( - debugToken: string | undefined, - options: AppCheckDebugOptions, - ): Promise => { - const { appId } = await getOrPromptProjectAndAppId(options); + async (debugToken: string | undefined, options: AppCheckDebugOptions): Promise => { + const validatedTokenArg = + debugToken !== undefined ? validateDebugTokenUuid(debugToken) : undefined; + const validatedDisplayNameOpt = + options.displayName !== undefined ? validateDisplayName(options.displayName) : undefined; + const saveLocal = options.saveLocal !== false; + const { appId } = await getOrPromptProjectAndAppId(options); const projectNumber = await needProjectNumber(options); - let token = debugToken; + let token = validatedTokenArg; if (!token) { - if (!options.nonInteractive) { + if (!options.nonInteractive && !options.force) { const action = await select({ message: "Would you like to register a token generated by the SDK, or create a new one?", @@ -59,10 +76,11 @@ export const command = new Command("appcheck:debugtokens:create [debugToken]") ], }); if (action === "sdk") { - token = await password({ + const entered = await password({ message: "Enter the debug token generated by the SDK:", - validate: (val) => (val.trim().length > 0 ? true : "Debug token cannot be empty."), + validate: (val) => getDebugTokenValidationError(val) ?? true, }); + token = validateDebugTokenUuid(entered); } else { token = randomUUID(); } @@ -71,14 +89,16 @@ export const command = new Command("appcheck:debugtokens:create [debugToken]") } } - let displayName = options.displayName; - const defaultName = `CLI Debug Token (${os.hostname() || "Unknown Host"})`; + let displayName = validatedDisplayNameOpt; if (!displayName) { - if (!options.nonInteractive) { - displayName = await input({ + const defaultName = getDefaultDisplayName(saveLocal); + if (!options.nonInteractive && !options.force) { + const entered = await input({ message: "What would you like to call this debug token?", default: defaultName, + validate: (val) => getDisplayNameValidationError(val) ?? true, }); + displayName = validateDisplayName(entered); } else { displayName = defaultName; } @@ -86,53 +106,70 @@ export const command = new Command("appcheck:debugtokens:create [debugToken]") const existingTokens = await listDebugTokens(projectNumber, appId); const matchingTokens = existingTokens.filter((t) => t.displayName === displayName); + ensureCanCreateOrOverwriteDebugToken({ appId, existingTokens, matchingTokens }); - if (matchingTokens.length > 0) { - let shouldOverwrite = options.force; - if (!shouldOverwrite) { - if (options.nonInteractive) { - throw new FirebaseError( - `A token with the display name "${displayName}" already exists. Must pass --force to overwrite in non-interactive mode.`, - { exit: 1 }, - ); - } - shouldOverwrite = await confirm({ - message: `A token with the display name "${displayName}" already exists. Delete the old token(s)?`, - default: true, - }); + if (matchingTokens.length > 0 && !options.force) { + if (options.nonInteractive) { + throw new FirebaseError( + `A token with the display name "${displayName}" already exists. Must pass --force to overwrite in non-interactive mode.`, + { exit: 1 }, + ); } - if (shouldOverwrite) { - for (const t of matchingTokens) { - await deleteDebugToken(t.name); - } - } else { + const shouldOverwrite = await confirm({ + message: `A token with the display name "${displayName}" already exists. Replace the existing token(s)?`, + default: true, + }); + if (!shouldOverwrite) { throw new FirebaseError("Registration canceled.", { exit: 1 }); } } const result = await promiseWithSpinner( - async () => await createDebugToken(projectNumber, appId, displayName, token), + () => + 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; logSuccess(`Successfully registered App Check debug token: - Display Name: ${clc.bold(result.displayName)} - - Resource Name: ${clc.cyan(result.name)}`); + - Resource Name: ${clc.cyan(result.name)} + - Token: ${clc.bold(clc.green(finalToken))}`); - if (!options.json) { - console.log(` - Token: ${clc.bold(clc.green(token))}\n`); + if (saveLocal) { + logger.info(`Saved debug token to local config: ${clc.bold(getLocalConfigPath())}`); + } + + if (isWebAppId(appId)) { + 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.info( clc.yellow( clc.bold("Warning: ") + - "This debug token is a secret and should not be shared or uploaded to source code.", + "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'.", ), ); - logger.info( - clc.yellow("TODO: Remember to delete this token once your testing has finished."), - ); - return result; + return finalToken; }, );