firebase-tools 15.35.0 → 15.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/lib/appcheck/debugTokens.js +293 -0
  2. package/lib/appcheck/localConfig.js +191 -0
  3. package/lib/appdistribution/options-parser-util.js +1 -1
  4. package/lib/apphosting/githubConnections.js +1 -1
  5. package/lib/auth.js +8 -2
  6. package/lib/commands/appcheck-debugtokens-create.js +60 -35
  7. package/lib/commands/appcheck-debugtokens-delete.js +21 -7
  8. package/lib/commands/appcheck-debugtokens-list.js +37 -8
  9. package/lib/commands/appcheck-debugtokens-prune.js +59 -0
  10. package/lib/commands/crashlytics-heapdumps-status.js +1 -1
  11. package/lib/commands/deploy.js +1 -3
  12. package/lib/commands/hosting-channel-create.js +1 -3
  13. package/lib/commands/hosting-channel-delete.js +1 -3
  14. package/lib/commands/hosting-channel-deploy.js +1 -3
  15. package/lib/commands/hosting-channel-list.js +1 -3
  16. package/lib/commands/hosting-channel-open.js +1 -3
  17. package/lib/commands/hosting-clone.js +3 -5
  18. package/lib/commands/hosting-disable.js +2 -2
  19. package/lib/commands/hosting-sites-create.js +1 -3
  20. package/lib/commands/hosting-sites-delete.js +1 -3
  21. package/lib/commands/hosting-sites-get.js +1 -3
  22. package/lib/commands/hosting-sites-list.js +1 -3
  23. package/lib/commands/index.js +1 -0
  24. package/lib/crashlytics/events.js +122 -1
  25. package/lib/crashlytics/filters.js +12 -6
  26. package/lib/crashlytics/profilingManager.js +14 -34
  27. package/lib/crashlytics/utils.js +14 -0
  28. package/lib/database/import.js +5 -4
  29. package/lib/dataconnect/names.js +3 -3
  30. package/lib/dataconnect/schemaMigration.js +1 -1
  31. package/lib/deploy/functions/backend.js +0 -10
  32. package/lib/deploy/functions/cel.js +1 -1
  33. package/lib/deploy/functions/release/reporter.js +0 -26
  34. package/lib/deploy/functions/runtimes/discovery/index.js +4 -1
  35. package/lib/deploy/functions/runtimes/discovery/v1alpha1.js +1 -1
  36. package/lib/deploy/functions/services/index.js +13 -11
  37. package/lib/deploy/hosting/prepare.js +1 -3
  38. package/lib/deploy/lifecycleHooks.js +1 -1
  39. package/lib/emulator/auth/operations.js +2 -2
  40. package/lib/emulator/auth/server.js +4 -2
  41. package/lib/emulator/auth/widget_ui.js +1 -1
  42. package/lib/emulator/commandUtils.js +4 -1
  43. package/lib/emulator/databaseEmulator.js +16 -11
  44. package/lib/emulator/dataconnect/pgliteServer.js +30 -24
  45. package/lib/emulator/downloadableEmulatorInfo.json +24 -24
  46. package/lib/emulator/downloadableEmulators.js +2 -2
  47. package/lib/emulator/extensions/postinstall.js +6 -6
  48. package/lib/emulator/firestoreEmulator.js +21 -15
  49. package/lib/emulator/functionsEmulator.js +11 -7
  50. package/lib/emulator/functionsEmulatorRuntime.js +7 -2
  51. package/lib/emulator/hub.js +12 -8
  52. package/lib/emulator/shared/express.js +30 -0
  53. package/lib/emulator/storage/apis/firebase.js +11 -10
  54. package/lib/emulator/storage/apis/gcloud.js +21 -20
  55. package/lib/emulator/storage/files.js +1 -1
  56. package/lib/emulator/storage/rules/manager.js +15 -12
  57. package/lib/emulator/storage/server.js +10 -5
  58. package/lib/extensions/extensionsHelper.js +2 -2
  59. package/lib/extensions/paramHelper.js +1 -1
  60. package/lib/extensions/provisioningHelper.js +1 -6
  61. package/lib/firestore/util.js +3 -3
  62. package/lib/frameworks/angular/utils.js +1 -1
  63. package/lib/frameworks/next/utils.js +1 -1
  64. package/lib/functions/kits/install.js +221 -316
  65. package/lib/functions/kits/sources/directory.js +32 -0
  66. package/lib/functions/kits/sources/npm.js +55 -5
  67. package/lib/functionsConfig.js +0 -4
  68. package/lib/functionsShellCommandAction.js +1 -1
  69. package/lib/gcp/cloudfunctionsv2.js +0 -6
  70. package/lib/gcp/devConnect.js +2 -2
  71. package/lib/hosting/api.js +79 -0
  72. package/lib/hosting/proxy.js +4 -1
  73. package/lib/init/features/hosting/github.js +6 -4
  74. package/lib/init/features/hosting/index.js +4 -0
  75. package/lib/mcp/apps/init/mcp-app.js +4 -1
  76. package/lib/mcp/index.js +8 -2
  77. package/lib/mcp/prompts/apptesting/run_test.js +3 -3
  78. package/lib/mcp/prompts/core/deploy.js +3 -3
  79. package/lib/mcp/resources/guides/init_ai.js +10 -10
  80. package/lib/mcp/tools/crashlytics/events.js +18 -93
  81. package/lib/mcp/tools/crashlytics/index.js +2 -0
  82. package/lib/mcp/tools/crashlytics/reports.js +1 -1
  83. package/lib/mcp/tools/crashlytics/setup.js +392 -0
  84. package/lib/tsconfig.compile.tsbuildinfo +1 -1
  85. package/lib/tsconfig.publish.tsbuildinfo +1 -1
  86. package/lib/utils.js +4 -10
  87. package/package.json +1 -1
  88. package/lib/functions/kits/sources/index.js +0 -19
@@ -0,0 +1,293 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getDebugTokenValidationError = getDebugTokenValidationError;
4
+ exports.validateDebugTokenUuid = validateDebugTokenUuid;
5
+ exports.getDisplayNameValidationError = getDisplayNameValidationError;
6
+ exports.validateDisplayName = validateDisplayName;
7
+ exports.getDefaultDisplayName = getDefaultDisplayName;
8
+ exports.isWebAppId = isWebAppId;
9
+ exports.formatLocalTokenStatus = formatLocalTokenStatus;
10
+ exports.ensureCanCreateOrOverwriteDebugToken = ensureCanCreateOrOverwriteDebugToken;
11
+ exports.provisionDebugToken = provisionDebugToken;
12
+ exports.inspectLocalDebugTokens = inspectLocalDebugTokens;
13
+ exports.findStaleLocalDebugTokens = findStaleLocalDebugTokens;
14
+ exports.deleteDebugTokenAndCleanLocal = deleteDebugTokenAndCleanLocal;
15
+ const clc = require("colorette");
16
+ const os = require("os");
17
+ const error_1 = require("../error");
18
+ const logger_1 = require("../logger");
19
+ const apps_1 = require("../management/apps");
20
+ const projectUtils_1 = require("../projectUtils");
21
+ const requireAuth_1 = require("../requireAuth");
22
+ const utils_1 = require("../utils");
23
+ const api_1 = require("./api");
24
+ const localConfig_1 = require("./localConfig");
25
+ const MAX_DEBUG_TOKENS_PER_APP = 20;
26
+ const MAX_DISPLAY_NAME_LENGTH = 50;
27
+ const MASK_PREFIX_LENGTH = 8;
28
+ 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;
29
+ const GMP_APP_ID_PROJECT_NUMBER_REGEX = /^\d+:(\d+):/;
30
+ function extractProjectNumberFromAppId(appId) {
31
+ const match = GMP_APP_ID_PROJECT_NUMBER_REGEX.exec(appId);
32
+ return match ? match[1] : undefined;
33
+ }
34
+ function maskDebugToken(token) {
35
+ if (token.length <= MASK_PREFIX_LENGTH) {
36
+ return "********";
37
+ }
38
+ const prefix = token.slice(0, MASK_PREFIX_LENGTH);
39
+ return token[MASK_PREFIX_LENGTH] === "-" ? `${prefix}-...` : `${prefix}...`;
40
+ }
41
+ async function deleteServerTokensIgnoringNotFound(tokens) {
42
+ for (const existing of tokens) {
43
+ try {
44
+ await (0, api_1.deleteDebugToken)(existing.name);
45
+ }
46
+ catch (err) {
47
+ if ((0, error_1.getErrStatus)(err) !== 404) {
48
+ throw err;
49
+ }
50
+ }
51
+ }
52
+ }
53
+ async function checkAppServerTokenStatus(projectNumber, appId, recordedResourceName) {
54
+ let serverTokens;
55
+ try {
56
+ serverTokens = await (0, api_1.listDebugTokens)(projectNumber, appId);
57
+ }
58
+ catch (err) {
59
+ const status = (0, error_1.getErrStatus)(err);
60
+ if (status === 404 || status === 409) {
61
+ return "APP_DELETED";
62
+ }
63
+ throw err;
64
+ }
65
+ if (serverTokens.length === 0) {
66
+ return "REVOKED";
67
+ }
68
+ if (recordedResourceName) {
69
+ return serverTokens.some((t) => t.name === recordedResourceName) ? "ACTIVE" : "REVOKED";
70
+ }
71
+ return "UNCHECKED";
72
+ }
73
+ async function resolveProjectTokenStatuses(params) {
74
+ const { projectId, projectNumber, candidateAppIds, tokenNames } = params;
75
+ const statuses = {};
76
+ if (candidateAppIds.length === 0) {
77
+ return statuses;
78
+ }
79
+ const apps = await (0, apps_1.listFirebaseApps)(projectId, apps_1.AppPlatform.ANY);
80
+ const activeProjectAppIds = new Set(apps.map((app) => app.appId));
81
+ await Promise.all(candidateAppIds.map(async (appId) => {
82
+ if (!activeProjectAppIds.has(appId)) {
83
+ statuses[appId] = "APP_DELETED";
84
+ return;
85
+ }
86
+ try {
87
+ statuses[appId] = await checkAppServerTokenStatus(projectNumber, appId, tokenNames[appId]);
88
+ }
89
+ catch (err) {
90
+ logger_1.logger.debug(`Failed to check server token status for app ${appId}: ${(0, error_1.getErrMsg)(err)}`);
91
+ statuses[appId] = "UNCHECKED";
92
+ }
93
+ }));
94
+ return statuses;
95
+ }
96
+ function buildLocalTokenEntry(params) {
97
+ const { appId, token, status, resourceName } = params;
98
+ const entry = {
99
+ appId,
100
+ tokenPrefix: maskDebugToken(token),
101
+ status,
102
+ };
103
+ if (resourceName) {
104
+ entry.name = resourceName;
105
+ }
106
+ return entry;
107
+ }
108
+ function getDebugTokenValidationError(raw) {
109
+ const trimmed = raw.trim();
110
+ if (!trimmed) {
111
+ return "Debug token cannot be empty.";
112
+ }
113
+ if (!UUID_V4_REGEX.test(trimmed)) {
114
+ return (`Invalid debug token "${trimmed}". Expected a UUID v4 string ` +
115
+ `(for example, xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx). To specify a Firebase App ID, pass --app <appId>.`);
116
+ }
117
+ return undefined;
118
+ }
119
+ function validateDebugTokenUuid(raw) {
120
+ const error = getDebugTokenValidationError(raw);
121
+ if (error) {
122
+ throw new error_1.FirebaseError(error, { exit: 1 });
123
+ }
124
+ return raw.trim();
125
+ }
126
+ function getDisplayNameValidationError(raw) {
127
+ const trimmed = raw.trim();
128
+ if (!trimmed) {
129
+ return "Display name cannot be empty.";
130
+ }
131
+ if (trimmed.length > MAX_DISPLAY_NAME_LENGTH) {
132
+ return (`Display name "${trimmed}" exceeds the maximum length of ${MAX_DISPLAY_NAME_LENGTH} characters ` +
133
+ `(got ${trimmed.length}). Pass a shorter --display-name.`);
134
+ }
135
+ return undefined;
136
+ }
137
+ function validateDisplayName(raw) {
138
+ const error = getDisplayNameValidationError(raw);
139
+ if (error) {
140
+ throw new error_1.FirebaseError(error, { exit: 1 });
141
+ }
142
+ return raw.trim();
143
+ }
144
+ function getDefaultDisplayName(saveLocal = true) {
145
+ const fullHost = os.hostname() || "unknown-host";
146
+ const shortHost = fullHost.split(".")[0] || fullHost;
147
+ if (!saveLocal) {
148
+ return `CLI Debug Token (${shortHost})`.slice(0, MAX_DISPLAY_NAME_LENGTH);
149
+ }
150
+ let username = "user";
151
+ try {
152
+ const info = os.userInfo();
153
+ if (info.username) {
154
+ username = info.username;
155
+ }
156
+ }
157
+ catch {
158
+ }
159
+ const fullCandidate = `${username}@${fullHost}`;
160
+ if (fullCandidate.length <= MAX_DISPLAY_NAME_LENGTH) {
161
+ return fullCandidate;
162
+ }
163
+ return `${username}@${shortHost}`.slice(0, MAX_DISPLAY_NAME_LENGTH);
164
+ }
165
+ function isWebAppId(appId) {
166
+ return appId.toLowerCase().includes(":web:");
167
+ }
168
+ function formatLocalTokenStatus(status) {
169
+ switch (status) {
170
+ case "ACTIVE":
171
+ return clc.green("Active");
172
+ case "REVOKED":
173
+ return clc.yellow("Revoked");
174
+ case "APP_DELETED":
175
+ return clc.red("App Deleted");
176
+ case "UNCHECKED":
177
+ return clc.gray("Unchecked");
178
+ }
179
+ }
180
+ function ensureCanCreateOrOverwriteDebugToken(params) {
181
+ const { appId, existingTokens, matchingTokens } = params;
182
+ if (matchingTokens.length === 0 && existingTokens.length >= MAX_DEBUG_TOKENS_PER_APP) {
183
+ throw new error_1.FirebaseError(`App ${appId} already has the maximum of ${MAX_DEBUG_TOKENS_PER_APP} debug tokens. ` +
184
+ `View existing tokens with "firebase appcheck:debugtokens:list --app ${appId}" and ` +
185
+ `revoke unused tokens with "firebase appcheck:debugtokens:delete <debugTokenId>".`, { exit: 1 });
186
+ }
187
+ }
188
+ async function provisionDebugToken(params) {
189
+ const { projectNumber, appId, displayName, token, existingTokens, matchingTokens, saveLocal } = params;
190
+ ensureCanCreateOrOverwriteDebugToken({ appId, existingTokens, matchingTokens });
191
+ const mustDeleteBeforeCreate = matchingTokens.length > 0 && existingTokens.length >= MAX_DEBUG_TOKENS_PER_APP;
192
+ if (mustDeleteBeforeCreate) {
193
+ await deleteServerTokensIgnoringNotFound(matchingTokens);
194
+ }
195
+ const created = await (0, api_1.createDebugToken)(projectNumber, appId, displayName, token);
196
+ if (matchingTokens.length > 0 && !mustDeleteBeforeCreate) {
197
+ await deleteServerTokensIgnoringNotFound(matchingTokens);
198
+ }
199
+ const finalToken = created.token || token;
200
+ const hydrated = {
201
+ ...created,
202
+ token: finalToken,
203
+ };
204
+ if (saveLocal) {
205
+ (0, localConfig_1.saveLocalToken)(appId, finalToken, hydrated.name);
206
+ }
207
+ return hydrated;
208
+ }
209
+ async function inspectLocalDebugTokens(options) {
210
+ let tokens;
211
+ if (options.app) {
212
+ const single = (0, localConfig_1.getLocalToken)(options.app);
213
+ tokens = single ? { [options.app]: single } : {};
214
+ }
215
+ else {
216
+ tokens = (0, localConfig_1.getAllLocalTokens)();
217
+ }
218
+ const appIds = Object.keys(tokens);
219
+ if (appIds.length === 0) {
220
+ return [];
221
+ }
222
+ const tokenNames = (0, localConfig_1.getAllLocalTokenNames)();
223
+ const statusByAppId = {};
224
+ for (const appId of appIds) {
225
+ statusByAppId[appId] = "UNCHECKED";
226
+ }
227
+ if ((0, projectUtils_1.getProjectId)(options) || options.projectNumber) {
228
+ try {
229
+ await (0, requireAuth_1.requireAuth)(options);
230
+ const projectId = (0, projectUtils_1.needProjectId)(options);
231
+ const projectNumber = await (0, projectUtils_1.needProjectNumber)(options);
232
+ const candidateAppIds = appIds.filter((appId) => extractProjectNumberFromAppId(appId) === projectNumber);
233
+ const resolvedStatuses = await resolveProjectTokenStatuses({
234
+ projectId,
235
+ projectNumber,
236
+ candidateAppIds,
237
+ tokenNames,
238
+ });
239
+ Object.assign(statusByAppId, resolvedStatuses);
240
+ }
241
+ catch (err) {
242
+ logger_1.logger.debug(`Skipping server status check for local App Check debug tokens: ${(0, error_1.getErrMsg)(err)}`);
243
+ }
244
+ }
245
+ return appIds.map((appId) => buildLocalTokenEntry({
246
+ appId,
247
+ token: tokens[appId],
248
+ status: statusByAppId[appId],
249
+ resourceName: tokenNames[appId],
250
+ }));
251
+ }
252
+ async function findStaleLocalDebugTokens(params) {
253
+ const { projectId, projectNumber } = params;
254
+ const tokens = (0, localConfig_1.getAllLocalTokens)();
255
+ const candidateAppIds = Object.keys(tokens).filter((appId) => extractProjectNumberFromAppId(appId) === projectNumber);
256
+ if (candidateAppIds.length === 0) {
257
+ return [];
258
+ }
259
+ const tokenNames = (0, localConfig_1.getAllLocalTokenNames)();
260
+ const statuses = await resolveProjectTokenStatuses({
261
+ projectId,
262
+ projectNumber,
263
+ candidateAppIds,
264
+ tokenNames,
265
+ });
266
+ const stale = [];
267
+ for (const appId of candidateAppIds) {
268
+ const status = statuses[appId];
269
+ if (status === "APP_DELETED" || status === "REVOKED") {
270
+ stale.push(buildLocalTokenEntry({
271
+ appId,
272
+ token: tokens[appId],
273
+ status,
274
+ resourceName: tokenNames[appId],
275
+ }));
276
+ }
277
+ }
278
+ return stale;
279
+ }
280
+ async function deleteDebugTokenAndCleanLocal(params) {
281
+ const { appId, debugTokenName } = params;
282
+ await (0, api_1.deleteDebugToken)(debugTokenName);
283
+ try {
284
+ if ((0, localConfig_1.getLocalTokenName)(appId) === debugTokenName) {
285
+ (0, localConfig_1.removeLocalTokens)([appId]);
286
+ return true;
287
+ }
288
+ }
289
+ catch (err) {
290
+ (0, utils_1.logWarning)(`Deleted server debug token, but failed to clean up local App Check config: ${(0, error_1.getErrMsg)(err)}`);
291
+ }
292
+ return false;
293
+ }
@@ -0,0 +1,191 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getLocalConfigPath = getLocalConfigPath;
4
+ exports.getAllLocalTokens = getAllLocalTokens;
5
+ exports.getAllLocalTokenNames = getAllLocalTokenNames;
6
+ exports.getLocalToken = getLocalToken;
7
+ exports.getLocalTokenName = getLocalTokenName;
8
+ exports.saveLocalToken = saveLocalToken;
9
+ exports.removeLocalTokens = removeLocalTokens;
10
+ const Configstore = require("configstore");
11
+ const fs = require("fs");
12
+ const os = require("os");
13
+ const path = require("path");
14
+ const error_1 = require("../error");
15
+ const CONFIGSTORE_ID = "firebase-appcheck";
16
+ const WARNING_COMMENT = "This file contains secrets and should not be committed to source repositories";
17
+ const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
18
+ const MANAGED_TOP_LEVEL_KEYS = new Set(["_comment", "tokens", "tokenNames"]);
19
+ function getCanonicalConfigDir() {
20
+ return path.join(os.homedir(), ".config");
21
+ }
22
+ function areSameDirectory(dirA, dirB) {
23
+ const resolvedA = path.resolve(dirA);
24
+ const resolvedB = path.resolve(dirB);
25
+ const caseInsensitive = process.platform === "win32" || process.platform === "darwin";
26
+ if (caseInsensitive ? resolvedA.toLowerCase() === resolvedB.toLowerCase() : resolvedA === resolvedB) {
27
+ return true;
28
+ }
29
+ try {
30
+ if (fs.existsSync(resolvedA) && fs.existsSync(resolvedB)) {
31
+ return fs.realpathSync(resolvedA) === fs.realpathSync(resolvedB);
32
+ }
33
+ }
34
+ catch {
35
+ }
36
+ return false;
37
+ }
38
+ function getConfigStorePaths() {
39
+ const canonicalDir = getCanonicalConfigDir();
40
+ const canonicalPath = path.join(canonicalDir, "configstore", `${CONFIGSTORE_ID}.json`);
41
+ const xdgConfigHome = process.env.XDG_CONFIG_HOME?.trim();
42
+ if (xdgConfigHome &&
43
+ path.isAbsolute(xdgConfigHome) &&
44
+ !areSameDirectory(xdgConfigHome, canonicalDir)) {
45
+ const xdgPath = path.join(xdgConfigHome, "configstore", `${CONFIGSTORE_ID}.json`);
46
+ return [canonicalPath, xdgPath];
47
+ }
48
+ return [canonicalPath];
49
+ }
50
+ function extractStringRecord(raw) {
51
+ if (!(0, error_1.isObject)(raw) || Array.isArray(raw)) {
52
+ return {};
53
+ }
54
+ const result = {};
55
+ for (const [key, value] of Object.entries(raw)) {
56
+ if (FORBIDDEN_KEYS.has(key)) {
57
+ continue;
58
+ }
59
+ if (typeof value === "string" && value.length > 0) {
60
+ result[key] = value;
61
+ }
62
+ }
63
+ return result;
64
+ }
65
+ function readConfigFile(configPath) {
66
+ let content;
67
+ try {
68
+ content = fs.readFileSync(configPath, "utf8");
69
+ }
70
+ catch (err) {
71
+ if (err?.code === "ENOENT") {
72
+ return undefined;
73
+ }
74
+ throw new error_1.FirebaseError(`Failed to read local App Check config at ${configPath}: ${(0, error_1.getErrMsg)(err)}`, { exit: 1, original: err instanceof Error ? err : undefined });
75
+ }
76
+ if (!content.trim()) {
77
+ return undefined;
78
+ }
79
+ let parsed;
80
+ try {
81
+ parsed = JSON.parse(content);
82
+ }
83
+ catch (err) {
84
+ throw new error_1.FirebaseError(`Failed to parse local App Check config at ${configPath}: ${(0, error_1.getErrMsg)(err)}. Fix or delete the file and try again.`, { exit: 1, original: err instanceof Error ? err : undefined });
85
+ }
86
+ if (!(0, error_1.isObject)(parsed) || Array.isArray(parsed)) {
87
+ throw new error_1.FirebaseError(`Invalid local App Check config at ${configPath}: expected a top-level JSON object.`, { exit: 1 });
88
+ }
89
+ return parsed;
90
+ }
91
+ function readMergedConfig() {
92
+ const tokens = {};
93
+ const tokenNames = {};
94
+ const extraFields = {};
95
+ const paths = getConfigStorePaths();
96
+ for (let i = paths.length - 1; i >= 0; i--) {
97
+ const raw = readConfigFile(paths[i]);
98
+ if (!raw) {
99
+ continue;
100
+ }
101
+ for (const [key, value] of Object.entries(raw)) {
102
+ if (!MANAGED_TOP_LEVEL_KEYS.has(key) && !FORBIDDEN_KEYS.has(key)) {
103
+ extraFields[key] = value;
104
+ }
105
+ }
106
+ Object.assign(tokens, extractStringRecord(raw.tokens));
107
+ Object.assign(tokenNames, extractStringRecord(raw.tokenNames));
108
+ }
109
+ for (const appId of Object.keys(tokenNames)) {
110
+ if (!Object.prototype.hasOwnProperty.call(tokens, appId)) {
111
+ delete tokenNames[appId];
112
+ }
113
+ }
114
+ return { tokens, tokenNames, extraFields };
115
+ }
116
+ function writeLocalConfig(config) {
117
+ const payload = {
118
+ ...config.extraFields,
119
+ _comment: WARNING_COMMENT,
120
+ tokens: config.tokens,
121
+ };
122
+ if (Object.keys(config.tokenNames).length > 0) {
123
+ payload.tokenNames = config.tokenNames;
124
+ }
125
+ for (const configPath of getConfigStorePaths()) {
126
+ const store = new Configstore(CONFIGSTORE_ID, undefined, { configPath });
127
+ store.all = payload;
128
+ try {
129
+ fs.chmodSync(configPath, 0o600);
130
+ }
131
+ catch {
132
+ }
133
+ }
134
+ }
135
+ function getLocalConfigPath() {
136
+ return path.join(getCanonicalConfigDir(), "configstore", `${CONFIGSTORE_ID}.json`);
137
+ }
138
+ function getAllLocalTokens() {
139
+ return readMergedConfig().tokens;
140
+ }
141
+ function getAllLocalTokenNames() {
142
+ return readMergedConfig().tokenNames;
143
+ }
144
+ function getLocalToken(appId) {
145
+ if (FORBIDDEN_KEYS.has(appId)) {
146
+ return undefined;
147
+ }
148
+ const tokens = getAllLocalTokens();
149
+ return Object.prototype.hasOwnProperty.call(tokens, appId) ? tokens[appId] : undefined;
150
+ }
151
+ function getLocalTokenName(appId) {
152
+ if (FORBIDDEN_KEYS.has(appId)) {
153
+ return undefined;
154
+ }
155
+ const tokenNames = getAllLocalTokenNames();
156
+ return Object.prototype.hasOwnProperty.call(tokenNames, appId) ? tokenNames[appId] : undefined;
157
+ }
158
+ function saveLocalToken(appId, token, resourceName) {
159
+ if (!appId || FORBIDDEN_KEYS.has(appId)) {
160
+ throw new error_1.FirebaseError(`Invalid Firebase App ID "${appId}".`, { exit: 1 });
161
+ }
162
+ const config = readMergedConfig();
163
+ config.tokens[appId] = token;
164
+ if (resourceName) {
165
+ config.tokenNames[appId] = resourceName;
166
+ }
167
+ else {
168
+ delete config.tokenNames[appId];
169
+ }
170
+ writeLocalConfig(config);
171
+ }
172
+ function removeLocalTokens(appIds) {
173
+ if (appIds.length === 0) {
174
+ return;
175
+ }
176
+ const config = readMergedConfig();
177
+ let modified = false;
178
+ for (const appId of appIds) {
179
+ if (FORBIDDEN_KEYS.has(appId)) {
180
+ continue;
181
+ }
182
+ if (Object.prototype.hasOwnProperty.call(config.tokens, appId)) {
183
+ delete config.tokens[appId];
184
+ delete config.tokenNames[appId];
185
+ modified = true;
186
+ }
187
+ }
188
+ if (modified) {
189
+ writeLocalConfig(config);
190
+ }
191
+ }
@@ -138,7 +138,7 @@ function getLoginCredential(args) {
138
138
  function isPresenceMismatched(value1, value2) {
139
139
  return (value1 && !value2) || (!value1 && value2);
140
140
  }
141
- const APP_NAME_REGEX = /^projects\/(?<projectNumber>[^\/]+)\/apps\/(?<appId>[^\/]+)$/;
141
+ const APP_NAME_REGEX = /^projects\/(?<projectNumber>[^/]+)\/apps\/(?<appId>[^/]+)$/;
142
142
  const BUCKET_NAME_FORMAT_REGEX = /^[a-z0-9_.-]+$/;
143
143
  function getResultsBucket(bucket, appName) {
144
144
  if (!bucket) {
@@ -32,7 +32,7 @@ const fuzzy = require("fuzzy");
32
32
  const apiv2_1 = require("../apiv2");
33
33
  const githubApiClient = new apiv2_1.Client({ urlPrefix: (0, api_1.githubApiOrigin)(), auth: false });
34
34
  const APPHOSTING_CONN_PATTERN = /.+\/apphosting-github-conn-.+$/;
35
- const CONNECTION_NAME_REGEX = /^projects\/(?<projectId>[^\/]+)\/locations\/(?<location>[^\/]+)\/connections\/(?<id>[^\/]+)$/;
35
+ const CONNECTION_NAME_REGEX = /^projects\/(?<projectId>[^/]+)\/locations\/(?<location>[^/]+)\/connections\/(?<id>[^/]+)$/;
36
36
  function parseConnectionName(name) {
37
37
  const match = CONNECTION_NAME_REGEX.exec(name);
38
38
  if (!match || typeof match.groups === "undefined") {
package/lib/auth.js CHANGED
@@ -413,7 +413,13 @@ async function loginWithLocalhostGitHub(port) {
413
413
  }
414
414
  async function loginWithLocalhost(port, callbackUrl, authUrl, successHtml, getTokens) {
415
415
  return new Promise((resolve, reject) => {
416
- const server = http.createServer(async (req, res) => {
416
+ const server = http.createServer((req, res) => {
417
+ handleCallback(req, res).catch((err) => {
418
+ reject(err);
419
+ server.close();
420
+ });
421
+ });
422
+ async function handleCallback(req, res) {
417
423
  let searchParams;
418
424
  try {
419
425
  searchParams = new URL(req.url || "", callbackUrl).searchParams;
@@ -442,7 +448,7 @@ async function loginWithLocalhost(port, callbackUrl, authUrl, successHtml, getTo
442
448
  }
443
449
  server.close();
444
450
  return;
445
- });
451
+ }
446
452
  server.listen(port, () => {
447
453
  logger_1.logger.info();
448
454
  logger_1.logger.info("Visit this URL on this device to log in:");
@@ -3,10 +3,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.command = void 0;
4
4
  const clc = require("colorette");
5
5
  const node_crypto_1 = require("node:crypto");
6
- const os = require("os");
7
6
  const command_1 = require("../command");
8
7
  const projectUtils_1 = require("../projectUtils");
9
8
  const api_1 = require("../appcheck/api");
9
+ const debugTokens_1 = require("../appcheck/debugTokens");
10
+ const localConfig_1 = require("../appcheck/localConfig");
10
11
  const appcheck_prompts_1 = require("./appcheck-prompts");
11
12
  const requireAuth_1 = require("../requireAuth");
12
13
  const utils_1 = require("../utils");
@@ -15,16 +16,23 @@ const prompt_1 = require("../prompt");
15
16
  const logger_1 = require("../logger");
16
17
  exports.command = new command_1.Command("appcheck:debugtokens:create [debugToken]")
17
18
  .description("generate and register an App Check debug token for an app")
19
+ .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.
20
+
21
+ 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.`)
18
22
  .option("--app <appId>", "the app id of your Firebase app")
19
- .option("--display-name <displayName>", "display name for the debug token")
20
- .option("--force", "overwrite existing debug token if it has the same display name without prompting")
21
- .before(requireAuth_1.requireAuth)
23
+ .option("--display-name <displayName>", "display name for the debug token (max 50 characters)")
24
+ .option("--no-save-local", "do not save the debug token to the local machine config")
25
+ .withForce("accept default prompts and overwrite any existing debug token with the same display name")
26
+ .before((options) => (0, requireAuth_1.requireAuth)(options))
22
27
  .action(async (debugToken, options) => {
28
+ const validatedTokenArg = debugToken !== undefined ? (0, debugTokens_1.validateDebugTokenUuid)(debugToken) : undefined;
29
+ const validatedDisplayNameOpt = options.displayName !== undefined ? (0, debugTokens_1.validateDisplayName)(options.displayName) : undefined;
30
+ const saveLocal = options.saveLocal !== false;
23
31
  const { appId } = await (0, appcheck_prompts_1.getOrPromptProjectAndAppId)(options);
24
32
  const projectNumber = await (0, projectUtils_1.needProjectNumber)(options);
25
- let token = debugToken;
33
+ let token = validatedTokenArg;
26
34
  if (!token) {
27
- if (!options.nonInteractive) {
35
+ if (!options.nonInteractive && !options.force) {
28
36
  const action = await (0, prompt_1.select)({
29
37
  message: "Would you like to register a token generated by the SDK, or create a new one?",
30
38
  choices: [
@@ -33,10 +41,11 @@ exports.command = new command_1.Command("appcheck:debugtokens:create [debugToken
33
41
  ],
34
42
  });
35
43
  if (action === "sdk") {
36
- token = await (0, prompt_1.password)({
44
+ const entered = await (0, prompt_1.password)({
37
45
  message: "Enter the debug token generated by the SDK:",
38
- validate: (val) => (val.trim().length > 0 ? true : "Debug token cannot be empty."),
46
+ validate: (val) => (0, debugTokens_1.getDebugTokenValidationError)(val) ?? true,
39
47
  });
48
+ token = (0, debugTokens_1.validateDebugTokenUuid)(entered);
40
49
  }
41
50
  else {
42
51
  token = (0, node_crypto_1.randomUUID)();
@@ -46,14 +55,16 @@ exports.command = new command_1.Command("appcheck:debugtokens:create [debugToken
46
55
  token = (0, node_crypto_1.randomUUID)();
47
56
  }
48
57
  }
49
- let displayName = options.displayName;
50
- const defaultName = `CLI Debug Token (${os.hostname() || "Unknown Host"})`;
58
+ let displayName = validatedDisplayNameOpt;
51
59
  if (!displayName) {
52
- if (!options.nonInteractive) {
53
- displayName = await (0, prompt_1.input)({
60
+ const defaultName = (0, debugTokens_1.getDefaultDisplayName)(saveLocal);
61
+ if (!options.nonInteractive && !options.force) {
62
+ const entered = await (0, prompt_1.input)({
54
63
  message: "What would you like to call this debug token?",
55
64
  default: defaultName,
65
+ validate: (val) => (0, debugTokens_1.getDisplayNameValidationError)(val) ?? true,
56
66
  });
67
+ displayName = (0, debugTokens_1.validateDisplayName)(entered);
57
68
  }
58
69
  else {
59
70
  displayName = defaultName;
@@ -61,35 +72,49 @@ exports.command = new command_1.Command("appcheck:debugtokens:create [debugToken
61
72
  }
62
73
  const existingTokens = await (0, api_1.listDebugTokens)(projectNumber, appId);
63
74
  const matchingTokens = existingTokens.filter((t) => t.displayName === displayName);
64
- if (matchingTokens.length > 0) {
65
- let shouldOverwrite = options.force;
66
- if (!shouldOverwrite) {
67
- if (options.nonInteractive) {
68
- 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 });
69
- }
70
- shouldOverwrite = await (0, prompt_1.confirm)({
71
- message: `A token with the display name "${displayName}" already exists. Delete the old token(s)?`,
72
- default: true,
73
- });
74
- }
75
- if (shouldOverwrite) {
76
- for (const t of matchingTokens) {
77
- await (0, api_1.deleteDebugToken)(t.name);
78
- }
75
+ (0, debugTokens_1.ensureCanCreateOrOverwriteDebugToken)({ appId, existingTokens, matchingTokens });
76
+ if (matchingTokens.length > 0 && !options.force) {
77
+ if (options.nonInteractive) {
78
+ 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 });
79
79
  }
80
- else {
80
+ const shouldOverwrite = await (0, prompt_1.confirm)({
81
+ message: `A token with the display name "${displayName}" already exists. Replace the existing token(s)?`,
82
+ default: true,
83
+ });
84
+ if (!shouldOverwrite) {
81
85
  throw new error_1.FirebaseError("Registration canceled.", { exit: 1 });
82
86
  }
83
87
  }
84
- const result = await (0, utils_1.promiseWithSpinner)(async () => await (0, api_1.createDebugToken)(projectNumber, appId, displayName, token), `Registering App Check debug token with Firebase for app ${clc.bold(appId)}`);
88
+ const result = await (0, utils_1.promiseWithSpinner)(() => (0, debugTokens_1.provisionDebugToken)({
89
+ projectNumber,
90
+ appId,
91
+ displayName,
92
+ token,
93
+ existingTokens,
94
+ matchingTokens,
95
+ saveLocal,
96
+ }), `Registering App Check debug token with Firebase for app ${clc.bold(appId)}`);
97
+ const finalToken = result.token || token;
85
98
  (0, utils_1.logSuccess)(`Successfully registered App Check debug token:
86
99
  - Display Name: ${clc.bold(result.displayName)}
87
- - Resource Name: ${clc.cyan(result.name)}`);
88
- if (!options.json) {
89
- console.log(` - Token: ${clc.bold(clc.green(token))}\n`);
100
+ - Resource Name: ${clc.cyan(result.name)}
101
+ - Token: ${clc.bold(clc.green(finalToken))}`);
102
+ if (saveLocal) {
103
+ logger_1.logger.info(`Saved debug token to local config: ${clc.bold((0, localConfig_1.getLocalConfigPath)())}`);
104
+ }
105
+ if ((0, debugTokens_1.isWebAppId)(appId)) {
106
+ logger_1.logger.info(`\nWeb Framework Instructions:\n` +
107
+ `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` +
108
+ ` # Vite\n` +
109
+ ` VITE_FIREBASE_APPCHECK_DEBUG_TOKEN=${finalToken}\n` +
110
+ ` # Next.js\n` +
111
+ ` NEXT_PUBLIC_FIREBASE_APPCHECK_DEBUG_TOKEN=${finalToken}\n` +
112
+ ` # Create React App\n` +
113
+ ` REACT_APP_FIREBASE_APPCHECK_DEBUG_TOKEN=${finalToken}\n` +
114
+ `Assign this variable to ${clc.bold("self.FIREBASE_APPCHECK_DEBUG_TOKEN")} in your app initialization code before initializing App Check.\n` +
115
+ `Ensure ${clc.bold(".env.local")} is in your ${clc.bold(".gitignore")} so debug tokens are never committed.`);
90
116
  }
91
117
  logger_1.logger.info(clc.yellow(clc.bold("Warning: ") +
92
- "This debug token is a secret and should not be shared or uploaded to source code."));
93
- logger_1.logger.info(clc.yellow("TODO: Remember to delete this token once your testing has finished."));
94
- return result;
118
+ "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'."));
119
+ return finalToken;
95
120
  });