very-express 0.9.0 → 0.10.1

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 (131) hide show
  1. package/.tmp/als-proof.mjs +15 -0
  2. package/.tmp/als-proof2.mjs +9 -0
  3. package/.tmp/gen/out/.env +41 -0
  4. package/.tmp/gen/out/.vex/meta.json +387 -0
  5. package/.tmp/gen/out/Dockerfile +20 -0
  6. package/.tmp/gen/out/README.md +39 -0
  7. package/.tmp/gen/out/package.json +51 -0
  8. package/.tmp/gen/out/public/css/style.css +8 -0
  9. package/.tmp/gen/out/public/js/deleteaccount.js +80 -0
  10. package/.tmp/gen/out/public/js/login.js +59 -0
  11. package/.tmp/gen/out/public/js/logincallback.js +19 -0
  12. package/.tmp/gen/out/public/js/mytokens.js +11 -0
  13. package/.tmp/gen/out/public/js/refreshtokens.js +23 -0
  14. package/.tmp/gen/out/scripts/build.js +39 -0
  15. package/.tmp/gen/out/scripts/oacg-fix.js +83 -0
  16. package/.tmp/gen/out/tsconfig.json +30 -0
  17. package/.tmp/gen/out/tsoa.json +32 -0
  18. package/.tmp/gen/schemas/Project.json +50 -0
  19. package/.tmp/gen/schemas/Session.json +49 -0
  20. package/.tmp/gen/schemas/User.json +81 -0
  21. package/.tmp/gen/schemas/UserAuthProfiles.json +54 -0
  22. package/.tmp/gen/schemas/UserRole.json +40 -0
  23. package/.tmp/gen/schemas/UserTenant.json +39 -0
  24. package/.tmp/gen/vex.config.json +39 -0
  25. package/.tmp/gen0/out/.env +41 -0
  26. package/.tmp/gen0/out/.vex/meta.json +323 -0
  27. package/.tmp/gen0/out/Dockerfile +20 -0
  28. package/.tmp/gen0/out/README.md +39 -0
  29. package/.tmp/gen0/out/package.json +51 -0
  30. package/.tmp/gen0/out/public/css/style.css +8 -0
  31. package/.tmp/gen0/out/public/js/deleteaccount.js +80 -0
  32. package/.tmp/gen0/out/public/js/login.js +59 -0
  33. package/.tmp/gen0/out/public/js/logincallback.js +19 -0
  34. package/.tmp/gen0/out/public/js/mytokens.js +11 -0
  35. package/.tmp/gen0/out/public/js/refreshtokens.js +23 -0
  36. package/.tmp/gen0/out/scripts/build.js +39 -0
  37. package/.tmp/gen0/out/scripts/oacg-fix.js +83 -0
  38. package/.tmp/gen0/out/tsconfig.json +30 -0
  39. package/.tmp/gen0/out/tsoa.json +32 -0
  40. package/.tmp/gen0/schemas/Session.json +49 -0
  41. package/.tmp/gen0/schemas/User.json +81 -0
  42. package/.tmp/gen0/schemas/UserAuthProfiles.json +54 -0
  43. package/.tmp/gen0/schemas/UserRole.json +38 -0
  44. package/.tmp/gen0/vex.config.json +32 -0
  45. package/.tmp/gend/out/.env +41 -0
  46. package/.tmp/gend/out/.vex/meta.json +317 -0
  47. package/.tmp/gend/out/Dockerfile +20 -0
  48. package/.tmp/gend/out/README.md +39 -0
  49. package/.tmp/gend/out/package.json +51 -0
  50. package/.tmp/gend/out/public/css/style.css +8 -0
  51. package/.tmp/gend/out/public/js/deleteaccount.js +80 -0
  52. package/.tmp/gend/out/public/js/login.js +59 -0
  53. package/.tmp/gend/out/public/js/logincallback.js +19 -0
  54. package/.tmp/gend/out/public/js/mytokens.js +11 -0
  55. package/.tmp/gend/out/public/js/refreshtokens.js +23 -0
  56. package/.tmp/gend/out/scripts/build.js +39 -0
  57. package/.tmp/gend/out/scripts/oacg-fix.js +83 -0
  58. package/.tmp/gend/out/tsconfig.json +30 -0
  59. package/.tmp/gend/out/tsoa.json +32 -0
  60. package/.tmp/gend/schemas/Session.json +49 -0
  61. package/.tmp/gend/schemas/User.json +81 -0
  62. package/.tmp/gend/schemas/UserAuthProfiles.json +54 -0
  63. package/.tmp/gend/schemas/UserContact.json +40 -0
  64. package/.tmp/gend/schemas/UserNote.json +27 -0
  65. package/.tmp/gend/vex.config.json +33 -0
  66. package/.tmp/genh/out/.env +41 -0
  67. package/.tmp/genh/out/.vex/meta.json +323 -0
  68. package/.tmp/genh/out/Dockerfile +20 -0
  69. package/.tmp/genh/out/README.md +39 -0
  70. package/.tmp/genh/out/package.json +51 -0
  71. package/.tmp/genh/out/public/css/style.css +8 -0
  72. package/.tmp/genh/out/public/js/deleteaccount.js +80 -0
  73. package/.tmp/genh/out/public/js/login.js +59 -0
  74. package/.tmp/genh/out/public/js/logincallback.js +19 -0
  75. package/.tmp/genh/out/public/js/mytokens.js +11 -0
  76. package/.tmp/genh/out/public/js/refreshtokens.js +23 -0
  77. package/.tmp/genh/out/scripts/build.js +39 -0
  78. package/.tmp/genh/out/scripts/oacg-fix.js +83 -0
  79. package/.tmp/genh/out/tsconfig.json +30 -0
  80. package/.tmp/genh/out/tsoa.json +32 -0
  81. package/.tmp/genh/schemas/Project.json +41 -0
  82. package/.tmp/genh/schemas/Session.json +49 -0
  83. package/.tmp/genh/schemas/User.json +81 -0
  84. package/.tmp/genh/schemas/UserAuthProfiles.json +54 -0
  85. package/.tmp/genh/schemas/UserTenant.json +39 -0
  86. package/.tmp/genh/vex.config.json +34 -0
  87. package/.tmp/gens/out/.env +41 -0
  88. package/.tmp/gens/out/.vex/meta.json +335 -0
  89. package/.tmp/gens/out/Dockerfile +20 -0
  90. package/.tmp/gens/out/README.md +39 -0
  91. package/.tmp/gens/out/package.json +51 -0
  92. package/.tmp/gens/out/public/css/style.css +8 -0
  93. package/.tmp/gens/out/public/js/deleteaccount.js +80 -0
  94. package/.tmp/gens/out/public/js/login.js +59 -0
  95. package/.tmp/gens/out/public/js/logincallback.js +19 -0
  96. package/.tmp/gens/out/public/js/mytokens.js +11 -0
  97. package/.tmp/gens/out/public/js/refreshtokens.js +23 -0
  98. package/.tmp/gens/out/scripts/build.js +39 -0
  99. package/.tmp/gens/out/scripts/oacg-fix.js +83 -0
  100. package/.tmp/gens/out/tsconfig.json +30 -0
  101. package/.tmp/gens/out/tsoa.json +32 -0
  102. package/.tmp/gens/schemas/Session.json +49 -0
  103. package/.tmp/gens/schemas/User.json +81 -0
  104. package/.tmp/gens/schemas/UserAuthProfiles.json +54 -0
  105. package/.tmp/gens/schemas/UserRole.json +38 -0
  106. package/.tmp/gens/vex.config.json +32 -0
  107. package/.tmp/npmtest/package.json +1 -0
  108. package/.tmp/ro-test +0 -0
  109. package/AGENTS.md +4 -3
  110. package/README.md +1 -0
  111. package/dist/index.js +955 -653
  112. package/dist/templates/_middlewares/Authentication.ts +1 -1
  113. package/dist/templates/_middlewares/UserContext.ts +30 -4
  114. package/dist/templates/_services/MongooseRepositoryAdapter.ts +94 -4
  115. package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +92 -17
  116. package/dist/templates/_services/VexDbConnector.ts +36 -1
  117. package/dist/templates/_services/auth/JWTService.ts +13 -2
  118. package/dist/templates/_tenant/TenantScopeContext.ts +56 -0
  119. package/dist/templates/_types/auth.ts +7 -1
  120. package/dist/templates/_types/vex/VexRepository.ts +9 -2
  121. package/dist/templates/tenantJsonSchema/UserTenant.json +33 -0
  122. package/docs/architecture/databaseTargets.md +37 -8
  123. package/docs/architecture/generatorPipeline.md +2 -1
  124. package/docs/features/accountDeletion.md +61 -9
  125. package/docs/features/dataIsolation.md +58 -31
  126. package/docs/features/tenantIsolation.md +147 -0
  127. package/docs/releaseNote/v0-10-0.md +147 -0
  128. package/docs/releaseNote/v0-10-1.md +84 -0
  129. package/docs/vexJsonSchema.md +22 -0
  130. package/package.json +1 -1
  131. package/vitest.config.ts +3 -0
@@ -28,7 +28,8 @@ Interface: `src/templates/_types/vex/VexRepository.ts`
28
28
  ```ts
29
29
  find(filter, join?, select?, pagination?) count(filter)
30
30
  findOne(filter, join?, select?) findOneWhere(filter, join?, select?)
31
- create(data) replace(id, data)
31
+ create(data) save(data)
32
+ replace(id, data)
32
33
  update(id, data) delete(id)
33
34
  deleteWhere(filter)
34
35
  ```
@@ -42,6 +43,26 @@ deleteWhere(filter)
42
43
 
43
44
  Both are static templates — file extensions are `.ts` in-repo, copied as `.gen.ts` into the generated app.
44
45
 
46
+ ## Transactions
47
+
48
+ `VexDbConnector` owns the transaction entry:
49
+
50
+ ```ts
51
+ await vexDb.transaction(async (tx) => {
52
+ const repo = tx.getRepository(OrderEntity);
53
+ await repo.create({ ... });
54
+ });
55
+ ```
56
+
57
+ The callback receives `getRepository` only — never the TypeORM manager. Repositories are the
58
+ normal adapters, so isolation, audit stamping and fail-closed checks apply inside the transaction.
59
+ Throwing rolls everything back; nesting throws; the mongo target throws because the generated
60
+ adapter has no transaction support. `dataSource` is private, so business code cannot open its own
61
+ transaction on the raw connection.
62
+
63
+ `save` is the upsert-shaped write: insert without `_id`, scoped update with one. Isolation fields
64
+ are stripped in both branches, so a row cannot be moved to another tenant or owner.
65
+
45
66
  ### The Mongo target does not currently type-check
46
67
 
47
68
  `npm run test:e2e` compiles a generated app per config variant. The Mongoose variant
@@ -66,17 +87,25 @@ move it into the passing variant matrix.
66
87
 
67
88
  The SQL adapter maps the filter DSL (`$and`, `$or`, `$like`, `$in`, comparison operators) onto TypeORM `FindOptions`. See [`docs/features/filterOperators.md`](../features/filterOperators.md).
68
89
 
69
- ## Data isolation (row-level ownership)
90
+ ## Isolation (ownership and tenancy)
70
91
 
71
- Declared per entity in `x-documentConfig → dataIsolation: { field: "ownerId" }`.
92
+ Declared per entity in `x-documentConfig → isolation: [{ field, source, onMissing }]`. The legacy
93
+ `dataIsolation: { field }` form is an ownership rule.
72
94
 
73
95
  Generation produces three pieces:
74
96
 
75
- 1. `DataIsolationRegistry.gen.ts` (`src/generators/middlewares/dataIsolationRegistry.generator.ts`) — entity → ownership-field map
76
- 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
77
- 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
78
-
79
- Full guide: [`docs/features/dataIsolation.md`](../features/dataIsolation.md).
97
+ 1. `DataIsolationRegistry.gen.ts` (`src/generators/middlewares/dataIsolationRegistry.generator.ts`) —
98
+ entity → rule list (`field`, `source`, `onMissing`)
99
+ 2. `UserContext.ts` — `AsyncLocalStorage` carrying the request scope (`tokenData`, `requestedTenantId`,
100
+ `tenantId`). `Authentication.middleware` writes the verified token; in tenant `option` mode the
101
+ generated controllers run `TenantScope.middleware` right after it, and the L0 pass in `server.ts`
102
+ captures the header first. `run` layers a patch onto the enclosing scope instead of replacing it.
103
+ 3. Both adapters resolve each rule from that scope and AND every term into the query. Tenant terms
104
+ fail closed (`onMissing: "deny"`); ownership terms keep their historical skip-when-unauthenticated
105
+ behaviour. Isolation fields are stripped from caller data and stamped on create.
106
+
107
+ Full guides: [`docs/features/dataIsolation.md`](../features/dataIsolation.md),
108
+ [`docs/features/tenantIsolation.md`](../features/tenantIsolation.md).
80
109
 
81
110
  ## Auto-written audit fields
82
111
 
@@ -96,7 +96,7 @@ Custom `x-*` properties drive generation. Full reference: [`docs/vexJsonSchema.m
96
96
 
97
97
  | Property | Purpose |
98
98
  |---|---|
99
- | `x-documentConfig` | `documentName` (must match filename), `restApi.methods`, `restApi.joinWhitelist`, `restApi.noRelations`, `restApi.dataIsolation`, `uniqueIndex`, `keyPrefix` |
99
+ | `x-documentConfig` | `documentName` (must match filename), `restApi.methods`, `restApi.joinWhitelist`, `restApi.noRelations`, `isolation` (legacy `dataIsolation`), `uniqueIndex`, `keyPrefix` |
100
100
  | `x-foreignKey` | Relations. Only `one-to-one` / `many-to-one` declared on the owning side; `one-to-many` is auto-derived |
101
101
  | `x-vexData: "role"` | Marks the field used for RBAC |
102
102
  | `x-format: "ObjectId"` | MongoDB ObjectId; converted to `"Primary"` for the SQL target |
@@ -107,6 +107,7 @@ Custom `x-*` properties drive generation. Full reference: [`docs/vexJsonSchema.m
107
107
  |---|---|
108
108
  | `jsonschemaFormat.ts` | Validate schema structure (`x-documentConfig`, FK config, `x-format` type constraints). Normalize per-prop `required: true` into root `required: string[]`. For SQL target: convert `ObjectId` → `Primary` on `_id`, warn on nested index/FK/vexData |
109
109
  | `jsonSchemaForeignKeys.ts` | Wire reverse-relation metadata (`one-to-many` derived from the other side's `many-to-one`). Auto-populate `restApi.joinWhitelist` when unset |
110
+ | `isolation.ts` | Normalize the legacy `dataIsolation` field into `isolation` rules; validate rule shape, sources, duplicate fields, the identity document and the tenant sources |
110
111
  | `roleDefinitions.ts` | Ensure per-role JSON files exist with default CRUD permissions for each resource document |
111
112
 
112
113
  ## Interface generation
@@ -11,18 +11,46 @@ This covers the identity domain only. Business rows, uploaded objects and third-
11
11
 
12
12
  ```json
13
13
  {
14
- "auth": { "deleteAccount": true },
15
- "app": { "showSoftDeleted": false }
14
+ "auth": {
15
+ "deleteAccount": {
16
+ "enabled": true,
17
+ "deleteTables": ["UserContact", "UserAddress"]
18
+ }
19
+ },
20
+ "app": { "showSoftDeleted": false }
16
21
  }
17
22
  ```
18
23
 
19
24
  | Option | Default | Meaning |
20
25
  |---|---|---|
21
- | `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. |
26
+ | `auth.deleteAccount` | `true` | `true` / `false`, or the object form. Emits 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. |
27
+ | `auth.deleteAccount.enabled` | `true` | The switch inside the object form. |
28
+ | `auth.deleteAccount.deleteTables` | `[]` | Documents whose rows linked to the deleted user are removed with the account. |
22
29
  | `app.showSoftDeleted` | `false` | Lifts the adapter's soft-delete filter app-wide, making tombstones visible (and writable) again. Loud on every generation run. |
23
30
 
24
- Both are read with `??`, so an explicit `false` is never swallowed. There is no `deleteAccountPlaceholder`:
25
- the tombstone label is the constant `"Deleted user"`.
31
+ Both switches are read with `??`, so an explicit `false` is never swallowed. There is no
32
+ `deleteAccountPlaceholder`: the tombstone label is the constant `"Deleted user"`.
33
+
34
+ ### `deleteTables`
35
+
36
+ Each name must be a document in the project that can be linked to the identity row. The generator
37
+ resolves the link at generation time:
38
+
39
+ 1. a property whose `x-foreignKey.schemaName` is the identity document and whose `fieldName` is its
40
+ identity field;
41
+ 2. otherwise a `userId` string property.
42
+
43
+ A name that does not resolve fails generation, as does a missing document, a duplicate entry, or the
44
+ identity document itself.
45
+
46
+ At deletion time the service removes the caller's rows from each table:
47
+
48
+ | Document declares `x-vexData: "softDelete"` | Behaviour |
49
+ |---|---|
50
+ | yes | find the rows and `softDelete` each one |
51
+ | no | count, then `deleteWhere` |
52
+
53
+ The cleanup runs in both modes — with or without tenant isolation — whenever it is configured.
26
54
 
27
55
  ## Declaring soft delete
28
56
 
@@ -105,16 +133,37 @@ unhandled rejection. The async work lives in `handle()` and every outcome is rou
105
133
  ## Deletion flow
106
134
 
107
135
  `AccountDeletionService.deleteSelf()` takes the identity from `UserContext` only; no id is ever
108
- accepted from a path or body, so one account cannot delete another. It is idempotent: a repeat call
109
- returns `alreadyDeleted` without re-stamping the row.
136
+ accepted from a path or body, so one account cannot delete another.
110
137
 
111
138
  Order is load-bearing:
112
139
 
113
140
  1. **Credentials first** — auth profiles, roles, sessions. Tombstoning first would leave the OAuth
114
141
  path able to resolve the account through `provider` / `oauthId`, i.e. a deleted user could log
115
142
  back into their own tombstone.
116
- 2. **Tombstone last** — `softDelete(userId, TOMBSTONE)`. A mid-flight failure therefore leaves a
117
- live account that can simply be retried.
143
+ 2. **Related tables** — the `deleteTables` cleanup.
144
+ 3. **Identity last** — either the tombstone (no tenant isolation) or the `UserTenant` row (tenant
145
+ isolation). A mid-flight failure therefore leaves a live account that can simply be retried.
146
+
147
+ ### Without tenant isolation
148
+
149
+ `softDelete(userId, TOMBSTONE)` writes the tombstone. The call is idempotent: a repeat call returns
150
+ `tombstonedAt: ""` without re-stamping the row.
151
+
152
+ ### With tenant isolation
153
+
154
+ The account may belong to several tenants, so deletion removes only the current tenant mapping:
155
+
156
+ 1. `UserContext.tenantId` must be set — `400` otherwise.
157
+ 2. The mapping must exist — `404` otherwise.
158
+ 3. `removeCredentials` runs.
159
+ 4. `deleteTables` runs.
160
+ 5. `TenantService.removeUserTenant(userId, tenantId)` removes the mapping.
161
+
162
+ The `User` row is not tombstoned: the account keeps working for its other tenants. The response
163
+ carries `tenantId` and `deleted.userTenants = 1`; `tombstonedAt` is empty.
164
+
165
+ The endpoint attaches `TenantScope.middleware` after authentication in `option` mode, so the claim
166
+ must be present. In `preSelect` mode the header already established the tenant at L0.
118
167
 
119
168
  The tombstone redacts the standard personal fields: `email` → NULL, `name` → `"Deleted user"`,
120
169
  `locale` / `profileErrors` → NULL, `active` → false. `email` is NULL rather than `""` because `User`
@@ -147,3 +196,6 @@ rejects would only produce confusing 401s.
147
196
  - **Per-request cost.** The guard costs one narrow indexed read per authenticated request.
148
197
  - **Third-party identity.** vex cannot delete a Firebase account. Do it from the app, and capture the
149
198
  provider uid *before* calling the service.
199
+ - **Response shape.** `deleteAccountResponse` carries `userId`, `tombstonedAt`, `deleted`, and — when
200
+ the tenant branch ran — `tenantId` and `deleted.userTenants`. `related` reports the row count per
201
+ cleaned table.
@@ -1,15 +1,16 @@
1
- # Data Isolation (Row-Level Ownership)
1
+ # Isolation Rules (Row-Level Ownership and Tenancy)
2
2
 
3
- Available from v0.6.x. Provides transparent per-entity ownership: all queries are automatically scoped to the authenticated user.
3
+ An isolation rule adds a query term the repository ANDs into every read and write of a document.
4
+ The current form is `x-documentConfig.isolation`; the older single-field `dataIsolation` form is
5
+ still accepted and normalized into it.
4
6
 
5
7
  ## How it works
6
8
 
7
- 1. Declare `dataIsolation` in `x-documentConfig` of your JSON Schema
8
- 2. Generator produces `DataIsolationRegistry.gen.ts` mapping entity → ownership field
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.
12
- 4. `TypeOrmRepositoryAdapter` reads the registry and injects `{ [field]: userId }` into every query
9
+ 1. Declare `isolation` in `x-documentConfig` of a JSON Schema.
10
+ 2. The generator writes `DataIsolationRegistry.gen.ts`: entity class name → rule list.
11
+ 3. `Authentication.middleware` establishes the request scope as an `AsyncLocalStorage` store
12
+ (`UserContext`) from the verified access token.
13
+ 4. Both repository adapters read the registry at runtime and resolve every rule from that scope.
13
14
 
14
15
  ## Configuration
15
16
 
@@ -17,46 +18,72 @@ Available from v0.6.x. Provides transparent per-entity ownership: all queries ar
17
18
  {
18
19
  "x-documentConfig": {
19
20
  "documentName": "Project",
20
- "dataIsolation": {
21
- "field": "ownerId"
22
- },
21
+ "isolation": [
22
+ { "field": "tenantId", "source": "user.tenantId", "onMissing": "deny" },
23
+ { "field": "ownerId", "source": "user._id", "onMissing": "skip" }
24
+ ],
23
25
  "restApi": {
24
26
  "methods": ["get", "getList", "post", "put", "patch", "delete"]
25
27
  }
26
28
  },
27
29
  "properties": {
28
- "ownerId": {
29
- "type": "string",
30
- "required": true
31
- },
32
- "title": {
33
- "type": "string"
34
- }
30
+ "tenantId": { "type": "string", "index": true },
31
+ "ownerId": { "type": "string", "index": true },
32
+ "title": { "type": "string" }
35
33
  }
36
34
  }
37
35
  ```
38
36
 
39
- The `field` value references a property on the same document that stores the owner's user ID.
37
+ | Key | Values | Meaning |
38
+ | --- | --- | --- |
39
+ | `field` | a string property of the document | column the rule filters and stamps |
40
+ | `source` | `user._id` \| `user.tenantId` | request-context value to resolve |
41
+ | `onMissing` | `skip` \| `deny` | what happens when the value is absent |
42
+
43
+ Defaults: `user._id` → `skip`, `user.tenantId` → `deny`. The tenant source requires
44
+ `vex.config.tenant.enable`; the rule is rejected at generation time otherwise.
45
+
46
+ The legacy form is an ownership rule:
40
47
 
41
- > Note: `dataIsolation` sits directly under `x-documentConfig` — earlier revisions of this page
42
- > showed it nested under `restApi`, which the generator never read.
48
+ ```jsonc
49
+ "dataIsolation": { "field": "ownerId" }
50
+ ```
51
+
52
+ is equivalent to `{ "field": "ownerId", "source": "user._id", "onMissing": "skip" }`.
43
53
 
44
54
  ## Behavior
45
55
 
46
- - **All queries** — `find`, `findOne`, `update`, `delete` — get an `AND` filter: `{ [field]: currentUserId }`
47
- - **Create** — the adapter stamps the owner field from the request context; a controller only has to
48
- set it by hand when the owner is *not* the authenticated user (e.g. an admin creating data for a third party).
49
- `field: "_id"` is never stamped (the row's own id is the caller's id only for the account document itself)
50
- - **No userId in context** — if `Authentication` middleware hasn't set a user (e.g., public routes), the ownership filter is skipped
51
- - **Only affects SQL/TypeORM target** — Mongoose adapter doesn't implement data isolation yet
56
+ - **Reads and writes** — `find`, `findOne`, `update`, `replace`, `delete`, `deleteWhere`,
57
+ `softDelete`, `count` all carry the terms. Isolation always wins over the caller's filter.
58
+ - **Create** — isolation fields are stripped from the request data, then stamped from the request
59
+ context. `field: "_id"` is never stamped; it only filters the row's own id.
60
+ - **Updates** — isolation fields are stripped, never re-stamped. A row cannot be moved to another
61
+ tenant or owner through the API.
62
+ - **Request bodies** — isolation fields are omitted from the generated `Payload{Document}` type,
63
+ so tsoa rejects a caller that tries to set one.
64
+ - **`skip`** — no value, no term. Used for ownership: public routes keep working.
65
+ - **`deny`** — no value, `403`. Used for tenancy: a document that declares a tenant rule is
66
+ unreachable without a tenant.
67
+
68
+ ## Validation
69
+
70
+ Generation fails when:
71
+
72
+ - `isolation` is not an array, or a rule names a field that does not exist or is not a `string`;
73
+ - a rule has an unknown `source` / `onMissing`, or declares the same field twice;
74
+ - a `user.tenantId` rule appears on the identity document (`x-vexData: "userId"`) or on
75
+ `UserTenant` — both are read before a tenant is known;
76
+ - the tenant feature is enabled without a usable `UserTenant` document, or its `userId` /
77
+ `tenantId` properties are missing or not strings.
52
78
 
53
79
  ## Related: audit fields
54
80
 
55
- `dataIsolation` scopes *queries*; the reserved `default` keywords (`onCreateUserId`, `onUpdateTimestamp`, …)
56
- fill *columns* on write. They are independent and can be combined. See
81
+ Isolation scopes *queries*; the reserved `default` keywords (`onCreateUserId`, `onUpdateTimestamp`,
82
+ …) fill *columns* on write. They are independent and can be combined. See
57
83
  [`auditFields.md`](auditFields.md).
58
84
 
59
85
  ## Dependencies
60
86
 
61
- - Requires authentication (`auth.localAuth: true` or OAuth) to establish request context
62
- - Works with RBAC — both filters compose (ownership AND role check)
87
+ - Requires authentication to establish the request context.
88
+ - Works with RBAC — both filters compose.
89
+ - See [`tenantIsolation.md`](tenantIsolation.md) for the tenant source and token claim.
@@ -0,0 +1,147 @@
1
+ # Tenant Isolation
2
+
3
+ Tenant isolation scopes documents to a tenant. It is a standalone module: it does not import the auth
4
+ module, and it is emitted only when `vex.config.tenant.enable` is true. The tenant id is always a
5
+ UUID; the header (`x-tenant-id`) and the token claim (`tenantId`) are fixed.
6
+
7
+ ```jsonc
8
+ "tenant": {
9
+ "enable": true,
10
+ "IsolationMode": "preSelect", // or "option"; defaults to "preSelect"
11
+ "scope": ["/api"] // optional; omitted = every route
12
+ }
13
+ ```
14
+
15
+ `IsolationMode` decides how a request gets its tenant:
16
+
17
+ | Mode | Who chooses the tenant | When |
18
+ | --- | --- | --- |
19
+ | `preSelect` | the app build / client (header) | one frontend per tenant, e.g. a branded app |
20
+ | `option` | the logged-in user | one app, user logs in then picks an organization |
21
+
22
+ Documents opt in with an isolation rule:
23
+
24
+ ```jsonc
25
+ "isolation": [
26
+ { "field": "tenantId", "source": "user.tenantId", "onMissing": "deny" }
27
+ ]
28
+ ```
29
+
30
+ The rule field is the document column; it does not have to be named `tenantId`. See
31
+ [`dataIsolation.md`](dataIsolation.md).
32
+
33
+ `scope` limits which request paths the middleware touches, for browsers and static assets that
34
+ cannot send the header. It is a boundary-aware prefix match (`/api` matches `/api/...`, not
35
+ `/apix`); an entry must start with `/`; `/hello` is always exempt. In `preSelect`, include the auth
36
+ routes the client uses (normally `/api` or `/api/auth`).
37
+
38
+ The middleware validates the UUID only. It does not check whether the tenant exists or is enabled:
39
+ that lookup belongs to the application, and a missing / deleted tenant is its normal `404`.
40
+
41
+ ## Generated files
42
+
43
+ Emitted only when the feature is enabled; turning it off removes them on the next run
44
+ (`cleanupStaleFiles`).
45
+
46
+ | File | When | Role |
47
+ | --- | --- | --- |
48
+ | `jsonSchema/UserTenant.json` | enabled, if absent | the user ↔ tenant mapping table |
49
+ | `_middlewares/TenantScopeContext.gen.ts` | enabled | pure decision + UUID check |
50
+ | `_middlewares/TenantScope.gen.ts` | enabled | the middleware |
51
+ | `_services/TenantService.gen.ts` | enabled | link / unlink / list |
52
+ | `_controllers/TenantController.gen.ts` | `option` | `GET /tenant`, `POST /tenant/select` |
53
+ | `_types/Tenant.gen.ts` | `option` | response types |
54
+
55
+ `Authentication.middleware` and `JWTService` contain no tenant code. The generated auth controller
56
+ uses `TenantService` in `preSelect` mode and `JWTService.generateAccessToken(user, index, { tenantId })`
57
+ in `option` mode.
58
+
59
+ ## `preSelect`
60
+
61
+ 1. `TenantScope.middleware` runs first in `server.ts`. The header is required on application routes:
62
+ missing → `400`, non-UUID → `400`. The framework health check `/hello` is exempt. It writes
63
+ `tenantId`.
64
+ 2. A token claim is ignored — the header is the space.
65
+ 3. Login and token refresh verify `UserTenant(userId, tenantId)`: not a member → `403`.
66
+ 4. Registration links the new account to the header tenant.
67
+ 5. `POST /tenant/select` does not exist; one build serves one tenant.
68
+
69
+ A request without a tenant never reaches the repository. `onMissing: "deny"` answers `403` for any
70
+ route that bypasses the middleware.
71
+
72
+ ## `option`
73
+
74
+ 1. `TenantScope.middleware` runs at L0 (guest pass): no token yet, so a valid header may set the
75
+ tenant for public endpoints.
76
+ 2. `Authentication.middleware` verifies the token.
77
+ 3. The generated controller runs `TenantScope.middleware` again: the `tenantId` claim decides; a
78
+ token without it → `401` (`tenant not selected`); a malformed claim → `401`.
79
+ 4. Registration and login need no header. Tokens are minted without a tenant claim.
80
+ 5. `GET /api/tenant` lists the user's mappings.
81
+ 6. `POST /api/tenant/select` `{ tenantId }` validates the mapping in the database (`403` if absent)
82
+ and returns new access + refresh tokens carrying the claim.
83
+ 7. Refresh keeps the claim and re-validates the mapping; a removed mapping → `401`.
84
+
85
+ `TenantController` itself attaches only `Authentication.middleware`, so a token without a tenant can
86
+ still list and select. Custom controllers that need a selected tenant must attach
87
+ `TenantScope.middleware` after their authentication middleware.
88
+
89
+ ## `UserTenant`
90
+
91
+ The module owns one table, copied into `jsonSchemaDir` on first enable:
92
+
93
+ ```jsonc
94
+ {
95
+ "documentName": "UserTenant",
96
+ "restApi": { "methods": [] },
97
+ "uniqueIndex": [["userId", "tenantId"]],
98
+ "properties": {
99
+ "userId": { "type": "string", "x-format": "UUID" },
100
+ "tenantId": { "type": "string", "x-format": "UUID" }
101
+ }
102
+ }
103
+ ```
104
+
105
+ An existing `UserTenant.json` is left alone, so the app can extend it.
106
+
107
+ `TenantService`:
108
+
109
+ ```ts
110
+ addUserTenant(tenantId) // userId from UserContext; idempotent
111
+ linkUserTenant(userId, tenantId) // registration / provisioning
112
+ hasUserTenant(userId, tenantId)
113
+ removeUserTenant(userId, tenantId)
114
+ listUserTenants(userId?)
115
+ ```
116
+
117
+ The tenant system decides where tenant ids come from (invite, billing, admin console); it only has
118
+ to call `addUserTenant` or `linkUserTenant`.
119
+
120
+ ## Account deletion
121
+
122
+ `AccountDeletionService` keeps owning deletion. With tenant isolation enabled it removes the
123
+ `UserTenant` mapping instead of tombstoning the shared account; `auth.deleteAccount.deleteTables`
124
+ runs in both modes. See [`accountDeletion.md`](accountDeletion.md).
125
+
126
+ ## Limits
127
+
128
+ - The claim is a snapshot. A revoked mapping stays usable until the access token expires; `refresh`
129
+ and `select` re-check the database.
130
+ - `preSelect` trusts the header. A caller that knows a tenant UUID can send it; use it only where the
131
+ client build is controlled and tenant ids are not secret.
132
+ - Registration links the header tenant when one is present, in both modes. An open registration
133
+ endpoint therefore lets a caller pick a tenant; gate registration where tenants are private.
134
+ - Unique indexes are not rewritten. Declare tenant-scoped uniqueness explicitly, e.g.
135
+ `"uniqueIndex": [["tenantId", "email"]]`.
136
+ - `listUserTenants` has no pagination and no ordering.
137
+
138
+ ## Tests
139
+
140
+ - `test/unit/tenantScopeContext.test.ts` — decision and UUID validation.
141
+ - `test/unit/isolation.test.ts` — rule and `UserTenant` validation.
142
+ - `test/e2e/tenant.test.ts` — `option`: login → list → select → scoped CRUD → account deletion.
143
+ - `test/e2e/tenantHeader.test.ts` — `preSelect` with no auth module.
144
+ - `test/fixtures/scenarios/sql-tenant` / `sql-tenant-header` — golden output for both modes.
145
+ - `test/e2e/compile.test.ts` — `tenant-option-rbac-off`, `tenant-preSelect-auth-off`.
146
+
147
+ The e2e suites are opt-in: `npm run test:e2e`.
@@ -0,0 +1,147 @@
1
+ # v0.10.0
2
+
3
+ ## Tenant isolation
4
+
5
+ A document can be scoped to a tenant. The feature is off by default: set `vex.config.tenant.enable`
6
+ and the generator emits the tenant module. With it off, no tenant file is written and
7
+ `Authentication.middleware` / `JWTService` contain no tenant code.
8
+
9
+ ```jsonc
10
+ // vex.config.json
11
+ "tenant": {
12
+ "enable": true,
13
+ "IsolationMode": "option" // "preSelect" | "option"; defaults to "preSelect"
14
+ }
15
+ ```
16
+
17
+ ```jsonc
18
+ // a document schema
19
+ "x-documentConfig": {
20
+ "documentName": "Project",
21
+ "isolation": [
22
+ { "field": "tenantId", "source": "user.tenantId", "onMissing": "deny" }
23
+ ]
24
+ }
25
+ ```
26
+
27
+ The tenant id is a UUID. The header (`x-tenant-id`) and the token claim (`tenantId`) are fixed;
28
+ there is no custom header or claim name.
29
+
30
+ ### `preSelect` — one app build per tenant
31
+
32
+ 1. Every request must carry `x-tenant-id`; missing or non-UUID → `400`.
33
+ 2. The header is the tenant; a token claim is ignored.
34
+ 3. Login and refresh verify the `UserTenant` mapping; not a member → `403`.
35
+ 4. Registration links the new account to the header tenant.
36
+
37
+ ### `option` — log in, then choose an organization
38
+
39
+ 1. Login and registration need no tenant. Tokens are minted without a claim.
40
+ 2. `GET /api/tenant` lists the user's tenants.
41
+ 3. `POST /api/tenant/select` `{ tenantId }` validates the mapping (`403` if absent) and returns new
42
+ access + refresh tokens carrying `tenantId`.
43
+ 4. Protected requests check the claim: missing → `401` (`tenant not selected`), malformed → `401`.
44
+ 5. A request with no token is a guest; a valid header may identify the tenant for public endpoints.
45
+ 6. Refresh keeps the claim and re-validates the mapping.
46
+
47
+ ### `UserTenant`
48
+
49
+ The module owns the mapping table. It is copied into `jsonSchemaDir` on first enable and left alone
50
+ afterwards, so the app can extend it. `(userId, tenantId)` is unique; both are UUID columns and no
51
+ REST controller is generated.
52
+
53
+ ```ts
54
+ // TenantService.gen.ts
55
+ addUserTenant(tenantId) // userId from UserContext; idempotent
56
+ linkUserTenant(userId, tenantId) // registration / provisioning
57
+ hasUserTenant(userId, tenantId)
58
+ removeUserTenant(userId, tenantId)
59
+ listUserTenants(userId?)
60
+ ```
61
+
62
+ The app decides where tenant ids come from; it only calls `addUserTenant` or `linkUserTenant`.
63
+
64
+ ## Account deletion
65
+
66
+ `auth.deleteAccount` accepts a boolean or an object:
67
+
68
+ ```jsonc
69
+ "auth": {
70
+ "deleteAccount": {
71
+ "enabled": true,
72
+ "deleteTables": ["UserContact", "UserAddress"]
73
+ }
74
+ }
75
+ ```
76
+
77
+ - `deleteTables` rows are removed with the account in **both** modes. The generator resolves the
78
+ link field per document (`x-foreignKey` to the identity document, else `userId`) and fails
79
+ generation when a table cannot be linked.
80
+ - A document with `x-vexData: "softDelete"` is soft-deleted row by row; the rest are hard-deleted.
81
+ - With tenant isolation enabled, deletion removes the `UserTenant` mapping instead of tombstoning
82
+ the `User`: the account can keep working in its other tenants. `UserContext.tenantId` is required
83
+ (`400`), and the mapping must exist (`404`).
84
+ - `deleteAccountResponse` gains `tenantId`, `related` (rows per cleaned table) and
85
+ `deleted.userTenants`.
86
+
87
+ ## Isolation rules replace the single ownership field
88
+
89
+ `x-documentConfig.isolation` is a list. Each rule is `{ field, source, onMissing }`:
90
+
91
+ | Key | Values |
92
+ | --- | --- |
93
+ | `field` | a `string` property of the document |
94
+ | `source` | `user._id` \| `user.tenantId` |
95
+ | `onMissing` | `skip` \| `deny` (default: `skip` for `user._id`, `deny` for `user.tenantId`) |
96
+
97
+ The legacy `dataIsolation: { field }` form keeps working and is normalized to
98
+ `{ field, source: "user._id", onMissing: "skip" }`.
99
+
100
+ Behaviour changes that follow:
101
+
102
+ - **Isolation fields are no longer accepted in request bodies.** They are omitted from the generated
103
+ `Payload{Document}` type, and tsoa answers `400` to a request that sends one.
104
+ - **Updates strip isolation fields.** A row cannot be moved to another owner or tenant through
105
+ `PATCH` / `PUT`.
106
+ - **`onMissing: "deny"` fails closed.** A document that declares a tenant rule answers `403` when
107
+ the request carries no tenant.
108
+ - **Both adapters apply isolation** to every read and write path.
109
+
110
+ ## `UserContext` layers instead of replacing
111
+
112
+ `UserContext.run(patch, fn)` merges the patch onto the store of the enclosing scope, so the L0 tenant
113
+ pass, authentication and the post-auth tenant pass do not erase each other. The store carries
114
+ `tokenData`, `requestedTenantId` and `tenantId`.
115
+
116
+ ## Generated files
117
+
118
+ | File | When |
119
+ | --- | --- |
120
+ | `jsonSchema/UserTenant.json` | `tenant.enable`, if absent |
121
+ | `_middlewares/TenantScopeContext.gen.ts` | `tenant.enable` |
122
+ | `_middlewares/TenantScope.gen.ts` | `tenant.enable` |
123
+ | `_services/TenantService.gen.ts` | `tenant.enable` |
124
+ | `_controllers/TenantController.gen.ts` | `option` mode |
125
+ | `_types/Tenant.gen.ts` | `option` mode |
126
+ | `_middlewares/DataIsolationRegistry.gen.ts` | always — entity → rule list (empty when no rules) |
127
+
128
+ Turning the feature off removes the tenant files on the next run.
129
+
130
+ ## Migration
131
+
132
+ 1. Re-run the generator.
133
+ 2. `tenant` config from an earlier draft (`resolve`, `claim`, `bypassRoles`, `membership`,
134
+ `userField`) is rejected with a message: replace it with `{ enable, IsolationMode }`.
135
+ 3. Existing `dataIsolation` schemas need no edit. To scope by tenant, add the `tenant` config and a
136
+ `user.tenantId` rule.
137
+ 4. Add a tenant column (and a tenant-scoped unique index where uniqueness is per tenant, for example
138
+ `[["tenantId", "email"]]`).
139
+ 5. In `option` mode, clients must call `POST /api/tenant/select` after login; tokens minted at login
140
+ carry no tenant.
141
+
142
+ ## Tests
143
+
144
+ `npm test` covers the rule preprocessor, the tenant decision, `deleteTables` generation and the
145
+ generated output, with a golden scenario for each mode and for the cleanup tables.
146
+ `npm run test:e2e` proves both modes against a real Postgres — option mode through login → list →
147
+ select → scoped CRUD → account deletion, and preSelect mode with no auth module at all.