very-express 0.7.9 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +116 -0
- package/CLAUDE.md +8 -160
- package/dist/index.js +501 -458
- package/dist/templates/_middlewares/DataIsolationContext.ts +10 -4
- package/dist/templates/_projectSettings/env +1 -0
- package/dist/templates/_services/MongooseRepositoryAdapter.ts +66 -3
- package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +72 -11
- package/dist/templates/_services/auth/JWTService.ts +32 -4
- package/dist/templates/_types/vex/VexRepository.ts +5 -4
- package/dist/templates/jsonSchema/User.json +17 -1
- package/docs/CONTRIBUTING.md +8 -3
- package/docs/architecture/authAndRouting.md +95 -0
- package/docs/architecture/databaseTargets.md +99 -0
- package/docs/architecture/generatorPipeline.md +198 -0
- package/docs/architecture/templates.md +66 -0
- package/docs/features/auditFields.md +240 -0
- package/docs/features/dataIsolation.md +19 -7
- package/docs/releaseNote/v0-8-0.md +95 -0
- package/docs/vexJsonSchema.md +40 -2
- package/package.json +8 -4
- package/vitest.config.ts +18 -0
- package/.github/copilot-instructions.md +0 -106
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
# Generator Pipeline
|
|
2
|
+
|
|
3
|
+
VeryExpress is a **code generator**. It reads JSON Schema files and writes a complete Express.js REST API into `output/`.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
jsonSchema/*.json → preprocess (validate/normalize) → generators → output/
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Two distinct things live in this repo — do not confuse them:
|
|
10
|
+
|
|
11
|
+
| | What it is | Where |
|
|
12
|
+
|---|---|---|
|
|
13
|
+
| **The generator** | This repo. TypeScript source in `src/`. | `src/`, built to `dist/` |
|
|
14
|
+
| **The generated app** | A standalone Express app with its own `package.json`. | `output/` |
|
|
15
|
+
|
|
16
|
+
Editing `src/` does nothing until `npm run compile` runs — `vex` executes `dist/index.js`.
|
|
17
|
+
|
|
18
|
+
## Source layout
|
|
19
|
+
|
|
20
|
+
| Path | Role |
|
|
21
|
+
|---|---|
|
|
22
|
+
| `src/cli.ts` | CLI entry (`vex`). Parses config, runs migrations, delegates to `generate()` |
|
|
23
|
+
| `src/index.ts` | Orchestrator — `generate()` runs the whole pipeline |
|
|
24
|
+
| `src/generators/` | Async `compile()` functions that write code files into `output/` |
|
|
25
|
+
| `src/templates/` | Static base files copied verbatim into the generated app |
|
|
26
|
+
| `src/preprocess/` | Schema validation, normalization, FK metadata wiring |
|
|
27
|
+
| `src/migrations/` | Version-bumped schema migrations, run before generation |
|
|
28
|
+
| `src/migration.ts` | Migration index — decides which migrations are pending |
|
|
29
|
+
| `src/types/types.ts` | Core interfaces: `compilerOptions`, `jsonSchema`, `jsonSchemaPropsItem`, `documentConfig` |
|
|
30
|
+
| `src/utils/` | File I/O, meta tracking, logging, JSON-schema helpers, template formatter, config defaults |
|
|
31
|
+
|
|
32
|
+
## Pipeline steps (`src/index.ts → generate()`)
|
|
33
|
+
|
|
34
|
+
1. Validate config (`utils.configChecker.checkConfigValid`) and create directories
|
|
35
|
+
2. Copy static templates into the system dir (`output/src/system/`) and sample schemas into `jsonSchemaDir`
|
|
36
|
+
3. Generate `userSchema`; run `formatJsonSchemaRoleDefinition` to sync RBAC role files
|
|
37
|
+
4. Read + format every `*.json` in `jsonSchemaDir`; non-JSON files warned and skipped. A failing schema logs an error and is dropped, generation continues
|
|
38
|
+
5. `applyFkMetadata(documents)` — wire reverse relations across all schemas at once
|
|
39
|
+
6. Generate roles + permissions
|
|
40
|
+
7. Per document (in parallel): TypeScript interface, DB model, controller
|
|
41
|
+
8. Generate join-whitelist registry and data-isolation registry (static maps in `_middlewares/`)
|
|
42
|
+
9. Generate routes, server entrypoint, project settings
|
|
43
|
+
10. `saveVexMeta()` then `cleanupStaleFiles()`
|
|
44
|
+
|
|
45
|
+
## Generated directory map
|
|
46
|
+
|
|
47
|
+
All under `vex.config.json → sysDir` (default `output/src/system`):
|
|
48
|
+
|
|
49
|
+
`_controllers/` `_middlewares/` `_models/` `_roles/` `_routes/` `_services/` `_types/` `_utils/`
|
|
50
|
+
|
|
51
|
+
Plus `src/roles/` (user-editable role sources) and the output root files.
|
|
52
|
+
|
|
53
|
+
## Generator contract
|
|
54
|
+
|
|
55
|
+
Every generator exports an async `compile(options)` that:
|
|
56
|
+
|
|
57
|
+
1. Validates / extracts data from `options`
|
|
58
|
+
2. Calls a `*Template()` function that returns a string
|
|
59
|
+
3. Writes via `utils.common.writeFile()`
|
|
60
|
+
|
|
61
|
+
`writeFile()` compares normalized content (header comments stripped) and **skips the write when unchanged**. It also records the file in the run's written-files set.
|
|
62
|
+
|
|
63
|
+
## `cleanupStaleFiles()` — sysDir is reconciled every run
|
|
64
|
+
|
|
65
|
+
After generation, every file under `sysDir` **not written during the current run is deleted**. Consequences:
|
|
66
|
+
|
|
67
|
+
- Never hand-place a file under `sysDir` — it disappears on the next `vex` run.
|
|
68
|
+
- Renaming a generator output removes the old file automatically; no manual cleanup needed.
|
|
69
|
+
|
|
70
|
+
## Meta tracking (`.vex/meta.json`)
|
|
71
|
+
|
|
72
|
+
Written to `<rootDir>/.vex/meta.json` (gitignored). Holds:
|
|
73
|
+
|
|
74
|
+
- `lastGeneratedVersion` — the package version that last completed a full generation
|
|
75
|
+
- `files[<relPath>].allowOverwrite` — per-file override, **default `true`**
|
|
76
|
+
|
|
77
|
+
When `allowOverwrite` is `false` for a file, `writeFile()` skips it if it already exists — the escape hatch for keeping hand-edits in a generated file. The value is read per-file on each run and rewritten immediately after a write, so edits between runs take effect.
|
|
78
|
+
|
|
79
|
+
## Migrations
|
|
80
|
+
|
|
81
|
+
`src/migration.ts` exports `runMigrations()`, called by `src/cli.ts` **before** generation. It reads `lastGeneratedVersion` from `.vex/meta.json` and runs every migration whose version is newer.
|
|
82
|
+
|
|
83
|
+
Each migration is `src/migrations/<version>.ts` exporting:
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
export function run(jsonSchemaDir: string): void
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
To add one: create the file, then add an entry to the `migrations` array in `src/migration.ts` with `version`, an explicit semver-sortable `order` tuple `[major, minor, patch, preIndex]`, and `run`. Version comparison is numeric-tuple — pre-release sorts below release.
|
|
90
|
+
|
|
91
|
+
Fresh project (no `meta.json`) → all migrations run.
|
|
92
|
+
|
|
93
|
+
## JSON Schema extensions
|
|
94
|
+
|
|
95
|
+
Custom `x-*` properties drive generation. Full reference: [`docs/vexJsonSchema.md`](../vexJsonSchema.md).
|
|
96
|
+
|
|
97
|
+
| Property | Purpose |
|
|
98
|
+
|---|---|
|
|
99
|
+
| `x-documentConfig` | `documentName` (must match filename), `restApi.methods`, `restApi.joinWhitelist`, `restApi.noRelations`, `restApi.dataIsolation`, `uniqueIndex`, `keyPrefix` |
|
|
100
|
+
| `x-foreignKey` | Relations. Only `one-to-one` / `many-to-one` declared on the owning side; `one-to-many` is auto-derived |
|
|
101
|
+
| `x-vexData: "role"` | Marks the field used for RBAC |
|
|
102
|
+
| `x-format: "ObjectId"` | MongoDB ObjectId; converted to `"Primary"` for the SQL target |
|
|
103
|
+
|
|
104
|
+
## Preprocessors (`src/preprocess/`)
|
|
105
|
+
|
|
106
|
+
| File | Role |
|
|
107
|
+
|---|---|
|
|
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
|
+
| `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
|
+
| `roleDefinitions.ts` | Ensure per-role JSON files exist with default CRUD permissions for each resource document |
|
|
111
|
+
|
|
112
|
+
## Interface generation
|
|
113
|
+
|
|
114
|
+
Uses `json-schema-to-typescript` to emit a TypeScript interface per schema, then injects FK relation types — `{DocName}Relations`, `{DocName}ApiRelations`, `{DocName}WithRelations`, `{DocName}WithApiRelations` — and generates enums for fields with `enum` arrays. `interface.fkProps` on each schema holds reverse-relation metadata populated during preprocessing.
|
|
115
|
+
|
|
116
|
+
## Project settings generation
|
|
117
|
+
|
|
118
|
+
`src/generators/projectSettings/` produces non-code files **for the generated app**: `package.json`, `.env`, `tsoa.json`, build scripts, `userSchema`. Not for this repo.
|
|
119
|
+
|
|
120
|
+
## CLI config normalization (`src/cli.ts`)
|
|
121
|
+
|
|
122
|
+
The CLI rewrites `vex.config.json` on every run, filling in defaults before
|
|
123
|
+
`generate()` sees the config. Use `??` for boolean defaults — `||` silently swallows
|
|
124
|
+
an explicit `false`.
|
|
125
|
+
|
|
126
|
+
| Setting | Behaviour |
|
|
127
|
+
|---|---|
|
|
128
|
+
| `app.enableSwagger` | `?? true` — omitting the key enables swagger; an explicit `false` disables it (`routeGen` skips `SwaggerRouter.gen.ts` and `serverGen` omits its wiring) |
|
|
129
|
+
| `useRBAC` | Opt-in. If the key is absent, or `roles` is empty, `useRBAC` is normalised to `undefined` and generation runs without RBAC |
|
|
130
|
+
|
|
131
|
+
## RBAC is opt-in
|
|
132
|
+
|
|
133
|
+
`utils.generator.isRbacEnabled(compilerOptions)` is the **single gate** for every RBAC
|
|
134
|
+
code path:
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
// src/utils/generator.ts
|
|
138
|
+
export function isRbacEnabled(compilerOptions: types.compilerOptions): boolean {
|
|
139
|
+
const roles = compilerOptions.useRBAC?.roles;
|
|
140
|
+
return Array.isArray(roles) && roles.length > 0;
|
|
141
|
+
}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
RBAC is on only when `useRBAC` is present **and** declares at least one role. An absent
|
|
145
|
+
`useRBAC`, or `roles: []`, means "RBAC off" — not "RBAC with zero roles".
|
|
146
|
+
|
|
147
|
+
Gated by it: the `jsonSchemaRBAC` template copy (`src/index.ts`), the `_roles/` static
|
|
148
|
+
templates, `role.generator`, `roleDefinitions`, `formatJsonSchemaRoleDefinition`, the
|
|
149
|
+
controller `@Middlewares(RoleBaseAccessControl…)` decorator, the route-level RBAC
|
|
150
|
+
middleware, the `AuthController`'s `userRoleRepo` and role lookups, and the `User`
|
|
151
|
+
schema's role enum.
|
|
152
|
+
|
|
153
|
+
With RBAC off the generated app contains no `RoleBaseAccessControl.gen.ts`, no
|
|
154
|
+
`_roles/`, no `UserRole` model/controller/types, and no `src/roles/*.json`.
|
|
155
|
+
|
|
156
|
+
### Switching an existing project to RBAC off
|
|
157
|
+
|
|
158
|
+
`cleanupStaleFiles()` deletes the RBAC artifacts under `sysDir` on the next run —
|
|
159
|
+
verified: `RoleBaseAccessControl.gen.ts`, `_roles/_RoleFactory.gen.ts`,
|
|
160
|
+
`_roles/index.ts` and one `_roles/<role>.gen.ts` per role.
|
|
161
|
+
|
|
162
|
+
Two things are deliberately **not** removed:
|
|
163
|
+
|
|
164
|
+
- `src/roles/*.json` — user-editable role permission sources; they live under
|
|
165
|
+
`srcDir`, not `sysDir`, so cleanup does not touch them.
|
|
166
|
+
- A leftover `UserRole.json` in *your* schema directory. The generator only copies
|
|
167
|
+
schemas in, never deletes them, so it keeps producing `UserRole.gen.ts` and
|
|
168
|
+
`UserRoleModel.gen.ts`. Delete the file yourself if you want them gone. It is
|
|
169
|
+
harmless: with RBAC off `formatJsonSchemaRoleDefinition` no longer rewrites its
|
|
170
|
+
enum, so a stale `enum` value cannot break generation.
|
|
171
|
+
|
|
172
|
+
### Why the empty-role case used to abort generation
|
|
173
|
+
|
|
174
|
+
`UserRole.json` is copied from `src/templates/jsonSchemaRBAC/` only when RBAC is on, and
|
|
175
|
+
`formatJsonSchemaRoleDefinition` then rewrites its `role` field's enum from
|
|
176
|
+
`useRBAC.roles`. With an empty list the enum became `[]`, which
|
|
177
|
+
`json-schema-to-typescript` renders as the invalid type `role: ()`:
|
|
178
|
+
|
|
179
|
+
```
|
|
180
|
+
SyntaxError: '=>' expected. (5:1)
|
|
181
|
+
3 | userId: string
|
|
182
|
+
4 | role: ()
|
|
183
|
+
> 5 | }
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
The CLI made this reachable for everyone: it injected `useRBAC = { roles: [], default: "" }`
|
|
187
|
+
when the key was absent, so a `vex.config.json` that simply omitted `useRBAC` crashed.
|
|
188
|
+
Fixed by normalising empty role lists to `undefined` and gating every RBAC path on
|
|
189
|
+
`isRbacEnabled`.
|
|
190
|
+
|
|
191
|
+
## Conventions
|
|
192
|
+
|
|
193
|
+
- Generated files: `{DocName}{Type}.gen.ts` — never hand-edit
|
|
194
|
+
- Controller class: PascalCase (`UserController`)
|
|
195
|
+
- `@Route()` path: `documentName.toLowerCase()` (`UserController` → `/user`)
|
|
196
|
+
- `@Tags()`: the raw `documentName`
|
|
197
|
+
- REST endpoint casing in `x-documentConfig.restApi` follows the lowercase route
|
|
198
|
+
- `required` fields: source schemas use the root-level array form; per-prop `required: true` is normalized into it
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# Template System
|
|
2
|
+
|
|
3
|
+
Two kinds of templates. Know which one you are editing — the failure modes differ.
|
|
4
|
+
|
|
5
|
+
## 1. Static templates (`src/templates/`)
|
|
6
|
+
|
|
7
|
+
Base files copied verbatim into the generated app. Copied to `dist/templates/` at build time by `scripts/copyTsTemplates.js`; the runtime reads them from `__dirname/templates`.
|
|
8
|
+
|
|
9
|
+
Copied groups (from `src/index.ts`):
|
|
10
|
+
|
|
11
|
+
| Template dir | Destination |
|
|
12
|
+
|---|---|
|
|
13
|
+
| `_controllers/` `_middlewares/` `_roles/` `_routes/` `_services/` `_types/` `_utils/` | `sysDir/<same name>` |
|
|
14
|
+
| `root/` | `rootDir` |
|
|
15
|
+
| `jsonSchema/` | `jsonSchemaDir` |
|
|
16
|
+
| `jsonSchemaRBAC/` | `jsonSchemaDir` (only when `useRBAC` is set) |
|
|
17
|
+
|
|
18
|
+
Files get a `.ts` → `.gen.ts` rename on copy, except `index.ts`.
|
|
19
|
+
|
|
20
|
+
**Hand-editing a `.gen.ts` file in `output/` does not survive.** Copies go through the same `writeFile()` as generated code:
|
|
21
|
+
|
|
22
|
+
- content identical after normalization (header comments stripped) → skipped, edit survives
|
|
23
|
+
- content differs → overwritten on the next `vex` run
|
|
24
|
+
- `.vex/meta.json` has `files[<relPath>].allowOverwrite: false` → skipped even when different
|
|
25
|
+
|
|
26
|
+
`allowOverwrite` defaults to `true`. It is per-file and read fresh each run, so flipping it between runs works — but `.vex/meta.json` is gitignored, so the flag resets on a fresh clone.
|
|
27
|
+
|
|
28
|
+
## 2. Template functions (`*.template.ts`)
|
|
29
|
+
|
|
30
|
+
Live beside their generator. Return a string built with placeholders.
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
content.replace(/{{placeholder}}/g, value)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
| Syntax | Meaning |
|
|
37
|
+
|---|---|
|
|
38
|
+
| `{{placeholder}}` | Simple textual substitution |
|
|
39
|
+
| `FUNC{{ <code> }}` | Embeds **runnable JS** into the generated file |
|
|
40
|
+
|
|
41
|
+
### `FUNC{{ }}`
|
|
42
|
+
|
|
43
|
+
The formatter `src/utils/template.ts → format()` strips the wrapping `'FUNC{{...}}'`
|
|
44
|
+
quotes so the inner code is emitted as runnable JavaScript instead of a string
|
|
45
|
+
literal. It replaces every block in one pass, including multi-line bodies.
|
|
46
|
+
|
|
47
|
+
Use it when a function (validator, callback, hook) must exist inside generated output.
|
|
48
|
+
The generated file must itself be JS/TS.
|
|
49
|
+
|
|
50
|
+
**Status: currently unused by any template.** `format()` is applied to three
|
|
51
|
+
outputs — `dataIsolationRegistry.generator.ts`, `joinWhitelistRegistry.generator.ts`
|
|
52
|
+
and `controller.template.ts` — but no template in `src/` contains a `FUNC{{ }}`
|
|
53
|
+
block, so the call is a no-op today. The mechanism is wired up and unit-tested; if
|
|
54
|
+
you add the first real block, the golden tests will show the change in output.
|
|
55
|
+
|
|
56
|
+
See [`test/unit/template.test.ts`](../../test/unit/template.test.ts) for the exact
|
|
57
|
+
supported syntax.
|
|
58
|
+
|
|
59
|
+
## Which to use
|
|
60
|
+
|
|
61
|
+
| Need | Use |
|
|
62
|
+
|---|---|
|
|
63
|
+
| Whole file that is mostly fixed boilerplate | static template in `src/templates/` |
|
|
64
|
+
| File whose body varies per document/schema | generator + `*.template.ts` |
|
|
65
|
+
| Small snippet of fixed boilerplate inside a varied file | inline string in the template function |
|
|
66
|
+
| Executable function inside generated output | `FUNC{{ }}` |
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
# Audit / Ownership Fields (auto-written on the write paths)
|
|
2
|
+
|
|
3
|
+
Status: **implemented** in v0.8.0. Supersedes the unmerged prototype commit `b21be2e`
|
|
4
|
+
(branch `fix/data-isolation-dynamic-field`), which was **not** merged into `main` and must not be merged as-is.
|
|
5
|
+
|
|
6
|
+
## Problem
|
|
7
|
+
|
|
8
|
+
Generated apps declare `createdBy` / `createdAt` / `updatedBy` / `updatedAt` in their JSON Schemas,
|
|
9
|
+
but nothing ever writes them — `grep -rn "createdBy\|updatedBy" src/` in the generator is empty.
|
|
10
|
+
The columns exist in the entities and stay NULL forever.
|
|
11
|
+
|
|
12
|
+
Consequences seen in the wild (RenoMaster):
|
|
13
|
+
|
|
14
|
+
- A custom controller checking `findOne({ _id, createdBy: request.user._id })` never matches → `404` on `DELETE /api/job/{id}`.
|
|
15
|
+
- Timeline ordering bugs, because `createdAt` is also never written.
|
|
16
|
+
|
|
17
|
+
## Goal
|
|
18
|
+
|
|
19
|
+
The DB layer maintains these fields **by itself** on the write paths, for every downstream app,
|
|
20
|
+
without per-app hand-written code. Declaration is schema-driven and reads like a SQL column definition.
|
|
21
|
+
|
|
22
|
+
## 1. Declaring auto-written fields — the `default` keyword family
|
|
23
|
+
|
|
24
|
+
Auto-written fields are declared with the JSON Schema native `default` keyword, using one of six reserved
|
|
25
|
+
keyword values. This mirrors SQL: *what the column is* is `x-format` / `type`, *what fills it* is `default`.
|
|
26
|
+
|
|
27
|
+
| `default` keyword | field declaration | PostgreSQL column | TS type | written on |
|
|
28
|
+
| --- | --- | --- | --- | --- |
|
|
29
|
+
| `onCreateTimestamp` | `{ "type": "string", "x-format": "Timestamp" }` | `timestamptz` | `string` (ISO-8601) | create only |
|
|
30
|
+
| `onCreateUnixTimestamp` | `{ "type": "integer", "x-format": "UnixTimestamp" }` | `bigint` | `number` | create only |
|
|
31
|
+
| `onUpdateTimestamp` | `{ "type": "string", "x-format": "Timestamp" }` | `timestamptz` | `string` (ISO-8601) | update / replace only |
|
|
32
|
+
| `onUpdateUnixTimestamp` | `{ "type": "integer", "x-format": "UnixTimestamp" }` | `bigint` | `number` | update / replace only |
|
|
33
|
+
| `onCreateUserId` | `{ "type": "string", "x-format": "UUID" }` | `uuid` | `string` | create only |
|
|
34
|
+
| `onUpdateUserId` | `{ "type": "string", "x-format": "UUID" }` | `uuid` | `string` | update / replace only |
|
|
35
|
+
|
|
36
|
+
Naming rule: `Timestamp` = datetime, `UnixTimestamp` = integer epoch **seconds**. Never mix the two for one field.
|
|
37
|
+
|
|
38
|
+
### Example (`Job.json`)
|
|
39
|
+
|
|
40
|
+
```jsonc
|
|
41
|
+
"active": {
|
|
42
|
+
"type": "boolean",
|
|
43
|
+
"default": true, // a literal default — untouched, still behaves as before
|
|
44
|
+
"required": true
|
|
45
|
+
},
|
|
46
|
+
"createdAt": { "type": "string", "x-format": "Timestamp", "default": "onCreateTimestamp" },
|
|
47
|
+
"createdBy": { "type": "string", "x-format": "UUID", "default": "onCreateUserId" },
|
|
48
|
+
"updatedAt": { "type": "string", "x-format": "Timestamp", "default": "onUpdateTimestamp" },
|
|
49
|
+
"updatedBy": { "type": "string", "x-format": "UUID", "default": "onUpdateUserId" }
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
A **literal** `default` (string / number / boolean / array / object that is not one of the six keywords)
|
|
53
|
+
keeps its current meaning and is not affected by this feature.
|
|
54
|
+
|
|
55
|
+
### New `x-format` value
|
|
56
|
+
|
|
57
|
+
`xFormatType` gains `Timestamp = "Timestamp"`, mapping to `timestamptz` in `X_FORMAT_DB_TYPE`.
|
|
58
|
+
`resolveDbType` already prefers `x-format` over the JSON Schema `format` hint, so `x-format` wins when both are present.
|
|
59
|
+
|
|
60
|
+
The driver returns a `Date` for `timestamptz`. Generated entities carry a transformer that writes the ISO
|
|
61
|
+
string through and converts it back on read, so the API, the generated interface and the entity all keep
|
|
62
|
+
the `string` contract — no `Date` leaks into responses, and the OpenAPI/DTO types stay truthful.
|
|
63
|
+
|
|
64
|
+
## 2. Where the user id comes from — `x-vexData: "userId"`
|
|
65
|
+
|
|
66
|
+
Exactly one field in the whole schema set is tagged as the identity source:
|
|
67
|
+
|
|
68
|
+
```jsonc
|
|
69
|
+
// User.json
|
|
70
|
+
"_id": {
|
|
71
|
+
"type": "string",
|
|
72
|
+
"x-format": "PrimaryUUID",
|
|
73
|
+
"x-vexData": "userId",
|
|
74
|
+
"index": true
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Semantics: *this column holds the identity value that audit fields store*. It is the equivalent of the
|
|
79
|
+
existing `x-vexData: "role"` marker, and the **only** precedent-style way a schema declares which column
|
|
80
|
+
carries identity.
|
|
81
|
+
|
|
82
|
+
Rules:
|
|
83
|
+
|
|
84
|
+
- The tag is required whenever any `onXXUserId` keyword is used — even when `app.useUserSchema` is false.
|
|
85
|
+
- The tag appears exactly once across all schemas. More than one is an error (ambiguous identity source).
|
|
86
|
+
- The tagged field should be indexed (`"index": true`) — it is used as a lookup key by the refresh flow.
|
|
87
|
+
|
|
88
|
+
## 3. Token claims
|
|
89
|
+
|
|
90
|
+
The generated JWT payload carries the identity explicitly, so no consumer needs to know the schema shape:
|
|
91
|
+
|
|
92
|
+
| token | payload |
|
|
93
|
+
| --- | --- |
|
|
94
|
+
| access | user profile fields + `vexUserId` + `vexRole` |
|
|
95
|
+
| refresh | `{ vexUserId }` (with `?? _id` fallback for tokens issued before the upgrade) |
|
|
96
|
+
|
|
97
|
+
- `vexUserId` = value of the `x-vexData: "userId"` tagged field.
|
|
98
|
+
- `vexRole` = `rolesOf(user)` — a snapshot at signing time. It is intentionally **absent from the refresh
|
|
99
|
+
token**: refresh tokens are long-lived, roles may change, and `POST /auth/refresh` re-reads the user
|
|
100
|
+
anyway. Only the access token (short-lived) carries roles.
|
|
101
|
+
- The API `profile` object returned to clients stays as it is — `vexUserId` / `vexRole` belong to the token
|
|
102
|
+
payload, not to the profile. `JWTService.sanitizeUser()` therefore splits into a profile builder and a
|
|
103
|
+
token-payload builder.
|
|
104
|
+
- `POST /auth/refresh` resolves the user by the tagged field (`{ [taggedField]: payload.vexUserId }`)
|
|
105
|
+
instead of a hardcoded `{ _id: payload._id }`, with `payload.vexUserId ?? payload._id` for old tokens.
|
|
106
|
+
|
|
107
|
+
## 4. Runtime behaviour (write paths)
|
|
108
|
+
|
|
109
|
+
A generated registry (`VexFieldRegistry.gen.ts`, entity → `[{ field, type }]`) is read by the repository
|
|
110
|
+
adapters. Both adapters apply the same two-step rule:
|
|
111
|
+
|
|
112
|
+
1. **Strip** — every declared auto field is removed from caller-supplied data. A client can never forge
|
|
113
|
+
`createdBy` / `updatedAt`; the context is always authoritative.
|
|
114
|
+
2. **Inject** — only the values valid for the current phase:
|
|
115
|
+
|
|
116
|
+
| phase | inject | strip-only (no inject) |
|
|
117
|
+
| --- | --- | --- |
|
|
118
|
+
| create | `onCreate*` | `onUpdate*` |
|
|
119
|
+
| update / replace | `onUpdate*` | `onCreate*` |
|
|
120
|
+
|
|
121
|
+
Stripping-without-injecting on the opposite phase is what keeps `createdBy` / `createdAt` immutable:
|
|
122
|
+
a PATCH never overwrites them.
|
|
123
|
+
|
|
124
|
+
Values written:
|
|
125
|
+
|
|
126
|
+
| keyword kind | value |
|
|
127
|
+
| --- | --- |
|
|
128
|
+
| `onXXTimestamp` | `new Date().toISOString()` — an ISO-8601 string the `timestamptz` column accepts directly |
|
|
129
|
+
| `onXXUnixTimestamp` | `Math.floor(Date.now() / 1000)` — epoch seconds |
|
|
130
|
+
| `onXXUserId` | the request context identity (`vexUserId`); **skipped** when there is none |
|
|
131
|
+
|
|
132
|
+
The registry generator is the only place that knows the mapping: adapters import
|
|
133
|
+
`entityVexFields` at runtime rather than re-deriving it from the schema.
|
|
134
|
+
|
|
135
|
+
### Request body type — `Create{Doc}`
|
|
136
|
+
|
|
137
|
+
Server-owned fields must not appear in the API *input*. The interface generator therefore emits, into
|
|
138
|
+
`src/system/_types/{Doc}.gen.ts`:
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
export type CreateJob = Omit<Job, "createdAt" | "createdBy" | "updatedAt" | "updatedBy" | "_id">;
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
and the controllers accept `Create{Doc}` (create, put) / `Partial<Create{Doc}>` (patch). The omission is
|
|
145
|
+
**declaration-based, never name-based**: a field is dropped when it carries a reserved `default` keyword,
|
|
146
|
+
or when it is the primary key (`x-format: Primary` / `PrimaryUUID`) and `app.allowApiCreateUpdate_id` is
|
|
147
|
+
false. A column literally named `createdAt` without a keyword stays client-writable — the declaration is
|
|
148
|
+
the contract.
|
|
149
|
+
|
|
150
|
+
Two consequences:
|
|
151
|
+
|
|
152
|
+
- The OpenAPI request schema stops advertising fields the server strips or overwrites; the response schema
|
|
153
|
+
keeps them, because clients still read them.
|
|
154
|
+
- The generated tsoa config is `noImplicitAdditionalProperties: "throw-on-extras"`, so a request that
|
|
155
|
+
**still sends** one of those fields is rejected with `400 Invalid Request Body` instead of having the
|
|
156
|
+
value quietly dropped. Clients that echo a whole row back on PATCH must strip these fields first.
|
|
157
|
+
|
|
158
|
+
The adapter's strip step stays as defence in depth: it also covers non-HTTP callers (internal services,
|
|
159
|
+
seed scripts) that bypass tsoa validation entirely.
|
|
160
|
+
|
|
161
|
+
`delete()` is **not** covered. There is no soft delete in the framework
|
|
162
|
+
(`grep -rn "softDelete\|active: false" src/` is empty) — `delete()` issues a real `DELETE`, so there is no
|
|
163
|
+
row left to audit. Soft delete is out of scope for this feature.
|
|
164
|
+
|
|
165
|
+
### App-layer only — no SQL `DEFAULT`
|
|
166
|
+
|
|
167
|
+
All six keywords are injected by the adapter; **no SQL `DEFAULT` / `ON UPDATE` expression is generated**.
|
|
168
|
+
|
|
169
|
+
Reasons:
|
|
170
|
+
|
|
171
|
+
- PostgreSQL has no `ON UPDATE CURRENT_TIMESTAMP` (MySQL only), so SQL-level `onUpdate` cannot be
|
|
172
|
+
expressed portably.
|
|
173
|
+
- Emitting a SQL default *and* injecting in the adapter gives one field two sources of truth, which
|
|
174
|
+
diverges for direct SQL writes and makes incidents harder to reason about.
|
|
175
|
+
|
|
176
|
+
All auto fields are generated `nullable: true`: `onUpdate*` is NULL until the first update, and
|
|
177
|
+
`onCreate*` must not break pre-existing rows.
|
|
178
|
+
|
|
179
|
+
Adapter is still the only writer, but `create()` is not the only entrance to a table. Anyone writing via
|
|
180
|
+
raw SQL bypasses the audit fields — same as any ORM-level convention. Documented, accepted.
|
|
181
|
+
|
|
182
|
+
## 5. No authenticated context
|
|
183
|
+
|
|
184
|
+
Public / anonymous / internal calls have no ALS store (`DataIsolationContext` does not run one when
|
|
185
|
+
`req.user` is absent):
|
|
186
|
+
|
|
187
|
+
- Timestamp keywords are context-free → **still injected**.
|
|
188
|
+
- `onXXUserId` keywords → **skipped**, field left unset (NULL column). Never `"undefined"`, never a throw.
|
|
189
|
+
- Nothing in the write path raises because the context is missing.
|
|
190
|
+
|
|
191
|
+
## 6. Validation (`formatJsonSchema` / checkSchema stage — fail at generation, not at runtime)
|
|
192
|
+
|
|
193
|
+
| # | rule | on violation |
|
|
194
|
+
| --- | --- | --- |
|
|
195
|
+
| R1 | at most one field tagged `x-vexData: "userId"` across all schemas | error |
|
|
196
|
+
| R2 | any `onXXUserId` keyword present requires R1 satisfied | error |
|
|
197
|
+
| R3 | tagged identity field must be `type: "string"` and indexed (or primary) | error |
|
|
198
|
+
| R4 | resolved column family of every `onXXUserId` field must equal that of the tagged field | error |
|
|
199
|
+
| R5 | `onXXTimestamp` must be `string` + `x-format: "Timestamp"`; `onXXUnixTimestamp` must be `integer` + `x-format: "UnixTimestamp"` | error |
|
|
200
|
+
| R6 | `x-vexData` value must be a known one (`role`, `userId`) — catches typos | error |
|
|
201
|
+
| R7 | an audit field must not be `required` — its value is stripped from the client body anyway | error |
|
|
202
|
+
|
|
203
|
+
R4 compares the **resolved** family, not the raw string: `Primary`, `PrimaryUUID` and `UUID` all resolve to
|
|
204
|
+
`uuid`, so tagging `_id` as `PrimaryUUID` and declaring `createdBy` as `UUID` is consistent and does not
|
|
205
|
+
raise. The error message names both offending paths (the tagged field and the audit field).
|
|
206
|
+
|
|
207
|
+
Validation runs once, after every schema is loaded (`validateAuditFields()` in
|
|
208
|
+
`src/preprocess/auditFields.ts`, called from the pipeline), because R1/R2 are cross-document. All problems
|
|
209
|
+
are collected and reported together; `log.error` exits the generator, so a contradiction never reaches runtime.
|
|
210
|
+
|
|
211
|
+
## 7. Backward compatibility
|
|
212
|
+
|
|
213
|
+
- Schema with no reserved keyword and no tag → nothing changes; generation output is identical.
|
|
214
|
+
- Schema with a literal `default` → unchanged.
|
|
215
|
+
- Existing generated apps: re-run `vex`; entities gain `nullable` audit columns if they were declared.
|
|
216
|
+
- Existing rows keep `createdBy = NULL`. This feature cannot backfill; a downstream app that needs
|
|
217
|
+
ownership on legacy rows must migrate data itself.
|
|
218
|
+
- Tokens issued before the upgrade still work (the `?? _id` fallback on refresh).
|
|
219
|
+
- The prototype branch's lowercase `x-format` values (`primary`, `uuid`, …) are **rejected** — this design
|
|
220
|
+
keeps the current capitalized values (`Primary`, `PrimaryUUID`, `UUID`, `UnixTimestamp`) and only adds
|
|
221
|
+
`Timestamp`.
|
|
222
|
+
|
|
223
|
+
## 8. Mongoose
|
|
224
|
+
|
|
225
|
+
Implemented in parallel with TypeORM — same registry, same strip/inject phases, same values
|
|
226
|
+
(ISO-8601 string for `onXXTimestamp`, epoch seconds for `onXXUnixTimestamp`), so both targets store
|
|
227
|
+
comparable data. One extra step: `mongooseModel.generator` hands the model generator a copy of the schema
|
|
228
|
+
with the reserved keywords removed, because that generator copies `default` straight into the mongoose
|
|
229
|
+
schema — a keyword would otherwise become a literal string default.
|
|
230
|
+
|
|
231
|
+
(The current Mongoose adapter has no data-isolation support; that gap is unrelated and stays out of scope.)
|
|
232
|
+
|
|
233
|
+
## 9. Out of scope
|
|
234
|
+
|
|
235
|
+
- Soft delete.
|
|
236
|
+
- Backfilling existing NULL rows.
|
|
237
|
+
- RenoMaster's own job-ownership check (its owner is the `Client` profile, not the `User`).
|
|
238
|
+
- Extending `useUserSchema: false` into a fully custom account model. Today `User.json` is copied from the
|
|
239
|
+
templates unconditionally and `localAuth` requires `useUserSchema: true`, so a custom identity schema is
|
|
240
|
+
not reachable yet; `x-vexData: "userId"` is the forward-compatible hook for it.
|
|
@@ -4,9 +4,10 @@ Available from v0.6.x. Provides transparent per-entity ownership: all queries ar
|
|
|
4
4
|
|
|
5
5
|
## How it works
|
|
6
6
|
|
|
7
|
-
1. Declare `dataIsolation` in `x-documentConfig
|
|
7
|
+
1. Declare `dataIsolation` in `x-documentConfig` of your JSON Schema
|
|
8
8
|
2. Generator produces `DataIsolationRegistry.gen.ts` mapping entity → ownership field
|
|
9
|
-
3. `DataIsolationContext` middleware runs before request handlers, storing current user
|
|
9
|
+
3. `DataIsolationContext` middleware runs before request handlers, storing the current user's identity
|
|
10
|
+
(`vexUserId` token claim, `_id` as fallback) in `AsyncLocalStorage`
|
|
10
11
|
4. `TypeOrmRepositoryAdapter` reads the registry and injects `{ [field]: userId }` into every query
|
|
11
12
|
|
|
12
13
|
## Configuration
|
|
@@ -15,11 +16,11 @@ Available from v0.6.x. Provides transparent per-entity ownership: all queries ar
|
|
|
15
16
|
{
|
|
16
17
|
"x-documentConfig": {
|
|
17
18
|
"documentName": "Project",
|
|
19
|
+
"dataIsolation": {
|
|
20
|
+
"field": "ownerId"
|
|
21
|
+
},
|
|
18
22
|
"restApi": {
|
|
19
|
-
"methods": ["get", "getList", "post", "put", "patch", "delete"]
|
|
20
|
-
"dataIsolation": {
|
|
21
|
-
"field": "ownerId"
|
|
22
|
-
}
|
|
23
|
+
"methods": ["get", "getList", "post", "put", "patch", "delete"]
|
|
23
24
|
}
|
|
24
25
|
},
|
|
25
26
|
"properties": {
|
|
@@ -36,13 +37,24 @@ Available from v0.6.x. Provides transparent per-entity ownership: all queries ar
|
|
|
36
37
|
|
|
37
38
|
The `field` value references a property on the same document that stores the owner's user ID.
|
|
38
39
|
|
|
40
|
+
> Note: `dataIsolation` sits directly under `x-documentConfig` — earlier revisions of this page
|
|
41
|
+
> showed it nested under `restApi`, which the generator never read.
|
|
42
|
+
|
|
39
43
|
## Behavior
|
|
40
44
|
|
|
41
45
|
- **All queries** — `find`, `findOne`, `update`, `delete` — get an `AND` filter: `{ [field]: currentUserId }`
|
|
42
|
-
- **Create** — the
|
|
46
|
+
- **Create** — the adapter stamps the owner field from the request context; a controller only has to
|
|
47
|
+
set it by hand when the owner is *not* the authenticated user (e.g. an admin creating data for a third party).
|
|
48
|
+
`field: "_id"` is never stamped (the row's own id is the caller's id only for the account document itself)
|
|
43
49
|
- **No userId in context** — if `Authentication` middleware hasn't set a user (e.g., public routes), the ownership filter is skipped
|
|
44
50
|
- **Only affects SQL/TypeORM target** — Mongoose adapter doesn't implement data isolation yet
|
|
45
51
|
|
|
52
|
+
## Related: audit fields
|
|
53
|
+
|
|
54
|
+
`dataIsolation` scopes *queries*; the reserved `default` keywords (`onCreateUserId`, `onUpdateTimestamp`, …)
|
|
55
|
+
fill *columns* on write. They are independent and can be combined. See
|
|
56
|
+
[`auditFields.md`](auditFields.md).
|
|
57
|
+
|
|
46
58
|
## Dependencies
|
|
47
59
|
|
|
48
60
|
- Requires authentication (`auth.localAuth: true` or OAuth) to establish request context
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# v0.8.0
|
|
2
|
+
|
|
3
|
+
## Auto-written audit / ownership fields
|
|
4
|
+
|
|
5
|
+
The DB layer now fills `createdBy` / `createdAt` / `updatedBy` / `updatedAt` itself, from the schema
|
|
6
|
+
declaration. Before this release those columns existed in every generated entity but nothing ever wrote
|
|
7
|
+
them — a `findOne({ _id, createdBy: user._id })` ownership check could never match, which surfaced as
|
|
8
|
+
silent `404`s in downstream apps.
|
|
9
|
+
|
|
10
|
+
Declare a field with one of six reserved `default` keywords:
|
|
11
|
+
|
|
12
|
+
```jsonc
|
|
13
|
+
"createdAt": { "type": "string", "x-format": "Timestamp", "default": "onCreateTimestamp" },
|
|
14
|
+
"createdBy": { "type": "string", "x-format": "UUID", "default": "onCreateUserId" },
|
|
15
|
+
"updatedAt": { "type": "string", "x-format": "Timestamp", "default": "onUpdateTimestamp" },
|
|
16
|
+
"updatedBy": { "type": "string", "x-format": "UUID", "default": "onUpdateUserId" }
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
- `onCreate*` is written on `create`; `onUpdate*` on `update` / `replace`. The opposite phase **strips**
|
|
20
|
+
the field without writing it, so `createdAt` / `createdBy` can never be overwritten by a PATCH.
|
|
21
|
+
- Client-supplied values for these fields are always discarded — a caller cannot forge `createdBy`.
|
|
22
|
+
- No authenticated context (public / internal call): timestamps are still written, owner fields are left
|
|
23
|
+
untouched. Never `"undefined"`, never a thrown error.
|
|
24
|
+
- Both targets implement it (TypeORM and Mongoose); no SQL `DEFAULT` / `ON UPDATE` is generated, so the
|
|
25
|
+
adapter stays the single source of truth.
|
|
26
|
+
|
|
27
|
+
## Identity source: `x-vexData: "userId"`
|
|
28
|
+
|
|
29
|
+
Exactly one field across all schemas is tagged as the identity source (the template tags `User._id`):
|
|
30
|
+
|
|
31
|
+
```jsonc
|
|
32
|
+
"_id": { "type": "string", "x-format": "PrimaryUUID", "x-vexData": "userId", "index": true }
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`useUserSchema` apps get the tag added automatically on the first run after upgrading; other apps declare
|
|
36
|
+
it themselves. `onCreateUserId` / `onUpdateUserId` require it and generation fails with a clear message
|
|
37
|
+
when it is missing, duplicated, or when the column types of the two sides disagree.
|
|
38
|
+
|
|
39
|
+
## Token claims
|
|
40
|
+
|
|
41
|
+
Access tokens now carry `vexUserId` (the tagged field's value) and `vexRole`. Refresh tokens carry
|
|
42
|
+
`vexUserId` only — roles are a signing-time snapshot and the refresh endpoint re-reads the user anyway.
|
|
43
|
+
`POST /auth/refresh` resolves the user by the tagged field; `payload._id` is still accepted, so refresh
|
|
44
|
+
tokens issued before the upgrade keep working. The public `profile` object is unchanged.
|
|
45
|
+
|
|
46
|
+
## New `x-format: "Timestamp"`
|
|
47
|
+
|
|
48
|
+
Datetime columns (`timestamptz` on PostgreSQL). Distinct from `UnixTimestamp`, which stays integer epoch
|
|
49
|
+
seconds. Generated entities convert the driver's `Date` back to an ISO-8601 string, so the API and the
|
|
50
|
+
generated interfaces keep their `string` contract.
|
|
51
|
+
|
|
52
|
+
## Request body no longer accepts server-managed fields
|
|
53
|
+
|
|
54
|
+
The interface generator now emits a request-body alias per document:
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
export type CreateJob = Omit<Job, "createdAt" | "createdBy" | "updatedAt" | "updatedBy" | "_id">;
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Controllers take `Create{Doc}` / `Partial<Create{Doc}>`, so the OpenAPI request schema only lists fields a
|
|
61
|
+
client may send, and `_id` is dropped from the input as well (unless `app.allowApiCreateUpdate_id` is
|
|
62
|
+
true). The response schema is unchanged — clients still read `createdAt` / `createdBy`.
|
|
63
|
+
|
|
64
|
+
The omission follows the **declaration**, not the field name: audit fields are recognised by their
|
|
65
|
+
reserved `default` keyword, the primary key by `x-format: Primary` / `PrimaryUUID`.
|
|
66
|
+
|
|
67
|
+
**Behaviour change:** the generated tsoa config is `noImplicitAdditionalProperties: "throw-on-extras"`, so
|
|
68
|
+
a request that still sends one of these fields is now rejected with `400 Invalid Request Body` instead of
|
|
69
|
+
being silently stripped. Any client that GETs a row and PATCHes the whole object back must remove
|
|
70
|
+
`_id` and the audit fields first.
|
|
71
|
+
|
|
72
|
+
## Breaking changes
|
|
73
|
+
|
|
74
|
+
- No schema is broken: a field without a reserved keyword keeps its exact previous behaviour, and a
|
|
75
|
+
literal `default` (`"default": true`, …) still means what it always did.
|
|
76
|
+
- **Behaviour change for clients**: a request that sends a server-managed field (`_id`, or any field
|
|
77
|
+
declared with a reserved keyword) is now rejected with `400` instead of being silently stripped.
|
|
78
|
+
- Rows created before the upgrade keep `createdBy = NULL`; nothing is backfilled.
|
|
79
|
+
|
|
80
|
+
## After upgrading
|
|
81
|
+
|
|
82
|
+
Re-run the generator. Consequences per app:
|
|
83
|
+
|
|
84
|
+
1. Entities pick up the audit columns (all `nullable`), plus a transformer on `x-format: "Timestamp"` columns.
|
|
85
|
+
2. Audit fields start being written from the next write onward. **Existing rows are not backfilled** — an
|
|
86
|
+
app that requires ownership on legacy rows has to migrate its own data.
|
|
87
|
+
3. Applications with a custom ownership check reading `createdBy` will start working once rows are written
|
|
88
|
+
again; rows created before the upgrade still have `NULL` there.
|
|
89
|
+
4. `x-format` values stay capitalized (`Primary`, `PrimaryUUID`, `UUID`, `UnixTimestamp`) with `Timestamp`
|
|
90
|
+
added — schemas written against the lowercase prototype variant must be corrected.
|
|
91
|
+
5. Clients that PATCH a whole row they previously GET'd must drop `_id` and the audit fields, otherwise
|
|
92
|
+
the request now fails with `400 Invalid Request Body`.
|
|
93
|
+
|
|
94
|
+
Guides: [`docs/features/auditFields.md`](../features/auditFields.md),
|
|
95
|
+
[`docs/vexJsonSchema.md`](../vexJsonSchema.md).
|