very-express 0.9.0-alpha → 0.9.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 (31) hide show
  1. package/AGENTS.md +24 -10
  2. package/dist/index.js +747 -969
  3. package/dist/templates/_middlewares/Authentication.ts +0 -3
  4. package/dist/templates/_middlewares/UserContext.ts +1 -18
  5. package/dist/templates/_projectSettings/env +13 -12
  6. package/dist/templates/_projectSettings/package.json +2 -2
  7. package/dist/templates/_routes/FirebaseAuthUI.gen.ts +20 -0
  8. package/dist/templates/_routes/LoginUI.ts +293 -242
  9. package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +0 -6
  10. package/dist/templates/_services/VexDbConnector.ts +1 -26
  11. package/dist/templates/_services/auth/JWTService.ts +0 -15
  12. package/dist/templates/_types/auth.ts +12 -8
  13. package/dist/templates/_utils/hash.ts +0 -16
  14. package/dist/templates/root/public/js/deleteaccount.js +0 -54
  15. package/docs/appGenerated/auth.md +84 -0
  16. package/docs/architecture/authAndRouting.md +1 -1
  17. package/docs/architecture/databaseTargets.md +4 -2
  18. package/docs/features/accountDeletion.md +2 -3
  19. package/docs/features/auditFields.md +2 -2
  20. package/docs/releaseNote/v0-8-5.md +98 -0
  21. package/docs/releaseNote/v0-9-0.md +41 -47
  22. package/docs/superpowers/specs/2026-09-22-usercontext-audit-enforcement-design.md +9 -9
  23. package/docs/vexJsonSchema.md +17 -0
  24. package/package.json +1 -1
  25. package/vex.config.json +1 -6
  26. package/dist/templates/_routes/ExternalIdentityUI.gen.ts +0 -20
  27. package/dist/templates/root/public/js/externallogin.js +0 -133
  28. package/docs/features/auth.md +0 -34
  29. package/docs/features/externalIdentity.md +0 -163
  30. /package/docs/{ForeignKey.md → features/ForeignKey.md} +0 -0
  31. /package/docs/{apiUsage.md → features/apiUsage.md} +0 -0
@@ -5,18 +5,18 @@ import fs from "fs";
5
5
  import path from "path";
6
6
  import dotenv from "dotenv";
7
7
 
8
- import { externalIdentityUI } from "./ExternalIdentityUI.gen";
8
+ import { firebaseAuthUI } from "./FirebaseAuthUI.gen";
9
9
 
10
10
  /**
11
11
  * Explain config values that `process.env` does not have.
12
12
  *
13
- * Two different situations produce the same symptom — the broker reports itself unconfigured — and they
13
+ * Two different situations produce the same symptom — Firebase reports itself unconfigured — and they
14
14
  * need different fixes, so they are separated here:
15
15
  *
16
16
  * - **present in `.env` but absent from `process.env`**: `dotenv` does not override a variable that is
17
17
  * already set in the environment, and it only runs once at startup. Either the process started before
18
- * the file was edited (the dev watcher used to watch TypeScript only, so a `.env` edit did not reload),
19
- * or the name is exported by the shell / IDE launch config / container with a different value.
18
+ * the file was edited, or the name is exported by the shell / IDE launch config / container with a
19
+ * different value.
20
20
  * - **absent from both**: nothing has set it.
21
21
  *
22
22
  * Pure so the diagnosis can be tested without touching the filesystem.
@@ -49,95 +49,43 @@ export function diagnoseMissingEnv(
49
49
  export interface LoginUIConfig {
50
50
  localAuth: boolean;
51
51
  oauthProviders: string[];
52
- /**
53
- * Serve the self-service deletion page at `/delete_account`.
54
- *
55
- * Optional and defaulting to true so an app generated before this feature existed still
56
- * constructs — its `server.ts` is generated once and is not overwritten on later runs.
57
- */
52
+ /** Serve the self-service deletion page at `/delete_account`. */
58
53
  deleteAccount?: boolean;
59
-
60
- /**
61
- * Override the external-identity (broker SSO) login wiring.
62
- *
63
- * Unnecessary in the normal case: `auth.externalIdentity` in `vex.config.json` makes the generator
64
- * emit a complete default into `ExternalIdentityUI.gen.ts`, which this page falls back to. This
65
- * field exists for the cases the generator cannot know — hand-editing the button label, pointing at
66
- * a self-hosted SDK build, or wiring a broker that has no preset.
67
- */
68
- externalIdentity?: ExternalIdentityUI;
54
+ /** Override the Firebase sign-in wiring. */
55
+ firebase?: FirebaseAuthUI;
69
56
  }
70
57
 
71
- /**
72
- * Everything the login page needs to drive a broker, as emitted into `ExternalIdentityUI.gen.ts`.
73
- *
74
- * vex owns the button, the nonce'd script tags and the POST to `/api/auth/external`; the broker's own
75
- * browser code arrives as `initScript`, because how to call a vendor's JS SDK is the one thing that
76
- * cannot be generalised. Nothing here is secret — `config` is the broker's *public* browser config,
77
- * resolved from env at request time.
78
- */
79
- export interface ExternalIdentityUI {
58
+ /** Everything the login page needs to drive Firebase, as emitted into `FirebaseAuthUI.gen.ts`. */
59
+ export interface FirebaseAuthUI {
80
60
  /** Button text template; `{provider}` is replaced by the provider's label. */
81
61
  label: string;
82
- /** Browser SDK scripts, pinned to a version, loaded in order before `initScript`. */
83
- sdkScripts: string[];
84
- /**
85
- * Global the init script defines for starting a sign-in. `signIn(providerId)` resolves to an ID
86
- * token; in `redirect` mode the page navigates away and the promise never settles, so the caller
87
- * does not need to know the mode.
88
- */
89
- getToken: string;
90
- /** Global that completes a redirect sign-in: `resume()` resolves to an ID token, or `null`. */
91
- resumeRedirect: string;
92
- /** Which mode the page is in; passed to the browser so the SDK can choose. */
93
- signInMethod: "popup" | "redirect";
94
- /** Sign-in methods rendered as buttons, each passed to `getToken` as its `id`. */
62
+ /** gstatic ESM directory for the pinned SDK version, trailing slash included. */
63
+ sdkBaseUrl: string;
64
+ /** Every provider the page can start. */
95
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;
96
70
  /** Public config key → env var name. Resolved at render time; missing values stay absent. */
97
71
  envKeys: Record<string, string>;
98
- /** Browser JS that initialises the SDK and defines `getToken`. */
99
- initScript: string;
100
- /**
101
- * Declarative checks on the resolved public config, applied server-side on each render.
102
- *
103
- * The broker's own errors for a misconfigured client are generic (Firebase's
104
- * `auth/internal-error` being the canonical example), so a knowable mistake should be named here
105
- * instead — in the server log, and in the message the browser shows.
106
- */
107
- configChecks?: externalIdentityConfigCheck[];
108
- /**
109
- * Extra CSP sources the broker's SDK needs on the login page.
110
- *
111
- * A nonce authorises the tags this page renders, but a broker SDK also injects scripts at runtime
112
- * (Firebase Auth loads `apis.google.com/js/api.js` for the popup handshake) and those carry no
113
- * nonce — so the hosts have to be allowed by name.
114
- */
115
- csp?: {
116
- scriptSrc?: string[];
117
- };
118
- /**
119
- * Where `sdkScripts` come from, when they are served from an installed npm package rather than a
120
- * CDN. `files` is the allowlist for the route, so the route cannot be walked out of the package.
121
- */
122
- sdkFromPackage?: {
123
- route: string;
124
- package: string;
125
- files: string[];
72
+ /** Hosts Firebase's sign-in needs, per directive. */
73
+ csp: {
74
+ scriptSrc: string[];
75
+ connectSrc: string[];
76
+ frameSrc: string[];
126
77
  };
127
78
  }
128
79
 
129
- export interface externalIdentityConfigCheck {
130
- /** Config key the check applies to. */
131
- key: string;
132
- warnIfMatches?: string;
133
- warnUnlessMatches?: string;
134
- /** What is wrong and what to do about it. */
135
- message: string;
80
+ /** A sign-in method to render a button for. */
81
+ interface firebaseProvider {
82
+ id: string;
83
+ label: string;
136
84
  }
137
85
 
138
86
  export default class LoginUI {
139
87
 
140
- /** Last set of problems warned about, so a page render logs it once. */
88
+ /** Last set of problems warned about, so a page render logs them once. */
141
89
  private static warnedEnvSignature = "";
142
90
 
143
91
  /** The parsed `.env`, read at most once per process. */
@@ -169,92 +117,43 @@ export default class LoginUI {
169
117
  if (this.deleteAccountEnabled) {
170
118
  this.router.get("/delete_account", this.deleteAccountPage.bind(this));
171
119
  }
172
-
173
- const sdk = this.externalUI?.sdkFromPackage;
174
- if (sdk) {
175
- this.router.get(`${sdk.route}/:file`, this.brokerSdkFile.bind(this));
176
- }
177
120
  }
178
121
 
179
- /**
180
- * Serve the broker's SDK out of the installed npm package.
181
- *
182
- * Self-hosting it is what makes the SDK version npm's business and keeps the scripts same-origin —
183
- * no CDN host needs a CSP allowance, and the page works offline. The package is read from
184
- * `node_modules` at request time rather than copied at generation, because generation runs before
185
- * `npm install`.
186
- */
187
- private brokerSdkFile(req: Request, res: Response): void {
188
- const sdk = this.externalUI?.sdkFromPackage;
189
- const file = typeof req.params?.file === "string" ? req.params.file : "";
190
-
191
- res.setHeader("Content-Type", "text/plain; charset=utf-8");
192
-
193
- // allowlist, not sanitising: a name that is not declared is rejected outright
194
- if (!sdk || !sdk.files.includes(file)) {
195
- res.status(404).send("Unknown broker SDK file.");
196
- return;
197
- }
198
-
199
- const fullPath = path.join(process.cwd(), "node_modules", sdk.package, file);
200
- let body: string;
201
- try {
202
- body = fs.readFileSync(fullPath, "utf8");
203
- }
204
- catch {
205
- const message =
206
- `Broker SDK not found at ${fullPath}. Run \`npm install\` — it is declared as a ` +
207
- `dependency, so it is missing only because the install has not run.`;
208
- console.warn(`[vex] ${message}`);
209
- res.status(500).send(message);
210
- return;
211
- }
212
-
213
- res.setHeader("Content-Type", "application/javascript; charset=utf-8");
214
- res.send(body);
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;
215
125
  }
216
126
 
217
- /**
218
- * Is the vendored broker SDK actually present?
219
- *
220
- * Worth checking at render time: the dependency is added to an existing project's `package.json` by
221
- * the generator, so the first run after upgrading has a page whose script tags 404 until `npm
222
- * install` runs.
223
- */
224
- private sdkProblems(external: ExternalIdentityUI): string[] {
225
- const sdk = external.sdkFromPackage;
226
- if (!sdk) return [];
227
-
228
- const missing = sdk.files.filter((file) =>
229
- !fs.existsSync(path.join(process.cwd(), "node_modules", sdk.package, file)));
230
-
231
- if (missing.length === 0) return [];
127
+ private nonce(): string {
128
+ return crypto.randomBytes(16).toString("base64");
129
+ }
232
130
 
233
- return [
234
- `broker SDK not installed: ${missing.join(", ")}. It is declared as a dependency of ` +
235
- `"${sdk.package}" — run \`npm install\`.`,
236
- ];
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);
237
134
  }
238
135
 
239
- private nonce(): string {
240
- return crypto.randomBytes(16).toString("base64");
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;
241
139
  }
242
140
 
243
- /**
244
- * `script-src` for the login page: the page's own scripts plus whatever the broker's SDK needs.
245
- *
246
- * The extra hosts are not optional decoration — a broker SDK that injects a script without a nonce
247
- * fails silently behind this policy, and the only symptom is a generic authentication error. See
248
- * `ExternalIdentityUI.csp`.
249
- */
141
+ /** CSP for the login page: the page's own scripts plus the hosts Firebase's sign-in needs. */
250
142
  private loginPageCsp(nonce: string): string {
251
- const extra = this.externalUI?.csp?.scriptSrc ?? [];
252
- const sources = ["'self'", `'nonce-${nonce}'`, ...extra.filter((host, i) => extra.indexOf(host) === i)];
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;
253
148
 
254
- return `script-src ${sources.join(" ")}`;
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("; ");
255
154
  }
256
155
 
257
- /** Escape for HTML text/attribute context. The label comes from the app's own server.ts. */
156
+ /** Escape for HTML text/attribute context. Labels and provider ids come from configuration. */
258
157
  private escapeHtml(value: string): string {
259
158
  return value
260
159
  .replace(/&/g, "&amp;")
@@ -264,26 +163,39 @@ export default class LoginUI {
264
163
  .replace(/'/g, "&#39;");
265
164
  }
266
165
 
267
- /**
268
- * The external-identity wiring in force: an explicit app override, else the generated default.
269
- *
270
- * The fallback is why `auth.externalIdentity` needs no `server.ts` edit — `server.ts` is written
271
- * once and never overwritten, so anything only reachable through it would not apply to an existing
272
- * project. This file and `ExternalIdentityUI.gen.ts` are both regenerated.
273
- */
274
- private get externalUI(): ExternalIdentityUI | undefined {
275
- return this.config.externalIdentity ?? externalIdentityUI;
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 };
276
188
  }
277
189
 
278
190
  /**
279
- * Auth is on when *any* sign-in path exists. `externalIdentity` counts: an app with
280
- * `localAuth: false` and no passport provider is not auth-less if a broker is configured, and
281
- * leaving it out of this test would hide the login link for exactly that app.
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.
282
194
  */
283
195
  private get authEnabled(): boolean {
284
196
  return this.config.localAuth
285
197
  || this.config.oauthProviders.length > 0
286
- || !!this.externalUI;
198
+ || !!this.firebaseUI;
287
199
  }
288
200
 
289
201
  private homePage(_req: Request, res: Response): void {
@@ -318,6 +230,10 @@ export default class LoginUI {
318
230
  const nonce = this.nonce();
319
231
  res.setHeader("Content-Security-Policy", this.loginPageCsp(nonce));
320
232
 
233
+ if (this.firebaseUI) {
234
+ res.setHeader("Cross-Origin-Opener-Policy", "same-origin-allow-popups");
235
+ }
236
+
321
237
  let formHtml = "";
322
238
  if (this.config.localAuth) {
323
239
  formHtml += `
@@ -331,9 +247,11 @@ export default class LoginUI {
331
247
  <br/><br/>`;
332
248
  }
333
249
 
250
+ const firebase = this.firebaseUI;
251
+ const selection = firebase ? this.firebaseProviderSelection(firebase) : undefined;
252
+
334
253
  formHtml += " <p>Login with SSO:</p>\n";
335
- const external = this.externalUI;
336
- if (this.config.oauthProviders.length === 0 && !external) {
254
+ if (this.config.oauthProviders.length === 0 && !firebase) {
337
255
  formHtml += " <p>No OAuth provider configured.</p>\n";
338
256
  }
339
257
  else {
@@ -342,75 +260,61 @@ export default class LoginUI {
342
260
  formHtml += ` <a href="/api/auth/${provider}">${provider}</a><br/>\n`;
343
261
  });
344
262
 
345
- // external identity: client-driven. One button per configured sign-in method; the
346
- // provider id travels to the glue as a data attribute, and on to getToken().
347
- if (external) {
348
- external.providers.forEach((provider) => {
349
- const text = external.label.replace("{provider}", provider.label);
350
- formHtml += ` <button class="externalLoginBtn" data-provider="${this.escapeHtml(provider.id)}">${this.escapeHtml(text)}</button><br/>\n`;
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`;
351
269
  });
352
270
  }
353
271
  }
354
272
 
355
- const scripts = this.externalIdentityScripts(nonce);
356
- const localAuthScript = this.config.localAuth
273
+ const scriptTag = this.config.localAuth
357
274
  ? `<script nonce="${nonce}" src="/js/login.js?d=${Date.now()}"></script>`
358
275
  : "";
276
+ const firebaseScripts = firebase && selection ? this.firebaseScripts(nonce, selection.problems) : "";
359
277
 
360
- res.send(`${localAuthScript}${scripts}<body>${formHtml}</body>`);
278
+ res.send(`${scriptTag}${firebaseScripts}<body>${formHtml}</body>`);
361
279
  }
362
280
 
363
281
  /**
364
- * Script tags for the external-identity login page, in load order: the broker's SDK, an inline
365
- * carrier holding the token getter's name and the broker's public browser config, the broker's
366
- * init script, and finally the glue.
367
- *
368
- * Every tag carries the page nonce, which is what permits a CDN URL under `script-src 'self'
369
- * 'nonce-…'`. They are blocking tags on purpose: `initScript` runs immediately and defines the
370
- * global the button calls, so it must not race the SDK.
371
- *
372
- * The public config is read from `process.env` at render time rather than baked in, so a value
373
- * rotated in the environment takes effect without regenerating.
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.
374
284
  */
375
- private externalIdentityScripts(nonce: string): string {
376
- const external = this.externalUI;
377
- if (!external) return "";
285
+ private firebaseScripts(nonce: string, providerProblems: string[]): string {
286
+ const ui = this.firebaseUI;
287
+ if (!ui) return "";
378
288
 
379
289
  const config: Record<string, string> = {};
380
290
  const missing: string[] = [];
381
- for (const [key, envName] of Object.entries(external.envKeys)) {
291
+ for (const [key, envName] of Object.entries(ui.envKeys)) {
382
292
  const value = process.env[envName];
383
293
  if (value) config[key] = value;
384
294
  else missing.push(envName);
385
295
  }
386
- const problems = [...diagnoseMissingEnv(missing, this.envFileValues()),
387
- ...this.sdkProblems(external),
388
- ...this.checkConfig(external, config)];
389
- this.warnIfUnconfigured(problems);
390
296
 
391
- const sdkScripts = external.sdkScripts
392
- .map((src) => `<script nonce="${nonce}" src="${this.escapeHtml(src)}"></script>`)
393
- .join("\n ");
297
+ const problems = [
298
+ ...providerProblems,
299
+ ...diagnoseMissingEnv(missing, this.envFileValues()),
300
+ ];
301
+ this.warnIfUnconfigured(problems);
394
302
 
395
303
  // `problems` travels to the browser so a failed sign-in can say what is actually wrong: the
396
- // broker's own errors for a misconfigured client are generic by design.
304
+ // SDK's own errors for a misconfigured client are generic by design.
397
305
  const carrier = JSON.stringify({
398
- getToken: external.getToken,
399
- resumeRedirect: external.resumeRedirect,
400
- signInMethod: external.signInMethod,
306
+ sdkBaseUrl: ui.sdkBaseUrl,
401
307
  config,
402
308
  problems,
403
309
  }).replace(/</g, "\\u003c");
404
310
 
405
- // The init script is preset-authored, not user input, but it is still interpolated into an
406
- // inline <script>: break any literal closing tag so a comment in it cannot end the block early.
407
- const initScript = external.initScript.replace(/<\/script/gi, "<\\/script");
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");
408
314
 
409
315
  return `
410
- ${sdkScripts}
411
- <script nonce="${nonce}">window.__vexExternalLogin = ${carrier};</script>
412
- <script nonce="${nonce}">${initScript}</script>
413
- <script nonce="${nonce}" src="/js/externallogin.js"></script>`;
316
+ <script nonce="${nonce}">window.__vexFirebaseLogin = ${carrier};</script>
317
+ <script nonce="${nonce}">${glue}</script>`;
414
318
  }
415
319
 
416
320
  /**
@@ -435,33 +339,12 @@ export default class LoginUI {
435
339
  }
436
340
 
437
341
  /**
438
- * Apply the preset's declarative config checks.
439
- *
440
- * These catch mistakes that are knowable here but surface in the browser as something generic — a
441
- * Firebase API key/appId from a *mobile* app registration being the motivating example.
442
- */
443
- private checkConfig(external: ExternalIdentityUI, config: Record<string, string>): string[] {
444
- const problems: string[] = [];
445
-
446
- for (const check of external.configChecks ?? []) {
447
- const value = config[check.key];
448
- if (value === undefined) continue; // already reported as missing
449
-
450
- const matched = check.warnIfMatches ? new RegExp(check.warnIfMatches).test(value) : false;
451
- const unmatched = check.warnUnlessMatches ? !new RegExp(check.warnUnlessMatches).test(value) : false;
452
- if (matched || unmatched) problems.push(check.message);
453
- }
454
-
455
- return problems;
456
- }
457
-
458
- /**
459
- * Say so on the server when the broker's public config is missing or looks wrong.
342
+ * Say so on the server when Firebase's public config is missing or looks wrong.
460
343
  *
461
344
  * Without this the only signal is a browser alert from the button — which for a missing value reads
462
345
  * as "you forgot to set the variables" even when they *are* set in `.env` (the actual cause is
463
346
  * usually that the process started before they were, and `.env` is read once at startup), and for a
464
- * wrong value is something generic from the broker.
347
+ * wrong value is something generic from Firebase.
465
348
  *
466
349
  * Logged once per distinct set of problems, not per request: this runs on a page render.
467
350
  */
@@ -473,7 +356,7 @@ export default class LoginUI {
473
356
  LoginUI.warnedEnvSignature = signature;
474
357
 
475
358
  console.warn(
476
- `[vex] external identity is enabled but its public browser config is not usable:\n - ` +
359
+ `[vex] auth.firebase is enabled but its public browser config is not usable:\n - ` +
477
360
  problems.join("\n - ") +
478
361
  "\nIf a value is already in .env, restart the server — .env is read once at startup."
479
362
  );
@@ -539,20 +422,10 @@ export default class LoginUI {
539
422
  *
540
423
  * The copy is deliberately explicit about what survives: this is a tombstone, not an erasure of
541
424
  * everything. Claiming otherwise would contradict both the implementation and the store listing.
542
- *
543
- * The sign-in prerequisite is stated in the page rather than left to the script, because the
544
- * server picks the account from the verified token only: with no token there is nothing to
545
- * delete, and a visitor arriving here directly would otherwise get a bare `401`. This page is
546
- * regenerated on every run, so the guidance reaches existing projects; `deleteaccount.js` is not
547
- * overwritten, which is why the check is not the only line of defence.
548
425
  */
549
426
  private deleteAccountPage(_req: Request, res: Response): void {
550
427
  const nonce = this.nonce();
551
428
  res.setHeader("Content-Security-Policy", `script-src 'self' 'nonce-${nonce}'`);
552
- const signInHint = this.authEnabled
553
- ? `<strong>You must be signed in.</strong> Deletion is self-service and the server takes the
554
- account from your access token, so <a href="/login">sign in first</a> if you are not.`
555
- : "<strong>You must be signed in.</strong> Deletion is self-service and the server takes the account from your access token.";
556
429
  res.send(`
557
430
  <link rel="stylesheet" href="/css/style.css">
558
431
  <body>
@@ -562,7 +435,6 @@ export default class LoginUI {
562
435
  You will need to create a new account to use the service again; the same
563
436
  sign-in provider will not restore this one.
564
437
  </p>
565
- <p id="signInRequired">${signInHint}</p>
566
438
  <p>Type <code>DELETE</code> to confirm:</p>
567
439
  <input type="text" id="confirmInput" autocomplete="off"/>
568
440
  <br/><br/>
@@ -575,3 +447,182 @@ export default class LoginUI {
575
447
  `);
576
448
  }
577
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
+ `;