very-express 0.8.3 → 0.8.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +21 -3
- package/dist/index.js +890 -396
- package/dist/templates/_middlewares/Authentication.ts +49 -32
- package/dist/templates/_middlewares/UserContext.ts +1 -18
- package/dist/templates/_projectSettings/env +14 -0
- package/dist/templates/_projectSettings/package.json +1 -0
- package/dist/templates/_routes/FirebaseAuthUI.gen.ts +20 -0
- package/dist/templates/_routes/LoginUI.ts +484 -4
- package/dist/templates/_services/MongooseRepositoryAdapter.ts +67 -5
- package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +70 -4
- package/dist/templates/_services/oauth/OAuthProfileMap.ts +27 -8
- package/dist/templates/_services/oauth/OAuthStrategyService.ts +5 -5
- package/dist/templates/_types/auth.ts +27 -0
- package/dist/templates/_types/vex/VexRepository.ts +21 -0
- package/dist/templates/jsonSchema/User.json +8 -1
- package/dist/templates/jsonSchema/UserAuthProfiles.json +13 -5
- package/dist/templates/root/public/js/deleteaccount.js +80 -0
- package/docs/appGenerated/auth.md +83 -22
- package/docs/architecture/authAndRouting.md +9 -2
- package/docs/architecture/databaseTargets.md +1 -1
- package/docs/features/accountDeletion.md +149 -0
- package/docs/features/auditFields.md +2 -32
- package/docs/releaseNote/v0-8-4.md +131 -0
- package/docs/releaseNote/v0-8-5.md +98 -0
- package/docs/superpowers/specs/2026-09-22-usercontext-audit-enforcement-design.md +9 -9
- package/docs/vexJsonSchema.md +11 -1
- package/package.json +1 -1
- package/vex.config.json +4 -1
- /package/docs/{ForeignKey.md → features/ForeignKey.md} +0 -0
- /package/docs/{apiUsage.md → features/apiUsage.md} +0 -0
|
@@ -1,14 +1,96 @@
|
|
|
1
1
|
// {{headerComment}}
|
|
2
2
|
import { Router, Request, Response } from "express";
|
|
3
3
|
import crypto from "crypto";
|
|
4
|
+
import fs from "fs";
|
|
5
|
+
import path from "path";
|
|
6
|
+
import dotenv from "dotenv";
|
|
7
|
+
|
|
8
|
+
import { firebaseAuthUI } from "./FirebaseAuthUI.gen";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Explain config values that `process.env` does not have.
|
|
12
|
+
*
|
|
13
|
+
* Two different situations produce the same symptom — Firebase reports itself unconfigured — and they
|
|
14
|
+
* need different fixes, so they are separated here:
|
|
15
|
+
*
|
|
16
|
+
* - **present in `.env` but absent from `process.env`**: `dotenv` does not override a variable that is
|
|
17
|
+
* already set in the environment, and it only runs once at startup. Either the process started before
|
|
18
|
+
* the file was edited, or the name is exported by the shell / IDE launch config / container with a
|
|
19
|
+
* different value.
|
|
20
|
+
* - **absent from both**: nothing has set it.
|
|
21
|
+
*
|
|
22
|
+
* Pure so the diagnosis can be tested without touching the filesystem.
|
|
23
|
+
*/
|
|
24
|
+
export function diagnoseMissingEnv(
|
|
25
|
+
names: string[],
|
|
26
|
+
envFile: Record<string, string | undefined>,
|
|
27
|
+
): string[] {
|
|
28
|
+
const shadowed = names.filter((name) => envFile[name]);
|
|
29
|
+
const unset = names.filter((name) => !envFile[name]);
|
|
30
|
+
const problems: string[] = [];
|
|
31
|
+
|
|
32
|
+
if (shadowed.length > 0) {
|
|
33
|
+
problems.push(
|
|
34
|
+
`set in .env but NOT in process.env: ${shadowed.join(", ")}. dotenv does not override a ` +
|
|
35
|
+
"variable that is already present in the environment, and .env is read once at startup — so " +
|
|
36
|
+
"either the server started before .env was edited, or these are exported by the shell / IDE " +
|
|
37
|
+
`launch config / container. Check \`env | grep -E '^(${shadowed.join("|")})='\`` +
|
|
38
|
+
", then unset them there or pass dotenv's `override` option in server.ts.",
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (unset.length > 0) {
|
|
43
|
+
problems.push(`not set in .env or process.env: ${unset.join(", ")}`);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return problems;
|
|
47
|
+
}
|
|
4
48
|
|
|
5
49
|
export interface LoginUIConfig {
|
|
6
50
|
localAuth: boolean;
|
|
7
51
|
oauthProviders: string[];
|
|
52
|
+
/** Serve the self-service deletion page at `/delete_account`. */
|
|
53
|
+
deleteAccount?: boolean;
|
|
54
|
+
/** Override the Firebase sign-in wiring. */
|
|
55
|
+
firebase?: FirebaseAuthUI;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Everything the login page needs to drive Firebase, as emitted into `FirebaseAuthUI.gen.ts`. */
|
|
59
|
+
export interface FirebaseAuthUI {
|
|
60
|
+
/** Button text template; `{provider}` is replaced by the provider's label. */
|
|
61
|
+
label: string;
|
|
62
|
+
/** gstatic ESM directory for the pinned SDK version, trailing slash included. */
|
|
63
|
+
sdkBaseUrl: string;
|
|
64
|
+
/** Every provider the page can start. */
|
|
65
|
+
providers: { id: string; label: string }[];
|
|
66
|
+
/** Rendered when `providersEnvKey` is unset. */
|
|
67
|
+
defaultProviders: string[];
|
|
68
|
+
/** env var holding the comma-separated list of providers to render buttons for. */
|
|
69
|
+
providersEnvKey: string;
|
|
70
|
+
/** Public config key → env var name. Resolved at render time; missing values stay absent. */
|
|
71
|
+
envKeys: Record<string, string>;
|
|
72
|
+
/** Hosts Firebase's sign-in needs, per directive. */
|
|
73
|
+
csp: {
|
|
74
|
+
scriptSrc: string[];
|
|
75
|
+
connectSrc: string[];
|
|
76
|
+
frameSrc: string[];
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A sign-in method to render a button for. */
|
|
81
|
+
interface firebaseProvider {
|
|
82
|
+
id: string;
|
|
83
|
+
label: string;
|
|
8
84
|
}
|
|
9
85
|
|
|
10
86
|
export default class LoginUI {
|
|
11
87
|
|
|
88
|
+
/** Last set of problems warned about, so a page render logs them once. */
|
|
89
|
+
private static warnedEnvSignature = "";
|
|
90
|
+
|
|
91
|
+
/** The parsed `.env`, read at most once per process. */
|
|
92
|
+
private static envFileCache: Record<string, string> | undefined;
|
|
93
|
+
|
|
12
94
|
private router: Router = Router();
|
|
13
95
|
private config: LoginUIConfig;
|
|
14
96
|
|
|
@@ -21,6 +103,10 @@ export default class LoginUI {
|
|
|
21
103
|
return this.router;
|
|
22
104
|
}
|
|
23
105
|
|
|
106
|
+
private get deleteAccountEnabled(): boolean {
|
|
107
|
+
return this.config.deleteAccount ?? true;
|
|
108
|
+
}
|
|
109
|
+
|
|
24
110
|
private registerRoutes(): void {
|
|
25
111
|
this.router.get("/", this.homePage.bind(this));
|
|
26
112
|
this.router.get("/login", this.loginPage.bind(this));
|
|
@@ -28,25 +114,108 @@ export default class LoginUI {
|
|
|
28
114
|
this.router.get("/mytokens", this.myTokensPage.bind(this));
|
|
29
115
|
this.router.get("/refreshtoken", this.refreshTokenPage.bind(this));
|
|
30
116
|
this.router.get("/logincallback", this.loginCallbackPage.bind(this));
|
|
117
|
+
if (this.deleteAccountEnabled) {
|
|
118
|
+
this.router.get("/delete_account", this.deleteAccountPage.bind(this));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** The Firebase wiring in force: an explicit app override, else the generated default. */
|
|
123
|
+
private get firebaseUI(): FirebaseAuthUI | undefined {
|
|
124
|
+
return this.config.firebase ?? firebaseAuthUI;
|
|
31
125
|
}
|
|
32
126
|
|
|
33
127
|
private nonce(): string {
|
|
34
128
|
return crypto.randomBytes(16).toString("base64");
|
|
35
129
|
}
|
|
36
130
|
|
|
131
|
+
/** De-duplicate while keeping declaration order; a repeated host adds nothing. */
|
|
132
|
+
private uniqueHosts(hosts: string[]): string[] {
|
|
133
|
+
return hosts.filter((host, index) => hosts.indexOf(host) === index);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The project's auth domain, e.g. `my-project.firebaseapp.com`. Absent when unconfigured. */
|
|
137
|
+
private firebaseAuthDomain(ui: FirebaseAuthUI): string | undefined {
|
|
138
|
+
return process.env[ui.envKeys.authDomain] || undefined;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** CSP for the login page: the page's own scripts plus the hosts Firebase's sign-in needs. */
|
|
142
|
+
private loginPageCsp(nonce: string): string {
|
|
143
|
+
const ui = this.firebaseUI;
|
|
144
|
+
if (!ui) return `script-src 'self' 'nonce-${nonce}'`;
|
|
145
|
+
|
|
146
|
+
const authDomain = this.firebaseAuthDomain(ui);
|
|
147
|
+
const frameSrc = authDomain ? [...ui.csp.frameSrc, `https://${authDomain}`] : ui.csp.frameSrc;
|
|
148
|
+
|
|
149
|
+
return [
|
|
150
|
+
`script-src ${this.uniqueHosts(["'self'", `'nonce-${nonce}'`, ...ui.csp.scriptSrc]).join(" ")}`,
|
|
151
|
+
`connect-src ${this.uniqueHosts(["'self'", ...ui.csp.connectSrc]).join(" ")}`,
|
|
152
|
+
`frame-src ${this.uniqueHosts(frameSrc).join(" ")}`,
|
|
153
|
+
].join("; ");
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Escape for HTML text/attribute context. Labels and provider ids come from configuration. */
|
|
157
|
+
private escapeHtml(value: string): string {
|
|
158
|
+
return value
|
|
159
|
+
.replace(/&/g, "&")
|
|
160
|
+
.replace(/</g, "<")
|
|
161
|
+
.replace(/>/g, ">")
|
|
162
|
+
.replace(/"/g, """)
|
|
163
|
+
.replace(/'/g, "'");
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Which providers to render a button for, and what is wrong with the names that were asked for. */
|
|
167
|
+
private firebaseProviderSelection(ui: FirebaseAuthUI): { providers: firebaseProvider[]; problems: string[] } {
|
|
168
|
+
const configured = process.env[ui.providersEnvKey];
|
|
169
|
+
const requested = (configured ? configured.split(",") : ui.defaultProviders)
|
|
170
|
+
.map((name) => name.trim())
|
|
171
|
+
.filter((name) => name.length > 0);
|
|
172
|
+
|
|
173
|
+
const providers: firebaseProvider[] = [];
|
|
174
|
+
const problems: string[] = [];
|
|
175
|
+
|
|
176
|
+
for (const name of requested) {
|
|
177
|
+
const match = ui.providers.find((provider) => provider.id === name);
|
|
178
|
+
if (match) providers.push(match);
|
|
179
|
+
else {
|
|
180
|
+
problems.push(
|
|
181
|
+
`${ui.providersEnvKey} names "${name}", which this login page cannot start ` +
|
|
182
|
+
`(known: ${ui.providers.map((provider) => provider.id).join(", ")})`,
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return { providers, problems };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Auth is on when *any* sign-in path exists. `firebase` counts: an app with `localAuth: false` and
|
|
192
|
+
* no passport provider is not auth-less if Firebase is configured, and leaving it out of this test
|
|
193
|
+
* would hide the login link for exactly that app.
|
|
194
|
+
*/
|
|
195
|
+
private get authEnabled(): boolean {
|
|
196
|
+
return this.config.localAuth
|
|
197
|
+
|| this.config.oauthProviders.length > 0
|
|
198
|
+
|| !!this.firebaseUI;
|
|
199
|
+
}
|
|
200
|
+
|
|
37
201
|
private homePage(_req: Request, res: Response): void {
|
|
38
|
-
const authLinks = this.
|
|
202
|
+
const authLinks = this.authEnabled
|
|
39
203
|
? `<li><a href="/login">Login</a></li>
|
|
40
204
|
<li><a href="/mytokens">myTokens</a></li>
|
|
41
205
|
<li><a href="/refreshtoken">RefreshToken</a></li>
|
|
42
206
|
<li><a href="/logout">LogOut</a></li>`
|
|
43
207
|
: "";
|
|
44
208
|
|
|
209
|
+
const deleteAccountLink = this.deleteAccountEnabled
|
|
210
|
+
? `<li><a href="/delete_account">Delete account</a></li>`
|
|
211
|
+
: "";
|
|
212
|
+
|
|
45
213
|
res.send(`
|
|
46
214
|
<div>
|
|
47
215
|
<h1>Hello World</h1>
|
|
48
216
|
<ul>
|
|
49
217
|
${authLinks}
|
|
218
|
+
${deleteAccountLink}
|
|
50
219
|
<li><a href="/swagger">Swagger UI</a></li>
|
|
51
220
|
</ul>
|
|
52
221
|
<h1>Others</h1>
|
|
@@ -59,7 +228,11 @@ export default class LoginUI {
|
|
|
59
228
|
|
|
60
229
|
private loginPage(_req: Request, res: Response): void {
|
|
61
230
|
const nonce = this.nonce();
|
|
62
|
-
res.setHeader("Content-Security-Policy",
|
|
231
|
+
res.setHeader("Content-Security-Policy", this.loginPageCsp(nonce));
|
|
232
|
+
|
|
233
|
+
if (this.firebaseUI) {
|
|
234
|
+
res.setHeader("Cross-Origin-Opener-Policy", "same-origin-allow-popups");
|
|
235
|
+
}
|
|
63
236
|
|
|
64
237
|
let formHtml = "";
|
|
65
238
|
if (this.config.localAuth) {
|
|
@@ -74,21 +247,119 @@ export default class LoginUI {
|
|
|
74
247
|
<br/><br/>`;
|
|
75
248
|
}
|
|
76
249
|
|
|
250
|
+
const firebase = this.firebaseUI;
|
|
251
|
+
const selection = firebase ? this.firebaseProviderSelection(firebase) : undefined;
|
|
252
|
+
|
|
77
253
|
formHtml += " <p>Login with SSO:</p>\n";
|
|
78
|
-
if (this.config.oauthProviders.length === 0) {
|
|
254
|
+
if (this.config.oauthProviders.length === 0 && !firebase) {
|
|
79
255
|
formHtml += " <p>No OAuth provider configured.</p>\n";
|
|
80
256
|
}
|
|
81
257
|
else {
|
|
258
|
+
// passport providers: server-driven redirect flows
|
|
82
259
|
this.config.oauthProviders.forEach((provider) => {
|
|
83
260
|
formHtml += ` <a href="/api/auth/${provider}">${provider}</a><br/>\n`;
|
|
84
261
|
});
|
|
262
|
+
|
|
263
|
+
// Firebase: client-driven. One button per configured sign-in method; the provider id
|
|
264
|
+
// travels to the glue as a data attribute, and on to signIn().
|
|
265
|
+
if (firebase && selection) {
|
|
266
|
+
selection.providers.forEach((provider) => {
|
|
267
|
+
const text = firebase.label.replace("{provider}", provider.label);
|
|
268
|
+
formHtml += ` <button class="firebaseLoginBtn" data-provider="${this.escapeHtml(provider.id)}">${this.escapeHtml(text)}</button><br/>\n`;
|
|
269
|
+
});
|
|
270
|
+
}
|
|
85
271
|
}
|
|
86
272
|
|
|
87
273
|
const scriptTag = this.config.localAuth
|
|
88
274
|
? `<script nonce="${nonce}" src="/js/login.js?d=${Date.now()}"></script>`
|
|
89
275
|
: "";
|
|
276
|
+
const firebaseScripts = firebase && selection ? this.firebaseScripts(nonce, selection.problems) : "";
|
|
90
277
|
|
|
91
|
-
res.send(`${scriptTag}<body>${formHtml}</body>`);
|
|
278
|
+
res.send(`${scriptTag}${firebaseScripts}<body>${formHtml}</body>`);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* The inline carrier and the glue. Inlined so the page and its glue cannot be different
|
|
283
|
+
* generations; the public config is read from `process.env` at render time.
|
|
284
|
+
*/
|
|
285
|
+
private firebaseScripts(nonce: string, providerProblems: string[]): string {
|
|
286
|
+
const ui = this.firebaseUI;
|
|
287
|
+
if (!ui) return "";
|
|
288
|
+
|
|
289
|
+
const config: Record<string, string> = {};
|
|
290
|
+
const missing: string[] = [];
|
|
291
|
+
for (const [key, envName] of Object.entries(ui.envKeys)) {
|
|
292
|
+
const value = process.env[envName];
|
|
293
|
+
if (value) config[key] = value;
|
|
294
|
+
else missing.push(envName);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const problems = [
|
|
298
|
+
...providerProblems,
|
|
299
|
+
...diagnoseMissingEnv(missing, this.envFileValues()),
|
|
300
|
+
];
|
|
301
|
+
this.warnIfUnconfigured(problems);
|
|
302
|
+
|
|
303
|
+
// `problems` travels to the browser so a failed sign-in can say what is actually wrong: the
|
|
304
|
+
// SDK's own errors for a misconfigured client are generic by design.
|
|
305
|
+
const carrier = JSON.stringify({
|
|
306
|
+
sdkBaseUrl: ui.sdkBaseUrl,
|
|
307
|
+
config,
|
|
308
|
+
problems,
|
|
309
|
+
}).replace(/</g, "\\u003c");
|
|
310
|
+
|
|
311
|
+
// Generator-authored, not user input, but still interpolated into an inline <script>: break
|
|
312
|
+
// any literal closing tag so a comment in it cannot end the block early.
|
|
313
|
+
const glue = firebaseGlueScript.replace(/<\/script/gi, "<\\/script");
|
|
314
|
+
|
|
315
|
+
return `
|
|
316
|
+
<script nonce="${nonce}">window.__vexFirebaseLogin = ${carrier};</script>
|
|
317
|
+
<script nonce="${nonce}">${glue}</script>`;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* The env file's own values, read once.
|
|
322
|
+
*
|
|
323
|
+
* Only used to tell a shadowed variable from an unset one; nothing here changes what the app reads.
|
|
324
|
+
* A missing or unparseable file is not an error — plenty of deployments have no `.env` at all.
|
|
325
|
+
*/
|
|
326
|
+
private envFileValues(): Record<string, string> {
|
|
327
|
+
if (LoginUI.envFileCache) return LoginUI.envFileCache;
|
|
328
|
+
|
|
329
|
+
let values: Record<string, string> = {};
|
|
330
|
+
try {
|
|
331
|
+
values = dotenv.parse(fs.readFileSync(path.join(process.cwd(), ".env")));
|
|
332
|
+
}
|
|
333
|
+
catch {
|
|
334
|
+
// no .env, or unreadable: every missing name is then simply unset
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
LoginUI.envFileCache = values;
|
|
338
|
+
return values;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Say so on the server when Firebase's public config is missing or looks wrong.
|
|
343
|
+
*
|
|
344
|
+
* Without this the only signal is a browser alert from the button — which for a missing value reads
|
|
345
|
+
* as "you forgot to set the variables" even when they *are* set in `.env` (the actual cause is
|
|
346
|
+
* usually that the process started before they were, and `.env` is read once at startup), and for a
|
|
347
|
+
* wrong value is something generic from Firebase.
|
|
348
|
+
*
|
|
349
|
+
* Logged once per distinct set of problems, not per request: this runs on a page render.
|
|
350
|
+
*/
|
|
351
|
+
private warnIfUnconfigured(problems: string[]): void {
|
|
352
|
+
if (problems.length === 0) return;
|
|
353
|
+
|
|
354
|
+
const signature = problems.join("|");
|
|
355
|
+
if (LoginUI.warnedEnvSignature === signature) return;
|
|
356
|
+
LoginUI.warnedEnvSignature = signature;
|
|
357
|
+
|
|
358
|
+
console.warn(
|
|
359
|
+
`[vex] auth.firebase is enabled but its public browser config is not usable:\n - ` +
|
|
360
|
+
problems.join("\n - ") +
|
|
361
|
+
"\nIf a value is already in .env, restart the server — .env is read once at startup."
|
|
362
|
+
);
|
|
92
363
|
}
|
|
93
364
|
|
|
94
365
|
private logoutPage(_req: Request, res: Response): void {
|
|
@@ -145,4 +416,213 @@ export default class LoginUI {
|
|
|
145
416
|
</body>
|
|
146
417
|
`);
|
|
147
418
|
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Self-service account deletion.
|
|
422
|
+
*
|
|
423
|
+
* The copy is deliberately explicit about what survives: this is a tombstone, not an erasure of
|
|
424
|
+
* everything. Claiming otherwise would contradict both the implementation and the store listing.
|
|
425
|
+
*/
|
|
426
|
+
private deleteAccountPage(_req: Request, res: Response): void {
|
|
427
|
+
const nonce = this.nonce();
|
|
428
|
+
res.setHeader("Content-Security-Policy", `script-src 'self' 'nonce-${nonce}'`);
|
|
429
|
+
res.send(`
|
|
430
|
+
<link rel="stylesheet" href="/css/style.css">
|
|
431
|
+
<body>
|
|
432
|
+
<h1>Delete account</h1>
|
|
433
|
+
<p><strong>This cannot be undone.</strong></p>
|
|
434
|
+
<p>
|
|
435
|
+
You will need to create a new account to use the service again; the same
|
|
436
|
+
sign-in provider will not restore this one.
|
|
437
|
+
</p>
|
|
438
|
+
<p>Type <code>DELETE</code> to confirm:</p>
|
|
439
|
+
<input type="text" id="confirmInput" autocomplete="off"/>
|
|
440
|
+
<br/><br/>
|
|
441
|
+
<button id="deleteAccountBtn">Delete my account</button>
|
|
442
|
+
<br/><br/>
|
|
443
|
+
<pre id="deleteResult"></pre>
|
|
444
|
+
<a href="/">back to home</a>
|
|
445
|
+
</body>
|
|
446
|
+
<script nonce="${nonce}" src="/js/deleteaccount.js"></script>
|
|
447
|
+
`);
|
|
448
|
+
}
|
|
148
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
|
+
`;
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { Model, Document } from "mongoose";
|
|
3
3
|
import { VexRepository, Select, Filter, Join, VexPagination, VexResErr } from "../_types/vex";
|
|
4
4
|
import UserContext from "../_middlewares/UserContext.gen";
|
|
5
|
-
import { entityVexFields, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
|
|
5
|
+
import { entityVexFields, entitySoftDeleteFields, showSoftDeleted, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
|
|
6
6
|
import utils from "../_utils";
|
|
7
7
|
|
|
8
8
|
/** When a framework-managed field is written. */
|
|
@@ -84,9 +84,34 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
84
84
|
return this.model;
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
+
/** Entity class name — the key used by the generated registries. */
|
|
88
|
+
private getEntityName(): string {
|
|
89
|
+
return this.model.modelName + "Entity";
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Soft-delete term for this model, or null when it declares no marker.
|
|
94
|
+
*
|
|
95
|
+
* `$ne: true` (not `$eq: false`) so documents written before the field existed still count as
|
|
96
|
+
* live — the same leniency the SQL side gets from NOT NULL DEFAULT false.
|
|
97
|
+
*/
|
|
98
|
+
private getSoftDeleteFilter(): Record<string, unknown> | null {
|
|
99
|
+
if (showSoftDeleted) return null;
|
|
100
|
+
|
|
101
|
+
const field = entitySoftDeleteFields[this.getEntityName()];
|
|
102
|
+
if (!field) return null;
|
|
103
|
+
|
|
104
|
+
return { [field]: { $ne: true } };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
private mergeFilter(filter: Filter, options?: { includeSoftDeleted?: boolean }): Record<string, unknown> {
|
|
108
|
+
const softDelete = options?.includeSoftDeleted ? null : this.getSoftDeleteFilter();
|
|
109
|
+
return { ...((filter || {}) as Record<string, unknown>), ...softDelete };
|
|
110
|
+
}
|
|
111
|
+
|
|
87
112
|
find(filter: Filter, join?: Join, select?: Select, pagination?: VexPagination): Promise<T[]> {
|
|
88
113
|
// TODO: complete mongoose support, handle join, select, and pagination
|
|
89
|
-
return this.model.find((filter
|
|
114
|
+
return this.model.find(this.mergeFilter(filter) as any).exec();
|
|
90
115
|
}
|
|
91
116
|
|
|
92
117
|
async count(filter: Filter): Promise<number> {
|
|
@@ -96,12 +121,12 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
96
121
|
|
|
97
122
|
findOne(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
|
|
98
123
|
// TODO: complete mongoose support, handle join and select
|
|
99
|
-
return this.model.findOne(filter as any).exec();
|
|
124
|
+
return this.model.findOne(this.mergeFilter(filter) as any).exec();
|
|
100
125
|
}
|
|
101
126
|
|
|
102
127
|
findOneWhere(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
|
|
103
128
|
// TODO: complete mongoose support, handle join and select
|
|
104
|
-
return this.model.findOne(filter as any).exec();
|
|
129
|
+
return this.model.findOne(this.mergeFilter(filter) as any).exec();
|
|
105
130
|
}
|
|
106
131
|
|
|
107
132
|
async create(data: Partial<T>): Promise<T> {
|
|
@@ -140,6 +165,43 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
140
165
|
}
|
|
141
166
|
|
|
142
167
|
async deleteWhere(filter: Record<string, unknown>): Promise<void> {
|
|
143
|
-
await this.model.deleteOne(filter as any).exec();
|
|
168
|
+
await this.model.deleteOne(this.mergeFilter(filter as Filter) as any).exec();
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Tombstone the document: run the normal update-phase field machinery (so `updatedAt` /
|
|
173
|
+
* `updatedBy` record who deleted it and when), then write the marker plus any redaction
|
|
174
|
+
* the caller merged in.
|
|
175
|
+
*/
|
|
176
|
+
async softDelete(id: string | undefined, data?: Partial<T>): Promise<T | null> {
|
|
177
|
+
if (!id) {
|
|
178
|
+
utils.log.error("MongooseRepositoryAdapter.softDelete called without id — refuse update document");
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const field = entitySoftDeleteFields[this.getEntityName()];
|
|
183
|
+
if (!field) {
|
|
184
|
+
utils.log.error(
|
|
185
|
+
`MongooseRepositoryAdapter.softDelete on ${this.getEntityName()} — entity declares no ` +
|
|
186
|
+
`x-vexData "softDelete" field, refuse update document`
|
|
187
|
+
);
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const enriched: Record<string, unknown> = { ...((data ?? {}) as Record<string, unknown>) };
|
|
192
|
+
this.applyVexFields(enriched as Partial<T>, "update");
|
|
193
|
+
enriched[field] = true;
|
|
194
|
+
|
|
195
|
+
const filter = this.mergeFilter({ _id: id } as Filter);
|
|
196
|
+
return this.model.findOneAndUpdate(filter as any, { $set: enriched }, { new: true }).exec();
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Read a document that may be soft-deleted: skips the soft-delete term only.
|
|
201
|
+
* Framework-internal — see VexRepository.
|
|
202
|
+
*/
|
|
203
|
+
findOneWithDeleted(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
|
|
204
|
+
// TODO: complete mongoose support, handle join and select
|
|
205
|
+
return this.model.findOne(this.mergeFilter(filter, { includeSoftDeleted: true }) as any).exec();
|
|
144
206
|
}
|
|
145
207
|
}
|