very-express 0.10.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.
- 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 +25 -0
- package/dist/templates/_services/VexDbConnector.ts +36 -1
- package/dist/templates/_types/vex/VexRepository.ts +7 -0
- package/docs/architecture/databaseTargets.md +22 -1
- package/docs/features/tenantIsolation.md +10 -1
- package/docs/releaseNote/v0-10-1.md +84 -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");
|
|
@@ -288,6 +288,31 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
288
288
|
return this.repo.save(this.repo.create(enriched as DeepPartial<T>));
|
|
289
289
|
}
|
|
290
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>);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
this.stampIsolationFields(enriched);
|
|
312
|
+
this.applyVexFields(enriched, "create");
|
|
313
|
+
return this.repo.save(this.repo.create(enriched as DeepPartial<T>));
|
|
314
|
+
}
|
|
315
|
+
|
|
291
316
|
async replace(id: string | undefined, data: Partial<T>): Promise<T | null> {
|
|
292
317
|
if (!id) {
|
|
293
318
|
utils.log.error("TypeOrmRepositoryAdapter.replace called without id — refuse replace entity");
|
|
@@ -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
|
|
@@ -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
|
|
@@ -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.
|