very-express 0.8.3 → 0.9.0-alpha

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.
@@ -2,7 +2,8 @@
2
2
  import { Request, Response, NextFunction } from "express";
3
3
  import { JsonWebTokenError } from "jsonwebtoken";
4
4
  import JWTService from "../_services/auth/JWTService.gen";
5
- import UserContext from "./UserContext.gen";
5
+ import { isActiveIdentity } from "../_services/auth/AccountStateGuard.gen";
6
+ import UserContext, { userIdOfToken } from "./UserContext.gen";
6
7
  import log from "../_utils/logger.gen";
7
8
  import { VexResErr } from "../_types/vex";
8
9
 
@@ -10,38 +11,54 @@ class Authentication {
10
11
 
11
12
  private JWTService = new JWTService();
12
13
 
13
- public middleware = (req: Request, res: Response, next: NextFunction) => {
14
- try {
15
- // gate keeper
16
- // log.info("Authentication.middleware", req.headers["x-auth-index"], req.headers.authorization);
17
- const token = req.headers.authorization?.split(" ")[1];
18
- const accessTokenIndex = req.headers["x-auth-index"]?.toString();
19
-
20
- if (!token || !accessTokenIndex) {
21
- log.warn("invalid header", {
22
- "X-Auth-Index": req.headers["x-auth-index"],
23
- "Authorization": req.headers.authorization
24
- });
25
- throw 401;
26
- }
27
-
28
- // verify token
29
- const tokenData = this.JWTService.verifyToken(token, accessTokenIndex);
30
- req.user = tokenData;
31
- UserContext.run(tokenData, () => next());
14
+ /**
15
+ * Express request handler.
16
+ *
17
+ * Deliberately NOT `async`: both call sites are express chains — `@Middlewares(...)`, which the
18
+ * tsoa route file spreads as a plain RequestHandler, and `router.use(...)`. Express 4 does not
19
+ * catch a rejected promise, so an async handler would turn every failure into an unhandled
20
+ * rejection instead of a response. The asynchronous part lives in `handle()` and every outcome
21
+ * is routed to `next()`.
22
+ */
23
+ public middleware = (req: Request, res: Response, next: NextFunction): void => {
24
+ this.handle(req, next).catch((e: unknown) => next(this.toVexErr(e)));
25
+ };
26
+
27
+ private async handle(req: Request, next: NextFunction): Promise<void> {
28
+ // gate keeper
29
+ // log.info("Authentication.middleware", req.headers["x-auth-index"], req.headers.authorization);
30
+ const token = req.headers.authorization?.split(" ")[1];
31
+ const accessTokenIndex = req.headers["x-auth-index"]?.toString();
32
+
33
+ if (!token || !accessTokenIndex) {
34
+ log.warn("invalid header", {
35
+ "X-Auth-Index": req.headers["x-auth-index"],
36
+ "Authorization": req.headers.authorization
37
+ });
38
+ throw 401;
32
39
  }
33
- catch (e: any) {
34
- if (typeof e === "number") {
35
- throw new VexResErr(e, undefined);
36
- }
37
- else if (e instanceof JsonWebTokenError) {
38
- throw new VexResErr(400, undefined, e?.message);
39
- }
40
- else {
41
- throw new VexResErr(500, undefined, e?.message);
42
- }
40
+
41
+ // verify token
42
+ const tokenData = this.JWTService.verifyToken(token, accessTokenIndex);
43
+
44
+ // The signature only proves the token was issued; it says nothing about the account still
45
+ // being there. A deleted account is soft-deleted, so this check is what stops its token
46
+ // from working for the rest of its lifetime.
47
+ if (!(await isActiveIdentity(userIdOfToken(tokenData)))) {
48
+ throw new VexResErr(401, undefined, "Account is not active");
43
49
  }
44
- };
50
+
51
+ req.user = tokenData;
52
+ UserContext.run(tokenData, () => next());
53
+ }
54
+
55
+ private toVexErr(e: unknown): VexResErr {
56
+ if (typeof e === "number") return new VexResErr(e, undefined);
57
+ if (e instanceof VexResErr) return e;
58
+ if (e instanceof JsonWebTokenError) return new VexResErr(400, undefined, e?.message);
59
+
60
+ return new VexResErr(500, undefined, e instanceof Error ? e.message : undefined);
61
+ }
45
62
  }
46
63
 
47
- export default new Authentication();
64
+ export default new Authentication();
@@ -19,6 +19,19 @@ OAUTH_GITHUB_CLIENTSECRET=
19
19
  # OAUTH_APPLE_CLIENTID=
20
20
  # OAUTH_APPLE_CLIENTSECRET=
21
21
 
22
+ # EXTERNAL IDENTITY (broker SSO) — see auth.externalIdentity in vex.config.json
23
+ # These are the broker's *public* browser config values: they are served to the login page by design,
24
+ # and are not secrets. There is no client secret here — the ID token is verified against the issuer's
25
+ # published JWKS, so the backend holds no broker credential at all.
26
+ # NOTE: .env is read once at process start; the dev watcher reloads on changes to this file. But
27
+ # dotenv never overrides a variable that is ALREADY set in the environment — if a name here is also
28
+ # exported by your shell, IDE launch config or container, that value wins and this file is ignored for
29
+ # it. The server logs which values it could not resolve, and says when one is being shadowed.
30
+ FIREBASE_API_KEY=
31
+ FIREBASE_AUTH_DOMAIN=
32
+ FIREBASE_PROJECT_ID=
33
+ FIREBASE_APP_ID=
34
+
22
35
  # JWT token
23
36
  ACCESS_TOKEN_EXPIRE_TIME='1h'
24
37
  REFRESH_TOKEN_EXPIRE_TIME='24h'
@@ -3,7 +3,7 @@
3
3
  "scripts": {
4
4
  "build": "npm run openapi && tsc -p . && node scripts/build.js",
5
5
  "start": "node dist/server.js",
6
- "dev": "nodemon --watch src --ext ts --ignore src/system/_routes/tsoa_routes.ts --ignore src/openapi/ --exec \"tsoa spec-and-routes && ts-node src/server.ts\"",
6
+ "dev": "nodemon --watch src --watch .env --ext ts,env --ignore src/system/_routes/tsoa_routes.ts --ignore src/openapi/ --exec \"tsoa spec-and-routes && ts-node src/server.ts\"",
7
7
  "openapi": "tsoa spec-and-routes",
8
8
  "docker-build": "docker build -t very-express .",
9
9
  "docker-start": "docker run -p 3000:3000 very-express"
@@ -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": "^12.19.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 { ExternalIdentityUI } 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 either the resolved
8
+ * `auth.externalIdentity` settings or `undefined` when the feature is off. It lives in the template
9
+ * directory so that `LoginUI.ts`'s unconditional import resolves in this repo — the import has to be
10
+ * unconditional because the default is how the configuration reaches the login page without editing
11
+ * the app-owned `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 externalIdentityUI: ExternalIdentityUI | undefined = undefined;
17
+
18
+ export function setExternalIdentityUI(ui: ExternalIdentityUI | undefined): void {
19
+ externalIdentityUI = ui;
20
+ }
@@ -1,14 +1,148 @@
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 { externalIdentityUI } from "./ExternalIdentityUI.gen";
9
+
10
+ /**
11
+ * Explain config values that `process.env` does not have.
12
+ *
13
+ * Two different situations produce the same symptom — the broker 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 (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.
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[];
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
+ */
58
+ 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;
69
+ }
70
+
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 {
80
+ /** Button text template; `{provider}` is replaced by the provider's label. */
81
+ 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`. */
95
+ providers: { id: string; label: string }[];
96
+ /** Public config key → env var name. Resolved at render time; missing values stay absent. */
97
+ 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[];
126
+ };
127
+ }
128
+
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;
8
136
  }
9
137
 
10
138
  export default class LoginUI {
11
139
 
140
+ /** Last set of problems warned about, so a page render logs it once. */
141
+ private static warnedEnvSignature = "";
142
+
143
+ /** The parsed `.env`, read at most once per process. */
144
+ private static envFileCache: Record<string, string> | undefined;
145
+
12
146
  private router: Router = Router();
13
147
  private config: LoginUIConfig;
14
148
 
@@ -21,6 +155,10 @@ export default class LoginUI {
21
155
  return this.router;
22
156
  }
23
157
 
158
+ private get deleteAccountEnabled(): boolean {
159
+ return this.config.deleteAccount ?? true;
160
+ }
161
+
24
162
  private registerRoutes(): void {
25
163
  this.router.get("/", this.homePage.bind(this));
26
164
  this.router.get("/login", this.loginPage.bind(this));
@@ -28,25 +166,144 @@ export default class LoginUI {
28
166
  this.router.get("/mytokens", this.myTokensPage.bind(this));
29
167
  this.router.get("/refreshtoken", this.refreshTokenPage.bind(this));
30
168
  this.router.get("/logincallback", this.loginCallbackPage.bind(this));
169
+ if (this.deleteAccountEnabled) {
170
+ this.router.get("/delete_account", this.deleteAccountPage.bind(this));
171
+ }
172
+
173
+ const sdk = this.externalUI?.sdkFromPackage;
174
+ if (sdk) {
175
+ this.router.get(`${sdk.route}/:file`, this.brokerSdkFile.bind(this));
176
+ }
177
+ }
178
+
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);
215
+ }
216
+
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 [];
232
+
233
+ return [
234
+ `broker SDK not installed: ${missing.join(", ")}. It is declared as a dependency of ` +
235
+ `"${sdk.package}" — run \`npm install\`.`,
236
+ ];
31
237
  }
32
238
 
33
239
  private nonce(): string {
34
240
  return crypto.randomBytes(16).toString("base64");
35
241
  }
36
242
 
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
+ */
250
+ 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)];
253
+
254
+ return `script-src ${sources.join(" ")}`;
255
+ }
256
+
257
+ /** Escape for HTML text/attribute context. The label comes from the app's own server.ts. */
258
+ private escapeHtml(value: string): string {
259
+ return value
260
+ .replace(/&/g, "&amp;")
261
+ .replace(/</g, "&lt;")
262
+ .replace(/>/g, "&gt;")
263
+ .replace(/"/g, "&quot;")
264
+ .replace(/'/g, "&#39;");
265
+ }
266
+
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;
276
+ }
277
+
278
+ /**
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.
282
+ */
283
+ private get authEnabled(): boolean {
284
+ return this.config.localAuth
285
+ || this.config.oauthProviders.length > 0
286
+ || !!this.externalUI;
287
+ }
288
+
37
289
  private homePage(_req: Request, res: Response): void {
38
- const authLinks = this.config.localAuth || this.config.oauthProviders.length > 0
290
+ const authLinks = this.authEnabled
39
291
  ? `<li><a href="/login">Login</a></li>
40
292
  <li><a href="/mytokens">myTokens</a></li>
41
293
  <li><a href="/refreshtoken">RefreshToken</a></li>
42
294
  <li><a href="/logout">LogOut</a></li>`
43
295
  : "";
44
296
 
297
+ const deleteAccountLink = this.deleteAccountEnabled
298
+ ? `<li><a href="/delete_account">Delete account</a></li>`
299
+ : "";
300
+
45
301
  res.send(`
46
302
  <div>
47
303
  <h1>Hello World</h1>
48
304
  <ul>
49
305
  ${authLinks}
306
+ ${deleteAccountLink}
50
307
  <li><a href="/swagger">Swagger UI</a></li>
51
308
  </ul>
52
309
  <h1>Others</h1>
@@ -59,7 +316,7 @@ export default class LoginUI {
59
316
 
60
317
  private loginPage(_req: Request, res: Response): void {
61
318
  const nonce = this.nonce();
62
- res.setHeader("Content-Security-Policy", `script-src 'self' 'nonce-${nonce}'`);
319
+ res.setHeader("Content-Security-Policy", this.loginPageCsp(nonce));
63
320
 
64
321
  let formHtml = "";
65
322
  if (this.config.localAuth) {
@@ -75,20 +332,151 @@ export default class LoginUI {
75
332
  }
76
333
 
77
334
  formHtml += " <p>Login with SSO:</p>\n";
78
- if (this.config.oauthProviders.length === 0) {
335
+ const external = this.externalUI;
336
+ if (this.config.oauthProviders.length === 0 && !external) {
79
337
  formHtml += " <p>No OAuth provider configured.</p>\n";
80
338
  }
81
339
  else {
340
+ // passport providers: server-driven redirect flows
82
341
  this.config.oauthProviders.forEach((provider) => {
83
342
  formHtml += ` <a href="/api/auth/${provider}">${provider}</a><br/>\n`;
84
343
  });
344
+
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`;
351
+ });
352
+ }
85
353
  }
86
354
 
87
- const scriptTag = this.config.localAuth
355
+ const scripts = this.externalIdentityScripts(nonce);
356
+ const localAuthScript = this.config.localAuth
88
357
  ? `<script nonce="${nonce}" src="/js/login.js?d=${Date.now()}"></script>`
89
358
  : "";
90
359
 
91
- res.send(`${scriptTag}<body>${formHtml}</body>`);
360
+ res.send(`${localAuthScript}${scripts}<body>${formHtml}</body>`);
361
+ }
362
+
363
+ /**
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.
374
+ */
375
+ private externalIdentityScripts(nonce: string): string {
376
+ const external = this.externalUI;
377
+ if (!external) return "";
378
+
379
+ const config: Record<string, string> = {};
380
+ const missing: string[] = [];
381
+ for (const [key, envName] of Object.entries(external.envKeys)) {
382
+ const value = process.env[envName];
383
+ if (value) config[key] = value;
384
+ else missing.push(envName);
385
+ }
386
+ const problems = [...diagnoseMissingEnv(missing, this.envFileValues()),
387
+ ...this.sdkProblems(external),
388
+ ...this.checkConfig(external, config)];
389
+ this.warnIfUnconfigured(problems);
390
+
391
+ const sdkScripts = external.sdkScripts
392
+ .map((src) => `<script nonce="${nonce}" src="${this.escapeHtml(src)}"></script>`)
393
+ .join("\n ");
394
+
395
+ // `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.
397
+ const carrier = JSON.stringify({
398
+ getToken: external.getToken,
399
+ resumeRedirect: external.resumeRedirect,
400
+ signInMethod: external.signInMethod,
401
+ config,
402
+ problems,
403
+ }).replace(/</g, "\\u003c");
404
+
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");
408
+
409
+ 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>`;
414
+ }
415
+
416
+ /**
417
+ * The env file's own values, read once.
418
+ *
419
+ * Only used to tell a shadowed variable from an unset one; nothing here changes what the app reads.
420
+ * A missing or unparseable file is not an error — plenty of deployments have no `.env` at all.
421
+ */
422
+ private envFileValues(): Record<string, string> {
423
+ if (LoginUI.envFileCache) return LoginUI.envFileCache;
424
+
425
+ let values: Record<string, string> = {};
426
+ try {
427
+ values = dotenv.parse(fs.readFileSync(path.join(process.cwd(), ".env")));
428
+ }
429
+ catch {
430
+ // no .env, or unreadable: every missing name is then simply unset
431
+ }
432
+
433
+ LoginUI.envFileCache = values;
434
+ return values;
435
+ }
436
+
437
+ /**
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.
460
+ *
461
+ * Without this the only signal is a browser alert from the button — which for a missing value reads
462
+ * as "you forgot to set the variables" even when they *are* set in `.env` (the actual cause is
463
+ * 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.
465
+ *
466
+ * Logged once per distinct set of problems, not per request: this runs on a page render.
467
+ */
468
+ private warnIfUnconfigured(problems: string[]): void {
469
+ if (problems.length === 0) return;
470
+
471
+ const signature = problems.join("|");
472
+ if (LoginUI.warnedEnvSignature === signature) return;
473
+ LoginUI.warnedEnvSignature = signature;
474
+
475
+ console.warn(
476
+ `[vex] external identity is enabled but its public browser config is not usable:\n - ` +
477
+ problems.join("\n - ") +
478
+ "\nIf a value is already in .env, restart the server — .env is read once at startup."
479
+ );
92
480
  }
93
481
 
94
482
  private logoutPage(_req: Request, res: Response): void {
@@ -145,4 +533,45 @@ export default class LoginUI {
145
533
  </body>
146
534
  `);
147
535
  }
536
+
537
+ /**
538
+ * Self-service account deletion.
539
+ *
540
+ * The copy is deliberately explicit about what survives: this is a tombstone, not an erasure of
541
+ * 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
+ */
549
+ private deleteAccountPage(_req: Request, res: Response): void {
550
+ const nonce = this.nonce();
551
+ 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
+ res.send(`
557
+ <link rel="stylesheet" href="/css/style.css">
558
+ <body>
559
+ <h1>Delete account</h1>
560
+ <p><strong>This cannot be undone.</strong></p>
561
+ <p>
562
+ You will need to create a new account to use the service again; the same
563
+ sign-in provider will not restore this one.
564
+ </p>
565
+ <p id="signInRequired">${signInHint}</p>
566
+ <p>Type <code>DELETE</code> to confirm:</p>
567
+ <input type="text" id="confirmInput" autocomplete="off"/>
568
+ <br/><br/>
569
+ <button id="deleteAccountBtn">Delete my account</button>
570
+ <br/><br/>
571
+ <pre id="deleteResult"></pre>
572
+ <a href="/">back to home</a>
573
+ </body>
574
+ <script nonce="${nonce}" src="/js/deleteaccount.js"></script>
575
+ `);
576
+ }
148
577
  }