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
@@ -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,34 @@ 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);
192
+ this.applyVexFields(enriched, "create");
193
+ const doc = new this.model(enriched);
194
+ return doc.save();
195
+ }
196
+
197
+ /**
198
+ * Insert when the payload has no `_id`, update that document otherwise.
199
+ *
200
+ * The update path runs the same guards as `update`: the document must be visible under the
201
+ * caller's isolation, and isolation fields are stripped so it cannot be moved.
202
+ */
203
+ async save(data: Partial<T>): Promise<T> {
204
+ const enriched = { ...data };
205
+ const id = (enriched as Record<string, unknown>)._id;
206
+ const hasId = id !== undefined && id !== null && id !== "";
207
+
208
+ this.stripIsolationFields(enriched);
209
+
210
+ if (hasId) {
211
+ this.applyVexFields(enriched, "update");
212
+ const existing = await this.findOne({ _id: id } as Filter);
213
+ if (!existing) throw new VexResErr(404);
214
+ return this.model.findByIdAndUpdate(id, { $set: enriched }, { new: true }).exec() as Promise<T>;
215
+ }
216
+
217
+ this.stampIsolationFields(enriched);
134
218
  this.applyVexFields(enriched, "create");
135
219
  const doc = new this.model(enriched);
136
220
  return doc.save();
@@ -142,8 +226,10 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
142
226
  return Promise.resolve(null);
143
227
  }
144
228
  const enriched = { ...data };
229
+ this.stripIsolationFields(enriched);
145
230
  this.applyVexFields(enriched, "update");
146
- return this.model.findByIdAndUpdate(id, enriched, { new: true, overwrite: true }).exec();
231
+ const filter = this.mergeFilter({ _id: id } as Filter);
232
+ return this.model.findOneAndUpdate(filter as any, enriched, { new: true, overwrite: true }).exec();
147
233
  }
148
234
 
149
235
  update(id: string | undefined, data: Partial<T>): Promise<T | null> {
@@ -152,8 +238,10 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
152
238
  return Promise.resolve(null);
153
239
  }
154
240
  const enriched = { ...data };
241
+ this.stripIsolationFields(enriched);
155
242
  this.applyVexFields(enriched, "update");
156
- return this.model.findByIdAndUpdate(id, { $set: enriched }, { new: true }).exec();
243
+ const filter = this.mergeFilter({ _id: id } as Filter);
244
+ return this.model.findOneAndUpdate(filter as any, { $set: enriched }, { new: true }).exec();
157
245
  }
158
246
 
159
247
  async delete(id: string | undefined): Promise<void> {
@@ -161,7 +249,8 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
161
249
  utils.log.error("MongooseRepositoryAdapter.delete called without id — refuse delete document");
162
250
  return;
163
251
  }
164
- await this.model.findByIdAndDelete(id).exec();
252
+ const filter = this.mergeFilter({ _id: id } as Filter);
253
+ await this.model.findOneAndDelete(filter as any).exec();
165
254
  }
166
255
 
167
256
  async deleteWhere(filter: Record<string, unknown>): Promise<void> {
@@ -189,6 +278,7 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
189
278
  }
190
279
 
191
280
  const enriched: Record<string, unknown> = { ...((data ?? {}) as Record<string, unknown>) };
281
+ this.stripIsolationFields(enriched as Partial<T>);
192
282
  this.applyVexFields(enriched as Partial<T>, "update");
193
283
  enriched[field] = true;
194
284
 
@@ -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
+ }
93
94
 
94
- const config = entityIsolation[this.getEntityName()];
95
- if (!config) return null;
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
+ }
117
+
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,33 @@ 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
- }
285
+ this.stripIsolationFields(enriched);
286
+ this.stampIsolationFields(enriched);
287
+ this.applyVexFields(enriched, "create");
288
+ return this.repo.save(this.repo.create(enriched as DeepPartial<T>));
289
+ }
290
+
291
+ /**
292
+ * Insert when the payload has no `_id`, update that row otherwise.
293
+ *
294
+ * The update path runs the same guards as `update`: the row must be visible under the
295
+ * caller's isolation, and isolation fields are stripped so it cannot be moved.
296
+ */
297
+ async save(data: Partial<T>): Promise<T> {
298
+ const enriched = { ...data };
299
+ const id = (enriched as Record<string, unknown>)._id;
300
+ const hasId = id !== undefined && id !== null && id !== "";
301
+
302
+ this.stripIsolationFields(enriched);
303
+
304
+ if (hasId) {
305
+ this.applyVexFields(enriched, "update");
306
+ const existing = await this.findOne({ _id: id } as unknown as Filter<T>);
307
+ if (!existing) throw new VexResErr(404);
308
+ return this.repo.save(enriched as DeepPartial<T>);
238
309
  }
310
+
311
+ this.stampIsolationFields(enriched);
239
312
  this.applyVexFields(enriched, "create");
240
313
  return this.repo.save(this.repo.create(enriched as DeepPartial<T>));
241
314
  }
@@ -246,6 +319,7 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
246
319
  return null;
247
320
  }
248
321
  const enriched = { ...data };
322
+ this.stripIsolationFields(enriched);
249
323
  this.applyVexFields(enriched, "update");
250
324
  const existing = await this.findOne({ _id: id } as unknown as Filter<T>);
251
325
  if (!existing) return null;
@@ -258,6 +332,7 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
258
332
  return null;
259
333
  }
260
334
  const enriched = { ...data };
335
+ this.stripIsolationFields(enriched);
261
336
  this.applyVexFields(enriched, "update");
262
337
  const where = this.mergeFilter({ _id: id } as unknown as Filter<T>);
263
338
  await this.repo.update(where as FindOptionsWhere<T>, enriched);
@@ -1,18 +1,25 @@
1
1
  // {{headerComment}}
2
2
  import { Request, Response, NextFunction } from "express";
3
+ import { AsyncLocalStorage } from "async_hooks";
3
4
  import { DataSource, EntityTarget, ObjectLiteral } from "typeorm";
4
5
  import mongoose from "mongoose";
5
6
  import { VexRepository } from "../_types/vex";
6
7
  import { TypeOrmRepositoryAdapter } from "./TypeOrmRepositoryAdapter.gen";
7
8
  import utils from "./../_utils";
8
9
 
10
+ /** The only surface a transaction callback gets. It never exposes the TypeORM manager. */
11
+ export interface VexTransaction {
12
+ getRepository<T extends ObjectLiteral>(target: EntityTarget<T>): VexRepository<T>;
13
+ }
14
+
9
15
  export class VexDbConnector {
10
16
  private sqlUrl: string;
11
17
  private sqlCa: string;
12
18
  private mongoUrl: string;
13
19
  private recordAccessLog: boolean = false;
14
20
 
15
- public dataSource?: DataSource;
21
+ private dataSource?: DataSource;
22
+ private transactionScope = new AsyncLocalStorage<boolean>();
16
23
 
17
24
  constructor(options: {
18
25
  sqlUrl?: string;
@@ -25,6 +32,34 @@ export class VexDbConnector {
25
32
  this.mongoUrl = options.mongoUrl || "";
26
33
  this.recordAccessLog = options.recordAccessLog || false;
27
34
  this.middleware = this.middleware.bind(this);
35
+ this.transaction = this.transaction.bind(this);
36
+ }
37
+
38
+ /**
39
+ * Run `fn` in one database transaction. Throwing inside `fn` rolls everything back.
40
+ *
41
+ * Repositories come from the transaction's own manager, but the callback only receives
42
+ * `getRepository`: handing out the manager would let call sites take the raw repository and
43
+ * bypass isolation, audit stamping and fail-closed checks.
44
+ *
45
+ * Isolation reads `UserContext` from AsyncLocalStorage, so it applies inside the callback
46
+ * unchanged. Nested calls are rejected rather than silently opening a second transaction.
47
+ */
48
+ async transaction<T>(fn: (tx: VexTransaction) => Promise<T>): Promise<T> {
49
+ if (!this.sqlUrl) {
50
+ throw new Error("VexDb.transaction is only available for the SQL target");
51
+ }
52
+ if (!this.dataSource) {
53
+ throw new Error("SQL DataSource not initialized");
54
+ }
55
+ if (this.transactionScope.getStore()) {
56
+ throw new Error("nested transaction is not supported");
57
+ }
58
+
59
+ return this.dataSource.transaction((manager) => this.transactionScope.run(true, () => fn({
60
+ getRepository: <E extends ObjectLiteral>(target: EntityTarget<E>): VexRepository<E> =>
61
+ new TypeOrmRepositoryAdapter<E & ObjectLiteral>(manager.getRepository(target)),
62
+ })));
28
63
  }
29
64
 
30
65
  connect(): void {
@@ -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
  }
@@ -16,6 +16,13 @@ export interface VexRepository<T, U=undefined> {
16
16
  findOne(filter: Filter<T>, join?: Join, select?: Select): Promise<[U] extends [undefined] ? T | null : U | null>;
17
17
  findOneWhere(filter: Filter<T>, join?: Join, select?: Select): Promise<[U] extends [undefined] ? T | null : U | null>;
18
18
  create(data: Partial<T>): Promise<T>;
19
+ /**
20
+ * Insert when the payload has no id; update that row when it does.
21
+ *
22
+ * The update path is scoped like every other write: a row outside the caller's isolation is
23
+ * a 404, and isolation fields are stripped so the row cannot be moved.
24
+ */
25
+ save(data: Partial<T>): Promise<T>;
19
26
  replace(id: string | undefined, data: Partial<T>): Promise<T | null>;
20
27
  update(id: string | undefined, data: Partial<T>): Promise<T | null>;
21
28
  delete(id: string | undefined): Promise<void>;
@@ -35,8 +42,8 @@ export interface VexRepository<T, U=undefined> {
35
42
  /**
36
43
  * Read a row that may be soft-deleted.
37
44
  *
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
45
+ * Skips ONLY the adapter's soft-delete term — the isolation terms still apply, so this is
46
+ * not a way around `isolation`. Exists for internal state checks (account-deletion
40
47
  * idempotency, the account-state guard); a `Filter`-level escape hatch would have been part of
41
48
  * every HTTP filter body, which is exactly what must not be possible.
42
49
  */
@@ -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
+ }