very-express 0.9.0-alpha → 0.10.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.
Files changed (149) hide show
  1. package/.tmp/als-proof.mjs +15 -0
  2. package/.tmp/als-proof2.mjs +9 -0
  3. package/.tmp/gen/out/.env +41 -0
  4. package/.tmp/gen/out/.vex/meta.json +381 -0
  5. package/.tmp/gen/out/Dockerfile +20 -0
  6. package/.tmp/gen/out/README.md +39 -0
  7. package/.tmp/gen/out/package.json +51 -0
  8. package/.tmp/gen/out/public/css/style.css +8 -0
  9. package/.tmp/gen/out/public/js/deleteaccount.js +80 -0
  10. package/.tmp/gen/out/public/js/login.js +59 -0
  11. package/.tmp/gen/out/public/js/logincallback.js +19 -0
  12. package/.tmp/gen/out/public/js/mytokens.js +11 -0
  13. package/.tmp/gen/out/public/js/refreshtokens.js +23 -0
  14. package/.tmp/gen/out/scripts/build.js +39 -0
  15. package/.tmp/gen/out/scripts/oacg-fix.js +83 -0
  16. package/.tmp/gen/out/tsconfig.json +30 -0
  17. package/.tmp/gen/out/tsoa.json +32 -0
  18. package/.tmp/gen/schemas/Project.json +50 -0
  19. package/.tmp/gen/schemas/Session.json +49 -0
  20. package/.tmp/gen/schemas/User.json +81 -0
  21. package/.tmp/gen/schemas/UserAuthProfiles.json +54 -0
  22. package/.tmp/gen/schemas/UserRole.json +40 -0
  23. package/.tmp/gen/schemas/UserTenant.json +39 -0
  24. package/.tmp/gen/vex.config.json +39 -0
  25. package/.tmp/gen0/out/.env +41 -0
  26. package/.tmp/gen0/out/.vex/meta.json +323 -0
  27. package/.tmp/gen0/out/Dockerfile +20 -0
  28. package/.tmp/gen0/out/README.md +39 -0
  29. package/.tmp/gen0/out/package.json +51 -0
  30. package/.tmp/gen0/out/public/css/style.css +8 -0
  31. package/.tmp/gen0/out/public/js/deleteaccount.js +80 -0
  32. package/.tmp/gen0/out/public/js/login.js +59 -0
  33. package/.tmp/gen0/out/public/js/logincallback.js +19 -0
  34. package/.tmp/gen0/out/public/js/mytokens.js +11 -0
  35. package/.tmp/gen0/out/public/js/refreshtokens.js +23 -0
  36. package/.tmp/gen0/out/scripts/build.js +39 -0
  37. package/.tmp/gen0/out/scripts/oacg-fix.js +83 -0
  38. package/.tmp/gen0/out/tsconfig.json +30 -0
  39. package/.tmp/gen0/out/tsoa.json +32 -0
  40. package/.tmp/gen0/schemas/Session.json +49 -0
  41. package/.tmp/gen0/schemas/User.json +81 -0
  42. package/.tmp/gen0/schemas/UserAuthProfiles.json +54 -0
  43. package/.tmp/gen0/schemas/UserRole.json +38 -0
  44. package/.tmp/gen0/vex.config.json +32 -0
  45. package/.tmp/gend/out/.env +41 -0
  46. package/.tmp/gend/out/.vex/meta.json +317 -0
  47. package/.tmp/gend/out/Dockerfile +20 -0
  48. package/.tmp/gend/out/README.md +39 -0
  49. package/.tmp/gend/out/package.json +51 -0
  50. package/.tmp/gend/out/public/css/style.css +8 -0
  51. package/.tmp/gend/out/public/js/deleteaccount.js +80 -0
  52. package/.tmp/gend/out/public/js/login.js +59 -0
  53. package/.tmp/gend/out/public/js/logincallback.js +19 -0
  54. package/.tmp/gend/out/public/js/mytokens.js +11 -0
  55. package/.tmp/gend/out/public/js/refreshtokens.js +23 -0
  56. package/.tmp/gend/out/scripts/build.js +39 -0
  57. package/.tmp/gend/out/scripts/oacg-fix.js +83 -0
  58. package/.tmp/gend/out/tsconfig.json +30 -0
  59. package/.tmp/gend/out/tsoa.json +32 -0
  60. package/.tmp/gend/schemas/Session.json +49 -0
  61. package/.tmp/gend/schemas/User.json +81 -0
  62. package/.tmp/gend/schemas/UserAuthProfiles.json +54 -0
  63. package/.tmp/gend/schemas/UserContact.json +40 -0
  64. package/.tmp/gend/schemas/UserNote.json +27 -0
  65. package/.tmp/gend/vex.config.json +33 -0
  66. package/.tmp/genh/out/.env +41 -0
  67. package/.tmp/genh/out/.vex/meta.json +323 -0
  68. package/.tmp/genh/out/Dockerfile +20 -0
  69. package/.tmp/genh/out/README.md +39 -0
  70. package/.tmp/genh/out/package.json +51 -0
  71. package/.tmp/genh/out/public/css/style.css +8 -0
  72. package/.tmp/genh/out/public/js/deleteaccount.js +80 -0
  73. package/.tmp/genh/out/public/js/login.js +59 -0
  74. package/.tmp/genh/out/public/js/logincallback.js +19 -0
  75. package/.tmp/genh/out/public/js/mytokens.js +11 -0
  76. package/.tmp/genh/out/public/js/refreshtokens.js +23 -0
  77. package/.tmp/genh/out/scripts/build.js +39 -0
  78. package/.tmp/genh/out/scripts/oacg-fix.js +83 -0
  79. package/.tmp/genh/out/tsconfig.json +30 -0
  80. package/.tmp/genh/out/tsoa.json +32 -0
  81. package/.tmp/genh/schemas/Project.json +41 -0
  82. package/.tmp/genh/schemas/Session.json +49 -0
  83. package/.tmp/genh/schemas/User.json +81 -0
  84. package/.tmp/genh/schemas/UserAuthProfiles.json +54 -0
  85. package/.tmp/genh/schemas/UserTenant.json +39 -0
  86. package/.tmp/genh/vex.config.json +31 -0
  87. package/.tmp/gens/out/.env +41 -0
  88. package/.tmp/gens/out/.vex/meta.json +335 -0
  89. package/.tmp/gens/out/Dockerfile +20 -0
  90. package/.tmp/gens/out/README.md +39 -0
  91. package/.tmp/gens/out/package.json +51 -0
  92. package/.tmp/gens/out/public/css/style.css +8 -0
  93. package/.tmp/gens/out/public/js/deleteaccount.js +80 -0
  94. package/.tmp/gens/out/public/js/login.js +59 -0
  95. package/.tmp/gens/out/public/js/logincallback.js +19 -0
  96. package/.tmp/gens/out/public/js/mytokens.js +11 -0
  97. package/.tmp/gens/out/public/js/refreshtokens.js +23 -0
  98. package/.tmp/gens/out/scripts/build.js +39 -0
  99. package/.tmp/gens/out/scripts/oacg-fix.js +83 -0
  100. package/.tmp/gens/out/tsconfig.json +30 -0
  101. package/.tmp/gens/out/tsoa.json +32 -0
  102. package/.tmp/gens/schemas/Session.json +49 -0
  103. package/.tmp/gens/schemas/User.json +81 -0
  104. package/.tmp/gens/schemas/UserAuthProfiles.json +54 -0
  105. package/.tmp/gens/schemas/UserRole.json +38 -0
  106. package/.tmp/gens/vex.config.json +32 -0
  107. package/.tmp/npmtest/package.json +1 -0
  108. package/.tmp/ro-test +0 -0
  109. package/AGENTS.md +26 -12
  110. package/README.md +1 -0
  111. package/dist/index.js +1108 -1037
  112. package/dist/templates/_middlewares/Authentication.ts +1 -4
  113. package/dist/templates/_middlewares/UserContext.ts +31 -22
  114. package/dist/templates/_projectSettings/env +13 -12
  115. package/dist/templates/_projectSettings/package.json +2 -2
  116. package/dist/templates/_routes/FirebaseAuthUI.gen.ts +20 -0
  117. package/dist/templates/_routes/LoginUI.ts +293 -242
  118. package/dist/templates/_services/MongooseRepositoryAdapter.ts +68 -4
  119. package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +68 -24
  120. package/dist/templates/_services/VexDbConnector.ts +1 -26
  121. package/dist/templates/_services/auth/JWTService.ts +13 -17
  122. package/dist/templates/_tenant/TenantScopeContext.ts +56 -0
  123. package/dist/templates/_types/auth.ts +19 -9
  124. package/dist/templates/_types/vex/VexRepository.ts +2 -2
  125. package/dist/templates/_utils/hash.ts +0 -16
  126. package/dist/templates/root/public/js/deleteaccount.js +0 -54
  127. package/dist/templates/tenantJsonSchema/UserTenant.json +33 -0
  128. package/docs/appGenerated/auth.md +84 -0
  129. package/docs/architecture/authAndRouting.md +1 -1
  130. package/docs/architecture/databaseTargets.md +18 -8
  131. package/docs/architecture/generatorPipeline.md +2 -1
  132. package/docs/features/accountDeletion.md +63 -12
  133. package/docs/features/auditFields.md +2 -2
  134. package/docs/features/dataIsolation.md +58 -31
  135. package/docs/features/tenantIsolation.md +138 -0
  136. package/docs/releaseNote/v0-10-0.md +147 -0
  137. package/docs/releaseNote/v0-8-5.md +98 -0
  138. package/docs/releaseNote/v0-9-0.md +41 -47
  139. package/docs/superpowers/specs/2026-09-22-usercontext-audit-enforcement-design.md +9 -9
  140. package/docs/vexJsonSchema.md +39 -0
  141. package/package.json +1 -1
  142. package/vex.config.json +1 -6
  143. package/vitest.config.ts +3 -0
  144. package/dist/templates/_routes/ExternalIdentityUI.gen.ts +0 -20
  145. package/dist/templates/root/public/js/externallogin.js +0 -133
  146. package/docs/features/auth.md +0 -34
  147. package/docs/features/externalIdentity.md +0 -163
  148. /package/docs/{ForeignKey.md → features/ForeignKey.md} +0 -0
  149. /package/docs/{apiUsage.md → features/apiUsage.md} +0 -0
@@ -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.
@@ -0,0 +1,98 @@
1
+ # v0.8.5
2
+
3
+ ## Breaking: the identity key is renamed, and now enforced
4
+
5
+ `UserAuthProfiles.oauthId` is **`providerUserId`**, and `(provider, providerUserId)` is a **composite
6
+ unique index**. The value never changed — it is the subject within `provider`'s namespace — but the old
7
+ name claimed a protocol the field does not require, and nothing stopped two rows claiming one identity.
8
+
9
+ Re-run the generator (migration `v0.8.5` rewrites the schema, and any `uniqueIndex` entry naming the old
10
+ field), then migrate the database:
11
+
12
+ ```sql
13
+ ALTER TABLE "userauthprofiles" RENAME COLUMN "oauthId" TO "providerUserId";
14
+ ALTER TABLE "userauthprofiles" ADD CONSTRAINT "unique_provider_providerUserId"
15
+ UNIQUE ("provider", "providerUserId");
16
+ ```
17
+
18
+ Look for existing duplicates before adding the constraint:
19
+
20
+ ```sql
21
+ SELECT provider, "providerUserId", COUNT(*) FROM "userauthprofiles"
22
+ GROUP BY 1,2 HAVING COUNT(*) > 1;
23
+ ```
24
+
25
+ `SQL_SYNCHRONIZE=true` covers development. App code that reads `oauthId` must be updated.
26
+
27
+ ## New: Firebase as a sign-in option
28
+
29
+ `auth.firebase: true` generates `POST /api/auth/firebase` and a button on the generated `/login` page.
30
+ The endpoint takes a Firebase ID token and answers with the vex token pair:
31
+
32
+ ```
33
+ POST /api/auth/firebase { "idToken": "<Firebase ID token>" }
34
+ 200 { "result": { accessToken, accessTokenIndex, refreshToken, refreshTokenIndex, isNewUser } }
35
+ 503 no usable service account 401 invalid or expired token
36
+ 400 the sign-in has no upstream IdP 409 the sign-in carries no email
37
+ ```
38
+
39
+ The identity written is the **upstream** IdP's — `("google", <Google sub>)` for a Google sign-in, the
40
+ same pair `passport-google-oauth20` writes, so both doors resolve to one `User` row.
41
+
42
+ ```jsonc
43
+ "auth": { "firebase": true }
44
+ ```
45
+
46
+ That boolean is the only switch. Everything else is environment. Four required values, under the names a
47
+ deployment already has; two variables earlier drafts carried are gone because nothing reads them
48
+ (`FIREBASE_APP_ID` — Firebase Auth takes no appId — and a file-path alternative to the service account).
49
+
50
+ | Variable | Used by |
51
+ |---|---|
52
+ | `FIREBASE_SERVICE_ACCOUNT_JSON` | server — `firebase-admin` |
53
+ | `FIREBASE_WEB_API_KEY`, `FIREBASE_WEB_AUTH_DOMAIN`, `FIREBASE_WEB_PROJECT_ID` | login page — public, by design |
54
+ | `FIREBASE_PROVIDERS` | optional; which buttons `/login` renders; default `google` |
55
+
56
+ Design record, including the identity rules and the reasons behind them:
57
+ [`docs/plan/spec-firebase-auth.md`](../plan/spec-firebase-auth.md).
58
+
59
+ ## Also fixed
60
+
61
+ - **A project with `localAuth: false` and any other sign-in path generated a controller that did not
62
+ compile** — `exchangeToken` / `refreshToken` call `this.userRepo`, which was only emitted when
63
+ `localAuth` was on. The getter is now emitted whenever auth is enabled. Reachable before this release
64
+ with `oauthProviders` alone; the Firebase-only configuration is the same shape.
65
+
66
+ ## After upgrading
67
+
68
+ 1. **`npm install`** — `firebase-admin` is a dependency of the generated app (the browser SDK is loaded
69
+ from gstatic by the login page, so the `firebase` package is not needed).
70
+ 2. **Re-run `vex`.**
71
+ 3. **Run the SQL above** if your identity table is older than this release.
72
+ 4. **Set the environment** — the service account, plus the three public values from one *Web* app
73
+ registration in the same Firebase project. Paste the downloaded key file into
74
+ `FIREBASE_SERVICE_ACCOUNT_JSON` as-is: its fields are snake_case (`project_id`, `private_key`,
75
+ `client_email`) and that is what the loader expects.
76
+ 5. **Turn it on** with `"auth": { "firebase": true }`, then re-run `vex`.
77
+ 6. **Open `/login`.** The button posts to `/api/auth/firebase`; a failed sign-in names the server-side
78
+ configuration problem it can see (missing variables, an unstartable provider name).
79
+
80
+ Notes:
81
+
82
+ - The login page loads the **modular** Firebase SDK as ES modules from gstatic (pinned version), the
83
+ same way the app's own web sign-in does, and preloads it on page load. That needs `www.gstatic.com` in
84
+ `script-src`, plus `connect-src` for the token endpoints and `frame-src` for the project's auth domain
85
+ — the generated page sets all three itself, so an app-wide `helmet` CSP does not have to change.
86
+ - The glue is **inlined into the generated page**, not served from `public/js/`. `public/**` is a
87
+ copy-once template, and an earlier draft of this feature put `public/js/firebaseauth.js` there — so a
88
+ project that ran that draft keeps a compat-era file while its page moved on, and the page fails with
89
+ `Firebase sign-in is not configured: window.undefined is missing`. **Delete
90
+ `public/js/firebaseauth.js`** from any project generated from that draft; nothing references it any
91
+ more. (Same for a stale `/js/firebase/*` route, if you carried one.)
92
+ - The login page overrides `Cross-Origin-Opener-Policy` to `same-origin-allow-popups`. helmet's default
93
+ (`same-origin`) nulls `window.opener` inside a cross-origin popup, which is the channel the Firebase
94
+ handler reports on, and the SDK then reports **`auth/popup-closed-by-user`** — a message that points at
95
+ the user and the network, never at the header that actually caused it. If you proxy or re-render the
96
+ login page yourself, keep this header.
97
+ - `LoginUI.gen.ts` and `FirebaseAuthUI.gen.ts` are regenerated even when `auth.firebase` is false; the
98
+ wiring module exports `undefined` and the page renders no Firebase button.
@@ -1,49 +1,43 @@
1
1
  # v0.9.0
2
2
 
3
- ## Breaking — `UserAuthProfiles.oauthId` → `providerUserId`
4
-
5
- - `(provider, providerUserId)` is the account-linking key, and it now has a **composite unique index**;
6
- nothing enforced it before.
7
- - A schema migration renames the property; one `ALTER TABLE` renames the column.
8
-
9
- ## External identity (broker SSO) — Firebase
10
-
11
- - `POST /api/auth/external` verifies a broker ID token against the issuer's JWKS and provisions the
12
- matching vex identity. **Off by default.**
13
- - Every token stays vex-issued: the broker's token is consumed at that one endpoint and never stored.
14
- - No broker SDK on the server, no client secret, no new dependency.
15
- - The generated login page renders the broker's buttons for you — configure it in `vex.config.json`,
16
- then `npm install` (the `firebase` dependency is new).
17
- - **Use a Web app's config**, all four values from the same registration.
18
- - Configuration, identity rules, troubleshooting: [`docs/features/externalIdentity.md`](../features/externalIdentity.md).
19
-
20
- ## `sessionCode` is single-use
21
-
22
- - `POST /api/auth/token` now consumes the code, instead of leaving it replayable for its whole TTL.
23
-
24
- ## Login and delete pages
25
-
26
- - The home page shows the login link for broker-only apps, which previously had none.
27
- - `/delete_account` states the sign-in prerequisite and links to `/login`.
28
- - `public/js/deleteaccount.js` no longer sends an empty `Bearer ` — **new projects only**, that file is
29
- copied once and not overwritten.
30
- - The login page's CSP now allows the hosts a broker SDK injects at runtime.
31
-
32
- ## After upgrading
33
-
34
- 1. **`npm install`** — `firebase` is a new dependency.
35
- 2. **Re-run the generator**, so the schema migration renames the property.
36
- 3. **Rename the column and add the constraint:**
37
- ```sql
38
- ALTER TABLE "userauthprofiles" RENAME COLUMN "oauthId" TO "providerUserId";
39
- ALTER TABLE "userauthprofiles" ADD CONSTRAINT "unique_provider_providerUserId"
40
- UNIQUE ("provider", "providerUserId");
41
- ```
42
- `SQL_SYNCHRONIZE=true` covers development. If the old code let two rows claim one identity, find them
43
- first: `SELECT provider, "providerUserId", COUNT(*) FROM "userauthprofiles" GROUP BY 1,2 HAVING COUNT(*) > 1;`
44
- 4. **Update app code** that reads `oauthId`.
45
- 5. **Keep `package.json` at `0.9.0` or later** — the migration runner compares the migration's label with
46
- `.vex/meta.json`'s last generated version, so a lower version re-runs it on every generation.
47
-
48
- Guides: [`docs/features/externalIdentity.md`](../features/externalIdentity.md),
49
- [`docs/features/accountDeletion.md`](../features/accountDeletion.md).
3
+ ## Binary fields: `x-format: "Binary"`
4
+
5
+ A property can now carry a binary payload. Declare it as a string with the `Binary` format:
6
+
7
+ ```jsonc
8
+ "data": { "type": "string", "x-format": "Binary", "description": "base64-encoded bytes" }
9
+ ```
10
+
11
+ | Layer | Value |
12
+ | --- | --- |
13
+ | SQL column | `bytea` |
14
+ | Entity property | `string` |
15
+ | API request / response | base64 string |
16
+
17
+ A TypeORM transformer converts `string → Buffer` on write and `Buffer → base64 string` on read, so
18
+ clients never see a `Buffer` and every generated type stays JSON-safe:
19
+
20
+ ```ts
21
+ @Column({type: "bytea", nullable: false,
22
+ transformer: {
23
+ to: (v: string | null) => (v == null ? v : Buffer.from(v, "base64")),
24
+ from: (v: Buffer | null) => (v == null ? v : v.toString("base64"))
25
+ }})
26
+ data!: string;
27
+ ```
28
+
29
+ `type` must be `string`; any other type fails generation. In mongo mode the column is a plain
30
+ `String` holding the same base64 text. The transformer does not validate base64 — `Buffer.from`
31
+ ignores invalid characters — and `maxLength` has no effect on a binary column.
32
+
33
+ Re-run the generator, then migrate the table. `SQL_SYNCHRONIZE=true` covers development; otherwise:
34
+
35
+ ```sql
36
+ ALTER TABLE "asset" ADD COLUMN "data" bytea;
37
+ ```
38
+
39
+ ## SQL target is PostgreSQL
40
+
41
+ The generated SQL app connects with a fixed `postgres` driver and depends on `pg` only. There is no
42
+ MySQL or SQLite path, so binary columns are always `bytea`. A MySQL target would need a dialect layer
43
+ between the schema and the entity generator; `blob` is not emitted today.
@@ -8,7 +8,7 @@ Branch: TBD
8
8
 
9
9
  `createdBy` / `createdAt` 这类审计字段在生成的应用里**静默留下 NULL**,且没有任何信号。
10
10
 
11
- RenoMaster 的实测现场:
11
+ 生产项目的实测现场:
12
12
 
13
13
  - 23/24 个 schema 声明了 `createdBy` / `updatedBy`(`onCreateUserId` / `onUpdateUserId`)
14
14
  - 只有 `User` 一个声明了 `dataIsolation`
@@ -67,7 +67,7 @@ if (useAuth) {
67
67
 
68
68
  改为 fail-loud 即推翻此契约,文档必须同步。
69
69
 
70
- ### 2.4 触发路径证明(RenoMaster)
70
+ ### 2.4 触发路径证明(生产项目实测)
71
71
 
72
72
  ```
73
73
  $ grep -rln "DataIsolationContext.middleware" src/system/_controllers/ | wc -l
@@ -211,7 +211,7 @@ UserContext.run(tokenData, () => next());
211
211
  - `:55` 的 `DataIsolationContext` 可选 import 删除
212
212
  - 不再生成独立的上下文中间件 —— `UserContext` 从 middleware 降级为 helper 模块(只剩 `run()` / `getStore()` / `userId`)
213
213
 
214
- **为什么这是从构造上消除挂载门**:`Authentication.middleware` 本来就挂在每个 `useAuth` 的 controller 上(生成 18 个 + RenoMaster 手写 17 个里的 14 个)。没有第二处需要记得挂的装饰器,就没有「忘了挂」这一态。
214
+ **为什么这是从构造上消除挂载门**:`Authentication.middleware` 本来就挂在每个 `useAuth` 的 controller 上(生成 18 个 + 应用手写 17 个里的 14 个)。没有第二处需要记得挂的装饰器,就没有「忘了挂」这一态。
215
215
 
216
216
  ### 4.4 Adapter 强制规则
217
217
 
@@ -338,9 +338,9 @@ Mongoose `replace` 与其余三者行为不一致。本 spec 接受,但要求
338
338
 
339
339
  **代价(明确接受)**:**没有逃生口**。任何处于请求链之外的写(seed、后台 job、tsoa 注册路径)都无法声明身份,只能硬失败或静默 NULL。
340
340
 
341
- **影响面(RenoMaster 实测)**:`VexDb.getRepository(...)` 构造点 79 处,其中写路径 19 处(4 处直连写 + 15 处 `this.repo`)。选 ALS 路线意味着这 79 处**零改动**。
341
+ **影响面(生产项目实测)**:`VexDb.getRepository(...)` 构造点 79 处,其中写路径 19 处(4 处直连写 + 15 处 `this.repo`)。选 ALS 路线意味着这 79 处**零改动**。
342
342
 
343
- **已识别的硬冲突**:RenoMaster 的注册路径在**无 auth** 的 controller 里 create `User`:
343
+ **已识别的硬冲突**:某应用的注册路径在**无 auth** 的 controller 里 create `User`:
344
344
 
345
345
  | 位置 | 装饰器 |
346
346
  |---|---|
@@ -391,11 +391,11 @@ const user = await this.userRepo.create({ name: email.split("@")[0], email, acti
391
391
 
392
392
  ### 6.1 注册路径(高)
393
393
 
394
- 见 D2。当前 RenoMaster 安全,但依赖「`User` 没有 `createdBy`」这一巧合。必须在 D2 的 A/B/C 中做出选择后才能认为风险闭环。
394
+ 见 D2。当前该应用安全,但依赖「`User` 没有 `createdBy`」这一巧合。必须在 D2 的 A/B/C 中做出选择后才能认为风险闭环。
395
395
 
396
396
  ### 6.2 请求链外的写入(中)
397
397
 
398
- `src/services/*` 中的写路径无请求上下文。RenoMaster 实测:
398
+ `src/services/*` 中的写路径无请求上下文。实测:
399
399
 
400
400
  | 位置 | 写入 | 该实体是否有 `onCreateUserId` |
401
401
  |---|---|---|
@@ -445,9 +445,9 @@ const user = await this.userRepo.create({ name: email.split("@")[0], email, acti
445
445
  | 删除生成的 `@Middlewares(DataIsolationContext.middleware)` | 破坏性(生成物) | 下游需重新 `vex`;旧的 `DataIsolationContext.gen.ts` 会被 `cleanupStaleFiles()` 清理 |
446
446
  | `pipeline` 生成 `UserContext.gen.ts` | 新增 | — |
447
447
  | 数据隔离功能 | 无变化 | 覆盖面顺带扩大(所有 authed controller) |
448
- | **数据隔离第一次真正生效** | **破坏性(下游可见)** | `entityIsolation` 里的实体,此前若其 controller 没挂中间件就不过滤;改后任何 authed controller 访问它都会过滤。`mergeFilter` 是 `{ ...mapped, ...ownership }`,**ownership 覆盖调用方 filter 的 `_id`** → 按 id 查/改的接口会静默变成「操作自己那一行」。**这是各 app 自己的接口问题,修复不在本卡范围** —— RenoMaster 的实例见其项目卡片 `t-mucc8ot0-9s8rfc` |
448
+ | **数据隔离第一次真正生效** | **破坏性(下游可见)** | `entityIsolation` 里的实体,此前若其 controller 没挂中间件就不过滤;改后任何 authed controller 访问它都会过滤。`mergeFilter` 是 `{ ...mapped, ...ownership }`,**ownership 覆盖调用方 filter 的 `_id`** → 按 id 查/改的接口会静默变成「操作自己那一行」。**这是各 app 自己的接口问题,修复不在本卡范围** |
449
449
 
450
- **迁移**:下游跑一次 `vex`。历史 NULL 行**不会**被回填 —— 需要各应用自行决定值(`createdBy` 有些可由关系推导,RenoMaster 的 owner 是 `Client` 而 `createdBy` 语义是 `User`,推不出来)。
450
+ **迁移**:下游跑一次 `vex`。历史 NULL 行**不会**被回填 —— 需要各应用自行决定值(`createdBy` 有些可由关系推导,有些应用的 owner 是 profile 行而 `createdBy` 语义是 `User`,推不出来)。
451
451
 
452
452
  ## 8. 测试计划
453
453
 
@@ -26,6 +26,8 @@ Each `.json` file defines one REST resource. Filename must match `x-documentConf
26
26
  | `documentName` | `string` | yes | Resource name. Must match filename (e.g. `User.json` → `"User"`). Used as collection name, controller class, route prefix. |
27
27
  | `methods` | `array<schemaMethod>` | yes | REST methods to generate. See values below. |
28
28
  | `uniqueIndex` | `array<array<string>>` | no | Compound unique index definitions, e.g. `[["email"], ["userId","role"]]`. |
29
+ | `isolation` | `array<object>` | no | Query terms the repository adds to every read and write. `{ field, source, onMissing }` — see [isolation rules](#isolation-rules). |
30
+ | `dataIsolation` | `object` | no | Legacy single-field form: `{ "field": "ownerId" }`. Normalized into `isolation`. |
29
31
 
30
32
  ### `methods` values
31
33
 
@@ -38,6 +40,26 @@ Each `.json` file defines one REST resource. Filename must match `x-documentConf
38
40
  | `patch` | `PATCH /:id` | Partial update |
39
41
  | `delete` | `DELETE /:id` | Delete document |
40
42
 
43
+ ### Isolation rules
44
+
45
+ ```jsonc
46
+ "isolation": [
47
+ { "field": "tenantId", "source": "user.tenantId", "onMissing": "deny" },
48
+ { "field": "ownerId", "source": "user._id", "onMissing": "skip" }
49
+ ]
50
+ ```
51
+
52
+ | Key | Values |
53
+ | --- | --- |
54
+ | `field` | a `string` property of the document |
55
+ | `source` | `user._id` (authenticated user) or `user.tenantId` (verified tenant) |
56
+ | `onMissing` | `skip` (no term) or `deny` (`403`). Default: `skip` for `user._id`, `deny` for `user.tenantId` |
57
+
58
+ `user.tenantId` requires `vex.config.tenant.enable`. The rule's field is server-managed: it is omitted from
59
+ the request payload, stripped from caller data, and stamped from the request context on create.
60
+ See [`docs/features/dataIsolation.md`](features/dataIsolation.md) and
61
+ [`docs/features/tenantIsolation.md`](features/tenantIsolation.md).
62
+
41
63
  ---
42
64
 
43
65
  ## Property fields
@@ -69,8 +91,25 @@ Each `.json` file defines one REST resource. Filename must match `x-documentConf
69
91
  | `ObjectId` | MongoDB ObjectId (mongo mode) |
70
92
  | `UnixTimestamp` | Integer epoch **seconds** (SQL: `bigint`) |
71
93
  | `Timestamp` | ISO-8601 datetime (SQL: `timestamptz`, mapped back to an ISO string) |
94
+ | `Binary` | Binary payload (SQL: `bytea`). The API reads and writes a **base64 string**. |
72
95
  | `enum` | Enum field — pair with `enum` array |
73
96
 
97
+ #### Binary fields (`x-format: "Binary"`)
98
+
99
+ ```jsonc
100
+ "data": { "type": "string", "x-format": "Binary", "description": "base64-encoded payload" }
101
+ ```
102
+
103
+ The column is `bytea`; the entity property and the generated API types stay `string`. A TypeORM
104
+ transformer converts `string → Buffer` on write and `Buffer → base64 string` on read, so JSON
105
+ responses and request bodies always carry base64 text. Requirements:
106
+
107
+ - `type` must be `string` — any other type is rejected at generation time.
108
+ - The transformer does not validate the text, and the generator emits no `pattern` check; `Buffer.from(v, "base64")` ignores invalid characters. Validate base64 in the client, or in a hand-written check.
109
+ - `maxLength` has no effect on a binary column — the delivered size is checked by the app, not the generator.
110
+ - Set `express.json({ limit })` in the app when uploads exceed the 100 kB body-parser default.
111
+ - In mongo mode the field is a plain `String` column holding the same base64 text.
112
+
74
113
  ### `x-vexData` values
75
114
 
76
115
  | Value | Description |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "very-express",
3
- "version": "0.9.0-alpha",
3
+ "version": "0.10.0",
4
4
  "description": "based on json schema and openapi, generate Express RestApi server with mongoDb ",
5
5
  "author": "Justin26l",
6
6
  "license": "MIT",
package/vex.config.json CHANGED
@@ -16,15 +16,10 @@
16
16
  "localAuth": true,
17
17
  "useHttpOnlyCookieToken": true,
18
18
  "deleteAccount": true,
19
+ "firebase": true,
19
20
  "oauthProviders": {
20
21
  "google": false,
21
22
  "github": false
22
- },
23
- "externalIdentity": {
24
- "enabled": true,
25
- "preset": "firebase",
26
- "projectId": "renomaster-c36d6",
27
- "signInMethod": "redirect"
28
23
  }
29
24
  },
30
25
  "useRBAC": {
package/vitest.config.ts CHANGED
@@ -14,5 +14,8 @@ export default defineConfig({
14
14
  // golden scenarios spawn a full generation each; give them room
15
15
  testTimeout: 120_000,
16
16
  hookTimeout: 120_000,
17
+ // The e2e suites share one generated app directory and one port, so files must not run
18
+ // in parallel with each other.
19
+ fileParallelism: false,
17
20
  },
18
21
  });
@@ -1,20 +0,0 @@
1
- // {{headerComment}}
2
- import type { ExternalIdentityUI } from "./LoginUI.gen";
3
-
4
- /**
5
- * Test/compile-time stand-in for the generated login-page wiring.
6
- *
7
- * **In a generated app this file is overwritten by the generator**, which emits either the resolved
8
- * `auth.externalIdentity` settings or `undefined` when the feature is off. It lives in the template
9
- * directory so that `LoginUI.ts`'s unconditional import resolves in this repo — the import has to be
10
- * unconditional because the default is how the configuration reaches the login page without editing
11
- * the app-owned `server.ts`.
12
- *
13
- * `let` plus a setter rather than a `const`, so the unit tests can vary what the generator "emitted".
14
- * The generated version is a plain `const`; nothing in the app calls the setter.
15
- */
16
- export let externalIdentityUI: ExternalIdentityUI | undefined = undefined;
17
-
18
- export function setExternalIdentityUI(ui: ExternalIdentityUI | undefined): void {
19
- externalIdentityUI = ui;
20
- }
@@ -1,133 +0,0 @@
1
- // External identity (broker SSO) sign-in glue.
2
- //
3
- // The login page renders one button per configured sign-in method, each carrying its provider id in a
4
- // `data-provider` attribute, and the broker's own init script defines a global that turns
5
- // `(providerId)` into a fresh ID token — for Firebase, `signInWithPopup` followed by `getIdToken()`.
6
- //
7
- // This file owns nothing vendor specific. It calls that global and hands the token to
8
- // POST /api/auth/external, the only endpoint in the system that accepts a non-vex credential. The
9
- // exchange consumes the token and answers with a vex session redirect; from that point on the client
10
- // holds only vex tokens and nothing here runs again.
11
- //
12
- // Configuration arrives as `window.__vexExternalLogin`, rendered inline by the login page:
13
- // { getToken: "<global name>", resumeRedirect: "<global name>", signInMethod: "popup"|"redirect",
14
- // config: { ...broker public config, from env... }, problems: [...] }
15
- //
16
- // Two entry points, and neither the page nor this file needs to know which mode is in use:
17
- // - a button calls getToken(providerId); in "redirect" mode the page navigates away before that
18
- // promise ever settles
19
- // - on page load, resumeRedirect() completes a redirect sign-in, or resolves null
20
-
21
- document.addEventListener("DOMContentLoaded", function () {
22
- var settings = window.__vexExternalLogin || {};
23
- var getTokenName = settings.getToken;
24
- var problems = settings.problems || [];
25
-
26
- var buttons = document.querySelectorAll ? document.querySelectorAll(".externalLoginBtn") : [];
27
-
28
- /**
29
- * Broker SDKs report a misconfigured client with something generic — Firebase's
30
- * `auth/internal-error` says nothing about the cause. The login page sends along what the server
31
- * could determine, so a developer is not left reading a network trace.
32
- */
33
- function report(message) {
34
- if (problems.length > 0) {
35
- message += "\n\nServer-side configuration problems:\n- " + problems.join("\n- ");
36
- }
37
-
38
- // alert rather than a DOM node: the login page has no result container.
39
- alert(message);
40
- }
41
-
42
- function exchange(idToken) {
43
- return fetch("/api/auth/external", {
44
- method: "POST",
45
- headers: { "Content-Type": "application/json" },
46
- body: JSON.stringify({ idToken: idToken }),
47
- }).then(function (response) {
48
- // read as text first: an error response may not be JSON (a proxy or the express error
49
- // handler can return HTML), and response.json() would then reject and hide the real status
50
- return response.text().then(function (text) {
51
- var body;
52
- try {
53
- body = text ? JSON.parse(text) : {};
54
- }
55
- catch (e) {
56
- body = { raw: text };
57
- }
58
-
59
- return { ok: response.ok, status: response.status, body: body };
60
- });
61
- });
62
- }
63
-
64
- /**
65
- * Complete a redirect sign-in.
66
- *
67
- * A no-op in popup mode, so this runs unconditionally: the redirect path cannot be distinguished
68
- * from an ordinary page load until the broker answers, and it must be asked on every load to catch
69
- * the return.
70
- */
71
- function resume() {
72
- var resumeName = settings.resumeRedirect;
73
- var fn = resumeName ? window[resumeName] : undefined;
74
- if (typeof fn !== "function") return;
75
-
76
- Promise.resolve()
77
- .then(function () { return fn(); })
78
- .then(function (idToken) {
79
- if (!idToken) return; // not a return from a redirect sign-in
80
- return exchange(idToken);
81
- })
82
- .then(function (outcome) {
83
- if (!outcome) return;
84
- if (outcome.ok && outcome.body && outcome.body.result && outcome.body.result.url) {
85
- window.location.href = outcome.body.result.url;
86
- return;
87
- }
88
- report("External sign-in failed (" + outcome.status + "): " + JSON.stringify(outcome.body));
89
- })
90
- .catch(function (err) {
91
- report("External sign-in error: " + String(err));
92
- });
93
- }
94
-
95
- Array.prototype.forEach.call(buttons, function (button) {
96
- button.addEventListener("click", function () {
97
- var getToken = getTokenName ? window[getTokenName] : undefined;
98
- if (typeof getToken !== "function") {
99
- report(
100
- "External sign-in is not configured: window." + getTokenName +
101
- " is missing. Check the broker's init script."
102
- );
103
- return;
104
- }
105
-
106
- button.disabled = true;
107
-
108
- Promise.resolve()
109
- .then(function () { return getToken(button.getAttribute("data-provider")); })
110
- .then(function (idToken) {
111
- if (!idToken) throw new Error("the configured getToken() resolved with no ID token");
112
- return exchange(idToken);
113
- })
114
- .then(function (outcome) {
115
- // mirrors the local flow: the server answers with the session redirect, and the
116
- // /logincallback page performs the code-for-tokens exchange
117
- if (outcome.ok && outcome.body && outcome.body.result && outcome.body.result.url) {
118
- window.location.href = outcome.body.result.url;
119
- return;
120
- }
121
-
122
- button.disabled = false;
123
- report("External sign-in failed (" + outcome.status + "): " + JSON.stringify(outcome.body));
124
- })
125
- .catch(function (err) {
126
- button.disabled = false;
127
- report("External sign-in error: " + String(err));
128
- });
129
- });
130
- });
131
-
132
- resume();
133
- });