firebase-tools 15.34.0 → 15.34.1

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.
package/lib/auth.js CHANGED
@@ -30,7 +30,6 @@ const http = require("http");
30
30
  const jwt = require("jsonwebtoken");
31
31
  const opn = require("open");
32
32
  const portfinder = require("portfinder");
33
- const url = require("url");
34
33
  const apiv2 = require("./apiv2");
35
34
  const configstore_1 = require("./configstore");
36
35
  const error_1 = require("./error");
@@ -415,10 +414,16 @@ async function loginWithLocalhostGitHub(port) {
415
414
  async function loginWithLocalhost(port, callbackUrl, authUrl, successHtml, getTokens) {
416
415
  return new Promise((resolve, reject) => {
417
416
  const server = http.createServer(async (req, res) => {
418
- const query = url.parse(`${req.url}`, true).query || {};
419
- const queryState = query.state;
420
- const queryCode = query.code;
421
- if (queryState !== _nonce || typeof queryCode !== "string") {
417
+ let searchParams;
418
+ try {
419
+ searchParams = new URL(req.url || "", callbackUrl).searchParams;
420
+ }
421
+ catch {
422
+ searchParams = new URLSearchParams();
423
+ }
424
+ const queryState = searchParams.get("state");
425
+ const queryCode = searchParams.get("code");
426
+ if (queryState !== _nonce || !queryCode) {
422
427
  const html = await (0, templates_1.readTemplate)("loginFailure.html");
423
428
  respondHtml(req, res, 400, html);
424
429
  reject(new error_1.FirebaseError("Unexpected error while logging in"));
@@ -16,6 +16,9 @@ const colorette_1 = require("colorette");
16
16
  const interactive_1 = require("../hosting/interactive");
17
17
  const utils_1 = require("../utils");
18
18
  const api_1 = require("../hosting/api");
19
+ const ensureApiEnabled_1 = require("../ensureApiEnabled");
20
+ const api_2 = require("../api");
21
+ const projectUtils_1 = require("../projectUtils");
19
22
  const experiments = require("../experiments");
20
23
  const clc = require("colorette");
21
24
  function getDeployHelp() {
@@ -85,6 +88,7 @@ exports.command
85
88
  await (0, requireDatabaseInstance_1.requireDatabaseInstance)(options);
86
89
  }
87
90
  if (options.filteredTargets.includes("hosting")) {
91
+ await (0, ensureApiEnabled_1.ensure)((0, projectUtils_1.needProjectId)(options), (0, api_2.hostingApiOrigin)(), "hosting", true);
88
92
  let shouldCreateSite = false;
89
93
  try {
90
94
  await (0, requireHostingSite_1.requireHostingSite)(options);
@@ -15,6 +15,8 @@ const requireConfig_1 = require("../requireConfig");
15
15
  const marked_1 = require("marked");
16
16
  const requireHostingSite_1 = require("../requireHostingSite");
17
17
  const getDefaultHostingSite_1 = require("../getDefaultHostingSite");
18
+ const ensureApiEnabled_1 = require("../ensureApiEnabled");
19
+ const api_2 = require("../api");
18
20
  const LOG_TAG = "hosting:channel";
19
21
  exports.command = new command_1.Command("hosting:channel:create [channelId]")
20
22
  .description("create a Firebase Hosting channel")
@@ -22,6 +24,7 @@ exports.command = new command_1.Command("hosting:channel:create [channelId]")
22
24
  .option("--site <siteId>", "site for which to create the channel")
23
25
  .before(requireConfig_1.requireConfig)
24
26
  .before(requirePermissions_1.requirePermissions, ["firebasehosting.sites.update"])
27
+ .before((options) => (0, ensureApiEnabled_1.ensure)((0, projectUtils_1.needProjectId)(options), (0, api_2.hostingApiOrigin)(), "hosting", true))
25
28
  .before(async (options) => {
26
29
  try {
27
30
  await (0, requireHostingSite_1.requireHostingSite)(options);
@@ -12,12 +12,15 @@ const requirePermissions_1 = require("../requirePermissions");
12
12
  const projectUtils_1 = require("../projectUtils");
13
13
  const requireConfig_1 = require("../requireConfig");
14
14
  const logger_1 = require("../logger");
15
+ const ensureApiEnabled_1 = require("../ensureApiEnabled");
16
+ const api_2 = require("../api");
15
17
  exports.command = new command_1.Command("hosting:channel:delete <channelId>")
16
18
  .description("delete a Firebase Hosting channel")
17
19
  .withForce()
18
20
  .option("--site <siteId>", "site in which the channel exists")
19
21
  .before(requireConfig_1.requireConfig)
20
22
  .before(requirePermissions_1.requirePermissions, ["firebasehosting.sites.update"])
23
+ .before((options) => (0, ensureApiEnabled_1.ensure)((0, projectUtils_1.needProjectId)(options), (0, api_2.hostingApiOrigin)(), "hosting", true))
21
24
  .before(requireHostingSite_1.requireHostingSite)
22
25
  .action(async (channelId, options) => {
23
26
  const projectId = (0, projectUtils_1.needProjectId)(options);
@@ -16,6 +16,8 @@ const utils_1 = require("../utils");
16
16
  const config_1 = require("../hosting/config");
17
17
  const marked_1 = require("marked");
18
18
  const requireHostingSite_1 = require("../requireHostingSite");
19
+ const ensureApiEnabled_1 = require("../ensureApiEnabled");
20
+ const api_2 = require("../api");
19
21
  const LOG_TAG = "hosting:channel";
20
22
  exports.command = new command_1.Command("hosting:channel:deploy [channelId]")
21
23
  .description("deploy to a specific Firebase Hosting channel")
@@ -25,6 +27,7 @@ exports.command = new command_1.Command("hosting:channel:deploy [channelId]")
25
27
  .option("--no-authorized-domains", "do not sync channel domains with Firebase Auth")
26
28
  .before(requireConfig_1.requireConfig)
27
29
  .before(requirePermissions_1.requirePermissions, ["firebasehosting.sites.update"])
30
+ .before((options) => (0, ensureApiEnabled_1.ensure)((0, projectUtils_1.needProjectId)(options), (0, api_2.hostingApiOrigin)(), "hosting", true))
28
31
  .before(requireHostingSite_1.requireHostingSite)
29
32
  .action(hostingChannelDeployAction);
30
33
  async function hostingChannelDeployAction(channelId, options) {
@@ -11,12 +11,15 @@ const logger_1 = require("../logger");
11
11
  const requireConfig_1 = require("../requireConfig");
12
12
  const utils_1 = require("../utils");
13
13
  const requireHostingSite_1 = require("../requireHostingSite");
14
+ const ensureApiEnabled_1 = require("../ensureApiEnabled");
15
+ const api_2 = require("../api");
14
16
  const TABLE_HEAD = ["Channel ID", "Last Release Time", "URL", "Expire Time"];
15
17
  exports.command = new command_1.Command("hosting:channel:list")
16
18
  .description("list all Firebase Hosting channels for your project")
17
19
  .option("--site <siteName>", "list channels for the specified site")
18
20
  .before(requireConfig_1.requireConfig)
19
21
  .before(requirePermissions_1.requirePermissions, ["firebasehosting.sites.update"])
22
+ .before((options) => (0, ensureApiEnabled_1.ensure)((0, projectUtils_1.needProjectId)(options), (0, api_2.hostingApiOrigin)(), "hosting", true))
20
23
  .before(requireHostingSite_1.requireHostingSite)
21
24
  .action(async (options) => {
22
25
  const projectId = (0, projectUtils_1.needProjectId)(options);
@@ -13,12 +13,15 @@ const requireConfig_1 = require("../requireConfig");
13
13
  const utils_1 = require("../utils");
14
14
  const requireHostingSite_1 = require("../requireHostingSite");
15
15
  const prompt_1 = require("../prompt");
16
+ const ensureApiEnabled_1 = require("../ensureApiEnabled");
17
+ const api_2 = require("../api");
16
18
  exports.command = new command_1.Command("hosting:channel:open [channelId]")
17
19
  .description("opens the URL for a Firebase Hosting channel")
18
20
  .help("if unable to open the URL in a browser, it will be displayed in the output")
19
21
  .option("--site <siteId>", "the site to which the channel belongs")
20
22
  .before(requireConfig_1.requireConfig)
21
23
  .before(requirePermissions_1.requirePermissions, ["firebasehosting.sites.get"])
24
+ .before((options) => (0, ensureApiEnabled_1.ensure)((0, projectUtils_1.needProjectId)(options), (0, api_2.hostingApiOrigin)(), "hosting", true))
22
25
  .before(requireHostingSite_1.requireHostingSite)
23
26
  .action(async (channelId, options) => {
24
27
  const projectId = (0, projectUtils_1.needProjectId)(options);
@@ -10,6 +10,8 @@ const utils = require("../utils");
10
10
  const requireAuth_1 = require("../requireAuth");
11
11
  const logger_1 = require("../logger");
12
12
  const projectUtils_1 = require("../projectUtils");
13
+ const ensureApiEnabled_1 = require("../ensureApiEnabled");
14
+ const api_2 = require("../api");
13
15
  exports.command = new command_1.Command("hosting:clone <source> <targetChannel>")
14
16
  .description("clone a version from one site to another")
15
17
  .help(`<source> and <targetChannel> accept the following formats:
@@ -70,10 +72,22 @@ To clone across different Firebase projects:
70
72
  if (!targetSiteId || !targetChannelId) {
71
73
  throw new error_1.FirebaseError(`"${targetChannel}" is not a valid target channel. Must be in the form "[<project>:]<site>:<channel>" (to clone to the active website, use "live" as the channel).`);
72
74
  }
75
+ const defaultProjectId = !sourceProjectId || !targetProjectId ? (0, projectUtils_1.getProjectId)(options) : undefined;
76
+ if (defaultProjectId) {
77
+ await (0, ensureApiEnabled_1.ensure)(defaultProjectId, (0, api_2.hostingApiOrigin)(), "hosting", true);
78
+ }
73
79
  [sourceProjectId, targetProjectId] = await Promise.all([
74
80
  resolveProjectId(sourceSiteId, sourceProjectId, options),
75
81
  resolveProjectId(targetSiteId, targetProjectId, options),
76
82
  ]);
83
+ const ensurePromises = [];
84
+ if (sourceProjectId !== defaultProjectId) {
85
+ ensurePromises.push((0, ensureApiEnabled_1.ensure)(sourceProjectId, (0, api_2.hostingApiOrigin)(), "hosting", true));
86
+ }
87
+ if (targetProjectId !== defaultProjectId && targetProjectId !== sourceProjectId) {
88
+ ensurePromises.push((0, ensureApiEnabled_1.ensure)(targetProjectId, (0, api_2.hostingApiOrigin)(), "hosting", true));
89
+ }
90
+ await Promise.all(ensurePromises);
77
91
  targetChannelId = (0, api_1.normalizeName)(targetChannelId);
78
92
  if (sourceChannelId) {
79
93
  sourceChannelId = (0, api_1.normalizeName)(sourceChannelId);
@@ -10,11 +10,13 @@ const requireHostingSite_1 = require("../requireHostingSite");
10
10
  const requirePermissions_1 = require("../requirePermissions");
11
11
  const projectUtils_1 = require("../projectUtils");
12
12
  const utils = require("../utils");
13
+ const ensureApiEnabled_1 = require("../ensureApiEnabled");
13
14
  exports.command = new command_1.Command("hosting:disable")
14
15
  .description("stop serving web traffic to your Firebase Hosting site")
15
16
  .option("-f, --force", "skip confirmation")
16
17
  .option("-s, --site <siteName>", "the site to disable")
17
18
  .before(requirePermissions_1.requirePermissions, ["firebasehosting.sites.update"])
19
+ .before((options) => (0, ensureApiEnabled_1.ensure)((0, projectUtils_1.needProjectId)(options), (0, api_1.hostingApiOrigin)(), "hosting", true))
18
20
  .before(requireHostingSite_1.requireHostingSite)
19
21
  .action(async (options) => {
20
22
  const projectId = (0, projectUtils_1.needProjectId)(options);
@@ -10,11 +10,14 @@ const projectUtils_1 = require("../projectUtils");
10
10
  const requirePermissions_1 = require("../requirePermissions");
11
11
  const api_1 = require("../hosting/api");
12
12
  const error_1 = require("../error");
13
+ const ensureApiEnabled_1 = require("../ensureApiEnabled");
14
+ const api_2 = require("../api");
13
15
  const LOG_TAG = "hosting:sites";
14
16
  exports.command = new command_1.Command("hosting:sites:create [siteId]")
15
17
  .description("create a Firebase Hosting site")
16
18
  .option("--app <appId>", "specify an existing Firebase Web App ID")
17
19
  .before(requirePermissions_1.requirePermissions, ["firebasehosting.sites.update"])
20
+ .before((options) => (0, ensureApiEnabled_1.ensure)((0, projectUtils_1.needProjectId)(options), (0, api_2.hostingApiOrigin)(), "hosting", true))
18
21
  .action(async (siteId, options) => {
19
22
  const projectId = (0, projectUtils_1.needProjectId)(options);
20
23
  const appId = options.app;
@@ -11,12 +11,15 @@ const requirePermissions_1 = require("../requirePermissions");
11
11
  const projectUtils_1 = require("../projectUtils");
12
12
  const requireConfig_1 = require("../requireConfig");
13
13
  const logger_1 = require("../logger");
14
+ const ensureApiEnabled_1 = require("../ensureApiEnabled");
15
+ const api_2 = require("../api");
14
16
  const LOG_TAG = "hosting:sites";
15
17
  exports.command = new command_1.Command("hosting:sites:delete <siteId>")
16
18
  .description("delete a Firebase Hosting site")
17
19
  .withForce()
18
20
  .before(requireConfig_1.requireConfig)
19
21
  .before(requirePermissions_1.requirePermissions, ["firebasehosting.sites.delete"])
22
+ .before((options) => (0, ensureApiEnabled_1.ensure)((0, projectUtils_1.needProjectId)(options), (0, api_2.hostingApiOrigin)(), "hosting", true))
20
23
  .action(async (siteId, options) => {
21
24
  const projectId = (0, projectUtils_1.needProjectId)(options);
22
25
  if (!siteId) {
@@ -8,9 +8,12 @@ const requirePermissions_1 = require("../requirePermissions");
8
8
  const projectUtils_1 = require("../projectUtils");
9
9
  const logger_1 = require("../logger");
10
10
  const error_1 = require("../error");
11
+ const ensureApiEnabled_1 = require("../ensureApiEnabled");
12
+ const api_2 = require("../api");
11
13
  exports.command = new command_1.Command("hosting:sites:get <siteId>")
12
14
  .description("print info about a Firebase Hosting site")
13
15
  .before(requirePermissions_1.requirePermissions, ["firebasehosting.sites.get"])
16
+ .before((options) => (0, ensureApiEnabled_1.ensure)((0, projectUtils_1.needProjectId)(options), (0, api_2.hostingApiOrigin)(), "hosting", true))
14
17
  .action(async (siteId, options) => {
15
18
  const projectId = (0, projectUtils_1.needProjectId)(options);
16
19
  if (!siteId) {
@@ -8,10 +8,13 @@ const api_1 = require("../hosting/api");
8
8
  const requirePermissions_1 = require("../requirePermissions");
9
9
  const projectUtils_1 = require("../projectUtils");
10
10
  const logger_1 = require("../logger");
11
+ const ensureApiEnabled_1 = require("../ensureApiEnabled");
12
+ const api_2 = require("../api");
11
13
  const TABLE_HEAD = ["Site ID", "Default URL", "App ID (if set)"];
12
14
  exports.command = new command_1.Command("hosting:sites:list")
13
15
  .description("list Firebase Hosting sites")
14
16
  .before(requirePermissions_1.requirePermissions, ["firebasehosting.sites.get"])
17
+ .before((options) => (0, ensureApiEnabled_1.ensure)((0, projectUtils_1.needProjectId)(options), (0, api_2.hostingApiOrigin)(), "hosting", true))
15
18
  .action(async (options) => {
16
19
  const projectId = (0, projectUtils_1.needProjectId)(options);
17
20
  const sites = await (0, api_1.listSites)(projectId);
@@ -11,6 +11,8 @@ exports.command = new command_1.Command("run:services:update <serviceId>")
11
11
  .option("--region <region>", "the service's region, if firebase.json lists the service ID in more than one region")
12
12
  .option("--base-image <baseImage>", "set the base image (e.g. nodejs22) and enable automatic base image updates")
13
13
  .option("--clear-base-image", "clear the base image and disable automatic base image updates")
14
+ .option("--app <appId>", "associate a Firebase Web App ID for SDK auto-initialization")
15
+ .option("--clear-app", "disassociate the Firebase Web App and disable SDK auto-initialization")
14
16
  .before(requireConfig_1.requireConfig)
15
17
  .before(requirePermissions_1.requirePermissions, deploy_1.TARGET_PERMISSIONS.run)
16
18
  .action((serviceId, options) => (0, update_1.updateService)(serviceId, options.region, options));
@@ -103,20 +103,10 @@ async function enableAlerts(projectId, appId, alertTypes, userEmail) {
103
103
  exit: 1,
104
104
  });
105
105
  }
106
- const results = await Promise.allSettled(alertTypes.map(async (alertType) => {
106
+ return await Promise.all(alertTypes.map(async (alertType) => {
107
107
  const { policy } = await enableAlert(projectId, appId, alertType, {
108
108
  channelName,
109
109
  });
110
110
  return policy;
111
111
  }));
112
- const policies = [];
113
- for (const res of results) {
114
- if (res.status === "fulfilled") {
115
- policies.push(res.value);
116
- }
117
- else {
118
- logger_1.logger.debug(`[crashlytics] Failed to enable alert: ${(0, error_1.getErrMsg)(res.reason)}`);
119
- }
120
- }
121
- return policies;
122
112
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CRASHLYTICS_TELEMETRY_SERVICE = exports.CRASHLYTICS_TELEMETRY_RESOURCE_TYPE = exports.CRASHLYTICS_TELEMETRY_SINK_ID = exports.CRASHLYTICS_TELEMETRY_BUCKET_ID = void 0;
3
+ exports.CLIENT_TELEMETRY_SERVICE = exports.CRASHLYTICS_SERVICE = exports.CRASHLYTICS_TELEMETRY_ADMIN_SERVICE = exports.CRASHLYTICS_TELEMETRY_SERVICE = exports.CRASHLYTICS_TELEMETRY_RESOURCE_TYPE = exports.CRASHLYTICS_TELEMETRY_SINK_ID = exports.CRASHLYTICS_TELEMETRY_BUCKET_ID = void 0;
4
4
  exports.onboardCrashlyticsWeb = onboardCrashlyticsWeb;
5
5
  const ensureApiEnabled_1 = require("../ensureApiEnabled");
6
6
  const error_1 = require("../error");
@@ -21,6 +21,9 @@ exports.CRASHLYTICS_TELEMETRY_BUCKET_ID = "firebase-telemetry";
21
21
  exports.CRASHLYTICS_TELEMETRY_SINK_ID = "firebase-telemetry-routing";
22
22
  exports.CRASHLYTICS_TELEMETRY_RESOURCE_TYPE = "firebasetelemetry.googleapis.com/App";
23
23
  exports.CRASHLYTICS_TELEMETRY_SERVICE = "firebasetelemetry.googleapis.com";
24
+ exports.CRASHLYTICS_TELEMETRY_ADMIN_SERVICE = "firebasetelemetryadmin.googleapis.com";
25
+ exports.CRASHLYTICS_SERVICE = "firebasecrashlytics.googleapis.com";
26
+ exports.CLIENT_TELEMETRY_SERVICE = "clienttelemetry.googleapis.com";
24
27
  async function resolveAuthenticatedUserEmail(options) {
25
28
  if (options.user?.email) {
26
29
  return options.user.email;
@@ -45,7 +48,9 @@ async function onboardCrashlyticsWeb(projectId, appId, options = {}) {
45
48
  (0, utils_1.logLabeledBullet)("crashlytics", "Enabling required telemetry APIs...");
46
49
  const requiredApis = [
47
50
  (0, ensureApiEnabled_1.ensure)(projectId, exports.CRASHLYTICS_TELEMETRY_SERVICE, "crashlytics", false),
48
- (0, ensureApiEnabled_1.ensure)(projectId, "firebasetelemetryadmin.googleapis.com", "crashlytics", false),
51
+ (0, ensureApiEnabled_1.ensure)(projectId, exports.CRASHLYTICS_TELEMETRY_ADMIN_SERVICE, "crashlytics", false),
52
+ (0, ensureApiEnabled_1.ensure)(projectId, exports.CRASHLYTICS_SERVICE, "crashlytics", false),
53
+ (0, ensureApiEnabled_1.ensure)(projectId, exports.CLIENT_TELEMETRY_SERVICE, "crashlytics", false),
49
54
  ];
50
55
  if (experiments.isEnabled("crashlyticsWebBreadcrumbs")) {
51
56
  requiredApis.push((0, ensureApiEnabled_1.ensure)(projectId, "cloudtrace.googleapis.com", "crashlytics", false));
@@ -91,7 +96,7 @@ async function onboardCrashlyticsWeb(projectId, appId, options = {}) {
91
96
  (0, utils_1.logLabeledBullet)("crashlytics", "Configuring Crashlytics telemetry for web app...");
92
97
  const config = await (0, firebasetelemetry_1.createOrUpdateTelemetryConfig)(projectId, appId, `projects/${projectId}/locations/global/buckets/${exports.CRASHLYTICS_TELEMETRY_BUCKET_ID}`, 1);
93
98
  (0, utils_1.logLabeledSuccess)("crashlytics", "Crashlytics telemetry configured successfully.");
94
- if (!experiments.isEnabled("crashlyticsWebAlerts") || options.nonInteractive) {
99
+ if (options.nonInteractive) {
95
100
  return { bucket, sink, config };
96
101
  }
97
102
  const userEmail = await resolveAuthenticatedUserEmail(options);
@@ -251,6 +251,7 @@ async function ensureSecret(secretParam, projectId, nonInteractive) {
251
251
  const promptMessage = `Enter ${secretParam.format === "json" ? "a JSON value" : "a value"} for ${label}:`;
252
252
  const secretValue = await (0, prompt_1.password)({
253
253
  message: promptMessage,
254
+ validate: (val) => (val !== "" ? true : "Secrets cannot have an empty value."),
254
255
  });
255
256
  if (secretParam.format === "json") {
256
257
  (0, secrets_1.validateJsonSecret)(secretParam.name, secretValue);
@@ -15,6 +15,8 @@ const utils = require("../../utils");
15
15
  const backend = require("../functions/backend");
16
16
  const ensureTargeted_1 = require("../../functions/ensureTargeted");
17
17
  const frameworks_1 = require("../../frameworks");
18
+ const ensureApiEnabled_1 = require("../../ensureApiEnabled");
19
+ const api_1 = require("../../api");
18
20
  function handlePublicDirectoryFlag(options) {
19
21
  if (options.public) {
20
22
  if (Array.isArray(options.config.get("hosting"))) {
@@ -73,6 +75,7 @@ async function prepare(context, options) {
73
75
  if (configs.length === 0) {
74
76
  return Promise.resolve();
75
77
  }
78
+ await (0, ensureApiEnabled_1.ensure)(context.projectId, (0, api_1.hostingApiOrigin)(), "hosting", true);
76
79
  const versions = await Promise.all(configs.map(async (config) => {
77
80
  await api.getSite(context.projectId, config.site);
78
81
  const labels = {
@@ -144,6 +144,14 @@ function revisionTemplate(svc, image, message) {
144
144
  else {
145
145
  delete container.baseImageUri;
146
146
  }
147
+ const wasLinked = svc.existing?.annotations?.[util_2.FIREBASE_APP_ANNOTATION] !== undefined;
148
+ const otherEnv = (container.env || []).filter((e) => e.name !== "FIREBASE_CONFIG");
149
+ if (svc.autoInit) {
150
+ container.env = [...otherEnv, { name: "FIREBASE_CONFIG", value: svc.autoInit.firebaseConfig }];
151
+ }
152
+ else if (wasLinked) {
153
+ container.env = otherEnv;
154
+ }
147
155
  if (message) {
148
156
  template.annotations = { ...template.annotations, [DEPLOY_MESSAGE_ANNOTATION]: message };
149
157
  }
@@ -170,31 +178,51 @@ function localBuildTemplate(svc, build, builtApp, message) {
170
178
  }
171
179
  return template;
172
180
  }
181
+ function serviceAnnotationsToDeploy(svc) {
182
+ const annotations = { ...svc.existing?.annotations };
183
+ if (svc.autoInit) {
184
+ annotations[util_2.FIREBASE_APP_ANNOTATION] = svc.autoInit.appId;
185
+ }
186
+ else {
187
+ delete annotations[util_2.FIREBASE_APP_ANNOTATION];
188
+ }
189
+ return annotations;
190
+ }
173
191
  function rollOut(projectId, svc, template) {
192
+ const annotations = serviceAnnotationsToDeploy(svc);
174
193
  if (svc.existing) {
175
- return deployRevision(svc.existing, template);
194
+ return deployRevision(svc.existing, template, annotations);
176
195
  }
177
- return createNewService(projectId, svc.config, template);
196
+ return createNewService(projectId, svc.config, template, annotations);
178
197
  }
179
- function createNewService(projectId, config, template) {
198
+ function createNewService(projectId, config, template, annotations) {
180
199
  const { serviceId, region } = config;
181
- return runv2.createService(projectId, region, serviceId, {
200
+ const service = {
182
201
  name: `projects/${projectId}/locations/${region}/services/${serviceId}`,
202
+ annotations,
183
203
  template,
184
204
  client: "cli-firebase",
185
205
  invokerIamDisabled: true,
186
206
  ingress: "INGRESS_TRAFFIC_ALL",
187
- }, { pollTimeoutMs: ROLLOUT_TIMEOUT_MS });
207
+ };
208
+ return runv2.createService(projectId, region, serviceId, service, {
209
+ pollTimeoutMs: ROLLOUT_TIMEOUT_MS,
210
+ });
188
211
  }
189
- function deployRevision(service, template) {
212
+ function deployRevision(service, template, annotations) {
190
213
  const tags = (service.traffic || [])
191
214
  .filter((t) => t.tag)
192
215
  .map((t) => ({ type: t.type, revision: t.revision, tag: t.tag }));
193
- return runv2.updateService({
216
+ const update = {
194
217
  name: service.name,
218
+ annotations,
195
219
  template,
196
220
  traffic: [{ type: "TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST", percent: 100 }, ...tags],
197
- }, { updateMask: ["template", "traffic"], pollTimeoutMs: ROLLOUT_TIMEOUT_MS });
221
+ };
222
+ return runv2.updateService(update, {
223
+ updateMask: ["template", "traffic", "annotations"],
224
+ pollTimeoutMs: ROLLOUT_TIMEOUT_MS,
225
+ });
198
226
  }
199
227
  function toAppHostingConfig(config) {
200
228
  return {
@@ -1,11 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.prepare = prepare;
4
+ const app_1 = require("../../apphosting/app");
5
+ const utils_1 = require("../../apphosting/utils");
4
6
  const error_1 = require("../../error");
5
- const utils_1 = require("../../utils");
7
+ const computeEngine_1 = require("../../gcp/computeEngine");
8
+ const resourceManager = require("../../gcp/resourceManager");
9
+ const getProjectNumber_1 = require("../../getProjectNumber");
10
+ const managementApps = require("../../management/apps");
11
+ const utils_2 = require("../../utils");
6
12
  const buildEnv_1 = require("./buildEnv");
7
13
  const prereqs_1 = require("./prereqs");
8
14
  const util_1 = require("./util");
15
+ const ADMIN_SDK_ROLE = "roles/firebase.sdkAdminServiceAgent";
9
16
  async function prepare(context, options, payload) {
10
17
  const configs = (0, util_1.getServiceConfigs)(options);
11
18
  if (!configs.length) {
@@ -24,6 +31,10 @@ async function prepareService(context, config) {
24
31
  if (context.baseImage !== undefined) {
25
32
  baseImage = context.baseImage ?? undefined;
26
33
  }
34
+ let appId = existing?.annotations?.[util_1.FIREBASE_APP_ANNOTATION];
35
+ if (context.appId !== undefined) {
36
+ appId = context.appId ?? undefined;
37
+ }
27
38
  if (config.localBuild && !baseImage) {
28
39
  const fix = existing
29
40
  ? `firebase run:services:update ${serviceId} --region ${region} --base-image <baseImage>`
@@ -39,9 +50,50 @@ async function prepareService(context, config) {
39
50
  }
40
51
  const svc = { config, existing, baseImage };
41
52
  if (Object.keys(buildEnv).length) {
42
- (0, utils_1.logLabeledBullet)("run", `Using build environment variables for service ${serviceId} in ${region} from ` +
53
+ (0, utils_2.logLabeledBullet)("run", `Using build environment variables for service ${serviceId} in ${region} from ` +
43
54
  `${buildEnv_1.BUILD_ENV_ANNOTATION}: ${Object.keys(buildEnv).join(", ")}`);
44
55
  svc.buildEnv = buildEnv;
45
56
  }
57
+ if (appId) {
58
+ const autoInitEnv = (0, utils_1.getAutoinitEnvVars)(await getWebAppConfig(context, config, appId));
59
+ if (appId !== existing?.annotations?.[util_1.FIREBASE_APP_ANNOTATION]) {
60
+ await checkAdminSdkRole(context, config, existing);
61
+ }
62
+ svc.autoInit = { appId, firebaseConfig: autoInitEnv.FIREBASE_CONFIG };
63
+ svc.buildEnv = { ...buildEnv, ...autoInitEnv };
64
+ }
46
65
  return svc;
47
66
  }
67
+ async function getWebAppConfig(context, config, appId) {
68
+ try {
69
+ await app_1.webApps.getOrCreateWebApp(context.projectId, appId, config.serviceId);
70
+ return (await managementApps.getAppConfig(appId, managementApps.AppPlatform.WEB));
71
+ }
72
+ catch (err) {
73
+ const update = `firebase run:services:update ${config.serviceId} --region ${config.region}`;
74
+ throw new error_1.FirebaseError(`Unable to look up Firebase Web App ${appId} for service ${config.serviceId} in ` +
75
+ `${config.region}: ${(0, error_1.getErrMsg)(err)}\n` +
76
+ `To use a different app, run "${update} --app <appId>". ` +
77
+ `To deploy without Firebase SDK auto-initialization, run "${update} --clear-app".`, { original: (0, error_1.getError)(err) });
78
+ }
79
+ }
80
+ async function checkAdminSdkRole(context, config, existing) {
81
+ const serviceAccount = existing?.template?.serviceAccount ||
82
+ (await (0, computeEngine_1.getDefaultServiceAccount)(await (0, getProjectNumber_1.getProjectNumber)(context)));
83
+ let problem = "";
84
+ try {
85
+ const hasRole = await resourceManager.serviceAccountHasRoles(context.projectId, serviceAccount, [ADMIN_SDK_ROLE], true);
86
+ if (!hasRole) {
87
+ problem = `${serviceAccount} doesn't have ${ADMIN_SDK_ROLE}`;
88
+ }
89
+ }
90
+ catch (err) {
91
+ problem = `Couldn't check whether ${serviceAccount} has ${ADMIN_SDK_ROLE} (${(0, error_1.getErrMsg)(err)})`;
92
+ }
93
+ if (problem) {
94
+ (0, utils_2.logLabeledWarning)("run", `${problem}. Service ${config.serviceId} runs as this account, so if its Firebase Admin SDK ` +
95
+ `calls fail with permission errors, grant the role with:\n` +
96
+ ` gcloud projects add-iam-policy-binding ${context.projectId} ` +
97
+ `--member=serviceAccount:${serviceAccount} --role=${ADMIN_SDK_ROLE} --condition=None`);
98
+ }
99
+ }
@@ -9,9 +9,10 @@ const util_1 = require("./util");
9
9
  async function updateService(serviceId, region, options) {
10
10
  const settings = {
11
11
  baseImage: readFlagPair(options.baseImage, options.clearBaseImage, "base-image"),
12
+ appId: readFlagPair(options.app, options.clearApp, "app"),
12
13
  };
13
14
  if (Object.values(settings).every((value) => value === undefined)) {
14
- throw new error_1.FirebaseError("Specify a setting to update: --base-image <baseImage> or --clear-base-image.");
15
+ throw new error_1.FirebaseError("Specify a setting to update: --base-image <baseImage>, --clear-base-image, --app <appId>, or --clear-app.");
15
16
  }
16
17
  const projectId = (0, projectUtils_1.needProjectId)(options);
17
18
  const config = findServiceToUpdate(serviceId, region, options);
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FIREBASE_APP_ANNOTATION = void 0;
3
4
  exports.getAllServiceConfigs = getAllServiceConfigs;
4
5
  exports.getServiceConfigs = getServiceConfigs;
5
6
  exports.findServices = findServices;
@@ -9,6 +10,7 @@ exports.mainContainer = mainContainer;
9
10
  const error_1 = require("../../error");
10
11
  const runv2 = require("../../gcp/runv2");
11
12
  const utils_1 = require("../../utils");
13
+ exports.FIREBASE_APP_ANNOTATION = "firebase.google.com/app-id";
12
14
  function getAllServiceConfigs(options) {
13
15
  const configs = [options.config?.src?.run ?? []].flat();
14
16
  const names = new Set();
@@ -19,9 +19,8 @@ class AuthCloudFunction {
19
19
  async dispatch(action, user) {
20
20
  if (!this.enabled)
21
21
  return;
22
- const userInfoPayload = this.createUserInfoPayload(user);
23
- const legacyEventBody = this.createEventRequestBody(action, userInfoPayload);
24
- const v2CloudEventBody = this.createCloudEventRequestBody(action, userInfoPayload);
22
+ const legacyEventBody = this.createEventRequestBody(action, user);
23
+ const v2CloudEventBody = this.createCloudEventRequestBody(action, user);
25
24
  const c = registry_1.EmulatorRegistry.client(types_1.Emulators.FUNCTIONS);
26
25
  const errStatus = [];
27
26
  let err;
@@ -49,7 +48,7 @@ class AuthCloudFunction {
49
48
  this.logger.logLabeled("WARN", "functions", `Firebase Authentication function was not triggered due to emulation error. Please file a bug.`);
50
49
  }
51
50
  }
52
- createEventRequestBody(action, userInfoPayload) {
51
+ createEventRequestBody(action, user) {
53
52
  return {
54
53
  eventId: (0, crypto_1.randomUUID)(),
55
54
  eventType: `providers/firebase.auth/eventTypes/user.${action}`,
@@ -59,26 +58,36 @@ class AuthCloudFunction {
59
58
  },
60
59
  params: {},
61
60
  timestamp: new Date().toISOString(),
62
- data: userInfoPayload,
61
+ data: this.createUserInfoPayload(user),
63
62
  };
64
63
  }
65
- createCloudEventRequestBody(action, userInfoPayload) {
64
+ createCloudEventRequestBody(action, user) {
66
65
  const ceAction = AUTH_V2_ACTION_MAP[action];
66
+ const v2UserPayload = this.createV2UserInfoPayload(user);
67
67
  const cloudEvent = {
68
68
  specversion: "1.0",
69
69
  id: (0, crypto_1.randomUUID)(),
70
70
  time: new Date().toISOString(),
71
71
  type: `google.firebase.auth.user.v2.${ceAction}`,
72
72
  source: `//identitytoolkit.googleapis.com/projects/${this.projectId}`,
73
- subject: `users/${userInfoPayload.uid}`,
74
- data: action === "create" ? { value: userInfoPayload } : { oldValue: userInfoPayload },
73
+ subject: `users/${v2UserPayload.uid}`,
74
+ data: action === "create" ? { value: v2UserPayload } : { oldValue: v2UserPayload },
75
75
  };
76
- if (userInfoPayload.tenantId) {
77
- cloudEvent.tenantid = userInfoPayload.tenantId;
76
+ if (user.tenantId) {
77
+ cloudEvent.tenantid = user.tenantId;
78
78
  }
79
79
  return cloudEvent;
80
80
  }
81
- createUserInfoPayload(user) {
81
+ toIsoTimestamp(epochMs) {
82
+ if (!epochMs)
83
+ return undefined;
84
+ const ms = parseInt(epochMs, 10);
85
+ if (isNaN(ms))
86
+ return undefined;
87
+ const date = new Date(ms);
88
+ return isNaN(date.getTime()) ? undefined : date.toISOString();
89
+ }
90
+ createBaseUserInfoPayload(user) {
82
91
  return {
83
92
  uid: user.localId,
84
93
  email: user.email,
@@ -87,15 +96,35 @@ class AuthCloudFunction {
87
96
  photoURL: user.photoUrl,
88
97
  phoneNumber: user.phoneNumber,
89
98
  disabled: user.disabled,
99
+ customClaims: JSON.parse(user.customAttributes || "{}"),
100
+ };
101
+ }
102
+ createV2UserInfoPayload(user) {
103
+ return {
104
+ ...this.createBaseUserInfoPayload(user),
90
105
  metadata: {
91
- creationTime: user.createdAt
92
- ? new Date(parseInt(user.createdAt, 10)).toISOString()
93
- : undefined,
94
- lastSignInTime: user.lastLoginAt
95
- ? new Date(parseInt(user.lastLoginAt, 10)).toISOString()
96
- : undefined,
106
+ createTime: this.toIsoTimestamp(user.createdAt),
107
+ lastSignInTime: this.toIsoTimestamp(user.lastLoginAt),
108
+ },
109
+ providerData: user.providerUserInfo?.map((info) => this.createV2ProviderUserInfoPayload(info)),
110
+ };
111
+ }
112
+ createV2ProviderUserInfoPayload(info) {
113
+ return {
114
+ uid: info.rawId,
115
+ providerId: info.providerId,
116
+ displayName: info.displayName,
117
+ email: info.email,
118
+ photoURL: info.photoUrl,
119
+ };
120
+ }
121
+ createUserInfoPayload(user) {
122
+ return {
123
+ ...this.createBaseUserInfoPayload(user),
124
+ metadata: {
125
+ creationTime: this.toIsoTimestamp(user.createdAt),
126
+ lastSignInTime: this.toIsoTimestamp(user.lastLoginAt),
97
127
  },
98
- customClaims: JSON.parse(user.customAttributes || "{}"),
99
128
  providerData: user.providerUserInfo?.map((info) => this.createProviderUserInfoPayload(info)),
100
129
  tenantId: user.tenantId,
101
130
  mfaInfo: user.mfaInfo,