very-express 0.8.4 → 0.8.5

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.
@@ -20,32 +20,15 @@ export function userIdOfToken(tokenData: Record<string, unknown> | undefined): s
20
20
  const als = new AsyncLocalStorage<UserContextData>();
21
21
 
22
22
  class UserContext {
23
- /**
24
- * Enter the per-request identity context.
25
- *
26
- * Called ONLY by Authentication.middleware, after token verification succeeded — at
27
- * that point a verified token always exists, so this runs unconditionally. The store
28
- * is the request's context; whether it carries a usable identity is decided when it
29
- * is read (`userId`), not when it is created.
30
- *
31
- * Never use `enterWith()`: it mutates the current execution context instead of
32
- * scoping a new one, and leaks into whatever runs next on the same tick.
33
- */
34
23
  run<T>(tokenData: Record<string, unknown>, fn: () => T): T {
35
24
  return als.run({ tokenData }, fn);
36
25
  }
37
26
 
38
- /** Current store from the per-request async context. */
39
27
  getStore(): UserContextData | undefined {
40
28
  return als.getStore();
41
29
  }
42
30
 
43
- /**
44
- * Normalized identity of the authenticated caller.
45
- *
46
- * The data layer MUST read the identity through this accessor and never inspect the
47
- * token shape itself — that keeps the token → identity mapping in exactly one place.
48
- */
31
+ /** Normalized identity of the authenticated caller. */
49
32
  get userId(): string | undefined {
50
33
  return userIdOfToken(als.getStore()?.tokenData);
51
34
  }
@@ -19,6 +19,20 @@ OAUTH_GITHUB_CLIENTSECRET=
19
19
  # OAUTH_APPLE_CLIENTID=
20
20
  # OAUTH_APPLE_CLIENTSECRET=
21
21
 
22
+ # FIREBASE (auth.firebase in vex.config.json) — see docs/appGenerated/auth.md
23
+ # Server credential: firebase-admin verifies ID tokens, so the project's service account is required.
24
+ # The JSON itself, as one value — generate it in the Firebase console:
25
+ # Project settings > Service accounts > Generate new private key.
26
+ FIREBASE_SERVICE_ACCOUNT_JSON=
27
+ # Browser config: Firebase's *public* web app values, served to the login page by design. There is no
28
+ # secret among them, and no appId — Firebase Auth does not read one.
29
+ FIREBASE_WEB_API_KEY=
30
+ FIREBASE_WEB_AUTH_DOMAIN=
31
+ FIREBASE_WEB_PROJECT_ID=
32
+ # Optional: which sign-in methods the login page renders a button for, comma separated. Defaults to
33
+ # google. The server accepts any provider it knows regardless of this list.
34
+ # FIREBASE_PROVIDERS=google
35
+
22
36
  # JWT token
23
37
  ACCESS_TOKEN_EXPIRE_TIME='1h'
24
38
  REFRESH_TOKEN_EXPIRE_TIME='24h'
@@ -13,6 +13,7 @@
13
13
  "cookie-parser": "^1.4.6",
14
14
  "dotenv": "^16.4.4",
15
15
  "express": "^4.18.2",
16
+ "firebase-admin": "^14.1.0",
16
17
  "helmet": "^7.1.0",
17
18
  "js-yaml": "^4.1.0",
18
19
  "jsonwebtoken": "^9.0.2",
@@ -0,0 +1,20 @@
1
+ // {{headerComment}}
2
+ import type { FirebaseAuthUI } from "./LoginUI.gen";
3
+
4
+ /**
5
+ * Test/compile-time stand-in for the generated login-page wiring.
6
+ *
7
+ * **In a generated app this file is overwritten by the generator**, which emits the Firebase wiring or
8
+ * `undefined` when `auth.firebase` is off. It lives in the template directory so that `LoginUI.ts`'s
9
+ * unconditional import resolves in this repo — that import has to be unconditional, because the
10
+ * generated default is how the configuration reaches the login page without editing the app-owned
11
+ * `server.ts`.
12
+ *
13
+ * `let` plus a setter rather than a `const`, so the unit tests can vary what the generator "emitted".
14
+ * The generated version is a plain `const`; nothing in the app calls the setter.
15
+ */
16
+ export let firebaseAuthUI: FirebaseAuthUI | undefined = undefined;
17
+
18
+ export function setFirebaseAuthUI(ui: FirebaseAuthUI | undefined): void {
19
+ firebaseAuthUI = ui;
20
+ }
@@ -1,21 +1,96 @@
1
1
  // {{headerComment}}
2
2
  import { Router, Request, Response } from "express";
3
3
  import crypto from "crypto";
4
+ import fs from "fs";
5
+ import path from "path";
6
+ import dotenv from "dotenv";
7
+
8
+ import { firebaseAuthUI } from "./FirebaseAuthUI.gen";
9
+
10
+ /**
11
+ * Explain config values that `process.env` does not have.
12
+ *
13
+ * Two different situations produce the same symptom — Firebase reports itself unconfigured — and they
14
+ * need different fixes, so they are separated here:
15
+ *
16
+ * - **present in `.env` but absent from `process.env`**: `dotenv` does not override a variable that is
17
+ * already set in the environment, and it only runs once at startup. Either the process started before
18
+ * the file was edited, or the name is exported by the shell / IDE launch config / container with a
19
+ * different value.
20
+ * - **absent from both**: nothing has set it.
21
+ *
22
+ * Pure so the diagnosis can be tested without touching the filesystem.
23
+ */
24
+ export function diagnoseMissingEnv(
25
+ names: string[],
26
+ envFile: Record<string, string | undefined>,
27
+ ): string[] {
28
+ const shadowed = names.filter((name) => envFile[name]);
29
+ const unset = names.filter((name) => !envFile[name]);
30
+ const problems: string[] = [];
31
+
32
+ if (shadowed.length > 0) {
33
+ problems.push(
34
+ `set in .env but NOT in process.env: ${shadowed.join(", ")}. dotenv does not override a ` +
35
+ "variable that is already present in the environment, and .env is read once at startup — so " +
36
+ "either the server started before .env was edited, or these are exported by the shell / IDE " +
37
+ `launch config / container. Check \`env | grep -E '^(${shadowed.join("|")})='\`` +
38
+ ", then unset them there or pass dotenv's `override` option in server.ts.",
39
+ );
40
+ }
41
+
42
+ if (unset.length > 0) {
43
+ problems.push(`not set in .env or process.env: ${unset.join(", ")}`);
44
+ }
45
+
46
+ return problems;
47
+ }
4
48
 
5
49
  export interface LoginUIConfig {
6
50
  localAuth: boolean;
7
51
  oauthProviders: string[];
8
- /**
9
- * Serve the self-service deletion page at `/delete_account`.
10
- *
11
- * Optional and defaulting to true so an app generated before this feature existed still
12
- * constructs — its `server.ts` is generated once and is not overwritten on later runs.
13
- */
52
+ /** Serve the self-service deletion page at `/delete_account`. */
14
53
  deleteAccount?: boolean;
54
+ /** Override the Firebase sign-in wiring. */
55
+ firebase?: FirebaseAuthUI;
56
+ }
57
+
58
+ /** Everything the login page needs to drive Firebase, as emitted into `FirebaseAuthUI.gen.ts`. */
59
+ export interface FirebaseAuthUI {
60
+ /** Button text template; `{provider}` is replaced by the provider's label. */
61
+ label: string;
62
+ /** gstatic ESM directory for the pinned SDK version, trailing slash included. */
63
+ sdkBaseUrl: string;
64
+ /** Every provider the page can start. */
65
+ providers: { id: string; label: string }[];
66
+ /** Rendered when `providersEnvKey` is unset. */
67
+ defaultProviders: string[];
68
+ /** env var holding the comma-separated list of providers to render buttons for. */
69
+ providersEnvKey: string;
70
+ /** Public config key → env var name. Resolved at render time; missing values stay absent. */
71
+ envKeys: Record<string, string>;
72
+ /** Hosts Firebase's sign-in needs, per directive. */
73
+ csp: {
74
+ scriptSrc: string[];
75
+ connectSrc: string[];
76
+ frameSrc: string[];
77
+ };
78
+ }
79
+
80
+ /** A sign-in method to render a button for. */
81
+ interface firebaseProvider {
82
+ id: string;
83
+ label: string;
15
84
  }
16
85
 
17
86
  export default class LoginUI {
18
87
 
88
+ /** Last set of problems warned about, so a page render logs them once. */
89
+ private static warnedEnvSignature = "";
90
+
91
+ /** The parsed `.env`, read at most once per process. */
92
+ private static envFileCache: Record<string, string> | undefined;
93
+
19
94
  private router: Router = Router();
20
95
  private config: LoginUIConfig;
21
96
 
@@ -44,12 +119,87 @@ export default class LoginUI {
44
119
  }
45
120
  }
46
121
 
122
+ /** The Firebase wiring in force: an explicit app override, else the generated default. */
123
+ private get firebaseUI(): FirebaseAuthUI | undefined {
124
+ return this.config.firebase ?? firebaseAuthUI;
125
+ }
126
+
47
127
  private nonce(): string {
48
128
  return crypto.randomBytes(16).toString("base64");
49
129
  }
50
130
 
131
+ /** De-duplicate while keeping declaration order; a repeated host adds nothing. */
132
+ private uniqueHosts(hosts: string[]): string[] {
133
+ return hosts.filter((host, index) => hosts.indexOf(host) === index);
134
+ }
135
+
136
+ /** The project's auth domain, e.g. `my-project.firebaseapp.com`. Absent when unconfigured. */
137
+ private firebaseAuthDomain(ui: FirebaseAuthUI): string | undefined {
138
+ return process.env[ui.envKeys.authDomain] || undefined;
139
+ }
140
+
141
+ /** CSP for the login page: the page's own scripts plus the hosts Firebase's sign-in needs. */
142
+ private loginPageCsp(nonce: string): string {
143
+ const ui = this.firebaseUI;
144
+ if (!ui) return `script-src 'self' 'nonce-${nonce}'`;
145
+
146
+ const authDomain = this.firebaseAuthDomain(ui);
147
+ const frameSrc = authDomain ? [...ui.csp.frameSrc, `https://${authDomain}`] : ui.csp.frameSrc;
148
+
149
+ return [
150
+ `script-src ${this.uniqueHosts(["'self'", `'nonce-${nonce}'`, ...ui.csp.scriptSrc]).join(" ")}`,
151
+ `connect-src ${this.uniqueHosts(["'self'", ...ui.csp.connectSrc]).join(" ")}`,
152
+ `frame-src ${this.uniqueHosts(frameSrc).join(" ")}`,
153
+ ].join("; ");
154
+ }
155
+
156
+ /** Escape for HTML text/attribute context. Labels and provider ids come from configuration. */
157
+ private escapeHtml(value: string): string {
158
+ return value
159
+ .replace(/&/g, "&amp;")
160
+ .replace(/</g, "&lt;")
161
+ .replace(/>/g, "&gt;")
162
+ .replace(/"/g, "&quot;")
163
+ .replace(/'/g, "&#39;");
164
+ }
165
+
166
+ /** Which providers to render a button for, and what is wrong with the names that were asked for. */
167
+ private firebaseProviderSelection(ui: FirebaseAuthUI): { providers: firebaseProvider[]; problems: string[] } {
168
+ const configured = process.env[ui.providersEnvKey];
169
+ const requested = (configured ? configured.split(",") : ui.defaultProviders)
170
+ .map((name) => name.trim())
171
+ .filter((name) => name.length > 0);
172
+
173
+ const providers: firebaseProvider[] = [];
174
+ const problems: string[] = [];
175
+
176
+ for (const name of requested) {
177
+ const match = ui.providers.find((provider) => provider.id === name);
178
+ if (match) providers.push(match);
179
+ else {
180
+ problems.push(
181
+ `${ui.providersEnvKey} names "${name}", which this login page cannot start ` +
182
+ `(known: ${ui.providers.map((provider) => provider.id).join(", ")})`,
183
+ );
184
+ }
185
+ }
186
+
187
+ return { providers, problems };
188
+ }
189
+
190
+ /**
191
+ * Auth is on when *any* sign-in path exists. `firebase` counts: an app with `localAuth: false` and
192
+ * no passport provider is not auth-less if Firebase is configured, and leaving it out of this test
193
+ * would hide the login link for exactly that app.
194
+ */
195
+ private get authEnabled(): boolean {
196
+ return this.config.localAuth
197
+ || this.config.oauthProviders.length > 0
198
+ || !!this.firebaseUI;
199
+ }
200
+
51
201
  private homePage(_req: Request, res: Response): void {
52
- const authLinks = this.config.localAuth || this.config.oauthProviders.length > 0
202
+ const authLinks = this.authEnabled
53
203
  ? `<li><a href="/login">Login</a></li>
54
204
  <li><a href="/mytokens">myTokens</a></li>
55
205
  <li><a href="/refreshtoken">RefreshToken</a></li>
@@ -78,7 +228,11 @@ export default class LoginUI {
78
228
 
79
229
  private loginPage(_req: Request, res: Response): void {
80
230
  const nonce = this.nonce();
81
- res.setHeader("Content-Security-Policy", `script-src 'self' 'nonce-${nonce}'`);
231
+ res.setHeader("Content-Security-Policy", this.loginPageCsp(nonce));
232
+
233
+ if (this.firebaseUI) {
234
+ res.setHeader("Cross-Origin-Opener-Policy", "same-origin-allow-popups");
235
+ }
82
236
 
83
237
  let formHtml = "";
84
238
  if (this.config.localAuth) {
@@ -93,21 +247,119 @@ export default class LoginUI {
93
247
  <br/><br/>`;
94
248
  }
95
249
 
250
+ const firebase = this.firebaseUI;
251
+ const selection = firebase ? this.firebaseProviderSelection(firebase) : undefined;
252
+
96
253
  formHtml += " <p>Login with SSO:</p>\n";
97
- if (this.config.oauthProviders.length === 0) {
254
+ if (this.config.oauthProviders.length === 0 && !firebase) {
98
255
  formHtml += " <p>No OAuth provider configured.</p>\n";
99
256
  }
100
257
  else {
258
+ // passport providers: server-driven redirect flows
101
259
  this.config.oauthProviders.forEach((provider) => {
102
260
  formHtml += ` <a href="/api/auth/${provider}">${provider}</a><br/>\n`;
103
261
  });
262
+
263
+ // Firebase: client-driven. One button per configured sign-in method; the provider id
264
+ // travels to the glue as a data attribute, and on to signIn().
265
+ if (firebase && selection) {
266
+ selection.providers.forEach((provider) => {
267
+ const text = firebase.label.replace("{provider}", provider.label);
268
+ formHtml += ` <button class="firebaseLoginBtn" data-provider="${this.escapeHtml(provider.id)}">${this.escapeHtml(text)}</button><br/>\n`;
269
+ });
270
+ }
104
271
  }
105
272
 
106
273
  const scriptTag = this.config.localAuth
107
274
  ? `<script nonce="${nonce}" src="/js/login.js?d=${Date.now()}"></script>`
108
275
  : "";
276
+ const firebaseScripts = firebase && selection ? this.firebaseScripts(nonce, selection.problems) : "";
277
+
278
+ res.send(`${scriptTag}${firebaseScripts}<body>${formHtml}</body>`);
279
+ }
280
+
281
+ /**
282
+ * The inline carrier and the glue. Inlined so the page and its glue cannot be different
283
+ * generations; the public config is read from `process.env` at render time.
284
+ */
285
+ private firebaseScripts(nonce: string, providerProblems: string[]): string {
286
+ const ui = this.firebaseUI;
287
+ if (!ui) return "";
288
+
289
+ const config: Record<string, string> = {};
290
+ const missing: string[] = [];
291
+ for (const [key, envName] of Object.entries(ui.envKeys)) {
292
+ const value = process.env[envName];
293
+ if (value) config[key] = value;
294
+ else missing.push(envName);
295
+ }
296
+
297
+ const problems = [
298
+ ...providerProblems,
299
+ ...diagnoseMissingEnv(missing, this.envFileValues()),
300
+ ];
301
+ this.warnIfUnconfigured(problems);
302
+
303
+ // `problems` travels to the browser so a failed sign-in can say what is actually wrong: the
304
+ // SDK's own errors for a misconfigured client are generic by design.
305
+ const carrier = JSON.stringify({
306
+ sdkBaseUrl: ui.sdkBaseUrl,
307
+ config,
308
+ problems,
309
+ }).replace(/</g, "\\u003c");
109
310
 
110
- res.send(`${scriptTag}<body>${formHtml}</body>`);
311
+ // Generator-authored, not user input, but still interpolated into an inline <script>: break
312
+ // any literal closing tag so a comment in it cannot end the block early.
313
+ const glue = firebaseGlueScript.replace(/<\/script/gi, "<\\/script");
314
+
315
+ return `
316
+ <script nonce="${nonce}">window.__vexFirebaseLogin = ${carrier};</script>
317
+ <script nonce="${nonce}">${glue}</script>`;
318
+ }
319
+
320
+ /**
321
+ * The env file's own values, read once.
322
+ *
323
+ * Only used to tell a shadowed variable from an unset one; nothing here changes what the app reads.
324
+ * A missing or unparseable file is not an error — plenty of deployments have no `.env` at all.
325
+ */
326
+ private envFileValues(): Record<string, string> {
327
+ if (LoginUI.envFileCache) return LoginUI.envFileCache;
328
+
329
+ let values: Record<string, string> = {};
330
+ try {
331
+ values = dotenv.parse(fs.readFileSync(path.join(process.cwd(), ".env")));
332
+ }
333
+ catch {
334
+ // no .env, or unreadable: every missing name is then simply unset
335
+ }
336
+
337
+ LoginUI.envFileCache = values;
338
+ return values;
339
+ }
340
+
341
+ /**
342
+ * Say so on the server when Firebase's public config is missing or looks wrong.
343
+ *
344
+ * Without this the only signal is a browser alert from the button — which for a missing value reads
345
+ * as "you forgot to set the variables" even when they *are* set in `.env` (the actual cause is
346
+ * usually that the process started before they were, and `.env` is read once at startup), and for a
347
+ * wrong value is something generic from Firebase.
348
+ *
349
+ * Logged once per distinct set of problems, not per request: this runs on a page render.
350
+ */
351
+ private warnIfUnconfigured(problems: string[]): void {
352
+ if (problems.length === 0) return;
353
+
354
+ const signature = problems.join("|");
355
+ if (LoginUI.warnedEnvSignature === signature) return;
356
+ LoginUI.warnedEnvSignature = signature;
357
+
358
+ console.warn(
359
+ `[vex] auth.firebase is enabled but its public browser config is not usable:\n - ` +
360
+ problems.join("\n - ") +
361
+ "\nIf a value is already in .env, restart the server — .env is read once at startup."
362
+ );
111
363
  }
112
364
 
113
365
  private logoutPage(_req: Request, res: Response): void {
@@ -195,3 +447,182 @@ export default class LoginUI {
195
447
  `);
196
448
  }
197
449
  }
450
+
451
+ /**
452
+ * The glue the login page runs inline: preload the modular SDK, popup sign-in, POST the ID token to
453
+ * `POST /api/auth/firebase`, store the token pair.
454
+ *
455
+ * Kept free of backticks and `${` — it is interpolated into a template literal above (there is a test).
456
+ */
457
+ const firebaseGlueScript = `
458
+ document.addEventListener("DOMContentLoaded", function () {
459
+ var settings = window.__vexFirebaseLogin || {};
460
+ var config = settings.config || {};
461
+ var base = settings.sdkBaseUrl;
462
+ var problems = settings.problems || [];
463
+
464
+ var buttons = document.querySelectorAll ? document.querySelectorAll(".firebaseLoginBtn") : [];
465
+
466
+ /**
467
+ * Firebase reports a misconfigured client with something generic - auth/internal-error says
468
+ * nothing about the cause. The login page sends along what the server could determine, so a
469
+ * developer is not left reading a network trace.
470
+ */
471
+ function describe(err) {
472
+ var code = err && err.code ? err.code : "(no code)";
473
+ var hints = {
474
+ "auth/unauthorized-domain":
475
+ "add this origin under Authentication > Settings > Authorized domains",
476
+ "auth/operation-not-allowed":
477
+ "enable this provider under Authentication > Sign-in method",
478
+ "auth/popup-blocked":
479
+ "the browser blocked the popup; allow popups for this origin",
480
+ "auth/popup-closed-by-user":
481
+ "the popup closed before sign-in finished. If you did not close it, the handshake " +
482
+ "between the popup and this page failed: third-party cookies are blocked (Chrome's " +
483
+ "default now), an extension or ad-blocker is interfering, or the popup never reached " +
484
+ "the provider. Open DevTools on the popup window and read the URL it is stuck on - " +
485
+ "that distinguishes all three. A private window with extensions disabled is the " +
486
+ "quickest way to tell an environment cause from a configuration one.",
487
+ "auth/cancelled-popup-request":
488
+ "another popup request was already in flight",
489
+ "auth/network-request-failed":
490
+ "the browser could not reach Firebase. Check whether the request failed with " +
491
+ "net::ERR_BLOCKED_BY_CLIENT - that means an extension blocked it, not the network",
492
+ "auth/internal-error":
493
+ "Firebase returned a generic error. Usual causes: (1) the API key is restricted - in " +
494
+ "Google Cloud console > APIs & Services > Credentials, the key this Web app uses must " +
495
+ "allow this origin under HTTP referrers; (2) an ad-blocker or privacy extension is " +
496
+ "blocking firebaseapp.com / apis.google.com; (3) the auth domain is wrong, so the " +
497
+ "popup lands somewhere that is not the sign-in handler. Check the browser Network tab " +
498
+ "for a failing identitytoolkit.googleapis.com request - its response body holds the " +
499
+ "real reason. A request failing with net::ERR_BLOCKED_BY_CLIENT was never sent: an " +
500
+ "extension blocked it, which is why the same flow often works in a private window."
501
+ };
502
+ var hint = hints[code];
503
+ return code + (hint ? " - " + hint : "") + (err && err.message ? " [" + err.message + "]" : "");
504
+ }
505
+
506
+ function report(message) {
507
+ if (problems.length > 0) {
508
+ message += "\\n\\nServer-side configuration problems:\\n- " + problems.join("\\n- ");
509
+ }
510
+
511
+ alert(message);
512
+ }
513
+
514
+ /** The SDK modules, preloaded on page load. See the note on firebaseGlueScript. */
515
+ var sdk = null;
516
+ var preload = null;
517
+
518
+ function loadSdk() {
519
+ if (!preload) {
520
+ preload = Promise.all([
521
+ import(base + "firebase-app.js"),
522
+ import(base + "firebase-auth.js"),
523
+ ]).then(function (loaded) {
524
+ sdk = { app: loaded[0], auth: loaded[1] };
525
+ return sdk;
526
+ }).catch(function (err) {
527
+ preload = null; // let the next attempt retry the download
528
+ throw err;
529
+ });
530
+ }
531
+ return preload;
532
+ }
533
+
534
+ function providerFor(auth, providerId) {
535
+ switch (providerId) {
536
+ case "google": return new auth.GoogleAuthProvider();
537
+ case "github": return new auth.GithubAuthProvider();
538
+ case "apple": return new auth.OAuthProvider("apple.com");
539
+ case "microsoft": return new auth.OAuthProvider("microsoft.com");
540
+ default: throw new Error("unsupported provider: " + providerId);
541
+ }
542
+ }
543
+
544
+ function appFor(app) {
545
+ return app.getApps().length ? app.getApps()[0] : app.initializeApp(config);
546
+ }
547
+
548
+ /** Open the provider's popup and resolve with a fresh Firebase ID token. */
549
+ function signIn(providerId) {
550
+ return loadSdk().then(function (modules) {
551
+ var provider = providerFor(modules.auth, providerId);
552
+ return modules.auth.signInWithPopup(modules.auth.getAuth(appFor(modules.app)), provider);
553
+ }).then(function (result) {
554
+ return result.user.getIdToken();
555
+ });
556
+ }
557
+
558
+ function post(idToken) {
559
+ return fetch("/api/auth/firebase", {
560
+ method: "POST",
561
+ headers: { "Content-Type": "application/json" },
562
+ body: JSON.stringify({ idToken: idToken }),
563
+ }).then(function (response) {
564
+ // text() first: an error body may be HTML, and json() would hide the status
565
+ return response.text().then(function (text) {
566
+ var body;
567
+ try {
568
+ body = text ? JSON.parse(text) : {};
569
+ }
570
+ catch (e) {
571
+ body = { raw: text };
572
+ }
573
+
574
+ return { ok: response.ok, status: response.status, body: body };
575
+ });
576
+ });
577
+ }
578
+
579
+ /** Same four keys logincallback writes, so the rest of the app reads one shape. */
580
+ function storeTokens(result) {
581
+ localStorage.setItem("accessToken", result.accessToken);
582
+ localStorage.setItem("accessTokenIndex", result.accessTokenIndex);
583
+ localStorage.setItem("refreshToken", result.refreshToken);
584
+ localStorage.setItem("refreshTokenIndex", result.refreshTokenIndex);
585
+ }
586
+
587
+ function unconfigured() {
588
+ return "Firebase is not configured on the server: set FIREBASE_WEB_API_KEY, " +
589
+ "FIREBASE_WEB_AUTH_DOMAIN and FIREBASE_WEB_PROJECT_ID in .env and restart the server " +
590
+ "(.env is read only at startup). The server log names the missing variables.";
591
+ }
592
+
593
+ // Warm the modules so the first click does not pay for the download.
594
+ if (base) loadSdk().catch(function () { /* reported on click */ });
595
+
596
+ Array.prototype.forEach.call(buttons, function (button) {
597
+ button.addEventListener("click", function () {
598
+ if (!config.apiKey || !config.authDomain || !config.projectId) {
599
+ report(unconfigured());
600
+ return;
601
+ }
602
+
603
+ button.disabled = true;
604
+
605
+ signIn(button.getAttribute("data-provider"))
606
+ .then(function (idToken) {
607
+ if (!idToken) throw new Error("sign-in resolved with no ID token");
608
+ return post(idToken);
609
+ })
610
+ .then(function (outcome) {
611
+ var result = outcome.body && outcome.body.result;
612
+ if (outcome.ok && result && result.accessToken) {
613
+ storeTokens(result);
614
+ window.location.href = "/mytokens";
615
+ return;
616
+ }
617
+
618
+ button.disabled = false;
619
+ report("Firebase sign-in failed (" + outcome.status + "): " + JSON.stringify(outcome.body));
620
+ })
621
+ .catch(function (err) {
622
+ button.disabled = false;
623
+ report("Firebase sign-in error: " + describe(err));
624
+ });
625
+ });
626
+ });
627
+ });
628
+ `;
@@ -48,7 +48,7 @@ export default class OAuthProfileMap {
48
48
  active: true,
49
49
  userAuthProfiles: [{
50
50
  provider: oauthProfile.provider,
51
- oauthId: oauthProfile.id,
51
+ providerUserId: oauthProfile.id,
52
52
  username: oauthProfile.username || oauthProfile.displayName
53
53
  }],
54
54
  name: oauthProfile.username || oauthProfile.displayName,
@@ -64,7 +64,7 @@ export default class OAuthProfileMap {
64
64
  active: true,
65
65
  userAuthProfiles: [{
66
66
  provider: oauthProfile.provider,
67
- oauthId: oauthProfile.id,
67
+ providerUserId: oauthProfile.id,
68
68
  username: oauthProfile.username || oauthProfile.displayName
69
69
  }],
70
70
  name: oauthProfile.username || oauthProfile.displayName,
@@ -26,11 +26,11 @@ export default class OAuthStrategyService {
26
26
  const authUser = new OAuthProfileMap().map(profile);
27
27
  const authProfile = authUser.userAuthProfiles?.[0];
28
28
 
29
- // find user by oauthId + provider, or fall back to email
29
+ // find user by providerUserId + provider, or fall back to email
30
30
  let existingUser: UserWithRelations | null = null;
31
- if (authProfile?.oauthId && authProfile?.provider) {
31
+ if (authProfile?.providerUserId && authProfile?.provider) {
32
32
  const matchedProfile = await this.uapRepo.findOneWhere(
33
- { oauthId: authProfile.oauthId, provider: authProfile.provider },
33
+ { providerUserId: authProfile.providerUserId, provider: authProfile.provider },
34
34
  );
35
35
  if (matchedProfile?.userId) {
36
36
  existingUser = await this.userRepo.findOne({ _id: matchedProfile.userId });
@@ -84,9 +84,9 @@ export default class OAuthStrategyService {
84
84
  throw new Error("Invalid OAuth Callback \"authProfile\"");
85
85
  }
86
86
 
87
- // check if this provider/oauthId already tracked
87
+ // check if this provider/providerUserId already tracked
88
88
  const existing = await this.uapRepo.findOneWhere(
89
- { userId: existingUser._id, provider: incomingProfile.provider, oauthId: incomingProfile.oauthId },
89
+ { userId: existingUser._id, provider: incomingProfile.provider, providerUserId: incomingProfile.providerUserId },
90
90
  );
91
91
 
92
92
  if (!existing) {
@@ -18,6 +18,18 @@ export interface localLoginResponse {
18
18
  url: string;
19
19
  }
20
20
 
21
+ /**
22
+ * `POST /auth/firebase` — the answer to a Firebase sign-in.
23
+ * `isNewUser` is true only when this call created the `User` row; a user linked by a verified email address is false.
24
+ */
25
+ export interface firebaseLoginResponse {
26
+ accessToken: string;
27
+ accessTokenIndex: string;
28
+ refreshToken: string;
29
+ refreshTokenIndex: string;
30
+ isNewUser: boolean;
31
+ }
32
+
21
33
  /** Row counts removed alongside the tombstone, so the caller can log and retry. */
22
34
  export interface deleteAccountCounts {
23
35
  authProfiles: number;