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