@openlup/platform 0.15.0 → 0.16.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 (239) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +350 -3
  3. package/dist/identity/adminAuthBinding.d.ts +28 -0
  4. package/dist/identity/adminAuthBinding.js +66 -0
  5. package/dist/identity/adminAuthorization.d.ts +34 -0
  6. package/dist/identity/adminAuthorization.js +72 -0
  7. package/dist/identity/adminContracts.d.ts +70 -0
  8. package/dist/identity/adminContracts.js +43 -0
  9. package/dist/identity/adminMagicLinkHandler.d.ts +39 -0
  10. package/dist/identity/adminMagicLinkHandler.js +94 -0
  11. package/dist/identity/adminMeHandler.d.ts +15 -0
  12. package/dist/identity/adminMeHandler.js +49 -0
  13. package/dist/identity/adminPreflight.d.ts +16 -0
  14. package/dist/identity/adminPreflight.js +38 -0
  15. package/dist/identity/adminUserActionPorts.d.ts +31 -0
  16. package/dist/identity/adminUserActionPorts.js +51 -0
  17. package/dist/identity/adminUserHandlers.d.ts +38 -0
  18. package/dist/identity/adminUserHandlers.js +140 -0
  19. package/dist/identity/authVerifyUrl.d.ts +6 -0
  20. package/dist/identity/authVerifyUrl.js +54 -0
  21. package/dist/identity/contracts/contracts.d.ts +8 -0
  22. package/dist/identity/contracts/contracts.js +2 -0
  23. package/dist/identity/contracts/emailTrust.d.ts +3 -0
  24. package/dist/identity/contracts/emailTrust.js +4 -0
  25. package/dist/identity/contracts/index.d.ts +8 -0
  26. package/dist/identity/contracts/index.js +8 -0
  27. package/dist/identity/contracts/oidc.d.ts +3 -0
  28. package/dist/identity/contracts/oidc.js +9 -0
  29. package/dist/identity/contracts/operatorAuth.d.ts +35 -0
  30. package/dist/identity/contracts/operatorAuth.js +53 -0
  31. package/dist/identity/contracts/operatorInvitations.d.ts +37 -0
  32. package/dist/identity/contracts/operatorInvitations.js +1 -0
  33. package/dist/identity/contracts/ports.d.ts +22 -0
  34. package/dist/identity/contracts/ports.js +1 -0
  35. package/dist/identity/contracts/privacy.d.ts +62 -0
  36. package/dist/identity/contracts/privacy.js +99 -0
  37. package/dist/identity/contracts/providerList.d.ts +3 -0
  38. package/dist/identity/contracts/providerList.js +11 -0
  39. package/dist/identity/contracts/types.d.ts +16 -0
  40. package/dist/identity/contracts/types.js +4 -0
  41. package/dist/identity/contribution.d.ts +8 -0
  42. package/dist/identity/contribution.js +22 -0
  43. package/dist/identity/customerAuth.d.ts +8 -0
  44. package/dist/identity/customerAuth.js +1 -0
  45. package/dist/identity/customerAuthorization.d.ts +5 -0
  46. package/dist/identity/customerAuthorization.js +22 -0
  47. package/dist/identity/customerContracts.d.ts +42 -0
  48. package/dist/identity/customerContracts.js +43 -0
  49. package/dist/identity/customerIdentityBinding.d.ts +44 -0
  50. package/dist/identity/customerIdentityBinding.js +60 -0
  51. package/dist/identity/customerIdentityVerifier.d.ts +8 -0
  52. package/dist/identity/customerIdentityVerifier.js +101 -0
  53. package/dist/identity/customerMagicLinkHandler.d.ts +38 -0
  54. package/dist/identity/customerMagicLinkHandler.js +115 -0
  55. package/dist/identity/customerMeHandler.d.ts +11 -0
  56. package/dist/identity/customerMeHandler.js +46 -0
  57. package/dist/identity/customerPorts.d.ts +4 -0
  58. package/dist/identity/customerPorts.js +1 -0
  59. package/dist/identity/customerSessionBinding.d.ts +38 -0
  60. package/dist/identity/customerSessionBinding.js +80 -0
  61. package/dist/identity/customerSessionIssuer.d.ts +10 -0
  62. package/dist/identity/customerSessionIssuer.js +57 -0
  63. package/dist/identity/customerVerifyOtpHandler.d.ts +8 -0
  64. package/dist/identity/customerVerifyOtpHandler.js +41 -0
  65. package/dist/identity/directOperatorInvitationStore.d.ts +19 -0
  66. package/dist/identity/directOperatorInvitationStore.js +193 -0
  67. package/dist/identity/emailTrustPolicy.d.ts +14 -0
  68. package/dist/identity/emailTrustPolicy.js +16 -0
  69. package/dist/identity/identityPersonalDataContributor.d.ts +7 -0
  70. package/dist/identity/identityPersonalDataContributor.js +46 -0
  71. package/dist/identity/identityReadiness.d.ts +10 -0
  72. package/dist/identity/identityReadiness.js +25 -0
  73. package/dist/identity/index.d.ts +67 -0
  74. package/dist/identity/index.js +66 -0
  75. package/dist/identity/inviteAdminUserUseCase.d.ts +89 -0
  76. package/dist/identity/inviteAdminUserUseCase.js +75 -0
  77. package/dist/identity/jwtLibrary.d.ts +54 -0
  78. package/dist/identity/jwtLibrary.js +1 -0
  79. package/dist/identity/machineActorWriteFence.d.ts +4 -0
  80. package/dist/identity/machineActorWriteFence.js +13 -0
  81. package/dist/identity/magicLinkPorts.d.ts +28 -0
  82. package/dist/identity/magicLinkPorts.js +1 -0
  83. package/dist/identity/managedAccountLinkStore.d.ts +2 -0
  84. package/dist/identity/managedAccountLinkStore.js +93 -0
  85. package/dist/identity/managedAdminAuthVerifier.d.ts +7 -0
  86. package/dist/identity/managedAdminAuthVerifier.js +27 -0
  87. package/dist/identity/managedAdminUserGateways.d.ts +123 -0
  88. package/dist/identity/managedAdminUserGateways.js +127 -0
  89. package/dist/identity/managedClient.d.ts +90 -0
  90. package/dist/identity/managedClient.js +10 -0
  91. package/dist/identity/managedClientAuthLink.d.ts +3 -0
  92. package/dist/identity/managedClientAuthLink.js +115 -0
  93. package/dist/identity/managedCustomerMe.d.ts +13 -0
  94. package/dist/identity/managedCustomerMe.js +30 -0
  95. package/dist/identity/managedEmailTrustPolicy.d.ts +11 -0
  96. package/dist/identity/managedEmailTrustPolicy.js +105 -0
  97. package/dist/identity/managedIdentityVerifier.d.ts +2 -0
  98. package/dist/identity/managedIdentityVerifier.js +16 -0
  99. package/dist/identity/managedPrivacy.d.ts +4 -0
  100. package/dist/identity/managedPrivacy.js +39 -0
  101. package/dist/identity/messages.d.ts +29 -0
  102. package/dist/identity/messages.js +39 -0
  103. package/dist/identity/oidcIdentityVerifier.d.ts +45 -0
  104. package/dist/identity/oidcIdentityVerifier.js +309 -0
  105. package/dist/identity/oidcPrincipal.d.ts +2 -0
  106. package/dist/identity/oidcPrincipal.js +10 -0
  107. package/dist/identity/operatorAdminAuth.d.ts +6 -0
  108. package/dist/identity/operatorAdminAuth.js +13 -0
  109. package/dist/identity/operatorAuthHandlers.d.ts +18 -0
  110. package/dist/identity/operatorAuthHandlers.js +71 -0
  111. package/dist/identity/operatorIdentityVerifier.d.ts +8 -0
  112. package/dist/identity/operatorIdentityVerifier.js +19 -0
  113. package/dist/identity/operatorInvitationLifecycle.d.ts +7 -0
  114. package/dist/identity/operatorInvitationLifecycle.js +15 -0
  115. package/dist/identity/operatorInvitationPorts.d.ts +31 -0
  116. package/dist/identity/operatorInvitationPorts.js +1 -0
  117. package/dist/identity/operatorPorts.d.ts +37 -0
  118. package/dist/identity/operatorPorts.js +1 -0
  119. package/dist/identity/operatorSession.d.ts +13 -0
  120. package/dist/identity/operatorSession.js +31 -0
  121. package/dist/identity/operatorTokenAdminAuth.d.ts +15 -0
  122. package/dist/identity/operatorTokenAdminAuth.js +50 -0
  123. package/dist/identity/personalDataRegistry.d.ts +4 -0
  124. package/dist/identity/personalDataRegistry.js +11 -0
  125. package/dist/identity/platformAdminAuth.d.ts +15 -0
  126. package/dist/identity/platformAdminAuth.js +1 -0
  127. package/dist/identity/ports.d.ts +127 -0
  128. package/dist/identity/ports.js +38 -0
  129. package/dist/identity/postgresAccountLinkStore.d.ts +7 -0
  130. package/dist/identity/postgresAccountLinkStore.js +52 -0
  131. package/dist/identity/postgresCustomerMe.d.ts +3 -0
  132. package/dist/identity/postgresCustomerMe.js +21 -0
  133. package/dist/identity/postgresCustomerRecovery.d.ts +11 -0
  134. package/dist/identity/postgresCustomerRecovery.js +57 -0
  135. package/dist/identity/postgresOperatorIdentity.d.ts +5 -0
  136. package/dist/identity/postgresOperatorIdentity.js +137 -0
  137. package/dist/identity/postgresPrivacy.d.ts +7 -0
  138. package/dist/identity/postgresPrivacy.js +126 -0
  139. package/dist/identity/privacyHandlers.d.ts +10 -0
  140. package/dist/identity/privacyHandlers.js +35 -0
  141. package/dist/identity/privacyPorts.d.ts +72 -0
  142. package/dist/identity/privacyPorts.js +8 -0
  143. package/dist/identity/privacyUseCases.d.ts +5 -0
  144. package/dist/identity/privacyUseCases.js +55 -0
  145. package/dist/identity/reconcileAccountForPrincipal.d.ts +20 -0
  146. package/dist/identity/reconcileAccountForPrincipal.js +66 -0
  147. package/dist/identity/reconcileAccountHandler.d.ts +11 -0
  148. package/dist/identity/reconcileAccountHandler.js +30 -0
  149. package/dist/identity/removeAdminUserUseCase.d.ts +31 -0
  150. package/dist/identity/removeAdminUserUseCase.js +60 -0
  151. package/dist/identity/response.d.ts +3 -0
  152. package/dist/identity/response.js +2 -0
  153. package/dist/identity/sql.d.ts +44 -0
  154. package/dist/identity/sql.js +10 -0
  155. package/package.json +12 -2
  156. package/release-gates.json +22 -0
  157. package/sql/20260810180001_self_host_actor_auth.sql +40 -0
  158. package/sql/20260810204057_customer_identity_read.sql +31 -0
  159. package/sql/20260814090000_customer_selfservice_recovery.sql +477 -0
  160. package/sql/20260901143000_admin_membership_authority_foundation.sql +234 -0
  161. package/sql/20261018120000_identity_operator_invitations.sql +42 -0
  162. package/sql/20261018180000_identity_operator_challenges.sql +56 -0
  163. package/sql/20261018190000_identity_privacy_erasures.sql +15 -0
  164. package/src/identity/adminAuthBinding.ts +76 -0
  165. package/src/identity/adminAuthorization.ts +106 -0
  166. package/src/identity/adminContracts.ts +52 -0
  167. package/src/identity/adminMagicLinkHandler.ts +132 -0
  168. package/src/identity/adminMeHandler.ts +64 -0
  169. package/src/identity/adminPreflight.ts +46 -0
  170. package/src/identity/adminUserActionPorts.ts +78 -0
  171. package/src/identity/adminUserHandlers.ts +174 -0
  172. package/src/identity/authVerifyUrl.ts +56 -0
  173. package/src/identity/contracts/contracts.ts +15 -0
  174. package/src/identity/contracts/emailTrust.ts +5 -0
  175. package/src/identity/contracts/index.ts +8 -0
  176. package/src/identity/contracts/oidc.ts +10 -0
  177. package/src/identity/contracts/operatorAuth.ts +61 -0
  178. package/src/identity/contracts/operatorInvitations.ts +32 -0
  179. package/src/identity/contracts/ports.ts +25 -0
  180. package/src/identity/contracts/privacy.ts +86 -0
  181. package/src/identity/contracts/providerList.ts +13 -0
  182. package/src/identity/contracts/types.ts +25 -0
  183. package/src/identity/contribution.ts +29 -0
  184. package/src/identity/customerAuth.ts +3 -0
  185. package/src/identity/customerAuthorization.ts +38 -0
  186. package/src/identity/customerContracts.ts +52 -0
  187. package/src/identity/customerIdentityBinding.ts +125 -0
  188. package/src/identity/customerIdentityVerifier.ts +141 -0
  189. package/src/identity/customerMagicLinkHandler.ts +171 -0
  190. package/src/identity/customerMeHandler.ts +64 -0
  191. package/src/identity/customerPorts.ts +2 -0
  192. package/src/identity/customerSessionBinding.ts +114 -0
  193. package/src/identity/customerSessionIssuer.ts +71 -0
  194. package/src/identity/customerVerifyOtpHandler.ts +44 -0
  195. package/src/identity/directOperatorInvitationStore.ts +178 -0
  196. package/src/identity/emailTrustPolicy.ts +16 -0
  197. package/src/identity/identityPersonalDataContributor.ts +48 -0
  198. package/src/identity/identityReadiness.ts +26 -0
  199. package/src/identity/index.ts +69 -0
  200. package/src/identity/inviteAdminUserUseCase.ts +134 -0
  201. package/src/identity/jwtLibrary.ts +24 -0
  202. package/src/identity/machineActorWriteFence.ts +19 -0
  203. package/src/identity/magicLinkPorts.ts +7 -0
  204. package/src/identity/managedAccountLinkStore.ts +105 -0
  205. package/src/identity/managedAdminAuthVerifier.ts +40 -0
  206. package/src/identity/managedAdminUserGateways.ts +164 -0
  207. package/src/identity/managedClient.ts +58 -0
  208. package/src/identity/managedClientAuthLink.ts +120 -0
  209. package/src/identity/managedCustomerMe.ts +52 -0
  210. package/src/identity/managedEmailTrustPolicy.ts +90 -0
  211. package/src/identity/managedIdentityVerifier.ts +20 -0
  212. package/src/identity/managedPrivacy.ts +37 -0
  213. package/src/identity/messages.ts +41 -0
  214. package/src/identity/oidcIdentityVerifier.ts +229 -0
  215. package/src/identity/oidcPrincipal.ts +10 -0
  216. package/src/identity/operatorAdminAuth.ts +14 -0
  217. package/src/identity/operatorAuthHandlers.ts +52 -0
  218. package/src/identity/operatorIdentityVerifier.ts +19 -0
  219. package/src/identity/operatorInvitationLifecycle.ts +14 -0
  220. package/src/identity/operatorInvitationPorts.ts +11 -0
  221. package/src/identity/operatorPorts.ts +11 -0
  222. package/src/identity/operatorSession.ts +30 -0
  223. package/src/identity/operatorTokenAdminAuth.ts +79 -0
  224. package/src/identity/personalDataRegistry.ts +8 -0
  225. package/src/identity/platformAdminAuth.ts +7 -0
  226. package/src/identity/ports.ts +158 -0
  227. package/src/identity/postgresAccountLinkStore.ts +49 -0
  228. package/src/identity/postgresCustomerMe.ts +33 -0
  229. package/src/identity/postgresCustomerRecovery.ts +72 -0
  230. package/src/identity/postgresOperatorIdentity.ts +123 -0
  231. package/src/identity/postgresPrivacy.ts +117 -0
  232. package/src/identity/privacyHandlers.ts +33 -0
  233. package/src/identity/privacyPorts.ts +52 -0
  234. package/src/identity/privacyUseCases.ts +48 -0
  235. package/src/identity/reconcileAccountForPrincipal.ts +99 -0
  236. package/src/identity/reconcileAccountHandler.ts +36 -0
  237. package/src/identity/removeAdminUserUseCase.ts +85 -0
  238. package/src/identity/response.ts +3 -0
  239. package/src/identity/sql.ts +10 -0
package/CHANGELOG.md CHANGED
@@ -8,6 +8,46 @@ SemVer promise.
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.16.0]
12
+
13
+ - Publishable on the npm `latest` dist-tag as `0.16.0`, from tag
14
+ `openlup-platform-v0.16.0`.
15
+
16
+ - Add the experimental identity capability at `./identity` and browser-safe
17
+ `./identity/contracts`: role-based authorization, actor-scoped profiles,
18
+ bounded normalized contact matching, unconfirmed soft accounts with explicit
19
+ email-trust policies, and configured-origin magic-link redirect resolution.
20
+ - Add operator invitations with transactional pending acceptance, expiry,
21
+ cancellation and revoked re-invitation for direct stores, and immediate active
22
+ membership with repeat/concurrent recovery for managed stores. Direct operator
23
+ login uses single-use email challenges, operator-audience sessions, live
24
+ membership authorization, explicit first-administrator bootstrap and bounded
25
+ challenge pruning. An opt-in OIDC access-token verifier provides pinned issuer
26
+ discovery, bounded rotating JWKS, strict claim validation and deterministic
27
+ issuer/subject principals for direct composition.
28
+ - Add versioned personal-data contributors, identity export and transactional
29
+ direct erasure with contributor vetoes, challenge/invitation cleanup,
30
+ pseudonymization, guarded operator revocation and idempotent receipts. Managed
31
+ export reports incomplete coverage; managed erasure refuses with
32
+ `MANAGED_PRIVACY_ERASURE_UNAVAILABLE` without mutation. Issued tokens may remain
33
+ valid until expiry.
34
+ - Add seven byte-identical identity SQL projections and host-selected module
35
+ schema readiness. The projections retain canonical migration identities and
36
+ positions; they are not a standalone installation chain.
37
+
38
+ Migration: identity adoption is opt-in; upgrade the complete package set together
39
+ for the exact `@openlup/core` `0.16.0` peer pin. Supply the selected bundle's schema
40
+ inventory, clients and delivery bindings, an explicit email-trust policy, exact
41
+ redirect origins, a distinct operator audience and a deployment policy for
42
+ admin, operator and privacy routes. Managed soft-account provisioning requires
43
+ an email-trust envelope with automatic confirmation disabled and all enabled
44
+ non-email providers declared email-verifying. Install the complete direct
45
+ catalogue through `20261018190000_identity_privacy_erasures` before enabling
46
+ identity; never reapply projections to an existing canonical history. Managed
47
+ adopters need their committed chain's
48
+ `20261018160000_identity_service_role_capabilities.sql` forward for contact linking
49
+ and operator membership capabilities, and must supply their own erasure path.
50
+
11
51
  ## [0.15.0]
12
52
 
13
53
  - Publishable on the npm `latest` dist-tag as `0.15.0`, from tag
package/README.md CHANGED
@@ -6,7 +6,7 @@ It holds the runnable server substrate an OpenLup application composes: the Node
6
6
 
7
7
  ## Package surface
8
8
 
9
- `release-gates.json` declares kind `rail`: this foundation provides runtime infrastructure over core ports, matching the architecture's rail responsibility. Its nine experimental entries each bind a declaration snapshot and package-owned smoke tests. The API checker reads this same inventory.
9
+ `release-gates.json` declares kind `rail`: this foundation provides runtime infrastructure over core ports, matching the architecture's rail responsibility. Its eleven experimental entries each bind a declaration snapshot and package-owned smoke tests. The API checker reads this same inventory.
10
10
 
11
11
  | Export | Contents |
12
12
  | --- | --- |
@@ -19,6 +19,8 @@ It holds the runnable server substrate an OpenLup application composes: the Node
19
19
  | `./job-ledger` | The job-run ledger port, its PostgreSQL and managed (Supabase) adapters, the managed v2/v3 compatibility calls and the location of its SQL |
20
20
  | `./kernel` | The bundle identifiers, descriptors and readiness |
21
21
  | `./composition` | `createBundleComposer`, the Node HTTP binding helpers and `createNodeHost` |
22
+ | `./identity` | Experimental capability: identity engine, authorization, profile readers, session adapters and BFF factories |
23
+ | `./identity/contracts` | Experimental capability: browser-safe customer auth port, value types and provider parser |
22
24
 
23
25
  ## Scheduled jobs
24
26
 
@@ -83,7 +85,32 @@ failed HEAD; use an upload or list operation to observe an S3 loading refusal.
83
85
 
84
86
  This package's tests are part of the repository's required test selection; from this directory, `npm test` runs them alone. The tests rewrite the originating application's characterization with neutral names and synthetic data, and a boundary test refuses any environment read or provider import in the package source.
85
87
 
86
- `npm run api:check` compares each of the nine declaration entry graphs with the
88
+ The module-boundary proof permits one optional `./<module>/contracts` export
89
+ only when that module declares `contracts: true` in `PLATFORM_MODULE_GRAPH` in
90
+ [`eslint.config.js`](../../eslint.config.js). Its `types`, `import` and `default`
91
+ targets follow the module entry shape at `dist/<module>/contracts/index`.
92
+ Contracts files may import only their own contracts subtree through canonical
93
+ relative `.js` paths and exact public `@openlup/core` entries. Both ESLint and
94
+ [`packageBoundary.test.ts`](test/packageBoundary.test.ts) enforce this allowlist
95
+ for static imports and re-exports (including types) and literal `import()`;
96
+ they refuse non-literal `import()` targets. Both checks reserve the identifier
97
+ names `require`, `module`, `exports`, `process`, `globalThis`, `global`,
98
+ `__dirname`, `__filename` and `Buffer` in every value and type position,
99
+ including local and property identifiers, and refuse every use of `import.meta`.
100
+ This rejects loader aliases and wrapped calls regardless of the load target.
101
+ The existing non-literal `require` member-call guard also remains, including
102
+ computed property calls.
103
+ The package test additionally requires every file in the contracts subtree to
104
+ be a scanned `.ts` file, refuses triple-slash type and path references and all
105
+ meta-properties (also `new.target`), and retains member-call `require` detection
106
+ outside contracts. Identity declares this entry; synthetic graphs also exercise these checks.
107
+
108
+
109
+ The job-run ledger SQL asset test verifies a readable, nonempty file within the
110
+ package SQL directory. Its SQL parity tests bind the actual adapter calls to the
111
+ shipped routine signatures; the asset's explanatory header may be edited freely.
112
+
113
+ `npm run api:check` compares each of the eleven declaration entry graphs with the
87
114
  committed `api/*.api.md` reports. After building, deliberately regenerate them
88
115
  with `node --experimental-strip-types ./scripts/api-contract.ts --update` from
89
116
  this package, and review the declaration changes.
@@ -120,7 +147,327 @@ phase redirects npm to an empty temporary cache.
120
147
 
121
148
  The composition declarations describe the injected Supabase factory structurally;
122
149
  they do not import the data entry or its PostgreSQL types. The cold proof still
123
- requires all five nonadapter entries to import in fresh processes and compile
150
+ requires all six nonadapter entries (including `./identity/contracts`) to import in fresh processes and compile
124
151
  in both resolution modes with all three optional peers absent.
125
152
 
126
153
  <!-- openlup-doc-impact {"unit":"platform-substrate","digest":"sha256-00994d288cfec0c8dc0ae9aeae2ff542e2e9af2fedcb4dd2dfeb6c99523be92d","reason":"The manifest moves to the 0.15.0 set version with the exact @openlup/core 0.15.0 peer pin. The package surface, settings and verification described here are unchanged by this preparation delta."} -->
154
+
155
+ ## Identity import candidate
156
+
157
+ The OIDC API adds `createOidcIdentityVerifier`,
158
+ `deriveOidcPrincipalId`, `createPostgresAccountLinkStore` and
159
+ `identityOidcReadiness` from `@openlup/platform/identity`, which also exports
160
+ `OIDC_FAILURE_CODES` and `OidcFailureCode` for hosts. The browser-shared
161
+ `@openlup/platform/identity/contracts` entry excludes OIDC refusals.
162
+ Inject the host's selected JWT library through `IdentityJwtLibraryLoader`.
163
+ Discovery and rotating keys load only on verification or readiness. The opt-in
164
+ direct composition uses normal reconcile with an explicit email-trust policy,
165
+ authenticated actor reads and live operator membership. Managed storage requires
166
+ native federation sessions and refuses raw upstream-token composition. Run
167
+ `node tests/postgres/runOidcIdentityConformance.mjs` from the repository root with
168
+ its cached pinned issuer and local prerequisites; the [OIDC recipe](../../docs/platform/IDENTITY.md#real-issuer-oidc-recipe)
169
+ owns timing, refusal, session and certification boundaries. There is no schema or
170
+ default login flow change; existing static session verification and default
171
+ reference/browser flows retain their runtime behaviour.
172
+
173
+ The existing `IdentityJwtLibrary.jwtVerify` contract widens with optional
174
+ `currentDate?: Date` and `clockTolerance?: number` verify options and now returns
175
+ `{ payload: IdentityJwtClaims }`, whose claims interface includes a string index
176
+ signature. **Migration:** hosts implementing or typing their own
177
+ `IdentityJwtLibrary` or `IdentityJwtLibraryLoader` must accept the optional verify
178
+ options and return claims as `IdentityJwtClaims`.
179
+
180
+ The direct operator API adds `createPostgresOperatorIdentityStore`,
181
+ `createOperatorSessionService`, `createOperatorIdentityVerifier`,
182
+ `createOperatorAdminAuth` and `createOperatorAuthHandlers` to `./identity`.
183
+ `./identity/contracts` exposes strict operator challenge/session schemas and
184
+ `OperatorBrowserAuthPort` without a server or provider import. Challenge delivery
185
+ and session signing use the existing structural ports. Operator handlers send
186
+ the padded generic acceptance before awaiting mailbox delivery, keeping delivery
187
+ latency out of the response. Custom HTTP composition uses the session service's
188
+ optional acceptance callback for the same ordering. Restoration reads preserve
189
+ in-flight browser redemption; explicit sign-out still cancels it. Active operator
190
+ login needs no pending invitation and preserves membership and invitation history. The new store's public
191
+ signature exposes no driver types and loads its optional driver only on use.
192
+
193
+ Apply the complete direct catalogue through position 68 before enabling human
194
+ login; `sql/20261018180000_identity_operator_challenges.sql` is its exact projection.
195
+ Configure a distinct operator audience and an adopter deployment route policy:
196
+ the public policy refuses all mounted operator routes, including `me`, with
197
+ `adopter_policy_required` before input or authentication-binding construction. The reference dispatcher accepts a
198
+ session-binding factory through `createReferenceBffDispatch`; use it to compose
199
+ separate operator delivery. Caller-supplied operator handlers retain the same
200
+ policy boundary. The browser hook consumes guarded auth-port notifications rather
201
+ than signing out from a stale post-redemption check. Use the
202
+ explicit bootstrap/prune commands in the [identity guide](../../docs/platform/IDENTITY.md#direct-human-login).
203
+ The bounded reference browser builds do not mount the admin shell; application
204
+ composition must mount the provided pages and hook. First redemption activates the existing invitation and consumes the challenge in
205
+ one transaction. Live membership, not a JWT role, authorizes each request. The
206
+ cold consumer includes both identity entries and the new adapter's missing-peer
207
+ refusal; real concurrency and upgrade proof needs the complete PostgreSQL chain.
208
+
209
+ Creating a client/contact records commerce contact data, not an authentication
210
+ identity. Creating an auth user provisions a principal. Neither a typed address
211
+ nor a soft-account link proves mailbox ownership; reconcile may create a contact
212
+ for an existing authenticated principal without creating that principal.
213
+
214
+ Customer soft-account provisioning now creates unconfirmed auth users
215
+ (`email_confirm:false`). The soft-account linker retains create-first lookup,
216
+ normalized duplicate recovery and conditional linking. Checkout and paid-order
217
+ retry are adopter composition that must call the linker. Failed links retain
218
+ the provisioned identity for retry. Customer magic links keep
219
+ `shouldCreateUser:false`: captured mailbox proof confirms that existing user;
220
+ unknown addresses cannot sign themselves up through this path.
221
+
222
+ The managed link store requires an injected `emailTrustPolicy`, assessed before
223
+ creation or linking an existing identity by email. Unsafe or unavailable settings
224
+ return a non-fatal soft-account refusal (`EMAIL_TRUST_ENVELOPE_REFUSED` or
225
+ `EMAIL_TRUST_SETTINGS_UNAVAILABLE`) without creating an identity or link. Matching
226
+ existing links retain their replay behaviour. The reference adapter binds managed
227
+ settings assessment regardless of the selected bundle.
228
+
229
+ **Migration:** soft-account provisioning requires a trusted envelope: automatic
230
+ email confirmation disabled and every enabled non-email provider explicitly
231
+ declared email-verifying. Automatic signup can otherwise confirm an unconfirmed
232
+ user and issue a session to someone who merely knows the contact's address.
233
+ Pass the policy to `createSupabaseClientAuthLinkStore(client, emailTrustPolicy)`;
234
+ custom `ClientAuthLinkStore` implementations must expose `emailTrustPolicy`.
235
+ An adopter may explicitly bind `createVerifierResultOnlyEmailTrustPolicy()` when
236
+ its own trust boundary supplies the guarantee. Ensure the selected Auth installation can deliver and verify the
237
+ first-login link for an existing unconfirmed user. Run the documented joint local conformance
238
+ command after building core/platform. Existing identities, contact links,
239
+ subscription references and migration history are not rewritten.
240
+
241
+ Managed verification now requires the confirmation timestamp. Email-derived
242
+ reconcile requires an injected `emailTrustPolicy`. Managed hosts share
243
+ `createManagedEmailTrustPolicy` with `identityEmailTrustReadiness`; it reports
244
+ module `identity` using core's existing codes. Hosts retaining verifier-only
245
+ admission explicitly bind `createVerifierResultOnlyEmailTrustPolicy()`.
246
+ See the [identity policy and migration](../../docs/platform/IDENTITY.md#responsibility-and-composition)
247
+ for the empty provider allowlist, cache/deadline, 403/503 failures and the opt-in
248
+ `node tests/postgres/runIdentityEnvelopeConformance.mjs --phase email-trust` and
249
+ `node tests/postgres/runIdentityEnvelopeConformance.mjs --phase joint` prerequisites
250
+ and conformance scope. Both phases replay the committed managed chain, including
251
+ the identity capabilities forward, and prove association under the shipped managed
252
+ reference grants.
253
+ Construction and imports perform no settings read or SDK initialization.
254
+
255
+
256
+ The `./identity` server entry imports the existing identity engine, authorization,
257
+ profile readers, session adapters and BFF factories into one capability. Its
258
+ `./identity/contracts` entry is declared browser-safe and currently exposes the
259
+ customer auth port, value types and provider parser. Runtime-schema extraction
260
+ is pending the contracts-boundary choice described in the
261
+ [identity owner page](../../docs/platform/IDENTITY.md). Both entries remain an
262
+ unpublished development-preview import candidate.
263
+
264
+ Application composition supplies SDK clients/loaders, feature admission, redirect
265
+ policy, rate limiting, messages, sender and deployment URLs. Factories use the
266
+ foundation BFF envelope and accept the application's observed request-ID reader.
267
+ The module depends only on the declared foundation entries, without changing the
268
+ artifact's rail kind. Its schema contribution requires a host-selected inventory;
269
+ its seven SQL files are verbatim projections at canonical positions 11, 12, 29,
270
+ 60, 67, 68 and 69, not an independent migration chain. The owner page maps the characterization
271
+ witnesses and records the remaining evidence.
272
+
273
+ Identity authorizes stored operator roles only when they are `admin` or
274
+ `distributor`; null and unknown values return `FORBIDDEN` (HTTP 403). The reference
275
+ admin-profile reader reports those rows as non-admin, and admin magic links do
276
+ not send for them while retaining the generic accepted response, padding and
277
+ quota. Adopters needing legacy role mapping must do it in their own adapter
278
+ before passing the role to the package; there is no package fallback option.
279
+
280
+ Both managed contact stores match normalized addresses case-insensitively,
281
+ including mixed-case stored contacts. Literal matching uses an anchored, escaped
282
+ `imatch` database prefilter plus an exact `email.trim().toLowerCase()` comparison
283
+ with the normalized input. Unicode regex folding alone cannot establish identity.
284
+ Both lookups select email and fetch at most ten candidates. Soft linking selects
285
+ the oldest accepted contact; reconciliation requires a single accepted contact
286
+ and throws the existing multiple-row error if several remain. A match beyond the
287
+ candidate bound is not selected. Injected structural query clients must implement
288
+ `filter(column, "imatch", value)` and the bounded array query. The direct customer
289
+ challenge already compares `lower(email)` to normalized input; no migration is
290
+ needed.
291
+
292
+ Magic-link factories default to the shared strict origin resolver. Pass
293
+ `redirectOrigins: ["https://example.com", "https://secondary.example.com:8443"]`;
294
+ the first configured origin builds the callback and every entry must be an exact
295
+ HTTP(S) origin, without credentials, a path, query or fragment (a root trailing
296
+ slash is accepted). Request headers never authorize an origin. Missing or invalid
297
+ configuration returns BFF `UPSTREAM_UNAVAILABLE` (503), with details reason
298
+ `magic_link_origin_not_configured`, before provider access. Customer `returnTo`
299
+ is normalized to a same-origin relative path; unsafe targets are omitted for the
300
+ callback's default landing page. An adopter needing its existing policy can keep
301
+ passing `resolveOrigin`; that explicit injection overrides the default. See the
302
+ [identity redirect contract](../../docs/platform/IDENTITY.md#magic-link-redirect-policy)
303
+ for reference configuration and migration.
304
+
305
+
306
+ ### Operator invitations
307
+
308
+ `identity/contracts` exposes distinct direct pending-invitation and managed
309
+ active-membership results. Matching runtime schemas remain in the server entry.
310
+ The admin-action port returns `OperatorInviteResult`, a union of those results.
311
+
312
+ `createDirectOperatorInvitationStore` provides the new pending, active, expired and
313
+ revoked lifecycle in its trusted PostgreSQL transaction lane, including ordered
314
+ membership locks and atomic membership/audit writes. Direct callers inject the
315
+ store and a parsed TTL. `createDirectOperatorIdentityDirectory` commits principal
316
+ creation/reuse separately. Apply the complete direct catalogue through position
317
+ 67; the byte-identical package projection is for inspection and composition, not
318
+ a standalone fresh chain. Direct human acceptance is a trusted command,
319
+ unmounted from machine authentication.
320
+
321
+ Managed hosts use `createInviteAdminUserGateway().activateMembership` in
322
+ `runInviteAdminUserUseCase`. Insertion immediately creates active `admin_users`
323
+ membership with invitation provenance; it omits `is_machine_actor` and relies on
324
+ the database default false. The result carries principal ID, role, active state
325
+ and `MEMBERSHIP_CREATED` or `ALREADY_ACTIVE`, without pending timestamps or an
326
+ invitation ID. Identical repeats and concurrent insert losers return the existing
327
+ membership without a second notification. Role differences conflict; revoked
328
+ members refuse with `MANAGED_REINVITE_UNSUPPORTED`. Failures retain identities
329
+ for retry, including after notification failure. No Auth metadata store,
330
+ first-entry acceptance, expiry or compensation is used. Magic-link eligibility
331
+ requires active membership and a known role. Authorization, removal and admin
332
+ `me` retain their actor bindings without a service key for lifecycle state.
333
+
334
+ **Migration:** direct hosts can adopt the new pending lifecycle by applying
335
+ `20261018120000_identity_operator_invitations` after the existing direct catalogue
336
+ and composing the store, trusted human acceptance and parsed TTL. Existing
337
+ memberships are preserved. Managed immediate activation is retained; managed
338
+ consumers must now parse the structured active result and its
339
+ `MEMBERSHIP_CREATED`/`ALREADY_ACTIVE` codes instead of message-only success.
340
+ Duplicates return existing membership rather than `ALREADY_ADDED`, and
341
+ notification failure returns 503 `INVITATION_NOTIFICATION_FAILED` while keeping
342
+ membership active. Managed pending/expiry remains a compatibility gap requiring
343
+ a separate transactional store and reviewed forward. No managed SQL, RPC or SDK
344
+ dependency is added. See the
345
+ [identity lifecycle owner](../../docs/platform/IDENTITY.md#operator-invitation-lifecycle).
346
+
347
+ The managed chain's identity capabilities forward
348
+ `20261018160000_identity_service_role_capabilities.sql` grants `service_role`
349
+ SELECT(email) and INSERT(id, email, role, membership_state, membership_provenance,
350
+ membership_accepted_at) on `admin_users`.
351
+ The opt-in managed conformance replays the complete committed chain with ambient
352
+ default ACLs removed and adds no grant. It proves immediate activation,
353
+ repeat/concurrent recovery and revoked-member refusal under the shipped grants.
354
+ It does not establish managed/direct lifecycle parity.
355
+
356
+ With a fresh local managed stack running, export its API URL, service key and
357
+ PostgreSQL owner (`supabase_admin`) connection URL as `OPENLUP_MANAGED_CONFORMANCE_URL`,
358
+ `OPENLUP_MANAGED_CONFORMANCE_SERVICE_KEY` and
359
+ `OPENLUP_MANAGED_CONFORMANCE_DATABASE_URL`, then run from the repository root:
360
+
361
+ ```sh
362
+ npm --workspace @openlup/platform run build
363
+ node --import tsx tests/postgres/operatorInvitationManaged.conformance.ts
364
+ ```
365
+
366
+ The module refuses non-loopback endpoints, an already-installed public schema,
367
+ and existing synthetic fixture identities. It retains synthetic identities;
368
+ discard the disposable stack after the run. Its database owner connection must
369
+ be able to replay the committed prerequisites, baseline and ordered forwards.
370
+
371
+ ## Personal data
372
+
373
+ The experimental identity entry exposes `createPersonalDataContributorRegistry`,
374
+ `createIdentityPersonalDataContributor`, `createPrivacyOperations`,
375
+ `exportPersonalData`, `erasePersonalData`, `createPrivacyExportHandler` and
376
+ `createPrivacyEraseHandler`. Browser requests, versioned contributor documents and
377
+ receipts come from `@openlup/platform/identity/contracts`. Register every required
378
+ contributor explicitly, with its owned fields, assessment, erase/retain operation
379
+ and remote/retention obligations. Missing required owners refuse erasure; export
380
+ reports missing coverage. This capability erases identity-owned data only.
381
+
382
+ Direct hosts compose `createPostgresPrivacyUnitOfWork` and
383
+ `createPostgresPrivacyStore` with the identity contributor and their domain vetoes
384
+ using the same executor. The reference subscriptions contributor holds a relation
385
+ lock through commit, refusing active and paused subscriptions without changing
386
+ them. `IdentityPrivacyPolicy.retainedContactFields` names explicit retention
387
+ owners for populated opaque columns; unknown ownership refuses. The reference
388
+ retains lifecycle/acquisition fields, and refuses nonempty metadata or external
389
+ references until an owner declares their disposition.
390
+
391
+ Migration: apply the complete direct catalogue including
392
+ `20261018190000_identity_privacy_erasures` before using privacy or the updated
393
+ customer challenge store. The forward appends one receipt table at position 69
394
+ without grants or stored functions. Direct erasure pseudonymizes identity-owned
395
+ fields, deletes challenges and outstanding invitations, uses guarded membership
396
+ revocation, clears only the selected contact's direct principal link, and commits
397
+ an idempotent audit receipt atomically. Contact IDs and managed auth links never
398
+ change. Failed writes roll back. Retained audit references are pseudonymous, not
399
+ an assertion of anonymization. Already-issued tokens may remain valid until expiry.
400
+ Customer challenge issuance and redemption reject a receipt for either the
401
+ contact or principal under the same transaction-held challenge relation lock as
402
+ erasure, including late challenges inserted after cleanup. Hosts must use the
403
+ package adapters; calling the retained raw challenge SQL functions directly
404
+ bypasses this erasure receipt fence.
405
+
406
+ Managed hosts compose `createManagedPrivacyStore` with their structural service
407
+ client for export. Coverage explicitly excludes inaccessible country and
408
+ identity history/receipt fields. Managed erasure refuses with
409
+ `MANAGED_PRIVACY_ERASURE_UNAVAILABLE`: a managed adopter must provide its own
410
+ erasure path. The committed grants and structural client cannot provide the
411
+ required mutations and atomic receipt. This change adds no managed forward or
412
+ erasure grants. Provider identity is never deleted; any future composed provider
413
+ erasure must disable it after committed local success. The managed refusal here
414
+ occurs before reaching any provider mutation.
415
+
416
+ The reference mounts authenticated human-admin export/erase POSTs and an Admin
417
+ Settings readback panel. Direct and managed mounts require the adopter deployment
418
+ policy under admin mutation risk; the public default returns
419
+ `adopter_policy_required` before body/query reads, and direct mounts also refuse
420
+ before authentication or privacy binding construction. The shipped dispatcher mounts
421
+ both routes for managed bundles even when its caller supplies no routes. After admission,
422
+ exports and receipts stay in memory with no-store
423
+ responses. The maintenance `prune-challenges` command prunes separate bounded
424
+ operator/customer batches. See [identity privacy](../../docs/platform/IDENTITY.md#identity-personal-data)
425
+ for refusals, token limits and retained obligations.
426
+
427
+ The complete direct conformance is included in
428
+ `ai-resource-gate run --wait openlup:coverage -- npx vitest run tests/postgres/operatorIdentityUpgrade.test.ts`.
429
+ For managed conformance, supply the same three `OPENLUP_MANAGED_CONFORMANCE_*`
430
+ local disposable-stack settings described for operator invitations, with
431
+ `OPENLUP_MANAGED_CONFORMANCE_DATABASE_URL` set to the database owner
432
+ (`supabase_admin`) connection, then run
433
+ `node --experimental-strip-types tests/postgres/identityPrivacyManaged.conformance.ts`.
434
+ Use a fresh public schema and reset the disposable stack between proofs; the
435
+ managed privacy proof replays the committed chain without fixture erasure grants.
436
+ Replay through node-postgres omits only the psql-only pg_dump `\restrict` and
437
+ `\unrestrict` guard lines; all migration SQL remains unchanged.
438
+
439
+
440
+ Reference startup can compose identity through `createReferenceIdentity` and
441
+ `startPublicReferenceServer({ identity })`, with explicit route functions,
442
+ selected adapters, trusted schema/migration observation and the bundle-specific
443
+ inventory. It consumes email-trust readiness before listening, and rejects
444
+ unknown or unsatisfied candidates. Direct reconcile reads the existing actor
445
+ link; direct invite/remove select the pending-invitation stores. The default
446
+ static reference and browser page sets remain unchanged. See the
447
+ [composition contract](../../docs/platform/IDENTITY.md#responsibility-and-composition).
448
+
449
+ Both identity entries already belong to the public export map and build output;
450
+ artifact availability does not imply registry publication or release activation.
451
+ The cold installed-artifact consumer imports both entries without optional peers,
452
+ compiles contracts without driver types, and invokes every driver-owning direct
453
+ identity adapter for its missing-peer refusal. Managed factories consume
454
+ structural clients. Server declarations compile after peer selection. Full
455
+ installed-artifact and database proof require the existing supervisor-run package
456
+ consumer command and an owned disposable database.
457
+
458
+ The managed identity service-role capabilities forward in the committed chain
459
+ supplies client link writes and operator membership insert/email-read
460
+ permissions; the local conformance runners add no fixture grant. No migration is
461
+ added by reference composition.
462
+
463
+
464
+ ## Disposable identity composition
465
+
466
+ The reference application's opt-in identity shell consumes the existing
467
+ `./identity` and `./identity/contracts` exports without changing their maturity
468
+ or publishing a registry version. It reuses the customer/operator pages and
469
+ captured-delivery port, with a private local mailbox and administrator privacy
470
+ panel. Its explicit runtime must supply actual routes and readiness admission;
471
+ the shell refuses a missing composition. See the
472
+ [identity reference guide](../../docs/platform/IDENTITY.md#disposable-identity-reference)
473
+ for both-bundle commands, the committed managed grants and installation limits.
@@ -0,0 +1,28 @@
1
+ import type { AdminAuthPort } from "./ports.js";
2
+ import type { AdminAuthBinding } from "./adminPreflight.js";
3
+ type Env = Record<string, string | undefined>;
4
+ export interface PlatformOperatorChecker {
5
+ isOperatorAllowed(principalId: string): Promise<boolean>;
6
+ close(): Promise<void>;
7
+ }
8
+ export type PlatformOperatorCheckerFactory = (env: Env) => PlatformOperatorChecker | Promise<PlatformOperatorChecker>;
9
+ export type AdminAuthBindingResolution = {
10
+ readonly binding: AdminAuthBinding;
11
+ readonly error?: undefined;
12
+ } | {
13
+ readonly binding?: undefined;
14
+ readonly error: "managed_admin_auth_env_required" | "direct_admin_auth_config_invalid";
15
+ };
16
+ export interface AdminAuthBindingOptions {
17
+ humanAuthFactory?: (env: Env) => AdminAuthPort & {
18
+ close(): Promise<void>;
19
+ };
20
+ checkerFactory?: PlatformOperatorCheckerFactory;
21
+ managedAuthFactory?: (env: {
22
+ url: string;
23
+ anonKey: string;
24
+ }, accessToken: string | null) => AdminAuthPort;
25
+ }
26
+ /** Bind the admin authorizer selected by PLATFORM_BUNDLE. */
27
+ export declare function createAdminAuthBindingResolver(defaults: Required<Pick<AdminAuthBindingOptions, "checkerFactory" | "managedAuthFactory">> & Pick<AdminAuthBindingOptions, "humanAuthFactory">): (env: Env, options?: AdminAuthBindingOptions) => AdminAuthBindingResolution;
28
+ export {};
@@ -0,0 +1,66 @@
1
+ import { createOperatorTokenAdminAuth, resolvePlatformOperatorAuthConfig } from "./operatorTokenAdminAuth.js";
2
+ import { resolveBundleId } from "../kernel/index.js";
3
+ function managedAuthEnv(env) {
4
+ const url = env.SUPABASE_URL ?? env.VITE_SUPABASE_URL;
5
+ const anonKey = env.VITE_SUPABASE_PUBLISHABLE_KEY ?? env.VITE_SUPABASE_ANON_KEY ?? env.SUPABASE_ANON_KEY;
6
+ return url && anonKey ? { url, anonKey } : null;
7
+ }
8
+ /** Bind the admin authorizer selected by PLATFORM_BUNDLE. */
9
+ export function createAdminAuthBindingResolver(defaults) {
10
+ return function resolveAdminAuthBinding(env, options = {}) {
11
+ const bundleId = resolveBundleId(env);
12
+ if (bundleId === "node-postgres") {
13
+ const config = resolvePlatformOperatorAuthConfig(env);
14
+ const humanFactory = options.humanAuthFactory ?? defaults.humanAuthFactory;
15
+ const humanEnabled = !!env.OPERATOR_IDENTITY_AUDIENCE && !!humanFactory;
16
+ if (!config.config && !humanEnabled)
17
+ return { error: "direct_admin_auth_config_invalid" };
18
+ const checkerFactory = options.checkerFactory ?? defaults.checkerFactory;
19
+ return {
20
+ binding: {
21
+ identity: bundleId,
22
+ async run(accessToken, work) {
23
+ const scope = {};
24
+ const machine = config.config ? createOperatorTokenAdminAuth(config.config, async (principalId) => {
25
+ scope.checker ??= await checkerFactory(env);
26
+ return scope.checker.isOperatorAllowed(principalId);
27
+ }) : null;
28
+ let human;
29
+ const auth = { async authorize(token, restrictions) {
30
+ // Only a credential mismatch may select human verification; machine
31
+ // revocation and database errors retain their existing result.
32
+ const result = machine ? await machine.authorize(token, restrictions) : null;
33
+ if (result && (result.ok || result.code !== "UNAUTHORIZED"))
34
+ return result;
35
+ if (!humanEnabled || !token)
36
+ return result ?? { ok: false, code: "UNAUTHORIZED", message: "Operator authentication required" };
37
+ human ??= humanFactory(env);
38
+ return human.authorize(token, restrictions);
39
+ } };
40
+ try {
41
+ return await work(auth);
42
+ }
43
+ finally {
44
+ try {
45
+ await scope.checker?.close();
46
+ }
47
+ finally {
48
+ await human?.close();
49
+ }
50
+ }
51
+ },
52
+ },
53
+ };
54
+ }
55
+ const authEnv = managedAuthEnv(env);
56
+ if (!authEnv)
57
+ return { error: "managed_admin_auth_env_required" };
58
+ const managedAuthFactory = options.managedAuthFactory ?? defaults.managedAuthFactory;
59
+ return {
60
+ binding: {
61
+ identity: bundleId,
62
+ run: (accessToken, work) => work(managedAuthFactory(authEnv, accessToken)),
63
+ },
64
+ };
65
+ };
66
+ }
@@ -0,0 +1,34 @@
1
+ import type { HttpResponse, HttpRequest } from "../http/index.js";
2
+ import { type IdentityResponseOptions } from "./response.js";
3
+ export type AdminRole = "admin" | "distributor";
4
+ /** Authorization outcome: a resolved admin `userId`, or a typed denial. */
5
+ export type AdminAuthorization = {
6
+ ok: true;
7
+ userId: string;
8
+ role: AdminRole;
9
+ isMachineActor: boolean;
10
+ } | {
11
+ ok: false;
12
+ code: "UNAUTHORIZED" | "FORBIDDEN";
13
+ message: string;
14
+ identityCode?: string;
15
+ };
16
+ /** A request-bound thunk that resolves the calling admin (or a denial). */
17
+ export type AuthorizeAdmin = () => Promise<AdminAuthorization>;
18
+ export declare function authorizeAdminWithUser(rawClient: unknown, accessToken: string | null, options?: {
19
+ allowedRoles?: readonly AdminRole[];
20
+ }): Promise<AdminAuthorization>;
21
+ export declare function authorizeCommerceAdminWithUser(client: unknown, accessToken: string | null): Promise<AdminAuthorization>;
22
+ export declare function authorizeAdminBooleanWithUser(client: unknown, accessToken: string | null, options?: {
23
+ allowedRoles?: readonly AdminRole[];
24
+ }): Promise<boolean>;
25
+ /**
26
+ * Shared authz gate: returns the resolved admin (`userId` + DB-derived
27
+ * `isMachineActor`) or sends the error envelope and returns null.
28
+ */
29
+ export declare function resolveAdmin(authorizeAdmin: AuthorizeAdmin, res: HttpResponse, options?: IdentityResponseOptions): Promise<{
30
+ userId: string;
31
+ role: AdminRole;
32
+ isMachineActor: boolean;
33
+ } | null>;
34
+ export declare function readBearerToken(req: HttpRequest): string | null;
@@ -0,0 +1,72 @@
1
+ import { createIdentityResponder } from "./response.js";
2
+ export async function authorizeAdminWithUser(rawClient, accessToken, options = {}) {
3
+ const client = rawClient;
4
+ if (!accessToken) {
5
+ return { ok: false, code: "UNAUTHORIZED", message: "Admin session required" };
6
+ }
7
+ const { data: userData, error: userError } = await client.auth.getUser(accessToken);
8
+ if (userError || !userData.user) {
9
+ return { ok: false, code: "UNAUTHORIZED", message: "Admin session required" };
10
+ }
11
+ const { data, error } = await client
12
+ .from("admin_users")
13
+ .select("id, role, is_machine_actor")
14
+ .eq("id", userData.user.id)
15
+ .eq("membership_state", "active")
16
+ .maybeSingle();
17
+ if (error)
18
+ throw error;
19
+ if (!data) {
20
+ return { ok: false, code: "FORBIDDEN", message: "Admin role required" };
21
+ }
22
+ const role = normalizeAdminRole(data.role);
23
+ if (role === null || (options.allowedRoles && !options.allowedRoles.includes(role))) {
24
+ return { ok: false, code: "FORBIDDEN", message: "Admin role required" };
25
+ }
26
+ // Fail closed: mirror the activate RPC's `COALESCE(is_machine_actor, true)` — only an
27
+ // explicit `false` is a human actor; anything else is treated as a machine. The DB row
28
+ // (`admin_users.is_machine_actor`, re-derived here and in every write RPC) is the single
29
+ // source of truth for actor kind — never trusted from the caller.
30
+ return {
31
+ ok: true,
32
+ userId: userData.user.id,
33
+ role,
34
+ isMachineActor: data.is_machine_actor !== false,
35
+ };
36
+ }
37
+ export function authorizeCommerceAdminWithUser(client, accessToken) {
38
+ return authorizeAdminWithUser(client, accessToken, { allowedRoles: ["admin"] });
39
+ }
40
+ export async function authorizeAdminBooleanWithUser(client, accessToken, options = {}) {
41
+ const authorization = await authorizeAdminWithUser(client, accessToken, options);
42
+ return authorization.ok;
43
+ }
44
+ /**
45
+ * Shared authz gate: returns the resolved admin (`userId` + DB-derived
46
+ * `isMachineActor`) or sends the error envelope and returns null.
47
+ */
48
+ export async function resolveAdmin(authorizeAdmin, res, options = {}) {
49
+ const { sendBffError } = createIdentityResponder(options);
50
+ let authz;
51
+ try {
52
+ authz = await authorizeAdmin();
53
+ }
54
+ catch {
55
+ sendBffError(res, "UPSTREAM_UNAVAILABLE", "Admin authorization failed");
56
+ return null;
57
+ }
58
+ if (authz.ok === false) {
59
+ sendBffError(res, authz.code, authz.message);
60
+ return null;
61
+ }
62
+ return { userId: authz.userId, role: authz.role, isMachineActor: authz.isMachineActor };
63
+ }
64
+ function normalizeAdminRole(role) {
65
+ return role === "admin" || role === "distributor" ? role : null;
66
+ }
67
+ export function readBearerToken(req) {
68
+ const raw = req.headers.authorization;
69
+ const value = Array.isArray(raw) ? raw[0] : raw;
70
+ const match = value?.match(/^Bearer\s+(.+)$/i);
71
+ return match?.[1]?.trim() || null;
72
+ }