very-express 0.9.0 → 0.10.0

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 (129) 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 +381 -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 +31 -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 +3 -3
  110. package/README.md +1 -0
  111. package/dist/index.js +946 -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 +68 -4
  115. package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +68 -18
  116. package/dist/templates/_services/auth/JWTService.ts +13 -2
  117. package/dist/templates/_tenant/TenantScopeContext.ts +56 -0
  118. package/dist/templates/_types/auth.ts +7 -1
  119. package/dist/templates/_types/vex/VexRepository.ts +2 -2
  120. package/dist/templates/tenantJsonSchema/UserTenant.json +33 -0
  121. package/docs/architecture/databaseTargets.md +15 -7
  122. package/docs/architecture/generatorPipeline.md +2 -1
  123. package/docs/features/accountDeletion.md +61 -9
  124. package/docs/features/dataIsolation.md +58 -31
  125. package/docs/features/tenantIsolation.md +138 -0
  126. package/docs/releaseNote/v0-10-0.md +147 -0
  127. package/docs/vexJsonSchema.md +22 -0
  128. package/package.json +1 -1
  129. package/vitest.config.ts +3 -0
@@ -46,7 +46,7 @@ class Authentication {
46
46
  }
47
47
 
48
48
  req.user = tokenData;
49
- UserContext.run(tokenData, () => next());
49
+ UserContext.run({ tokenData }, () => next());
50
50
  }
51
51
 
52
52
  private toVexErr(e: unknown): VexResErr {
@@ -1,9 +1,13 @@
1
1
  // {{headerComment}}
2
2
  import { AsyncLocalStorage } from "async_hooks";
3
3
 
4
- /** Identity-bearing claims carried from the verified access token. */
4
+ /** Identity-bearing claims carried from the verified access token, plus request scope. */
5
5
  export interface UserContextData {
6
- tokenData: Record<string, unknown>;
6
+ tokenData?: Record<string, unknown>;
7
+ /** Tenant the client asked for, captured from the request header before authentication. */
8
+ requestedTenantId?: string;
9
+ /** Tenant of this request. The DB layer reads only this value. */
10
+ tenantId?: string;
7
11
  }
8
12
 
9
13
  /**
@@ -19,9 +23,23 @@ export function userIdOfToken(tokenData: Record<string, unknown> | undefined): s
19
23
 
20
24
  const als = new AsyncLocalStorage<UserContextData>();
21
25
 
26
+ /**
27
+ * Request-scoped values shared by middleware layers.
28
+ *
29
+ * `run` layers a patch onto whatever the enclosing layer established, so a later
30
+ * middleware (authentication) does not erase what an earlier one (tenant header) set.
31
+ * The store is replaced, never merged in place, so concurrent requests stay isolated.
32
+ */
22
33
  class UserContext {
23
- run<T>(tokenData: Record<string, unknown>, fn: () => T): T {
24
- return als.run({ tokenData }, fn);
34
+ run<T>(patch: Partial<UserContextData>, fn: () => T): T {
35
+ return als.run({ ...als.getStore(), ...patch }, fn);
36
+ }
37
+
38
+ /** Merge into the store of the enclosing `run`. Throws outside a request scope. */
39
+ set(patch: Partial<UserContextData>): void {
40
+ const store = als.getStore();
41
+ if (!store) throw new Error("UserContext.set called outside a request scope");
42
+ Object.assign(store, patch);
25
43
  }
26
44
 
27
45
  getStore(): UserContextData | undefined {
@@ -32,6 +50,14 @@ class UserContext {
32
50
  get userId(): string | undefined {
33
51
  return userIdOfToken(als.getStore()?.tokenData);
34
52
  }
53
+
54
+ get requestedTenantId(): string | undefined {
55
+ return als.getStore()?.requestedTenantId;
56
+ }
57
+
58
+ get tenantId(): string | undefined {
59
+ return als.getStore()?.tenantId;
60
+ }
35
61
  }
36
62
 
37
63
  export default new UserContext();
@@ -2,6 +2,7 @@
2
2
  import { Model, Document } from "mongoose";
3
3
  import { VexRepository, Select, Filter, Join, VexPagination, VexResErr } from "../_types/vex";
4
4
  import UserContext from "../_middlewares/UserContext.gen";
5
+ import { entityIsolation, DataIsolationEntry } from "../_middlewares/DataIsolationRegistry.gen";
5
6
  import { entityVexFields, entitySoftDeleteFields, showSoftDeleted, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
6
7
  import utils from "../_utils";
7
8
 
@@ -104,9 +105,64 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
104
105
  return { [field]: { $ne: true } };
105
106
  }
106
107
 
108
+ /** Value the request context supplies for one isolation rule. */
109
+ private resolveIsolationValue(source: DataIsolationEntry["source"]): string | undefined {
110
+ return source === "user.tenantId" ? UserContext.tenantId : UserContext.userId;
111
+ }
112
+
113
+ /**
114
+ * Isolation terms for this model, ANDed into the caller's filter.
115
+ * A tenant term fails closed; an ownership term skips when unauthenticated.
116
+ */
117
+ private getIsolationFilter(): Record<string, unknown> | null {
118
+ const rules = entityIsolation[this.getEntityName()] ?? [];
119
+ if (rules.length === 0) return null;
120
+
121
+ const terms: Record<string, unknown> = {};
122
+
123
+ for (const rule of rules) {
124
+ const value = this.resolveIsolationValue(rule.source);
125
+ if (value === undefined) {
126
+ if (rule.onMissing === "deny") {
127
+ throw new VexResErr(403, undefined,
128
+ `${this.model.modelName} is isolated by ${rule.source} but the request carries no such value`);
129
+ }
130
+ continue;
131
+ }
132
+
133
+ terms[rule.field] = value;
134
+ }
135
+
136
+ return Object.keys(terms).length > 0 ? terms : null;
137
+ }
138
+
139
+ private stripIsolationFields(data: Partial<T>): void {
140
+ for (const rule of entityIsolation[this.getEntityName()] ?? []) {
141
+ if (rule.field === "_id") continue;
142
+ delete (data as Record<string, unknown>)[rule.field];
143
+ }
144
+ }
145
+
146
+ private stampIsolationFields(data: Partial<T>): void {
147
+ for (const rule of entityIsolation[this.getEntityName()] ?? []) {
148
+ if (rule.field === "_id") continue;
149
+
150
+ // `all` is a read scope: a write still needs a concrete tenant to stamp.
151
+ const value = this.resolveIsolationValue(rule.source);
152
+ if (value !== undefined) {
153
+ (data as Record<string, unknown>)[rule.field] = value;
154
+ }
155
+ else if (rule.onMissing === "deny") {
156
+ throw new VexResErr(403, undefined,
157
+ `${this.model.modelName} is isolated by ${rule.source} but the request carries no such value`);
158
+ }
159
+ }
160
+ }
161
+
107
162
  private mergeFilter(filter: Filter, options?: { includeSoftDeleted?: boolean }): Record<string, unknown> {
163
+ const isolation = this.getIsolationFilter();
108
164
  const softDelete = options?.includeSoftDeleted ? null : this.getSoftDeleteFilter();
109
- return { ...((filter || {}) as Record<string, unknown>), ...softDelete };
165
+ return { ...((filter || {}) as Record<string, unknown>), ...softDelete, ...isolation };
110
166
  }
111
167
 
112
168
  find(filter: Filter, join?: Join, select?: Select, pagination?: VexPagination): Promise<T[]> {
@@ -131,6 +187,8 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
131
187
 
132
188
  async create(data: Partial<T>): Promise<T> {
133
189
  const enriched = { ...data };
190
+ this.stripIsolationFields(enriched);
191
+ this.stampIsolationFields(enriched);
134
192
  this.applyVexFields(enriched, "create");
135
193
  const doc = new this.model(enriched);
136
194
  return doc.save();
@@ -142,8 +200,10 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
142
200
  return Promise.resolve(null);
143
201
  }
144
202
  const enriched = { ...data };
203
+ this.stripIsolationFields(enriched);
145
204
  this.applyVexFields(enriched, "update");
146
- return this.model.findByIdAndUpdate(id, enriched, { new: true, overwrite: true }).exec();
205
+ const filter = this.mergeFilter({ _id: id } as Filter);
206
+ return this.model.findOneAndUpdate(filter as any, enriched, { new: true, overwrite: true }).exec();
147
207
  }
148
208
 
149
209
  update(id: string | undefined, data: Partial<T>): Promise<T | null> {
@@ -152,8 +212,10 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
152
212
  return Promise.resolve(null);
153
213
  }
154
214
  const enriched = { ...data };
215
+ this.stripIsolationFields(enriched);
155
216
  this.applyVexFields(enriched, "update");
156
- return this.model.findByIdAndUpdate(id, { $set: enriched }, { new: true }).exec();
217
+ const filter = this.mergeFilter({ _id: id } as Filter);
218
+ return this.model.findOneAndUpdate(filter as any, { $set: enriched }, { new: true }).exec();
157
219
  }
158
220
 
159
221
  async delete(id: string | undefined): Promise<void> {
@@ -161,7 +223,8 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
161
223
  utils.log.error("MongooseRepositoryAdapter.delete called without id — refuse delete document");
162
224
  return;
163
225
  }
164
- await this.model.findByIdAndDelete(id).exec();
226
+ const filter = this.mergeFilter({ _id: id } as Filter);
227
+ await this.model.findOneAndDelete(filter as any).exec();
165
228
  }
166
229
 
167
230
  async deleteWhere(filter: Record<string, unknown>): Promise<void> {
@@ -189,6 +252,7 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
189
252
  }
190
253
 
191
254
  const enriched: Record<string, unknown> = { ...((data ?? {}) as Record<string, unknown>) };
255
+ this.stripIsolationFields(enriched as Partial<T>);
192
256
  this.applyVexFields(enriched as Partial<T>, "update");
193
257
  enriched[field] = true;
194
258
 
@@ -2,7 +2,7 @@
2
2
  import { Repository, ObjectLiteral, FindOptionsWhere, DeepPartial, In, Not, Like, MoreThan, LessThan, MoreThanOrEqual, LessThanOrEqual, FindManyOptions } from "typeorm";
3
3
  import { VexRepository, Select, Filter, Join, FieldOperators, VexPagination, VexResErr } from "../_types/vex";
4
4
  import UserContext from "../_middlewares/UserContext.gen";
5
- import { entityIsolation } from "../_middlewares/DataIsolationRegistry.gen";
5
+ import { entityIsolation, DataIsolationEntry } from "../_middlewares/DataIsolationRegistry.gen";
6
6
  import { entityVexFields, entitySoftDeleteFields, showSoftDeleted, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
7
7
  import utils from "../_utils";
8
8
 
@@ -87,14 +87,67 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
87
87
  Object.assign(data, values);
88
88
  }
89
89
 
90
- private getOwnershipFilter(): Record<string, unknown> | null {
91
- const userId = UserContext.userId;
92
- if (!userId) return null;
90
+ /** Value the request context supplies for one isolation rule. */
91
+ private resolveIsolationValue(source: DataIsolationEntry["source"]): string | undefined {
92
+ return source === "user.tenantId" ? UserContext.tenantId : UserContext.userId;
93
+ }
94
+
95
+ /**
96
+ * Isolation terms for this entity, ANDed into the caller's filter.
97
+ *
98
+ * A tenant term fails closed: a document that declares one is unreachable when the
99
+ * request carries no tenant, unless a cross-tenant role lifted the scope. An ownership
100
+ * term keeps its historical skip-when-unauthenticated behaviour.
101
+ */
102
+ private getIsolationFilter(): Record<string, unknown> | null {
103
+ const rules = entityIsolation[this.getEntityName()] ?? [];
104
+ if (rules.length === 0) return null;
105
+
106
+ const terms: Record<string, unknown> = {};
107
+
108
+ for (const rule of rules) {
109
+ const value = this.resolveIsolationValue(rule.source);
110
+ if (value === undefined) {
111
+ if (rule.onMissing === "deny") {
112
+ throw new VexResErr(403, undefined,
113
+ `${this.getEntityName()} is isolated by ${rule.source} but the request carries no such value`);
114
+ }
115
+ continue;
116
+ }
93
117
 
94
- const config = entityIsolation[this.getEntityName()];
95
- if (!config) return null;
118
+ terms[rule.field] = value;
119
+ }
96
120
 
97
- return { [config.field]: userId };
121
+ return Object.keys(terms).length > 0 ? terms : null;
122
+ }
123
+
124
+ /**
125
+ * Remove isolation fields from caller-supplied data. A client must never be able to
126
+ * move a row under another owner or into another tenant.
127
+ */
128
+ private stripIsolationFields(data: Partial<T>): void {
129
+ for (const rule of entityIsolation[this.getEntityName()] ?? []) {
130
+ if (rule.field === "_id") continue;
131
+ delete (data as Record<string, unknown>)[rule.field];
132
+ }
133
+ }
134
+
135
+ /** Fill isolation fields from the request context on create. */
136
+ private stampIsolationFields(data: Partial<T>): void {
137
+ for (const rule of entityIsolation[this.getEntityName()] ?? []) {
138
+ // a rule on `_id` filters the row's own id; it is never stamped
139
+ if (rule.field === "_id") continue;
140
+
141
+ // `all` is a read scope: a write still needs a concrete tenant to stamp.
142
+ const value = this.resolveIsolationValue(rule.source);
143
+ if (value !== undefined) {
144
+ (data as Record<string, unknown>)[rule.field] = value;
145
+ }
146
+ else if (rule.onMissing === "deny") {
147
+ throw new VexResErr(403, undefined,
148
+ `${this.getEntityName()} is isolated by ${rule.source} but the request carries no such value`);
149
+ }
150
+ }
98
151
  }
99
152
 
100
153
  /**
@@ -113,20 +166,20 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
113
166
  return { [field]: Not(true) };
114
167
  }
115
168
 
116
- /** Merge caller filter with ownership filter. Ownership always wins. */
169
+ /** Merge caller filter with isolation and soft-delete terms. Isolation always wins. */
117
170
  private mergeFilter(
118
171
  callerFilter: Filter<T>,
119
172
  options?: { includeSoftDeleted?: boolean },
120
173
  ): Record<string, unknown> | Array<Record<string, unknown>> {
121
174
  const mapped = this.mapOperators(callerFilter);
122
- const ownership = this.getOwnershipFilter();
175
+ const isolation = this.getIsolationFilter();
123
176
  const softDelete = options?.includeSoftDeleted ? null : this.getSoftDeleteFilter();
124
177
 
125
178
  if (mapped instanceof Array) {
126
- return mapped.map(branch => ({ ...branch, ...softDelete, ...ownership }));
179
+ return mapped.map(branch => ({ ...branch, ...softDelete, ...isolation }));
127
180
  }
128
181
  else {
129
- return { ...mapped, ...softDelete, ...ownership };
182
+ return { ...mapped, ...softDelete, ...isolation };
130
183
  }
131
184
  }
132
185
 
@@ -229,13 +282,8 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
229
282
 
230
283
  async create(data: Partial<T>): Promise<T> {
231
284
  const enriched = { ...data };
232
- const userId = UserContext.userId;
233
- if (userId) {
234
- const config = entityIsolation[this.getEntityName()];
235
- if (config && config.field !== "_id") {
236
- (enriched as Record<string, unknown>)[config.field] = userId;
237
- }
238
- }
285
+ this.stripIsolationFields(enriched);
286
+ this.stampIsolationFields(enriched);
239
287
  this.applyVexFields(enriched, "create");
240
288
  return this.repo.save(this.repo.create(enriched as DeepPartial<T>));
241
289
  }
@@ -246,6 +294,7 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
246
294
  return null;
247
295
  }
248
296
  const enriched = { ...data };
297
+ this.stripIsolationFields(enriched);
249
298
  this.applyVexFields(enriched, "update");
250
299
  const existing = await this.findOne({ _id: id } as unknown as Filter<T>);
251
300
  if (!existing) return null;
@@ -258,6 +307,7 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
258
307
  return null;
259
308
  }
260
309
  const enriched = { ...data };
310
+ this.stripIsolationFields(enriched);
261
311
  this.applyVexFields(enriched, "update");
262
312
  const where = this.mergeFilter({ _id: id } as unknown as Filter<T>);
263
313
  await this.repo.update(where as FindOptionsWhere<T>, enriched);
@@ -150,9 +150,20 @@ export default class JWTService {
150
150
  };
151
151
  }
152
152
 
153
- public async generateAccessToken(user: UserWithRelations, index?: number): Promise<tokenObj> {
153
+ /**
154
+ * `extraClaims` carries caller-supplied claims (for example a tenant) into the payload.
155
+ * The auth module stays unaware of which features add them.
156
+ */
157
+ public async generateAccessToken(
158
+ user: UserWithRelations,
159
+ index?: number,
160
+ extraClaims?: Record<string, unknown>,
161
+ ): Promise<tokenObj> {
154
162
 
155
- const userInfo = this.tokenPayload(user);
163
+ const userInfo = {
164
+ ...this.tokenPayload(user) as Record<string, unknown>,
165
+ ...(extraClaims ?? {}),
166
+ };
156
167
 
157
168
  return this.generateToken(userInfo, index, process.env.ACCESS_TOKEN_EXPIRE_TIME);
158
169
  }
@@ -0,0 +1,56 @@
1
+ // {{headerComment}}
2
+
3
+ export type TenantIsolationMode = "preSelect" | "option";
4
+
5
+ export type TenantError =
6
+ | "missing-header"
7
+ | "invalid-tenant"
8
+ | "missing-claim"
9
+ | "invalid-claim";
10
+
11
+ export interface TenantDecision {
12
+ tenantId?: string;
13
+ error?: TenantError;
14
+ }
15
+
16
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
17
+
18
+ /** Tenant ids are UUIDs everywhere: header, claim and the UserTenant table. */
19
+ export function isTenantId(value: unknown): value is string {
20
+ return typeof value === "string" && UUID_PATTERN.test(value);
21
+ }
22
+
23
+ /**
24
+ * Decide the tenant of a request.
25
+ *
26
+ * `preSelect` — the app build is bound to one tenant: the header is required and is the only
27
+ * source; a token claim is not used.
28
+ *
29
+ * `option` — the user logs in first and then selects a tenant. A token that carries the
30
+ * `tenantId` claim decides; a token without one is rejected. A request with no token is a
31
+ * guest, and the header identifies the tenant for public endpoints.
32
+ *
33
+ * `tokenData` is absent on the L0 pass because authentication has not run yet.
34
+ */
35
+ export function resolveTenantContext(
36
+ mode: TenantIsolationMode,
37
+ tokenData: Record<string, unknown> | undefined,
38
+ headerTenantId: string | undefined,
39
+ ): TenantDecision {
40
+ if (mode === "preSelect") {
41
+ if (!headerTenantId) return { error: "missing-header" };
42
+ if (!isTenantId(headerTenantId)) return { error: "invalid-tenant" };
43
+ return { tenantId: headerTenantId };
44
+ }
45
+
46
+ if (tokenData) {
47
+ const claimed = tokenData.tenantId;
48
+ if (claimed === undefined || claimed === "") return { error: "missing-claim" };
49
+ if (!isTenantId(claimed)) return { error: "invalid-claim" };
50
+ return { tenantId: claimed };
51
+ }
52
+
53
+ if (!headerTenantId) return {};
54
+ if (!isTenantId(headerTenantId)) return { error: "invalid-tenant" };
55
+ return { tenantId: headerTenantId };
56
+ }
@@ -35,12 +35,18 @@ export interface deleteAccountCounts {
35
35
  authProfiles: number;
36
36
  userRoles: number;
37
37
  sessions: number;
38
+ /** Tenant mappings removed (tenant isolation only). */
39
+ userTenants?: number;
38
40
  }
39
41
 
40
42
  /** Result of a self-service account deletion. */
41
43
  export interface deleteAccountResponse {
42
44
  userId: string;
43
- /** When the tombstone was written (the row's updatedAt). Empty on a repeat call. */
45
+ /** When the tombstone was written (the row's updatedAt). Empty on a repeat call or a tenant leave. */
44
46
  tombstonedAt: string;
45
47
  deleted: deleteAccountCounts;
48
+ /** Set when the account left one tenant instead of being tombstoned. */
49
+ tenantId?: string;
50
+ /** Rows removed from `auth.deleteAccount.deleteTables`, keyed by document name. */
51
+ related?: Record<string, number>;
46
52
  }
@@ -35,8 +35,8 @@ export interface VexRepository<T, U=undefined> {
35
35
  /**
36
36
  * Read a row that may be soft-deleted.
37
37
  *
38
- * Skips ONLY the adapter's soft-delete term — the ownership filter still applies, so this is
39
- * not a way around `dataIsolation`. Exists for internal state checks (account-deletion
38
+ * Skips ONLY the adapter's soft-delete term — the isolation terms still apply, so this is
39
+ * not a way around `isolation`. Exists for internal state checks (account-deletion
40
40
  * idempotency, the account-state guard); a `Filter`-level escape hatch would have been part of
41
41
  * every HTTP filter body, which is exactly what must not be possible.
42
42
  */
@@ -0,0 +1,33 @@
1
+ {
2
+ "type": "object",
3
+ "x-documentConfig": {
4
+ "documentName": "UserTenant",
5
+ "restApi": {
6
+ "methods": [],
7
+ "joinWhitelist": []
8
+ },
9
+ "uniqueIndex": [
10
+ ["userId", "tenantId"]
11
+ ]
12
+ },
13
+ "required": ["userId", "tenantId"],
14
+ "properties": {
15
+ "_id": {
16
+ "type": "string",
17
+ "x-format": "PrimaryUUID",
18
+ "index": true
19
+ },
20
+ "userId": {
21
+ "type": "string",
22
+ "x-format": "UUID",
23
+ "index": true,
24
+ "description": "Identity document id. Managed by TenantService."
25
+ },
26
+ "tenantId": {
27
+ "type": "string",
28
+ "x-format": "UUID",
29
+ "index": true,
30
+ "description": "Tenant id (UUID). Managed by TenantService."
31
+ }
32
+ }
33
+ }
@@ -66,17 +66,25 @@ move it into the passing variant matrix.
66
66
 
67
67
  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
68
 
69
- ## Data isolation (row-level ownership)
69
+ ## Isolation (ownership and tenancy)
70
70
 
71
- Declared per entity in `x-documentConfig → dataIsolation: { field: "ownerId" }`.
71
+ Declared per entity in `x-documentConfig → isolation: [{ field, source, onMissing }]`. The legacy
72
+ `dataIsolation: { field }` form is an ownership rule.
72
73
 
73
74
  Generation produces three pieces:
74
75
 
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).
76
+ 1. `DataIsolationRegistry.gen.ts` (`src/generators/middlewares/dataIsolationRegistry.generator.ts`) —
77
+ entity → rule list (`field`, `source`, `onMissing`)
78
+ 2. `UserContext.ts` — `AsyncLocalStorage` carrying the request scope (`tokenData`, `requestedTenantId`,
79
+ `tenantId`). `Authentication.middleware` writes the verified token; in tenant `option` mode the
80
+ generated controllers run `TenantScope.middleware` right after it, and the L0 pass in `server.ts`
81
+ captures the header first. `run` layers a patch onto the enclosing scope instead of replacing it.
82
+ 3. Both adapters resolve each rule from that scope and AND every term into the query. Tenant terms
83
+ fail closed (`onMissing: "deny"`); ownership terms keep their historical skip-when-unauthenticated
84
+ behaviour. Isolation fields are stripped from caller data and stamped on create.
85
+
86
+ Full guides: [`docs/features/dataIsolation.md`](../features/dataIsolation.md),
87
+ [`docs/features/tenantIsolation.md`](../features/tenantIsolation.md).
80
88
 
81
89
  ## Auto-written audit fields
82
90
 
@@ -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.