very-express 0.8.4 → 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.
- package/AGENTS.md +8 -1
- package/dist/index.js +1120 -580
- package/dist/templates/_projectSettings/env +13 -0
- package/dist/templates/_projectSettings/package.json +2 -1
- package/dist/templates/_routes/ExternalIdentityUI.gen.ts +20 -0
- package/dist/templates/_routes/LoginUI.ts +385 -5
- package/dist/templates/_services/oauth/OAuthProfileMap.ts +2 -2
- package/dist/templates/_services/oauth/OAuthStrategyService.ts +5 -5
- package/dist/templates/_types/auth.ts +9 -1
- package/dist/templates/jsonSchema/UserAuthProfiles.json +13 -5
- package/dist/templates/root/public/js/deleteaccount.js +54 -0
- package/dist/templates/root/public/js/externallogin.js +133 -0
- package/docs/features/accountDeletion.md +1 -1
- package/docs/features/auth.md +34 -0
- package/docs/features/externalIdentity.md +163 -0
- package/docs/releaseNote/v0-8-4.md +131 -0
- package/docs/releaseNote/v0-9-0.md +49 -0
- package/package.json +1 -1
- package/vex.config.json +6 -0
- package/docs/appGenerated/auth.md +0 -23
|
@@ -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,6 +1,50 @@
|
|
|
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;
|
|
@@ -12,10 +56,93 @@ export interface LoginUIConfig {
|
|
|
12
56
|
* constructs — its `server.ts` is generated once and is not overwritten on later runs.
|
|
13
57
|
*/
|
|
14
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;
|
|
15
136
|
}
|
|
16
137
|
|
|
17
138
|
export default class LoginUI {
|
|
18
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
|
+
|
|
19
146
|
private router: Router = Router();
|
|
20
147
|
private config: LoginUIConfig;
|
|
21
148
|
|
|
@@ -42,14 +169,125 @@ export default class LoginUI {
|
|
|
42
169
|
if (this.deleteAccountEnabled) {
|
|
43
170
|
this.router.get("/delete_account", this.deleteAccountPage.bind(this));
|
|
44
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
|
+
];
|
|
45
237
|
}
|
|
46
238
|
|
|
47
239
|
private nonce(): string {
|
|
48
240
|
return crypto.randomBytes(16).toString("base64");
|
|
49
241
|
}
|
|
50
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, "&")
|
|
261
|
+
.replace(/</g, "<")
|
|
262
|
+
.replace(/>/g, ">")
|
|
263
|
+
.replace(/"/g, """)
|
|
264
|
+
.replace(/'/g, "'");
|
|
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
|
+
|
|
51
289
|
private homePage(_req: Request, res: Response): void {
|
|
52
|
-
const authLinks = this.
|
|
290
|
+
const authLinks = this.authEnabled
|
|
53
291
|
? `<li><a href="/login">Login</a></li>
|
|
54
292
|
<li><a href="/mytokens">myTokens</a></li>
|
|
55
293
|
<li><a href="/refreshtoken">RefreshToken</a></li>
|
|
@@ -78,7 +316,7 @@ export default class LoginUI {
|
|
|
78
316
|
|
|
79
317
|
private loginPage(_req: Request, res: Response): void {
|
|
80
318
|
const nonce = this.nonce();
|
|
81
|
-
res.setHeader("Content-Security-Policy",
|
|
319
|
+
res.setHeader("Content-Security-Policy", this.loginPageCsp(nonce));
|
|
82
320
|
|
|
83
321
|
let formHtml = "";
|
|
84
322
|
if (this.config.localAuth) {
|
|
@@ -94,20 +332,151 @@ export default class LoginUI {
|
|
|
94
332
|
}
|
|
95
333
|
|
|
96
334
|
formHtml += " <p>Login with SSO:</p>\n";
|
|
97
|
-
|
|
335
|
+
const external = this.externalUI;
|
|
336
|
+
if (this.config.oauthProviders.length === 0 && !external) {
|
|
98
337
|
formHtml += " <p>No OAuth provider configured.</p>\n";
|
|
99
338
|
}
|
|
100
339
|
else {
|
|
340
|
+
// passport providers: server-driven redirect flows
|
|
101
341
|
this.config.oauthProviders.forEach((provider) => {
|
|
102
342
|
formHtml += ` <a href="/api/auth/${provider}">${provider}</a><br/>\n`;
|
|
103
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
|
+
}
|
|
104
353
|
}
|
|
105
354
|
|
|
106
|
-
const
|
|
355
|
+
const scripts = this.externalIdentityScripts(nonce);
|
|
356
|
+
const localAuthScript = this.config.localAuth
|
|
107
357
|
? `<script nonce="${nonce}" src="/js/login.js?d=${Date.now()}"></script>`
|
|
108
358
|
: "";
|
|
109
359
|
|
|
110
|
-
res.send(`${
|
|
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
|
+
);
|
|
111
480
|
}
|
|
112
481
|
|
|
113
482
|
private logoutPage(_req: Request, res: Response): void {
|
|
@@ -170,10 +539,20 @@ export default class LoginUI {
|
|
|
170
539
|
*
|
|
171
540
|
* The copy is deliberately explicit about what survives: this is a tombstone, not an erasure of
|
|
172
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.
|
|
173
548
|
*/
|
|
174
549
|
private deleteAccountPage(_req: Request, res: Response): void {
|
|
175
550
|
const nonce = this.nonce();
|
|
176
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.";
|
|
177
556
|
res.send(`
|
|
178
557
|
<link rel="stylesheet" href="/css/style.css">
|
|
179
558
|
<body>
|
|
@@ -183,6 +562,7 @@ export default class LoginUI {
|
|
|
183
562
|
You will need to create a new account to use the service again; the same
|
|
184
563
|
sign-in provider will not restore this one.
|
|
185
564
|
</p>
|
|
565
|
+
<p id="signInRequired">${signInHint}</p>
|
|
186
566
|
<p>Type <code>DELETE</code> to confirm:</p>
|
|
187
567
|
<input type="text" id="confirmInput" autocomplete="off"/>
|
|
188
568
|
<br/><br/>
|
|
@@ -48,7 +48,7 @@ export default class OAuthProfileMap {
|
|
|
48
48
|
active: true,
|
|
49
49
|
userAuthProfiles: [{
|
|
50
50
|
provider: oauthProfile.provider,
|
|
51
|
-
|
|
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
|
-
|
|
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
|
|
29
|
+
// find user by providerUserId + provider, or fall back to email
|
|
30
30
|
let existingUser: UserWithRelations | null = null;
|
|
31
|
-
if (authProfile?.
|
|
31
|
+
if (authProfile?.providerUserId && authProfile?.provider) {
|
|
32
32
|
const matchedProfile = await this.uapRepo.findOneWhere(
|
|
33
|
-
{
|
|
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/
|
|
87
|
+
// check if this provider/providerUserId already tracked
|
|
88
88
|
const existing = await this.uapRepo.findOneWhere(
|
|
89
|
-
{ userId: existingUser._id, provider: incomingProfile.provider,
|
|
89
|
+
{ userId: existingUser._id, provider: incomingProfile.provider, providerUserId: incomingProfile.providerUserId },
|
|
90
90
|
);
|
|
91
91
|
|
|
92
92
|
if (!existing) {
|
|
@@ -14,7 +14,15 @@ export interface registerResponse {
|
|
|
14
14
|
message: string
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
/**
|
|
18
|
+
* A redirect back to the client carrying a single-use `sessionCode`, which the client exchanges at
|
|
19
|
+
* `POST /auth/token` for the token pair.
|
|
20
|
+
*
|
|
21
|
+
* Neutral name on purpose: `/auth/local` and `/auth/external` both answer with this shape, and the two
|
|
22
|
+
* are independently enabled (`localAuth` vs `auth.externalIdentity`), so the type cannot live behind
|
|
23
|
+
* either flag.
|
|
24
|
+
*/
|
|
25
|
+
export interface loginRedirectResponse {
|
|
18
26
|
url: string;
|
|
19
27
|
}
|
|
20
28
|
|
|
@@ -5,7 +5,13 @@
|
|
|
5
5
|
"methods": [],
|
|
6
6
|
"joinWhitelist": []
|
|
7
7
|
},
|
|
8
|
-
"documentName": "UserAuthProfiles"
|
|
8
|
+
"documentName": "UserAuthProfiles",
|
|
9
|
+
"uniqueIndex": [
|
|
10
|
+
[
|
|
11
|
+
"provider",
|
|
12
|
+
"providerUserId"
|
|
13
|
+
]
|
|
14
|
+
]
|
|
9
15
|
},
|
|
10
16
|
"properties": {
|
|
11
17
|
"_id": {
|
|
@@ -25,11 +31,13 @@
|
|
|
25
31
|
},
|
|
26
32
|
"provider": {
|
|
27
33
|
"type": "string",
|
|
28
|
-
"index": true
|
|
34
|
+
"index": true,
|
|
35
|
+
"description": "Namespace label of the identity source: an upstream IdP (\"google\"), a broker (\"firebase\"), or vex's own password path (\"local\"). The value \"local\" is reserved."
|
|
29
36
|
},
|
|
30
|
-
"
|
|
37
|
+
"providerUserId": {
|
|
31
38
|
"type": "string",
|
|
32
|
-
"index": true
|
|
39
|
+
"index": true,
|
|
40
|
+
"description": "External subject within `provider`'s namespace. With `provider` it forms the account-linking key and the composite unique index. NULL for provider=\"local\". This is the subject (an OIDC `sub` or a broker user id), never a token."
|
|
33
41
|
},
|
|
34
42
|
"email": {
|
|
35
43
|
"type": "string"
|
|
@@ -42,4 +50,4 @@
|
|
|
42
50
|
"x-hidden": true
|
|
43
51
|
}
|
|
44
52
|
}
|
|
45
|
-
}
|
|
53
|
+
}
|