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.
Files changed (30) hide show
  1. package/AGENTS.md +21 -3
  2. package/dist/index.js +890 -396
  3. package/dist/templates/_middlewares/Authentication.ts +49 -32
  4. package/dist/templates/_middlewares/UserContext.ts +1 -18
  5. package/dist/templates/_projectSettings/env +14 -0
  6. package/dist/templates/_projectSettings/package.json +1 -0
  7. package/dist/templates/_routes/FirebaseAuthUI.gen.ts +20 -0
  8. package/dist/templates/_routes/LoginUI.ts +484 -4
  9. package/dist/templates/_services/MongooseRepositoryAdapter.ts +67 -5
  10. package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +70 -4
  11. package/dist/templates/_services/oauth/OAuthProfileMap.ts +27 -8
  12. package/dist/templates/_services/oauth/OAuthStrategyService.ts +5 -5
  13. package/dist/templates/_types/auth.ts +27 -0
  14. package/dist/templates/_types/vex/VexRepository.ts +21 -0
  15. package/dist/templates/jsonSchema/User.json +8 -1
  16. package/dist/templates/jsonSchema/UserAuthProfiles.json +13 -5
  17. package/dist/templates/root/public/js/deleteaccount.js +80 -0
  18. package/docs/appGenerated/auth.md +83 -22
  19. package/docs/architecture/authAndRouting.md +9 -2
  20. package/docs/architecture/databaseTargets.md +1 -1
  21. package/docs/features/accountDeletion.md +149 -0
  22. package/docs/features/auditFields.md +2 -32
  23. package/docs/releaseNote/v0-8-4.md +131 -0
  24. package/docs/releaseNote/v0-8-5.md +98 -0
  25. package/docs/superpowers/specs/2026-09-22-usercontext-audit-enforcement-design.md +9 -9
  26. package/docs/vexJsonSchema.md +11 -1
  27. package/package.json +1 -1
  28. package/vex.config.json +4 -1
  29. /package/docs/{ForeignKey.md → features/ForeignKey.md} +0 -0
  30. /package/docs/{apiUsage.md → features/apiUsage.md} +0 -0
@@ -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();
@@ -20,32 +20,15 @@ export function userIdOfToken(tokenData: Record<string, unknown> | undefined): s
20
20
  const als = new AsyncLocalStorage<UserContextData>();
21
21
 
22
22
  class UserContext {
23
- /**
24
- * Enter the per-request identity context.
25
- *
26
- * Called ONLY by Authentication.middleware, after token verification succeeded — at
27
- * that point a verified token always exists, so this runs unconditionally. The store
28
- * is the request's context; whether it carries a usable identity is decided when it
29
- * is read (`userId`), not when it is created.
30
- *
31
- * Never use `enterWith()`: it mutates the current execution context instead of
32
- * scoping a new one, and leaks into whatever runs next on the same tick.
33
- */
34
23
  run<T>(tokenData: Record<string, unknown>, fn: () => T): T {
35
24
  return als.run({ tokenData }, fn);
36
25
  }
37
26
 
38
- /** Current store from the per-request async context. */
39
27
  getStore(): UserContextData | undefined {
40
28
  return als.getStore();
41
29
  }
42
30
 
43
- /**
44
- * Normalized identity of the authenticated caller.
45
- *
46
- * The data layer MUST read the identity through this accessor and never inspect the
47
- * token shape itself — that keeps the token → identity mapping in exactly one place.
48
- */
31
+ /** Normalized identity of the authenticated caller. */
49
32
  get userId(): string | undefined {
50
33
  return userIdOfToken(als.getStore()?.tokenData);
51
34
  }
@@ -19,6 +19,20 @@ OAUTH_GITHUB_CLIENTSECRET=
19
19
  # OAUTH_APPLE_CLIENTID=
20
20
  # OAUTH_APPLE_CLIENTSECRET=
21
21
 
22
+ # FIREBASE (auth.firebase in vex.config.json) — see docs/appGenerated/auth.md
23
+ # Server credential: firebase-admin verifies ID tokens, so the project's service account is required.
24
+ # The JSON itself, as one value — generate it in the Firebase console:
25
+ # Project settings > Service accounts > Generate new private key.
26
+ FIREBASE_SERVICE_ACCOUNT_JSON=
27
+ # Browser config: Firebase's *public* web app values, served to the login page by design. There is no
28
+ # secret among them, and no appId — Firebase Auth does not read one.
29
+ FIREBASE_WEB_API_KEY=
30
+ FIREBASE_WEB_AUTH_DOMAIN=
31
+ FIREBASE_WEB_PROJECT_ID=
32
+ # Optional: which sign-in methods the login page renders a button for, comma separated. Defaults to
33
+ # google. The server accepts any provider it knows regardless of this list.
34
+ # FIREBASE_PROVIDERS=google
35
+
22
36
  # JWT token
23
37
  ACCESS_TOKEN_EXPIRE_TIME='1h'
24
38
  REFRESH_TOKEN_EXPIRE_TIME='24h'
@@ -13,6 +13,7 @@
13
13
  "cookie-parser": "^1.4.6",
14
14
  "dotenv": "^16.4.4",
15
15
  "express": "^4.18.2",
16
+ "firebase-admin": "^14.1.0",
16
17
  "helmet": "^7.1.0",
17
18
  "js-yaml": "^4.1.0",
18
19
  "jsonwebtoken": "^9.0.2",
@@ -0,0 +1,20 @@
1
+ // {{headerComment}}
2
+ import type { FirebaseAuthUI } from "./LoginUI.gen";
3
+
4
+ /**
5
+ * Test/compile-time stand-in for the generated login-page wiring.
6
+ *
7
+ * **In a generated app this file is overwritten by the generator**, which emits the Firebase wiring or
8
+ * `undefined` when `auth.firebase` is off. It lives in the template directory so that `LoginUI.ts`'s
9
+ * unconditional import resolves in this repo — that import has to be unconditional, because the
10
+ * generated default is how the configuration reaches the login page without editing the app-owned
11
+ * `server.ts`.
12
+ *
13
+ * `let` plus a setter rather than a `const`, so the unit tests can vary what the generator "emitted".
14
+ * The generated version is a plain `const`; nothing in the app calls the setter.
15
+ */
16
+ export let firebaseAuthUI: FirebaseAuthUI | undefined = undefined;
17
+
18
+ export function setFirebaseAuthUI(ui: FirebaseAuthUI | undefined): void {
19
+ firebaseAuthUI = ui;
20
+ }