very-express 0.8.0 → 0.8.3

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,6 +2,7 @@
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
6
  import log from "../_utils/logger.gen";
6
7
  import { VexResErr } from "../_types/vex";
7
8
 
@@ -27,7 +28,7 @@ class Authentication {
27
28
  // verify token
28
29
  const tokenData = this.JWTService.verifyToken(token, accessTokenIndex);
29
30
  req.user = tokenData;
30
- next();
31
+ UserContext.run(tokenData, () => next());
31
32
  }
32
33
  catch (e: any) {
33
34
  if (typeof e === "number") {
@@ -0,0 +1,54 @@
1
+ // {{headerComment}}
2
+ import { AsyncLocalStorage } from "async_hooks";
3
+
4
+ /** Identity-bearing claims carried from the verified access token. */
5
+ export interface UserContextData {
6
+ tokenData: Record<string, unknown>;
7
+ }
8
+
9
+ /**
10
+ * Pure: identity value carried by a verified access token.
11
+ *
12
+ * `vexUserId` is the schema-declared identity (the field tagged `x-vexData: "userId"`,
13
+ * which JWTService copies into the token); `_id` keeps tokens issued before that claim
14
+ * existed working.
15
+ */
16
+ export function userIdOfToken(tokenData: Record<string, unknown> | undefined): string | undefined {
17
+ return (tokenData?.vexUserId as string | undefined) ?? (tokenData?._id as string | undefined);
18
+ }
19
+
20
+ const als = new AsyncLocalStorage<UserContextData>();
21
+
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
+ run<T>(tokenData: Record<string, unknown>, fn: () => T): T {
35
+ return als.run({ tokenData }, fn);
36
+ }
37
+
38
+ /** Current store from the per-request async context. */
39
+ getStore(): UserContextData | undefined {
40
+ return als.getStore();
41
+ }
42
+
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
+ */
49
+ get userId(): string | undefined {
50
+ return userIdOfToken(als.getStore()?.tokenData);
51
+ }
52
+ }
53
+
54
+ export default new UserContext();
@@ -1,7 +1,7 @@
1
1
  // {{headerComment}}
2
2
  import { Model, Document } from "mongoose";
3
- import { VexRepository, Select, Filter, Join, VexPagination } from "../_types/vex";
4
- import DataIsolationContext from "../_middlewares/DataIsolationContext.gen";
3
+ import { VexRepository, Select, Filter, Join, VexPagination, VexResErr } from "../_types/vex";
4
+ import UserContext from "../_middlewares/UserContext.gen";
5
5
  import { entityVexFields, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
6
6
  import utils from "../_utils";
7
7
 
@@ -38,6 +38,21 @@ function resolveVexFieldValue(type: VexFieldEntry["type"], userId?: string): unk
38
38
  export class MongooseRepositoryAdapter<T extends Document> implements VexRepository<T> {
39
39
  constructor(private model: Model<T>) {}
40
40
 
41
+ /**
42
+ * Fail loud when an entity declares a create-phase user field but no identity is in
43
+ * scope — a silent NULL is exactly the failure this enforcement exists to kill.
44
+ *
45
+ * `onUpdateUserId` is deliberately NOT enforced: `updatedBy` is allowed to stay absent,
46
+ * and refusing a context-less update would also break pre-auth writes that don't touch it.
47
+ */
48
+ private assertCreateIdentity(fields: VexFieldEntry[]): void {
49
+ if (!fields.some(f => f.type === "onCreateUserId")) return;
50
+ if (UserContext.userId) return;
51
+
52
+ throw new VexResErr(500, undefined,
53
+ `${this.model.modelName} declares onCreateUserId but UserContext carries no user identity`);
54
+ }
55
+
41
56
  /**
42
57
  * Framework-managed audit fields: strip the caller's values first — a client must never
43
58
  * forge createdBy / updatedAt — then fill the ones owned by this write phase.
@@ -48,7 +63,9 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
48
63
  const fields = entityVexFields[this.model.modelName + "Entity"] ?? [];
49
64
  if (fields.length === 0) return;
50
65
 
51
- const userId = DataIsolationContext.getStore()?.userId;
66
+ if (phase === "create") this.assertCreateIdentity(fields);
67
+
68
+ const userId = UserContext.userId;
52
69
  const values: Record<string, unknown> = {};
53
70
 
54
71
  for (const entry of fields) {
@@ -1,7 +1,7 @@
1
1
  // {{headerComment}}
2
2
  import { Repository, ObjectLiteral, FindOptionsWhere, DeepPartial, In, Not, Like, MoreThan, LessThan, MoreThanOrEqual, LessThanOrEqual, FindManyOptions } from "typeorm";
3
- import { VexRepository, Select, Filter, Join, FieldOperators, VexPagination } from "../_types/vex";
4
- import DataIsolationContext from "../_middlewares/DataIsolationContext.gen";
3
+ import { VexRepository, Select, Filter, Join, FieldOperators, VexPagination, VexResErr } from "../_types/vex";
4
+ import UserContext from "../_middlewares/UserContext.gen";
5
5
  import { entityIsolation } from "../_middlewares/DataIsolationRegistry.gen";
6
6
  import { entityVexFields, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
7
7
  import utils from "../_utils";
@@ -45,6 +45,21 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
45
45
  : "";
46
46
  }
47
47
 
48
+ /**
49
+ * Fail loud when an entity declares a create-phase user field but no identity is in
50
+ * scope — a silent NULL is exactly the failure this enforcement exists to kill.
51
+ *
52
+ * `onUpdateUserId` is deliberately NOT enforced: `updatedBy` is allowed to stay absent,
53
+ * and refusing a context-less update would also break pre-auth writes that don't touch it.
54
+ */
55
+ private assertCreateIdentity(fields: VexFieldEntry[]): void {
56
+ if (!fields.some(f => f.type === "onCreateUserId")) return;
57
+ if (UserContext.userId) return;
58
+
59
+ throw new VexResErr(500, undefined,
60
+ `${this.getEntityName()} declares onCreateUserId but UserContext carries no user identity`);
61
+ }
62
+
48
63
  /**
49
64
  * Framework-managed audit fields: strip the caller's values first — a client must never
50
65
  * forge createdBy / updatedAt — then fill the ones owned by this write phase.
@@ -55,7 +70,9 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
55
70
  const fields = entityVexFields[this.getEntityName()] ?? [];
56
71
  if (fields.length === 0) return;
57
72
 
58
- const userId = DataIsolationContext.getStore()?.userId;
73
+ if (phase === "create") this.assertCreateIdentity(fields);
74
+
75
+ const userId = UserContext.userId;
59
76
  const values: Record<string, unknown> = {};
60
77
 
61
78
  for (const entry of fields) {
@@ -72,13 +89,13 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
72
89
 
73
90
  /** Build ownership filter from current request context, or null. */
74
91
  private getOwnershipFilter(): Record<string, unknown> | null {
75
- const store = DataIsolationContext.getStore();
76
- if (!store?.userId) return null;
92
+ const userId = UserContext.userId;
93
+ if (!userId) return null;
77
94
 
78
95
  const config = entityIsolation[this.getEntityName()];
79
96
  if (!config) return null;
80
97
 
81
- return { [config.field]: store.userId };
98
+ return { [config.field]: userId };
82
99
  }
83
100
 
84
101
  /** Merge caller filter with ownership filter. Ownership always wins. */
@@ -198,11 +215,11 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
198
215
 
199
216
  async create(data: Partial<T>): Promise<T> {
200
217
  const enriched = { ...data };
201
- const store = DataIsolationContext.getStore();
202
- if (store?.userId) {
218
+ const userId = UserContext.userId;
219
+ if (userId) {
203
220
  const config = entityIsolation[this.getEntityName()];
204
221
  if (config && config.field !== "_id") {
205
- (enriched as Record<string, unknown>)[config.field] = store.userId;
222
+ (enriched as Record<string, unknown>)[config.field] = userId;
206
223
  }
207
224
  }
208
225
  this.applyVexFields(enriched, "create");
@@ -71,7 +71,7 @@ Declared per entity in `x-documentConfig → dataIsolation: { field: "ownerId" }
71
71
  Generation produces three pieces:
72
72
 
73
73
  1. `DataIsolationRegistry.gen.ts` (`src/generators/middlewares/dataIsolationRegistry.generator.ts`) — entity → ownership-field map
74
- 2. `DataIsolationContext.ts` middleware — `AsyncLocalStorage` carrying the current user through the request pipeline
74
+ 2. `UserContext.ts` — `AsyncLocalStorage` carrying the current user through the request pipeline; filled by `Authentication.middleware` from the verified token, not by a dedicated middleware
75
75
  3. The TypeORM adapter reads the user ID from that context and injects `{ [field]: userId }` into every query — transparent row-level ownership, no per-controller code
76
76
 
77
77
  Full guide: [`docs/features/dataIsolation.md`](../features/dataIsolation.md).
@@ -82,7 +82,8 @@ Columns declared with a reserved `default` keyword (`onCreateTimestamp`, `onUpda
82
82
  the repository adapters on `create` / `update` / `replace` — a shared helper strips client-supplied values
83
83
  first, then injects per write phase. Both targets implement it; the entity → field map comes from
84
84
  `VexFieldRegistry.gen.ts` (`src/generators/middlewares/vexFieldRegistry.generator.ts`), which also exports the
85
- `x-vexData: "userId"` identity field the token pipeline reads.
85
+ `x-vexData: "userId"` identity field the token pipeline reads. A `create` that declares `onCreateUserId` but
86
+ finds no identity in `UserContext` throws rather than writing NULL.
86
87
 
87
88
  Guide: [`docs/features/auditFields.md`](../features/auditFields.md).
88
89
 
@@ -121,27 +121,39 @@ adapters. Both adapters apply the same two-step rule:
121
121
  Stripping-without-injecting on the opposite phase is what keeps `createdBy` / `createdAt` immutable:
122
122
  a PATCH never overwrites them.
123
123
 
124
+ ### Where the identity comes from
125
+
126
+ `UserContext` (`src/system/_middlewares/UserContext.gen.ts`) is an `AsyncLocalStorage` store that
127
+ `Authentication.middleware` fills from the **verified access token** — `vexUserId` (the value of the
128
+ field tagged `x-vexData: "userId"`), with `_id` as the fallback for tokens issued before that claim
129
+ existed.
130
+
131
+ There is no separate context middleware to mount. Authentication *is* the mount point, so any
132
+ controller that authenticates establishes the context for the whole downstream chain — the repository
133
+ adapters included. The data layer never inspects the token shape; it reads the normalized
134
+ `UserContext.userId`.
135
+
124
136
  Values written:
125
137
 
126
138
  | keyword kind | value |
127
139
  | --- | --- |
128
140
  | `onXXTimestamp` | `new Date().toISOString()` — an ISO-8601 string the `timestamptz` column accepts directly |
129
141
  | `onXXUnixTimestamp` | `Math.floor(Date.now() / 1000)` — epoch seconds |
130
- | `onXXUserId` | the request context identity (`vexUserId`); **skipped** when there is none |
142
+ | `onXXUserId` | the request context identity (`UserContext.userId`); **skipped** when there is none — except on create, which raises instead (see §5) |
131
143
 
132
144
  The registry generator is the only place that knows the mapping: adapters import
133
145
  `entityVexFields` at runtime rather than re-deriving it from the schema.
134
146
 
135
- ### Request body type — `Create{Doc}`
147
+ ### Request body type — `Payload{Doc}`
136
148
 
137
149
  Server-owned fields must not appear in the API *input*. The interface generator therefore emits, into
138
150
  `src/system/_types/{Doc}.gen.ts`:
139
151
 
140
152
  ```ts
141
- export type CreateJob = Omit<Job, "createdAt" | "createdBy" | "updatedAt" | "updatedBy" | "_id">;
153
+ export type PayloadJob = Omit<Job, "createdAt" | "createdBy" | "updatedAt" | "updatedBy" | "_id">;
142
154
  ```
143
155
 
144
- and the controllers accept `Create{Doc}` (create, put) / `Partial<Create{Doc}>` (patch). The omission is
156
+ and the controllers accept `Payload{Doc}` (create, put) / `Partial<Payload{Doc}>` (patch). The omission is
145
157
  **declaration-based, never name-based**: a field is dropped when it carries a reserved `default` keyword,
146
158
  or when it is the primary key (`x-format: Primary` / `PrimaryUUID`) and `app.allowApiCreateUpdate_id` is
147
159
  false. A column literally named `createdAt` without a keyword stays client-writable — the declaration is
@@ -181,12 +193,22 @@ raw SQL bypasses the audit fields — same as any ORM-level convention. Document
181
193
 
182
194
  ## 5. No authenticated context
183
195
 
184
- Public / anonymous / internal calls have no ALS store (`DataIsolationContext` does not run one when
185
- `req.user` is absent):
196
+ Public / anonymous / internal calls have no `UserContext` store at all — `Authentication.middleware`
197
+ is what creates one, so a route that does not authenticate never has an identity to offer.
186
198
 
187
199
  - Timestamp keywords are context-free → **still injected**.
188
- - `onXXUserId` keywords → **skipped**, field left unset (NULL column). Never `"undefined"`, never a throw.
189
- - Nothing in the write path raises because the context is missing.
200
+ - `onUpdateUserId` → **skipped**, field left absent. Never `"undefined"`, never a throw. On an update
201
+ the column keeps whatever value it already had (the field is stripped from the payload either way),
202
+ so a context-less update silently preserves a stale `updatedBy` rather than blanking it.
203
+ - `onCreateUserId` → **throws**. A create that cannot record who created the row is a broken invariant,
204
+ not a value that may be "missing": the whole point of the keyword is that the column is trustworthy.
205
+ This is the regression that left `createdBy` NULL in every generated app — see the release note.
206
+ - Nothing else in the write path raises because the context is missing.
207
+
208
+ The check lives in the repository adapters (`assertCreateIdentity`) and is deliberately scoped to
209
+ `onCreateUserId`: it fires for the phase that declares the keyword, so an entity that only declares
210
+ `onUpdateUserId` is unaffected. R8 (§6) rejects the config earlier, at generation time, when the app has
211
+ no auth at all and therefore *no* create could ever succeed.
190
212
 
191
213
  ## 6. Validation (`formatJsonSchema` / checkSchema stage — fail at generation, not at runtime)
192
214
 
@@ -199,11 +221,18 @@ Public / anonymous / internal calls have no ALS store (`DataIsolationContext` do
199
221
  | R5 | `onXXTimestamp` must be `string` + `x-format: "Timestamp"`; `onXXUnixTimestamp` must be `integer` + `x-format: "UnixTimestamp"` | error |
200
222
  | R6 | `x-vexData` value must be a known one (`role`, `userId`) — catches typos | error |
201
223
  | R7 | an audit field must not be `required` — its value is stripped from the client body anyway | error |
224
+ | R8 | `onCreateUserId` present but the app enables no authentication (`auth.localAuth` false and every oauth provider off) | error |
202
225
 
203
226
  R4 compares the **resolved** family, not the raw string: `Primary`, `PrimaryUUID` and `UUID` all resolve to
204
227
  `uuid`, so tagging `_id` as `PrimaryUUID` and declaring `createdBy` as `UUID` is consistent and does not
205
228
  raise. The error message names both offending paths (the tagged field and the audit field).
206
229
 
230
+ R8 mirrors the runtime guard rather than the declaration surface: it fires on `onCreateUserId` only, because
231
+ that is the only keyword the adapters refuse to skip. A schema that declares just `onUpdateUserId` in an
232
+ auth-less app is accepted — nothing will ever throw, the column simply stays unset. Being stricter here would
233
+ reject configs that cannot actually fail, and would break the default `User.json` template (which declares
234
+ `updatedBy` and is copied into every app, auth or not).
235
+
207
236
  Validation runs once, after every schema is loaded (`validateAuditFields()` in
208
237
  `src/preprocess/auditFields.ts`, called from the pipeline), because R1/R2 are cross-document. All problems
209
238
  are collected and reported together; `log.error` exits the generator, so a contradiction never reaches runtime.
@@ -220,6 +249,24 @@ are collected and reported together; `log.error` exits the generator, so a contr
220
249
  keeps the current capitalized values (`Primary`, `PrimaryUUID`, `UUID`, `UnixTimestamp`) and only adds
221
250
  `Timestamp`.
222
251
 
252
+ ### Breaking since v0.8.2
253
+
254
+ Three changes downstream apps must absorb when they re-run `vex`:
255
+
256
+ 1. **The context module was renamed.** `DataIsolationContext.gen.ts` is gone; `UserContext.gen.ts` replaces
257
+ it. `cleanupStaleFiles()` removes the old file on the next run, so anything importing it by name breaks.
258
+ 2. **A create without an identity now throws** where it previously wrote NULL. This affects
259
+ `onCreateUserId` only, and only a path that reaches `create()` with no authenticated request context
260
+ (seed scripts, background jobs, or a controller that does not mount `Authentication.middleware`).
261
+ 3. **Data isolation becomes effective for the first time.** It used to be mounted only on entities declaring
262
+ `dataIsolation`, which in practice meant it rarely ran at all. It now has a context on every
263
+ authenticating controller. Ownership still wins over the caller's filter, so an endpoint that queries
264
+ *another* user's row by id will silently act on the caller's own row instead. Audit those endpoints per
265
+ app.
266
+
267
+ Downstream apps no longer need the `dataIsolation` config merely to get the ALS context mounted — that
268
+ coupling is gone. Use `dataIsolation` only when ownership filtering is actually wanted.
269
+
223
270
  ## 8. Mongoose
224
271
 
225
272
  Implemented in parallel with TypeORM — same registry, same strip/inject phases, same values
@@ -6,8 +6,9 @@ Available from v0.6.x. Provides transparent per-entity ownership: all queries ar
6
6
 
7
7
  1. Declare `dataIsolation` in `x-documentConfig` of your JSON Schema
8
8
  2. Generator produces `DataIsolationRegistry.gen.ts` mapping entity → ownership field
9
- 3. `DataIsolationContext` middleware runs before request handlers, storing the current user's identity
10
- (`vexUserId` token claim, `_id` as fallback) in `AsyncLocalStorage`
9
+ 3. `Authentication.middleware` establishes a `UserContext` (an `AsyncLocalStorage` store) from the
10
+ verified access token — `vexUserId`, `_id` as fallback. There is no separate context middleware: any
11
+ authenticating controller sets it up for the whole downstream chain.
11
12
  4. `TypeOrmRepositoryAdapter` reads the registry and injects `{ [field]: userId }` into every query
12
13
 
13
14
  ## Configuration
@@ -54,10 +54,10 @@ generated interfaces keep their `string` contract.
54
54
  The interface generator now emits a request-body alias per document:
55
55
 
56
56
  ```ts
57
- export type CreateJob = Omit<Job, "createdAt" | "createdBy" | "updatedAt" | "updatedBy" | "_id">;
57
+ export type PayloadJob = Omit<Job, "createdAt" | "createdBy" | "updatedAt" | "updatedBy" | "_id">;
58
58
  ```
59
59
 
60
- Controllers take `Create{Doc}` / `Partial<Create{Doc}>`, so the OpenAPI request schema only lists fields a
60
+ Controllers take `Payload{Doc}` / `Partial<Payload{Doc}>`, so the OpenAPI request schema only lists fields a
61
61
  client may send, and `_id` is dropped from the input as well (unless `app.allowApiCreateUpdate_id` is
62
62
  true). The response schema is unchanged — clients still read `createdAt` / `createdBy`.
63
63
 
@@ -0,0 +1,12 @@
1
+ v0.8.2
2
+ - Fixed `createdBy` staying NULL in every generated app — audit user fields had no identity context.
3
+ - Removed `DataIsolationContext.middleware`; `Authentication.middleware` now establishes identity context from verified access token.
4
+ - Renamed `DataIsolationContext` to `UserContext`.
5
+ - Added `UserContext.run()` storing full access token payload, with normalized `userId` getter (`vexUserId` claim, `_id` fallback).
6
+ - Removed `dataIsolation` condition that gated context mounting.
7
+ - Removed `dataIsolation` parameter from controller generator.
8
+ - Added fail-loud error on create when entity declares `onCreateUserId` and context carries no identity.
9
+ - Added generation-time rule R8 — rejects `onCreateUserId` when app enables no authentication.
10
+ - Enabled data isolation on every authenticating controller; ownership filter previously mounted only on entities declaring `dataIsolation`.
11
+ - Added unit tests for `UserContext` normalization, async scope and concurrent isolation.
12
+ - Added unit tests for generation-time rule R8.
@@ -255,7 +255,7 @@ Filter 类型是编译期类型工具,不影响 OAS。
255
255
  |---------|--------|
256
256
  | `tsoaAuthentication.ts` | ❌ 废弃 |
257
257
  | `Authentication.ts` | Ts.ED `@Middleware()` class |
258
- | `DataIsolationContext.ts` | Ts.ED `@Middleware()` |
258
+ | `UserContext.ts` (原 `DataIsolationContext.ts`) | 无需 `@Middleware()` —— 由 `Authentication` 建立上下文 |
259
259
  | `JoinWhitelistMiddleware.ts` | Ts.ED `@Middleware()` + 补充循环路径检测 |
260
260
 
261
261
  Authentication 迁移示例:
@@ -392,7 +392,7 @@ OAS 3.x spec 本身不会因此循环展开——$ref 是静态引用定义。
392
392
  |------|------|
393
393
  | `_middlewares/tsoaAuthentication.ts` | **删除** |
394
394
  | `_middlewares/Authentication.ts` | 重写为 Ts.ED `@Middleware()` |
395
- | `_middlewares/DataIsolationContext.ts` | 注册模式改 Ts.ED |
395
+ | `_middlewares/UserContext.ts` | 无需注册 —— 由 `Authentication` 建立上下文 |
396
396
  | `_middlewares/JoinWhitelistMiddleware.ts` | 注册模式改 Ts.ED |
397
397
  | `_controllers/_ControllerFactory.ts` | tsoa `Controller` → Ts.ED `Controller` |
398
398
  | `_projectSettings/package.json` | +Ts.ED deps, -tsoa |