very-express 0.10.0 → 0.10.2
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.
- package/.tmp/gen/out/.vex/meta.json +108 -102
- package/.tmp/gen/vex.config.json +1 -1
- package/.tmp/genh/out/.vex/meta.json +71 -71
- package/.tmp/genh/vex.config.json +4 -1
- package/AGENTS.md +1 -0
- package/dist/index.js +138 -129
- package/dist/templates/_services/MongooseRepositoryAdapter.ts +26 -0
- package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +131 -4
- package/dist/templates/_services/VexDbConnector.ts +36 -1
- package/dist/templates/_types/vex/VexRepository.ts +7 -0
- package/docs/architecture/databaseTargets.md +25 -1
- package/docs/features/dataIsolation.md +2 -0
- package/docs/features/tenantIsolation.md +23 -1
- package/docs/releaseNote/v0-10-1.md +84 -0
- package/docs/releaseNote/v0-10-2.md +54 -0
- package/package.json +1 -1
|
@@ -194,6 +194,32 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
194
194
|
return doc.save();
|
|
195
195
|
}
|
|
196
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);
|
|
218
|
+
this.applyVexFields(enriched, "create");
|
|
219
|
+
const doc = new this.model(enriched);
|
|
220
|
+
return doc.save();
|
|
221
|
+
}
|
|
222
|
+
|
|
197
223
|
replace(id: string | undefined, data: Partial<T>): Promise<T | null> {
|
|
198
224
|
if(!id) {
|
|
199
225
|
utils.log.error("MongooseRepositoryAdapter.replace called without id — refuse replace document");
|
|
@@ -35,6 +35,18 @@ function resolveVexFieldValue(type: VexFieldEntry["type"], userId?: string): unk
|
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
+
/** Deep-merge two nested `where` fragments; a scalar leaf replaces whatever was there. */
|
|
39
|
+
function mergeTerms(target: Record<string, unknown>, source: Record<string, unknown>): void {
|
|
40
|
+
for (const [key, value] of Object.entries(source)) {
|
|
41
|
+
const existing = target[key];
|
|
42
|
+
if (existing && typeof existing === "object" && value && typeof value === "object") {
|
|
43
|
+
mergeTerms(existing as Record<string, unknown>, value as Record<string, unknown>);
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
target[key] = value;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
38
50
|
export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRepository<T> {
|
|
39
51
|
constructor(private repo: Repository<T>) {}
|
|
40
52
|
|
|
@@ -121,6 +133,93 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
121
133
|
return Object.keys(terms).length > 0 ? terms : null;
|
|
122
134
|
}
|
|
123
135
|
|
|
136
|
+
/**
|
|
137
|
+
* Tenant terms for one related entity, or null when it declares no tenant rule.
|
|
138
|
+
*
|
|
139
|
+
* Ownership rules (`user._id`) are not applied to a joined row: joining another user's
|
|
140
|
+
* profile is legitimate, joining another tenant's row is not.
|
|
141
|
+
*/
|
|
142
|
+
private getTenantJoinFilter(entityName: string): Record<string, unknown> | null {
|
|
143
|
+
const terms: Record<string, unknown> = {};
|
|
144
|
+
|
|
145
|
+
for (const rule of entityIsolation[entityName] ?? []) {
|
|
146
|
+
if (rule.source !== "user.tenantId") continue;
|
|
147
|
+
|
|
148
|
+
const value = UserContext.tenantId;
|
|
149
|
+
if (value === undefined) {
|
|
150
|
+
if (rule.onMissing === "deny") {
|
|
151
|
+
throw new VexResErr(403, undefined,
|
|
152
|
+
`${entityName} is isolated by ${rule.source} but the request carries no such value`);
|
|
153
|
+
}
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
terms[rule.field] = value;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return Object.keys(terms).length > 0 ? terms : null;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Nested `where` fragment scoping every joined row by its own entity's tenant rule.
|
|
165
|
+
*
|
|
166
|
+
* A nested term makes TypeORM constrain the join, so a row whose foreign key points at
|
|
167
|
+
* another tenant is not returned with the other tenant's columns.
|
|
168
|
+
*/
|
|
169
|
+
private getJoinIsolationFilter(join?: Join): Record<string, unknown> | null {
|
|
170
|
+
if (!join || join.length === 0) return null;
|
|
171
|
+
|
|
172
|
+
const out: Record<string, unknown> = {};
|
|
173
|
+
|
|
174
|
+
for (const path of join) {
|
|
175
|
+
const filter = this.joinPathFilter(path);
|
|
176
|
+
if (filter) mergeTerms(out, filter);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return Object.keys(out).length > 0 ? out : null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** One join path as `{ hop: { … { field: tenantId } } }`, or null when no hop is tenant-isolated. */
|
|
183
|
+
private joinPathFilter(path: string): Record<string, unknown> | null {
|
|
184
|
+
const hops: { segment: string; entityName: string }[] = [];
|
|
185
|
+
let metadata = this.repo.metadata;
|
|
186
|
+
|
|
187
|
+
for (const segment of path.split(".")) {
|
|
188
|
+
const relation = metadata.relations.find(r => r.propertyName === segment);
|
|
189
|
+
if (!relation) return null;
|
|
190
|
+
|
|
191
|
+
const target = relation.inverseEntityMetadata;
|
|
192
|
+
// `metadata.name` is the class name the generated registry is keyed by, and stays
|
|
193
|
+
// correct when the entity was declared through `EntitySchema` (string target).
|
|
194
|
+
hops.push({ segment, entityName: target.name });
|
|
195
|
+
metadata = target;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
let child: Record<string, unknown> | null = null;
|
|
199
|
+
|
|
200
|
+
for (let i = hops.length - 1; i >= 0; i--) {
|
|
201
|
+
const terms = this.getTenantJoinFilter(hops[i].entityName);
|
|
202
|
+
if (!terms && !child) continue;
|
|
203
|
+
child = { [hops[i].segment]: { ...(terms ?? {}), ...(child ?? {}) } };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return child;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** AND the join terms into the caller's where — every `$or` branch gets them. */
|
|
210
|
+
private withJoinIsolation(
|
|
211
|
+
where: Record<string, unknown> | Array<Record<string, unknown>>,
|
|
212
|
+
join?: Join,
|
|
213
|
+
): Record<string, unknown> | Array<Record<string, unknown>> {
|
|
214
|
+
const joinFilter = this.getJoinIsolationFilter(join);
|
|
215
|
+
if (!joinFilter) return where;
|
|
216
|
+
|
|
217
|
+
if (where instanceof Array) {
|
|
218
|
+
return where.map(branch => ({ ...branch, ...joinFilter }));
|
|
219
|
+
}
|
|
220
|
+
return { ...where, ...joinFilter };
|
|
221
|
+
}
|
|
222
|
+
|
|
124
223
|
/**
|
|
125
224
|
* Remove isolation fields from caller-supplied data. A client must never be able to
|
|
126
225
|
* move a row under another owner or into another tenant.
|
|
@@ -240,7 +339,7 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
240
339
|
}
|
|
241
340
|
|
|
242
341
|
find(filter: Filter<T>, join?: Join, select?: Select, pagination?: VexPagination): Promise<T[]> {
|
|
243
|
-
const where = this.mergeFilter(filter) as FindOptionsWhere<T>;
|
|
342
|
+
const where = this.withJoinIsolation(this.mergeFilter(filter), join) as FindOptionsWhere<T>;
|
|
244
343
|
const options: FindManyOptions<T> = {
|
|
245
344
|
select: select as any,
|
|
246
345
|
where,
|
|
@@ -263,7 +362,7 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
263
362
|
}
|
|
264
363
|
|
|
265
364
|
findOne(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null> {
|
|
266
|
-
const where = this.mergeFilter(filter) as FindOptionsWhere<T>;
|
|
365
|
+
const where = this.withJoinIsolation(this.mergeFilter(filter), join) as FindOptionsWhere<T>;
|
|
267
366
|
return this.repo.findOne({
|
|
268
367
|
select,
|
|
269
368
|
where,
|
|
@@ -272,7 +371,7 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
272
371
|
}
|
|
273
372
|
|
|
274
373
|
findOneWhere(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null> {
|
|
275
|
-
const where = this.mergeFilter(filter) as FindOptionsWhere<T>;
|
|
374
|
+
const where = this.withJoinIsolation(this.mergeFilter(filter), join) as FindOptionsWhere<T>;
|
|
276
375
|
return this.repo.findOne({
|
|
277
376
|
select,
|
|
278
377
|
where,
|
|
@@ -288,6 +387,31 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
288
387
|
return this.repo.save(this.repo.create(enriched as DeepPartial<T>));
|
|
289
388
|
}
|
|
290
389
|
|
|
390
|
+
/**
|
|
391
|
+
* Insert when the payload has no `_id`, update that row otherwise.
|
|
392
|
+
*
|
|
393
|
+
* The update path runs the same guards as `update`: the row must be visible under the
|
|
394
|
+
* caller's isolation, and isolation fields are stripped so it cannot be moved.
|
|
395
|
+
*/
|
|
396
|
+
async save(data: Partial<T>): Promise<T> {
|
|
397
|
+
const enriched = { ...data };
|
|
398
|
+
const id = (enriched as Record<string, unknown>)._id;
|
|
399
|
+
const hasId = id !== undefined && id !== null && id !== "";
|
|
400
|
+
|
|
401
|
+
this.stripIsolationFields(enriched);
|
|
402
|
+
|
|
403
|
+
if (hasId) {
|
|
404
|
+
this.applyVexFields(enriched, "update");
|
|
405
|
+
const existing = await this.findOne({ _id: id } as unknown as Filter<T>);
|
|
406
|
+
if (!existing) throw new VexResErr(404);
|
|
407
|
+
return this.repo.save(enriched as DeepPartial<T>);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
this.stampIsolationFields(enriched);
|
|
411
|
+
this.applyVexFields(enriched, "create");
|
|
412
|
+
return this.repo.save(this.repo.create(enriched as DeepPartial<T>));
|
|
413
|
+
}
|
|
414
|
+
|
|
291
415
|
async replace(id: string | undefined, data: Partial<T>): Promise<T | null> {
|
|
292
416
|
if (!id) {
|
|
293
417
|
utils.log.error("TypeOrmRepositoryAdapter.replace called without id — refuse replace entity");
|
|
@@ -366,7 +490,10 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
366
490
|
* filter still applies. Framework-internal — see VexRepository.
|
|
367
491
|
*/
|
|
368
492
|
findOneWithDeleted(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null> {
|
|
369
|
-
const where = this.
|
|
493
|
+
const where = this.withJoinIsolation(
|
|
494
|
+
this.mergeFilter(filter, { includeSoftDeleted: true }),
|
|
495
|
+
join,
|
|
496
|
+
) as FindOptionsWhere<T>;
|
|
370
497
|
return this.repo.findOne({
|
|
371
498
|
select,
|
|
372
499
|
where,
|
|
@@ -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
|
-
|
|
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 {
|
|
@@ -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>;
|
|
@@ -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)
|
|
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
|
|
@@ -82,6 +103,9 @@ Generation produces three pieces:
|
|
|
82
103
|
3. Both adapters resolve each rule from that scope and AND every term into the query. Tenant terms
|
|
83
104
|
fail closed (`onMissing: "deny"`); ownership terms keep their historical skip-when-unauthenticated
|
|
84
105
|
behaviour. Isolation fields are stripped from caller data and stamped on create.
|
|
106
|
+
4. The SQL adapter scopes a `join` by the joined entity's own tenant rule — one nested `where` term
|
|
107
|
+
per hop of the join path — so a row whose foreign key points at another tenant does not come back
|
|
108
|
+
with that row's columns. Ownership rules are not applied to joined rows.
|
|
85
109
|
|
|
86
110
|
Full guides: [`docs/features/dataIsolation.md`](../features/dataIsolation.md),
|
|
87
111
|
[`docs/features/tenantIsolation.md`](../features/tenantIsolation.md).
|
|
@@ -64,6 +64,8 @@ is equivalent to `{ "field": "ownerId", "source": "user._id", "onMissing": "skip
|
|
|
64
64
|
- **`skip`** — no value, no term. Used for ownership: public routes keep working.
|
|
65
65
|
- **`deny`** — no value, `403`. Used for tenancy: a document that declares a tenant rule is
|
|
66
66
|
unreachable without a tenant.
|
|
67
|
+
- **Joins** — the SQL adapter scopes a joined entity by that entity's own tenant rule, so a join
|
|
68
|
+
cannot return another tenant's row. Ownership rules are not applied to joined rows.
|
|
67
69
|
|
|
68
70
|
## Validation
|
|
69
71
|
|
|
@@ -7,7 +7,8 @@ UUID; the header (`x-tenant-id`) and the token claim (`tenantId`) are fixed.
|
|
|
7
7
|
```jsonc
|
|
8
8
|
"tenant": {
|
|
9
9
|
"enable": true,
|
|
10
|
-
"IsolationMode": "preSelect" // or "option"; defaults to "preSelect"
|
|
10
|
+
"IsolationMode": "preSelect", // or "option"; defaults to "preSelect"
|
|
11
|
+
"scope": ["/api"] // optional; omitted = every route
|
|
11
12
|
}
|
|
12
13
|
```
|
|
13
14
|
|
|
@@ -29,6 +30,14 @@ Documents opt in with an isolation rule:
|
|
|
29
30
|
The rule field is the document column; it does not have to be named `tenantId`. See
|
|
30
31
|
[`dataIsolation.md`](dataIsolation.md).
|
|
31
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
|
+
|
|
32
41
|
## Generated files
|
|
33
42
|
|
|
34
43
|
Emitted only when the feature is enabled; turning it off removes them on the next run
|
|
@@ -114,6 +123,19 @@ to call `addUserTenant` or `linkUserTenant`.
|
|
|
114
123
|
`UserTenant` mapping instead of tombstoning the shared account; `auth.deleteAccount.deleteTables`
|
|
115
124
|
runs in both modes. See [`accountDeletion.md`](accountDeletion.md).
|
|
116
125
|
|
|
126
|
+
## Joins
|
|
127
|
+
|
|
128
|
+
A `join` is scoped by the joined document's own tenant rule, not only by the root document's. The
|
|
129
|
+
SQL adapter adds the rule as a nested `where` term for every hop of the path: `join=["menuItem"]`
|
|
130
|
+
filters `menuItem`, and `join=["menuItem.category"]` filters both `menuItem` and `category`.
|
|
131
|
+
|
|
132
|
+
A row whose foreign key points at another tenant's row is not returned with that row's columns; the
|
|
133
|
+
read comes back empty. A joined document with no tenant rule joins unchanged. A missing tenant with
|
|
134
|
+
`onMissing: "deny"` answers `403`, the same as the root document.
|
|
135
|
+
|
|
136
|
+
Ownership rules (`user._id`) are not applied to joined rows — joining another user's profile is
|
|
137
|
+
legitimate. The Mongoose adapter does not implement joins, so this applies to the SQL target only.
|
|
138
|
+
|
|
117
139
|
## Limits
|
|
118
140
|
|
|
119
141
|
- The claim is a snapshot. A revoked mapping stays usable until the access token expires; `refresh`
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# v0.10.1
|
|
2
|
+
|
|
3
|
+
## Transaction entry owned by the DB layer
|
|
4
|
+
|
|
5
|
+
Business code can run several writes in one transaction without touching the TypeORM manager:
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
await vexDb.transaction(async (tx) => {
|
|
9
|
+
const orderRepo = tx.getRepository(OrderEntity);
|
|
10
|
+
await orderRepo.create({ ... });
|
|
11
|
+
});
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
- `tx` only exposes `getRepository`; the manager and the data source are not reachable.
|
|
15
|
+
- Returned repositories are the normal adapters, so isolation, audit stamping and fail-closed
|
|
16
|
+
checks behave exactly as they do outside a transaction.
|
|
17
|
+
- Throwing inside the callback rolls the whole transaction back.
|
|
18
|
+
- Nested calls throw `nested transaction is not supported` instead of silently opening a second
|
|
19
|
+
transaction.
|
|
20
|
+
- The mongo target throws `VexDb.transaction is only available for the SQL target`.
|
|
21
|
+
|
|
22
|
+
`vexDb.dataSource` is now private. `VexDbConnector` is the only place that reads it.
|
|
23
|
+
|
|
24
|
+
### `VexRepository.save`
|
|
25
|
+
|
|
26
|
+
`save` is the upsert-shaped write the transaction callback exposes:
|
|
27
|
+
|
|
28
|
+
| Payload | Behaviour |
|
|
29
|
+
| --- | --- |
|
|
30
|
+
| no `_id` | insert, with the normal create-phase audit fields and isolation stamping |
|
|
31
|
+
| with `_id` | update that row; a row outside the caller's isolation is a `404` |
|
|
32
|
+
|
|
33
|
+
Isolation fields are stripped before the write, so `save` cannot move a row to another tenant or
|
|
34
|
+
owner. Both adapters implement it.
|
|
35
|
+
|
|
36
|
+
## `tenant.scope`
|
|
37
|
+
|
|
38
|
+
The tenant middleware applies to every route by default. A deployment whose browser-facing paths
|
|
39
|
+
cannot send the tenant header narrows it:
|
|
40
|
+
|
|
41
|
+
```jsonc
|
|
42
|
+
"tenant": {
|
|
43
|
+
"enable": true,
|
|
44
|
+
"IsolationMode": "preSelect",
|
|
45
|
+
"scope": ["/api"]
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
- Prefix match on `req.path`, boundary-aware: `/api` matches `/api/...` but not `/apix`.
|
|
50
|
+
- Omitted → every route (the previous behaviour).
|
|
51
|
+
- An entry must start with `/`; an empty list is rejected at generation time.
|
|
52
|
+
- `/hello` stays exempt.
|
|
53
|
+
|
|
54
|
+
In `preSelect`, `scope` must cover the auth routes used by the client (normally `/api` or
|
|
55
|
+
`/api/auth`): login reads the tenant captured by the middleware.
|
|
56
|
+
|
|
57
|
+
Tenant existence is not checked by the middleware. It validates the UUID only; whether the tenant
|
|
58
|
+
exists, is disabled or was deleted is the application's lookup, whose normal answer is `404`.
|
|
59
|
+
|
|
60
|
+
## Generated output
|
|
61
|
+
|
|
62
|
+
| File | Change |
|
|
63
|
+
| --- | --- |
|
|
64
|
+
| `_services/VexDbConnector.gen.ts` | `transaction`, private `dataSource` |
|
|
65
|
+
| `_services/TypeOrmRepositoryAdapter.gen.ts` | `save`, transaction-scoped repository support |
|
|
66
|
+
| `_services/MongooseRepositoryAdapter.gen.ts` | `save` (transactions throw) |
|
|
67
|
+
| `_types/vex/VexRepository.gen.ts` | `save` |
|
|
68
|
+
| `_middlewares/TenantScope.gen.ts` | `scope` guard when `tenant.scope` is set |
|
|
69
|
+
|
|
70
|
+
## Migration
|
|
71
|
+
|
|
72
|
+
1. Re-run the generator.
|
|
73
|
+
2. Replace any `vexDb.dataSource.transaction(async (manager) => ...)` with
|
|
74
|
+
`vexDb.transaction(async (tx) => ...)`; `manager.getRepository(...)` becomes
|
|
75
|
+
`tx.getRepository(...)`.
|
|
76
|
+
3. `dataSource` is private, so direct reads no longer compile. This is intended: the transaction
|
|
77
|
+
handle is the supported boundary.
|
|
78
|
+
4. `tenant` config without `scope` keeps the previous routing behaviour.
|
|
79
|
+
|
|
80
|
+
## Tests
|
|
81
|
+
|
|
82
|
+
`npm test` covers the generated shapes and the unchanged default. `npm run test:e2e` runs a probe
|
|
83
|
+
inside a generated app against Postgres: tenant stamping inside a transaction, fail-closed `403`
|
|
84
|
+
without a tenant, rollback of every write on throw, and the nested-call rejection.
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# v0.10.2
|
|
2
|
+
|
|
3
|
+
## Joins are scoped by the joined document's tenant rule
|
|
4
|
+
|
|
5
|
+
A `join` used to filter the root document only. The joined rows came back unfiltered, so a row whose
|
|
6
|
+
foreign key pointed at another tenant's row returned that row's columns.
|
|
7
|
+
|
|
8
|
+
The SQL adapter now adds the tenant rule of every joined document as a nested `where` term:
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
repo.find({}, ["menuItem"]); // menuItem.tenantId = :tenantId
|
|
12
|
+
repo.find({}, ["menuItem.category"]); // menuItem.tenantId and category.tenantId
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
- Applies to `find`, `findOne`, `findOneWhere` and `findOneWithDeleted`.
|
|
16
|
+
- The path is resolved hop by hop against the entity metadata, matching the hop-by-hop check in
|
|
17
|
+
`JoinWhitelistMiddleware`.
|
|
18
|
+
- A row whose foreign key points at another tenant is not returned with that row's columns. A
|
|
19
|
+
`findOne` by id returns `null`.
|
|
20
|
+
- A joined document that declares no tenant rule joins as before.
|
|
21
|
+
- A missing tenant with `onMissing: "deny"` answers `403`, the same as the root document.
|
|
22
|
+
|
|
23
|
+
Ownership rules (`user._id`) are not applied to joined rows. Joining another user's profile stays
|
|
24
|
+
allowed; only tenancy crosses a tenant boundary.
|
|
25
|
+
|
|
26
|
+
`select`, `pagination`, `$or`, `$and` and the operator DSL are unchanged: the read still goes
|
|
27
|
+
through `repo.find`, the join terms are merged into the existing `where`.
|
|
28
|
+
|
|
29
|
+
## Mongo target
|
|
30
|
+
|
|
31
|
+
The Mongoose adapter does not implement joins, so this change is SQL-only.
|
|
32
|
+
|
|
33
|
+
## Generated output
|
|
34
|
+
|
|
35
|
+
| File | Change |
|
|
36
|
+
| --- | --- |
|
|
37
|
+
| `_services/TypeOrmRepositoryAdapter.gen.ts` | join isolation terms on the four read methods |
|
|
38
|
+
|
|
39
|
+
Every scenario's golden output changes: the adapter is a static template copied into every app. An
|
|
40
|
+
app with no `tenant.enable` and no isolation rule takes the same query path as before — the registry
|
|
41
|
+
lookup returns no rule, so the caller's `where` is passed through untouched.
|
|
42
|
+
|
|
43
|
+
## Migration
|
|
44
|
+
|
|
45
|
+
1. Re-run the generator.
|
|
46
|
+
2. No schema or config change. A request that joins a tenant-scoped document can now return fewer
|
|
47
|
+
rows when its data holds a foreign key across tenants.
|
|
48
|
+
|
|
49
|
+
## Tests
|
|
50
|
+
|
|
51
|
+
`npm test` covers the new adapter source and the regenerated goldens. The join scoping is checked
|
|
52
|
+
against a real PostgreSQL: same-tenant join, cross-tenant foreign key, nested path, missing tenant
|
|
53
|
+
under `deny`, and `$or` / pagination / `select` interaction. `npm run test:e2e` type-checks the
|
|
54
|
+
generated app for every config variant, including the tenant ones.
|