very-express 0.8.1 → 0.8.4

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.
@@ -0,0 +1,80 @@
1
+ // Self-service account deletion page.
2
+ //
3
+ // Sends the access token the same way the rest of the app does — Authorization + X-Auth-Index —
4
+ // and clears the stored tokens on success, because the account is gone the moment the tombstone
5
+ // is written: keeping a token the server will now reject only produces confusing 401s.
6
+
7
+ // The page loads this script from <head>, so it must wait for the DOM: at parse time the
8
+ // button does not exist yet and getElementById would return null.
9
+ document.addEventListener("DOMContentLoaded", function () {
10
+ var button = document.getElementById("deleteAccountBtn");
11
+ var input = document.getElementById("confirmInput");
12
+ var result = document.getElementById("deleteResult");
13
+
14
+ if (!button || !input || !result) return;
15
+
16
+ function clearTokens() {
17
+ localStorage.removeItem("accessToken");
18
+ localStorage.removeItem("accessTokenIndex");
19
+ localStorage.removeItem("refreshToken");
20
+ localStorage.removeItem("refreshTokenIndex");
21
+ }
22
+
23
+ function render(data) {
24
+ result.textContent = JSON.stringify(data, null, 2);
25
+ }
26
+
27
+ button.addEventListener("click", function () {
28
+ if (input.value !== "DELETE") {
29
+ render({ error: 'Type DELETE in the box to confirm.' });
30
+ return;
31
+ }
32
+
33
+ button.disabled = true;
34
+ render({ status: "Deleting…" });
35
+
36
+ fetch("/api/auth/delete-account", {
37
+ method: "POST",
38
+ credentials: "include",
39
+ headers: {
40
+ "Content-Type": "application/json",
41
+ "Authorization": "Bearer " + (localStorage.getItem("accessToken") || ""),
42
+ "X-Auth-Index": localStorage.getItem("accessTokenIndex") || "",
43
+ },
44
+ })
45
+ .then(function (response) {
46
+ // read as text first: an error response may not be JSON (a proxy or the
47
+ // express error handler can return HTML), and response.json() would then
48
+ // reject and hide the real status behind a parse error
49
+ return response.text().then(function (text) {
50
+ var body;
51
+ try {
52
+ body = text ? JSON.parse(text) : {};
53
+ }
54
+ catch (e) {
55
+ body = { raw: text };
56
+ }
57
+
58
+ return { ok: response.ok, status: response.status, body: body };
59
+ });
60
+ })
61
+ .then(function (outcome) {
62
+ if (!outcome.ok) {
63
+ render({ status: outcome.status, error: outcome.body });
64
+ button.disabled = false;
65
+ return;
66
+ }
67
+
68
+ clearTokens();
69
+ render({
70
+ status: "Account deleted. You have been signed out.",
71
+ result: outcome.body,
72
+ });
73
+ input.value = "";
74
+ })
75
+ .catch(function (err) {
76
+ render({ error: String(err) });
77
+ button.disabled = false;
78
+ });
79
+ });
80
+ });
@@ -65,10 +65,11 @@ Conditional emission:
65
65
 
66
66
  ```jsonc
67
67
  {
68
- "app": { "enableSwagger": true },
68
+ "app": { "enableSwagger": true, "showSoftDeleted": false },
69
69
  "auth": {
70
70
  "localAuth": true,
71
71
  "useHttpOnlyCookieToken": true,
72
+ "deleteAccount": true,
72
73
  "oauthProviders": { "google": false, "github": false }
73
74
  },
74
75
  "useRBAC": { "roles": ["visitor", "member", "admin"], "default": "admin" }
@@ -84,6 +85,12 @@ least one role (`utils.generator.isRbacEnabled`). Omitting the key, or passing
84
85
  When RBAC is on, `src/templates/jsonSchemaRBAC/` is copied over the sample schemas and
85
86
  `UserRole.role`'s enum is synced from `useRBAC.roles`.
86
87
 
88
+ Account deletion is the opposite — **opt-out**. `auth.deleteAccount` defaults to true, so
89
+ `AuthController` gains `POST /api/auth/delete-account` and the UI gains `/delete_account` unless the
90
+ project explicitly disables it (auth must also be enabled). `app.showSoftDeleted` controls whether
91
+ the repository hides soft-deleted rows; unset means hidden. See
92
+ [`docs/features/accountDeletion.md`](../features/accountDeletion.md).
93
+
87
94
  ## Auth internals
88
95
 
89
96
  JWT rolling keys and OAuth2 provider setup are documented in [`docs/appGenerated/auth.md`](../appGenerated/auth.md).
@@ -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
 
@@ -0,0 +1,150 @@
1
+ # Account deletion (tombstone)
2
+
3
+ Self-service account deletion for generated apps: `POST /api/auth/delete-account` plus a
4
+ `/delete_account` page. The account is **soft-deleted** — the row survives so business tables can
5
+ keep their required foreign keys — and its credentials and personal data are erased.
6
+
7
+ This covers the identity domain only. Business rows, uploaded objects and third-party identities
8
+ (Firebase, etc.) belong to the application. See the Renomaster spec for the full table-by-table
9
+ split.
10
+
11
+ ## Configuration
12
+
13
+ ```json
14
+ {
15
+ "auth": { "deleteAccount": true },
16
+ "app": { "showSoftDeleted": false }
17
+ }
18
+ ```
19
+
20
+ | Option | Default | Meaning |
21
+ |---|---|---|
22
+ | `auth.deleteAccount` | `true` | Emit the endpoint, the service and the page. Also requires auth to be enabled — a deletion endpoint that cannot authenticate a caller could only delete the wrong account. |
23
+ | `app.showSoftDeleted` | `false` | Lifts the adapter's soft-delete filter app-wide, making tombstones visible (and writable) again. Loud on every generation run. |
24
+
25
+ Both are read with `??`, so an explicit `false` is never swallowed. There is no `deleteAccountPlaceholder`:
26
+ the tombstone label is the constant `"Deleted user"`.
27
+
28
+ ## Declaring soft delete
29
+
30
+ Tag one boolean property with `x-vexData: "softDelete"`:
31
+
32
+ ```jsonc
33
+ "properties": {
34
+ "deleted": {
35
+ "type": "boolean",
36
+ "default": false,
37
+ "x-vexData": "softDelete",
38
+ "description": "Framework-managed; never client-writable."
39
+ }
40
+ },
41
+ "required": ["deleted"]
42
+ ```
43
+
44
+ The framework then owns that field:
45
+
46
+ - **Not client-writable.** `collectRequestManagedFields()` omits it, so it never appears in a
47
+ generated request body (`PayloadUser`), and the OpenAPI schema stops advertising it. A client
48
+ cannot soft-delete, resurrect or pre-tombstone a row through the CRUD API.
49
+ - **Hidden by default.** The adapters add `marker IS NOT TRUE` (`$ne: true` on Mongo) to every read
50
+ and write filter, so a tombstoned row is unreachable without any call-site change.
51
+ - **Owned writes.** `softDelete(id, data)` writes the marker through the normal update-phase
52
+ machinery, so `updatedAt` / `updatedBy` record who deleted the row and when. No `deletedAt` /
53
+ `deletedBy` columns are added.
54
+
55
+ Validation (generation-time, fails loud):
56
+
57
+ - at most **one** marker per document;
58
+ - it must be `"type": "boolean"`, `"default": false` and **required**.
59
+
60
+ The required/default rules are load-bearing. The hide-filter is `marker IS NOT TRUE`, so a nullable
61
+ column would drop every row written before it existed. `required` + `default: false` produce a
62
+ `boolean NOT NULL DEFAULT false` column.
63
+
64
+ ## Query semantics
65
+
66
+ `app.showSoftDeleted` is a **generation-time constant** baked into `VexFieldRegistry.gen.ts`, so no
67
+ request can flip it. There is deliberately no soft-delete key in `Filter<T>`: `Filter` is the shape
68
+ of every HTTP `filter` body, so a filter-level escape hatch would be a client-side bypass.
69
+
70
+ Internal callers use dedicated methods instead:
71
+
72
+ ```ts
73
+ softDelete(id, data?) // write the marker + redaction in one update
74
+ findOneWithDeleted(filter, join, select) // skip ONLY the soft-delete term; ownership still applies
75
+ ```
76
+
77
+ The hide term is **not** applied to relation loading, which is why the marker is a plain column and
78
+ not TypeORM's `@DeleteDateColumn` — the decorator nulls relation loads, and retained conversations
79
+ must still resolve their author to show "Deleted user".
80
+
81
+ > Enabling `app.showSoftDeleted` is a blunt instrument: it applies to every entity, including ones
82
+ > added later, and it removes the write protection that keeps a tombstone's audit fields frozen.
83
+
84
+ ## The token guard
85
+
86
+ `Authentication.middleware` verifies the JWT signature and nothing else, so a deleted user's
87
+ unexpired access token would keep working for the rest of its lifetime. The generated
88
+ `AccountStateGuard` closes that gap.
89
+
90
+ It reads the marker **value** rather than relying on the row being hidden, so the answer holds under
91
+ `app.showSoftDeleted` — a visibility-based check would call every tombstone alive. It uses
92
+ `findOneWithDeleted` so the ownership filter still applies, and treats a missing marker as live
93
+ (`!== true`), matching the adapters.
94
+
95
+ Every other auth path is already fail-closed: refresh and the OAuth exchange look the user up
96
+ through a soft-filtered read, local login compares an email that has been wiped to NULL, and the
97
+ OAuth callback cannot re-bind because the profile rows are gone.
98
+
99
+ The guard is emitted as a no-op when the identity document declares no marker, so the middleware's
100
+ import always resolves and projects without soft delete pay nothing.
101
+
102
+ The exported middleware is **synchronous** on purpose. Both call sites are express chains, and
103
+ Express 4 does not catch a rejected promise — an `async` handler would turn every failure into an
104
+ unhandled rejection. The async work lives in `handle()` and every outcome is routed to `next()`.
105
+
106
+ ## Deletion flow
107
+
108
+ `AccountDeletionService.deleteSelf()` takes the identity from `UserContext` only; no id is ever
109
+ accepted from a path or body, so one account cannot delete another. It is idempotent: a repeat call
110
+ returns `alreadyDeleted` without re-stamping the row.
111
+
112
+ Order is load-bearing:
113
+
114
+ 1. **Credentials first** — auth profiles, roles, sessions. Tombstoning first would leave the OAuth
115
+ path able to resolve the account through `provider` / `oauthId`, i.e. a deleted user could log
116
+ back into their own tombstone.
117
+ 2. **Tombstone last** — `softDelete(userId, TOMBSTONE)`. A mid-flight failure therefore leaves a
118
+ live account that can simply be retried.
119
+
120
+ The tombstone redacts the standard personal fields: `email` → NULL, `name` → `"Deleted user"`,
121
+ `locale` / `profileErrors` → NULL, `active` → false. `email` is NULL rather than `""` because `User`
122
+ declares a unique index on it — a second deletion would collide on the empty string, and the same
123
+ address must be able to register a fresh account immediately.
124
+
125
+ The payload is derived from the project's own schema, so absent or renamed fields are never emitted
126
+ and audit / identity fields are skipped.
127
+
128
+ ## The page
129
+
130
+ `GET /delete_account`, served from `LoginUI` rather than as a static file — `express.static("public")`
131
+ would expose `public/delete_account.html` at `/delete_account.html`, not at the route the store
132
+ listing points people at.
133
+
134
+ `LoginUIConfig.deleteAccount` is **optional and defaults to true**, because an app's `server.ts` is
135
+ generated once and is not overwritten on later runs; a required field would stop such a project from
136
+ compiling.
137
+
138
+ The copy is explicit that this is a tombstone, not an erasure. The client clears its stored tokens on
139
+ success: the account is gone the moment the tombstone is written, so keeping a token the server now
140
+ rejects would only produce confusing 401s.
141
+
142
+ ## Integration notes
143
+
144
+ - **Migration.** Adding the marker adds a column. `SQL_SYNCHRONIZE=true` covers development;
145
+ production needs `ALTER TABLE "user" ADD COLUMN "deleted" boolean NOT NULL DEFAULT false`.
146
+ - **`allowOverwrite: false`.** A project that pinned `UserModel.gen.ts` / `User.gen.ts` must add the
147
+ column by hand, or clear the `.vex/meta.json` entry for those files.
148
+ - **Per-request cost.** The guard costs one narrow indexed read per authenticated request.
149
+ - **Third-party identity.** vex cannot delete a Firebase account. Do it from the app, and capture the
150
+ provider uid *before* calling the service.
@@ -121,13 +121,25 @@ 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.
@@ -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,27 +221,22 @@ 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.
210
239
 
211
- ## 7. Backward compatibility
212
-
213
- - Schema with no reserved keyword and no tag → nothing changes; generation output is identical.
214
- - Schema with a literal `default` → unchanged.
215
- - Existing generated apps: re-run `vex`; entities gain `nullable` audit columns if they were declared.
216
- - Existing rows keep `createdBy = NULL`. This feature cannot backfill; a downstream app that needs
217
- ownership on legacy rows must migrate data itself.
218
- - Tokens issued before the upgrade still work (the `?? _id` fallback on refresh).
219
- - The prototype branch's lowercase `x-format` values (`primary`, `uuid`, …) are **rejected** — this design
220
- keeps the current capitalized values (`Primary`, `PrimaryUUID`, `UUID`, `UnixTimestamp`) and only adds
221
- `Timestamp`.
222
-
223
240
  ## 8. Mongoose
224
241
 
225
242
  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
@@ -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 |