@fabrika/iam 0.0.0-stage → 0.9.0-dev.26

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 (312) hide show
  1. package/fabrika.config.ts +267 -0
  2. package/migrations/0001_init.sql +316 -0
  3. package/migrations/0002_oauth.sql +38 -0
  4. package/migrations/0003_contract_apps.sql +11 -0
  5. package/migrations/0004_membership.sql +93 -0
  6. package/migrations/0005_workloads.sql +23 -0
  7. package/migrations/0006_membership_transport_keys.sql +16 -0
  8. package/migrations/0007_member_directory.sql +7 -0
  9. package/migrations/0008_durable_audit.sql +28 -0
  10. package/migrations/0009_member_lookups.sql +7 -0
  11. package/migrations/0010_workload_issues.sql +6 -0
  12. package/migrations/0011_app_presentation.sql +15 -0
  13. package/migrations/0012_external_principals.sql +10 -0
  14. package/migrations/0013_app_mail_templates.sql +14 -0
  15. package/migrations/0014_invitation_wording.sql +8 -0
  16. package/migrations/0015_app_schema_revisions.sql +15 -0
  17. package/migrations/0016_principal_grant_revision.sql +9 -0
  18. package/migrations/0017_app_sign_ins.sql +12 -0
  19. package/migrations/0018_app_members.sql +13 -0
  20. package/migrations/0019_app_mail_html.sql +7 -0
  21. package/migrations/0020_public_workloads.sql +34 -0
  22. package/migrations/0021_installation_brand.sql +19 -0
  23. package/migrations/0022_password_policy.sql +12 -0
  24. package/migrations/0023_terminals.sql +155 -0
  25. package/migrations/0024_app_terminals.sql +10 -0
  26. package/migrations/0025_terminal_completion.sql +10 -0
  27. package/migrations/0026_terminal_generation.sql +12 -0
  28. package/migrations/0027_application_exact_actions.sql +28 -0
  29. package/migrations/0028_oauth_client_assertions.sql +10 -0
  30. package/migrations/0029_role_via.sql +6 -0
  31. package/migrations/0030_membership_role_via.sql +12 -0
  32. package/migrations/0031_person_locale.sql +11 -0
  33. package/migrations-postgres/0001_init.sql +331 -0
  34. package/migrations-postgres/0002_oauth.sql +36 -0
  35. package/migrations-postgres/0003_contract_apps.sql +8 -0
  36. package/migrations-postgres/0004_membership.sql +92 -0
  37. package/migrations-postgres/0005_workloads.sql +18 -0
  38. package/migrations-postgres/0006_membership_transport_keys.sql +12 -0
  39. package/migrations-postgres/0007_member_directory.sql +7 -0
  40. package/migrations-postgres/0008_durable_audit.sql +8 -0
  41. package/migrations-postgres/0009_member_lookups.sql +7 -0
  42. package/migrations-postgres/0010_workload_issues.sql +6 -0
  43. package/migrations-postgres/0011_app_presentation.sql +15 -0
  44. package/migrations-postgres/0012_external_principals.sql +10 -0
  45. package/migrations-postgres/0013_app_mail_templates.sql +14 -0
  46. package/migrations-postgres/0014_invitation_wording.sql +8 -0
  47. package/migrations-postgres/0015_app_schema_revisions.sql +15 -0
  48. package/migrations-postgres/0016_principal_grant_revision.sql +9 -0
  49. package/migrations-postgres/0017_app_sign_ins.sql +12 -0
  50. package/migrations-postgres/0018_app_members.sql +13 -0
  51. package/migrations-postgres/0019_app_mail_html.sql +7 -0
  52. package/migrations-postgres/0020_public_workloads.sql +9 -0
  53. package/migrations-postgres/0021_installation_brand.sql +19 -0
  54. package/migrations-postgres/0022_password_policy.sql +12 -0
  55. package/migrations-postgres/0023_terminals.sql +70 -0
  56. package/migrations-postgres/0024_app_terminals.sql +10 -0
  57. package/migrations-postgres/0025_terminal_completion.sql +10 -0
  58. package/migrations-postgres/0026_terminal_generation.sql +12 -0
  59. package/migrations-postgres/0027_application_exact_actions.sql +28 -0
  60. package/migrations-postgres/0028_oauth_client_assertions.sql +9 -0
  61. package/migrations-postgres/0029_role_via.sql +4 -0
  62. package/migrations-postgres/0030_membership_role_via.sql +7 -0
  63. package/migrations-postgres/0031_person_locale.sql +11 -0
  64. package/package.json +70 -5
  65. package/src/admin/access.ts +47 -0
  66. package/src/admin/api-keys.ts +280 -0
  67. package/src/admin/app-people.ts +209 -0
  68. package/src/admin/app-schema.ts +308 -0
  69. package/src/admin/audit.ts +81 -0
  70. package/src/admin/brand.ts +54 -0
  71. package/src/admin/connections.ts +48 -0
  72. package/src/admin/context.ts +70 -0
  73. package/src/admin/grant-support.ts +192 -0
  74. package/src/admin/grants.ts +189 -0
  75. package/src/admin/handlers.ts +102 -0
  76. package/src/admin/http.ts +24 -0
  77. package/src/admin/membership-keys.ts +38 -0
  78. package/src/admin/pagination.ts +28 -0
  79. package/src/admin/password-policy.ts +48 -0
  80. package/src/admin/passwords.ts +78 -0
  81. package/src/admin/policies.ts +136 -0
  82. package/src/admin/principals.ts +226 -0
  83. package/src/admin/router.ts +291 -0
  84. package/src/admin/rpc.ts +387 -0
  85. package/src/admin/sessions.ts +115 -0
  86. package/src/admin/share-links.ts +127 -0
  87. package/src/admin/terminals.ts +115 -0
  88. package/src/admin/user-admin.ts +76 -0
  89. package/src/admin/workloads.ts +85 -0
  90. package/src/app-presentation.ts +178 -0
  91. package/src/app.ts +158 -0
  92. package/src/auth/cookies.ts +64 -0
  93. package/src/auth/failure.ts +25 -0
  94. package/src/auth/handoff.ts +136 -0
  95. package/src/auth/http.ts +88 -0
  96. package/src/auth/invitations.ts +220 -0
  97. package/src/auth/known-device.ts +44 -0
  98. package/src/auth/login.ts +162 -0
  99. package/src/auth/oidc-flight.ts +91 -0
  100. package/src/auth/oidc.ts +148 -0
  101. package/src/auth/password.ts +416 -0
  102. package/src/auth/routes.ts +108 -0
  103. package/src/auth/sessions.ts +249 -0
  104. package/src/auth/terminals.ts +284 -0
  105. package/src/auth.ts +193 -0
  106. package/src/binding-identity.ts +25 -0
  107. package/src/bounded-body.ts +35 -0
  108. package/src/catalog/cs.ts +147 -0
  109. package/src/catalog/en.ts +148 -0
  110. package/src/catalog/index.ts +122 -0
  111. package/src/catalog/uk.ts +164 -0
  112. package/src/client-address.ts +39 -0
  113. package/src/common-passwords.ts +37 -0
  114. package/src/contract-rules.ts +80 -0
  115. package/src/cron.ts +54 -0
  116. package/src/db.ts +128 -0
  117. package/src/delegation.ts +100 -0
  118. package/src/device-http.ts +39 -0
  119. package/src/device.ts +269 -0
  120. package/src/email-identity.ts +2 -0
  121. package/src/env.ts +132 -0
  122. package/src/handoff.ts +175 -0
  123. package/src/html.ts +4 -0
  124. package/src/human-admission.ts +40 -0
  125. package/src/identification.ts +185 -0
  126. package/src/index.ts +292 -0
  127. package/src/installation-brand.ts +82 -0
  128. package/src/issue.ts +265 -0
  129. package/src/json.ts +30 -0
  130. package/src/log.ts +26 -0
  131. package/src/membership-http.ts +135 -0
  132. package/src/membership.ts +1210 -0
  133. package/src/messages.ts +44 -0
  134. package/src/narrow-permissions.ts +26 -0
  135. package/src/node/browser-identity.ts +69 -0
  136. package/src/node/migrate.ts +52 -0
  137. package/src/node/prune.ts +34 -0
  138. package/src/node/runtime.ts +221 -0
  139. package/src/node/server.ts +104 -0
  140. package/src/oauth-client-auth.ts +93 -0
  141. package/src/oauth-client.ts +145 -0
  142. package/src/oauth-config.ts +72 -0
  143. package/src/oauth-http.ts +262 -0
  144. package/src/oauth.ts +272 -0
  145. package/src/oidc.ts +260 -0
  146. package/src/origin.ts +29 -0
  147. package/src/password-crypto.ts +148 -0
  148. package/src/password-db.ts +419 -0
  149. package/src/password-minimum.ts +44 -0
  150. package/src/password-pages.ts +397 -0
  151. package/src/password-policy.ts +79 -0
  152. package/src/password-service.ts +67 -0
  153. package/src/person-locale.ts +103 -0
  154. package/src/proxy-proof.ts +36 -0
  155. package/src/relay-mail.ts +64 -0
  156. package/src/repositories/app-schema.ts +550 -0
  157. package/src/repositories/audit.ts +405 -0
  158. package/src/repositories/brand.ts +66 -0
  159. package/src/repositories/credentials.ts +331 -0
  160. package/src/repositories/device.ts +137 -0
  161. package/src/repositories/grants.ts +404 -0
  162. package/src/repositories/handoff.ts +103 -0
  163. package/src/repositories/membership-transport.ts +49 -0
  164. package/src/repositories/membership.ts +875 -0
  165. package/src/repositories/oauth.ts +122 -0
  166. package/src/repositories/password-policy.ts +44 -0
  167. package/src/repositories/principals.ts +358 -0
  168. package/src/repositories/sessions.ts +339 -0
  169. package/src/repositories/sql.ts +23 -0
  170. package/src/repositories/terminals.ts +346 -0
  171. package/src/repositories/workloads.ts +134 -0
  172. package/src/request-id.ts +46 -0
  173. package/src/resolve.ts +396 -0
  174. package/src/retention.ts +34 -0
  175. package/src/roles.ts +54 -0
  176. package/src/rpc-http.ts +333 -0
  177. package/src/rpc-inputs.ts +110 -0
  178. package/src/rpc.ts +440 -0
  179. package/src/secret.ts +45 -0
  180. package/src/service.ts +59 -0
  181. package/src/services.ts +199 -0
  182. package/src/signing.ts +260 -0
  183. package/src/stored-chain.ts +23 -0
  184. package/src/stored-permissions.ts +34 -0
  185. package/src/terminals.ts +15 -0
  186. package/src/tokens.ts +506 -0
  187. package/src/workload-token.ts +130 -0
  188. package/types/fabrika.config.d.ts +11 -0
  189. package/types/src/admin/access.d.ts +19 -0
  190. package/types/src/admin/api-keys.d.ts +26 -0
  191. package/types/src/admin/app-people.d.ts +8 -0
  192. package/types/src/admin/app-schema.d.ts +32 -0
  193. package/types/src/admin/audit.d.ts +10 -0
  194. package/types/src/admin/brand.d.ts +10 -0
  195. package/types/src/admin/connections.d.ts +5 -0
  196. package/types/src/admin/context.d.ts +46 -0
  197. package/types/src/admin/grant-support.d.ts +59 -0
  198. package/types/src/admin/grants.d.ts +8 -0
  199. package/types/src/admin/handlers.d.ts +82 -0
  200. package/types/src/admin/http.d.ts +9 -0
  201. package/types/src/admin/membership-keys.d.ts +8 -0
  202. package/types/src/admin/pagination.d.ts +5 -0
  203. package/types/src/admin/password-policy.d.ts +9 -0
  204. package/types/src/admin/passwords.d.ts +5 -0
  205. package/types/src/admin/policies.d.ts +15 -0
  206. package/types/src/admin/principals.d.ts +15 -0
  207. package/types/src/admin/router.d.ts +75 -0
  208. package/types/src/admin/rpc.d.ts +6 -0
  209. package/types/src/admin/sessions.d.ts +14 -0
  210. package/types/src/admin/share-links.d.ts +21 -0
  211. package/types/src/admin/terminals.d.ts +13 -0
  212. package/types/src/admin/user-admin.d.ts +30 -0
  213. package/types/src/admin/workloads.d.ts +5 -0
  214. package/types/src/app-presentation.d.ts +86 -0
  215. package/types/src/app.d.ts +62 -0
  216. package/types/src/auth/cookies.d.ts +29 -0
  217. package/types/src/auth/failure.d.ts +47 -0
  218. package/types/src/auth/handoff.d.ts +66 -0
  219. package/types/src/auth/http.d.ts +29 -0
  220. package/types/src/auth/invitations.d.ts +18 -0
  221. package/types/src/auth/known-device.d.ts +12 -0
  222. package/types/src/auth/login.d.ts +10 -0
  223. package/types/src/auth/oidc-flight.d.ts +39 -0
  224. package/types/src/auth/oidc.d.ts +7 -0
  225. package/types/src/auth/password.d.ts +7 -0
  226. package/types/src/auth/routes.d.ts +15 -0
  227. package/types/src/auth/sessions.d.ts +60 -0
  228. package/types/src/auth/terminals.d.ts +47 -0
  229. package/types/src/auth.d.ts +70 -0
  230. package/types/src/binding-identity.d.ts +12 -0
  231. package/types/src/bounded-body.d.ts +12 -0
  232. package/types/src/catalog/cs.d.ts +2 -0
  233. package/types/src/catalog/en.d.ts +2 -0
  234. package/types/src/catalog/index.d.ts +112 -0
  235. package/types/src/catalog/uk.d.ts +2 -0
  236. package/types/src/client-address.d.ts +31 -0
  237. package/types/src/common-passwords.d.ts +2 -0
  238. package/types/src/contract-rules.d.ts +25 -0
  239. package/types/src/cron.d.ts +15 -0
  240. package/types/src/db.d.ts +58 -0
  241. package/types/src/delegation.d.ts +38 -0
  242. package/types/src/device-http.d.ts +2 -0
  243. package/types/src/device.d.ts +11 -0
  244. package/types/src/email-identity.d.ts +1 -0
  245. package/types/src/env.d.ts +127 -0
  246. package/types/src/handoff.d.ts +57 -0
  247. package/types/src/html.d.ts +2 -0
  248. package/types/src/human-admission.d.ts +22 -0
  249. package/types/src/identification.d.ts +30 -0
  250. package/types/src/index.d.ts +62 -0
  251. package/types/src/installation-brand.d.ts +22 -0
  252. package/types/src/issue.d.ts +62 -0
  253. package/types/src/json.d.ts +15 -0
  254. package/types/src/log.d.ts +15 -0
  255. package/types/src/membership-http.d.ts +8 -0
  256. package/types/src/membership.d.ts +156 -0
  257. package/types/src/messages.d.ts +20 -0
  258. package/types/src/narrow-permissions.d.ts +7 -0
  259. package/types/src/node/browser-identity.d.ts +1 -0
  260. package/types/src/node/migrate.d.ts +4 -0
  261. package/types/src/node/prune.d.ts +1 -0
  262. package/types/src/node/runtime.d.ts +51 -0
  263. package/types/src/node/server.d.ts +5 -0
  264. package/types/src/oauth-client-auth.d.ts +26 -0
  265. package/types/src/oauth-client.d.ts +17 -0
  266. package/types/src/oauth-config.d.ts +16 -0
  267. package/types/src/oauth-http.d.ts +7 -0
  268. package/types/src/oauth.d.ts +51 -0
  269. package/types/src/oidc.d.ts +81 -0
  270. package/types/src/origin.d.ts +9 -0
  271. package/types/src/password-crypto.d.ts +37 -0
  272. package/types/src/password-db.d.ts +134 -0
  273. package/types/src/password-minimum.d.ts +23 -0
  274. package/types/src/password-pages.d.ts +143 -0
  275. package/types/src/password-policy.d.ts +19 -0
  276. package/types/src/password-service.d.ts +24 -0
  277. package/types/src/person-locale.d.ts +50 -0
  278. package/types/src/proxy-proof.d.ts +21 -0
  279. package/types/src/relay-mail.d.ts +25 -0
  280. package/types/src/repositories/app-schema.d.ts +244 -0
  281. package/types/src/repositories/audit.d.ts +187 -0
  282. package/types/src/repositories/brand.d.ts +41 -0
  283. package/types/src/repositories/credentials.d.ts +148 -0
  284. package/types/src/repositories/device.d.ts +50 -0
  285. package/types/src/repositories/grants.d.ts +177 -0
  286. package/types/src/repositories/handoff.d.ts +52 -0
  287. package/types/src/repositories/membership-transport.d.ts +31 -0
  288. package/types/src/repositories/membership.d.ts +273 -0
  289. package/types/src/repositories/oauth.d.ts +55 -0
  290. package/types/src/repositories/password-policy.d.ts +25 -0
  291. package/types/src/repositories/principals.d.ts +159 -0
  292. package/types/src/repositories/sessions.d.ts +150 -0
  293. package/types/src/repositories/sql.d.ts +13 -0
  294. package/types/src/repositories/terminals.d.ts +144 -0
  295. package/types/src/repositories/workloads.d.ts +61 -0
  296. package/types/src/request-id.d.ts +25 -0
  297. package/types/src/resolve.d.ts +118 -0
  298. package/types/src/retention.d.ts +18 -0
  299. package/types/src/roles.d.ts +34 -0
  300. package/types/src/rpc-http.d.ts +53 -0
  301. package/types/src/rpc-inputs.d.ts +707 -0
  302. package/types/src/rpc.d.ts +4 -0
  303. package/types/src/secret.d.ts +21 -0
  304. package/types/src/service.d.ts +19 -0
  305. package/types/src/services.d.ts +72 -0
  306. package/types/src/signing.d.ts +72 -0
  307. package/types/src/stored-chain.d.ts +6 -0
  308. package/types/src/stored-permissions.d.ts +12 -0
  309. package/types/src/terminals.d.ts +7 -0
  310. package/types/src/tokens.d.ts +113 -0
  311. package/types/src/workload-token.d.ts +7 -0
  312. package/README.md +0 -3
package/src/rpc.ts ADDED
@@ -0,0 +1,440 @@
1
+ // The `IamRpc` implementation — the whole management + minting surface, in ONE runtime-neutral place.
2
+ //
3
+ // This file used to be the body of the Cloudflare `WorkerEntrypoint` in `index.ts`. It moved out
4
+ // unchanged when the service gained a second entrypoint: on Workers apps reach these methods over a
5
+ // service binding (`index.ts` delegates each one straight here), and in a long-running process they
6
+ // are reached over HTTP (`rpc-http.ts` dispatches onto the SAME object). Neither entrypoint owns a
7
+ // copy — that is the point. `IamRpc` (@fabrika/auth-core) is the contract in both directions and is
8
+ // not modified by either transport.
9
+ //
10
+ // The two runtime handles it needs are the `Env` ports and a `RequestContext`; nothing here knows
11
+ // what fills them.
12
+ //
13
+ // SECURITY MODEL (unchanged by the move): the management RPCs (`issueKey`/`revokeKey`/`listPrincipals`)
14
+ // resolve the CALLER server-side from a forwarded IAM-native credential (`resolveCaller` — a
15
+ // `px_token` verified against our own signing keys, or a `px_` key), never app-asserted. On a valid `px_token` the credential's `aud` identifies the app and supersedes the
16
+ // SDK-passed `app` for the audit row. `audit` takes its app from the caller's verified token the same
17
+ // way (`verifiedTokenApp`). Note what this does NOT cover: `mintToken`, `mintFromKey` and `getJwks`
18
+ // authenticate no caller of their own — on Workers the binding's unreachability is what stands in for
19
+ // that, so an HTTP transport MUST supply an equivalent (see `rpc-http.ts`).
20
+
21
+ import type {
22
+ AuditInput,
23
+ ExchangeAuthCodeInput,
24
+ ExchangeAuthCodeResult,
25
+ IamHandoffRpc,
26
+ IamMembershipRpc,
27
+ IamRpc,
28
+ IamTerminalRpc,
29
+ IssueKeyInput,
30
+ IssueKeyResult,
31
+ Jwks,
32
+ ListPrincipalsInput,
33
+ ListPrincipalsResult,
34
+ MintFromKeyInput,
35
+ MintFromKeyResult,
36
+ MintTokenInput,
37
+ MintTokenResult,
38
+ PrincipalListItem,
39
+ RevokeKeyInput,
40
+ RevokeKeyResult,
41
+ } from '@fabrika/auth-core'
42
+ import { IAM_APP } from './admin/router'
43
+ import { resolveCaller, verifiedTokenApp } from './auth'
44
+ import { auditLabelOf } from './db'
45
+ import { approveDeviceAuthorization, denyDeviceAuthorization, inspectDeviceAuthorization, listOwnDeviceAuthorizations } from './device'
46
+ import type { Env, RequestContext } from './env'
47
+ import { exchangeAuthCode } from './handoff'
48
+ import { assertIdentity, cancelIdentification, inspectIdentification } from './identification'
49
+ import { issueKey, revokeKey } from './issue'
50
+ import { logError } from './log'
51
+ import {
52
+ assignMember,
53
+ createScope,
54
+ findMember,
55
+ issueLink,
56
+ listAppMembers,
57
+ listMembers,
58
+ requestDelegation,
59
+ revokeLink,
60
+ revokeMember,
61
+ } from './membership'
62
+ import { acceptRequestId } from './request-id'
63
+ import { buildServices, type Services } from './services'
64
+ import { getSigner } from './signing'
65
+ import { mintFromKey, mintToken } from './tokens'
66
+
67
+ /** Build the RPC surface bound to one env + request context. */
68
+ export function createIamRpc(env: Env, ctx: RequestContext): IamRpc & IamHandoffRpc & IamMembershipRpc & IamTerminalRpc {
69
+ // Built ONCE per RPC surface, not once per call (ARCH-1). It was constructed inside every method
70
+ // and, in `audit`, OUTSIDE the fail-closed try — so a configuration error there threw to the
71
+ // caller instead of failing closed. It also allocated an `OidcClient` and an email sender on the
72
+ // mint path, which the proxy hits on every cold request and which needs neither.
73
+ const services = buildServices(env)
74
+ /** A membership operation never throws to its caller; an unexpected failure is a logged refusal. */
75
+ const membership = <I extends { requestId: string }, R>(
76
+ name: string,
77
+ operation: (services: Services, env: Env, ctx: RequestContext, input: I) => Promise<R | { ok: false; reason: 'not_allowed' }>,
78
+ ) =>
79
+ async (raw: I): Promise<R | { ok: false; reason: 'not_allowed' }> => {
80
+ const input = withAcceptedRequestId(raw)
81
+ try {
82
+ return await operation(services, env, ctx, input)
83
+ } catch (err) {
84
+ logError(`${name} failed for request '${input.requestId}'`, err)
85
+ return { ok: false, reason: 'not_allowed' }
86
+ }
87
+ }
88
+ return {
89
+ requestDelegation: membership('requestDelegation', requestDelegation),
90
+ createScope: membership('createScope', createScope),
91
+ assignMember: membership('assignMember', assignMember),
92
+ revokeMember: membership('revokeMember', revokeMember),
93
+ listMembers: membership('listMembers', listMembers),
94
+ listAppMembers: membership('listAppMembers', listAppMembers),
95
+ findMember: membership('findMember', findMember),
96
+ issueLink: membership('issueLink', issueLink),
97
+ revokeLink: membership('revokeLink', revokeLink),
98
+ /** The identification operations (ADR-0067 §3) never throw to the application; an unexpected failure is a logged refusal. */
99
+ async inspectIdentification(raw) {
100
+ const input = withAcceptedRequestId(raw)
101
+ try {
102
+ return await inspectIdentification(services, env, input)
103
+ } catch (err) {
104
+ logError(`inspectIdentification failed for request '${input.requestId}'`, err)
105
+ return { ok: false, reason: 'not_allowed' }
106
+ }
107
+ },
108
+ /** An assertion logged its `allow` row in the login's own batch; a refusal opened nothing and is logged after it. */
109
+ async assertIdentity(raw) {
110
+ const input = withAcceptedRequestId(raw)
111
+ try {
112
+ const { result, principalId, terminal } = await assertIdentity(services, env, input)
113
+ if (!result.ok) {
114
+ ctx.waitUntil(
115
+ services.repositories.audit.writeAuthLog({
116
+ requestId: input.requestId,
117
+ app: IAM_APP,
118
+ kind: 'authenticate',
119
+ principalId,
120
+ decision: 'deny',
121
+ reason: `terminal_assertion_${result.reason}`,
122
+ terminal,
123
+ }),
124
+ )
125
+ }
126
+ return result
127
+ } catch (err) {
128
+ logError(`assertIdentity failed for request '${input.requestId}'`, err)
129
+ return { ok: false, reason: 'not_allowed' }
130
+ }
131
+ },
132
+ async cancelIdentification(raw) {
133
+ const input = withAcceptedRequestId(raw)
134
+ try {
135
+ return await cancelIdentification(services, env, input)
136
+ } catch (err) {
137
+ logError(`cancelIdentification failed for request '${input.requestId}'`, err)
138
+ return { ok: false, reason: 'not_allowed' }
139
+ }
140
+ },
141
+ inspectDeviceAuthorization: (input) => inspectDeviceAuthorization(services, env, input),
142
+ approveDeviceAuthorization: (input) => approveDeviceAuthorization(services, env, input),
143
+ denyDeviceAuthorization: (input) => denyDeviceAuthorization(services, env, input),
144
+ listOwnDeviceAuthorizations: (input) => listOwnDeviceAuthorizations(services, env, input),
145
+ /**
146
+ * Redeem a cross-host handoff code for an app-bound session (ADR-0022). Reached only over the
147
+ * proxy's own surface — see `IamHandoffRpc` for why it is not part of `IamRpc`. Fails closed
148
+ * like every mint front: an unusable code is a decided `{ ok: false }`, never a throw.
149
+ */
150
+ async exchangeAuthCode(raw: ExchangeAuthCodeInput): Promise<ExchangeAuthCodeResult> {
151
+ const input = withAcceptedRequestId(raw)
152
+ try {
153
+ const { result, principalId, terminal } = await exchangeAuthCode(services, input)
154
+ // A redemption logged its `allow` row in the child session's own batch; a refusal opened nothing.
155
+ if (!result.ok) {
156
+ ctx.waitUntil(
157
+ services.repositories.audit.writeAuthLog({
158
+ requestId: input.requestId,
159
+ app: input.app,
160
+ kind: 'authenticate',
161
+ principalId,
162
+ decision: 'deny',
163
+ reason: result.reason,
164
+ terminal,
165
+ }),
166
+ )
167
+ }
168
+ return result
169
+ } catch (err) {
170
+ logError(`exchangeAuthCode failed for request '${input.requestId}'`, err)
171
+ ctx.waitUntil(
172
+ services.repositories.audit.writeAuthLog({
173
+ requestId: input.requestId,
174
+ app: input.app,
175
+ kind: 'authenticate',
176
+ principalId: null,
177
+ decision: 'deny',
178
+ reason: 'internal_error',
179
+ }),
180
+ )
181
+ return { ok: false, reason: 'invalid_code' }
182
+ }
183
+ },
184
+ /**
185
+ * Mint a per-app permission token from the browser's SSO session (IAM-native auth). The
186
+ * session is validated, the principal's permissions for the calling app resolved, and a
187
+ * short-lived token signed; the SDK then authorizes locally off it until it expires. Never
188
+ * throws — fails closed to `invalid_session` (the SDK then bounces the user to /auth/login).
189
+ */
190
+ async mintToken(raw: MintTokenInput): Promise<MintTokenResult> {
191
+ const input = withAcceptedRequestId(raw)
192
+ try {
193
+ const { result, principalId, terminal } = await mintToken(services, env, input)
194
+ ctx.waitUntil(
195
+ services.repositories.audit.writeAuthLog({
196
+ requestId: input.requestId,
197
+ app: input.app,
198
+ kind: 'authenticate',
199
+ principalId,
200
+ decision: result.ok ? 'allow' : 'deny',
201
+ reason: result.ok ? 'mint' : result.reason,
202
+ terminal,
203
+ }),
204
+ )
205
+ return result
206
+ } catch (err) {
207
+ // Same fail-closed posture as authenticate(): never surface a 500.
208
+ logError(`mintToken failed for request '${input.requestId}'`, err)
209
+ ctx.waitUntil(
210
+ services.repositories.audit.writeAuthLog({
211
+ requestId: input.requestId,
212
+ app: input.app,
213
+ kind: 'authenticate',
214
+ principalId: null,
215
+ decision: 'deny',
216
+ reason: 'internal_error',
217
+ }),
218
+ )
219
+ return { ok: false, reason: 'invalid_session' }
220
+ }
221
+ },
222
+
223
+ /**
224
+ * Mint a per-app access token from an opaque `px_` credential (API key / share link) — the other
225
+ * front over the same resolve→sign core as `mintToken`. Validates the credential, resolves its
226
+ * effective permissions, signs a short-lived token. Never throws — fails closed to `invalid_key`.
227
+ */
228
+ async mintFromKey(raw: MintFromKeyInput): Promise<MintFromKeyResult> {
229
+ const input = withAcceptedRequestId(raw)
230
+ try {
231
+ const { result, principalId, credentialId } = await mintFromKey(services, env, input)
232
+ ctx.waitUntil(
233
+ services.repositories.audit.writeAuthLog({
234
+ requestId: input.requestId,
235
+ app: input.app,
236
+ kind: 'authenticate',
237
+ principalId,
238
+ credentialId,
239
+ decision: result.ok ? 'allow' : 'deny',
240
+ reason: result.ok ? 'mint_key' : result.reason,
241
+ }),
242
+ )
243
+ return result
244
+ } catch (err) {
245
+ // Same fail-closed posture as mintToken(): never surface a 500.
246
+ logError(`mintFromKey failed for request '${input.requestId}'`, err)
247
+ ctx.waitUntil(
248
+ services.repositories.audit.writeAuthLog({
249
+ requestId: input.requestId,
250
+ app: input.app,
251
+ kind: 'authenticate',
252
+ principalId: null,
253
+ decision: 'deny',
254
+ reason: 'internal_error',
255
+ }),
256
+ )
257
+ return { ok: false, reason: 'invalid_key' }
258
+ }
259
+ },
260
+
261
+ /** The public signing key set — fetched once per isolate by the SDK to verify tokens locally. */
262
+ async getJwks(): Promise<Jwks> {
263
+ const signer = await getSigner(env)
264
+ return signer.jwks()
265
+ },
266
+
267
+ /**
268
+ * Fire-and-forget domain audit write. Returns void and NEVER throws to the caller — a failed
269
+ * audit write must not fail or delay the user-facing op. The app is the one the caller's token
270
+ * was minted for; an event whose token does not verify is dropped with a warning, never written
271
+ * under an app nobody proved.
272
+ */
273
+ audit(raw: AuditInput): Promise<void> {
274
+ const { credential, ...event } = withAcceptedRequestId(raw)
275
+ ctx.waitUntil(
276
+ verifiedTokenApp(services, env, credential)
277
+ .then((app) => {
278
+ if (app === null) {
279
+ console.warn(`audit event refused for request '${event.requestId}': the credential does not verify`)
280
+ return
281
+ }
282
+ return services.repositories.audit.writeAuditEvent({
283
+ requestId: event.requestId,
284
+ principalId: event.principalId,
285
+ principalLabel: event.principalLabel,
286
+ credentialId: event.credentialId ?? null,
287
+ app,
288
+ action: event.action,
289
+ resourceType: event.resourceType,
290
+ resourceId: event.resourceId ?? null,
291
+ diff: event.diff,
292
+ metadata: event.metadata,
293
+ })
294
+ })
295
+ .catch((err: unknown) => {
296
+ logError('audit write failed', err)
297
+ }),
298
+ )
299
+ return Promise.resolve()
300
+ },
301
+
302
+ async listPrincipals(raw: ListPrincipalsInput): Promise<ListPrincipalsResult> {
303
+ const input = withAcceptedRequestId(raw)
304
+ try {
305
+ // Resolve the CALLER from the forwarded native credential — never a self-asserted principal.
306
+ // The app we list is the credential's verified app, so an operator only ever enumerates the
307
+ // roster of an app it holds a token for.
308
+ const res = await resolveCaller(services, env, { app: input.app, credential: input.credential, requestId: input.requestId })
309
+ if (!res.ok) {
310
+ return { ok: false, reason: res.reason }
311
+ }
312
+ // Authorize: a real principal-bound MEMBER holding ≥1 permission on the app. An anonymous
313
+ // credential (a share link) and a zero-grant user cannot enumerate the roster. An application
314
+ // lists the members of a value with `listMembers`, which checks the dimension's list action.
315
+ if (res.caller.type === undefined || res.caller.permissions.length === 0 || isApplicationCaller(services, res.verifiedApp)) {
316
+ return { ok: false, reason: 'not_allowed' }
317
+ }
318
+ const rows = await services.repositories.principals.getPrincipalsForApp(res.verifiedApp, { includeCrossApp: true })
319
+ const principals: PrincipalListItem[] = rows.map((p) => ({
320
+ id: p.id,
321
+ type: p.type,
322
+ label: p.label,
323
+ email: p.email,
324
+ disabled: p.disabled_at !== null,
325
+ }))
326
+ return { ok: true, principals }
327
+ } catch (err) {
328
+ // Fail closed — never surface a 500. A read needs no auth_log row.
329
+ logError(`listPrincipals failed for request '${input.requestId}'`, err)
330
+ return { ok: false, reason: 'unknown_principal' }
331
+ }
332
+ },
333
+
334
+ async revokeKey(raw: RevokeKeyInput): Promise<RevokeKeyResult> {
335
+ const input = withAcceptedRequestId(raw)
336
+ try {
337
+ // Resolve + authorize the REVOKER from the forwarded native credential — like the issue path.
338
+ const res = await resolveCaller(services, env, { app: input.app, credential: input.credential, requestId: input.requestId })
339
+ if (!res.ok) {
340
+ return { ok: false, reason: res.reason }
341
+ }
342
+ if (res.caller.type === undefined || isApplicationCaller(services, res.verifiedApp)) {
343
+ // An anonymous credential has no accountable principal; an application issues no credentials.
344
+ return { ok: false, reason: 'not_allowed' }
345
+ }
346
+ const revoker = res.caller
347
+
348
+ // Recorded in the revocation's own transaction and only for an actual state change: a no-op idempotent
349
+ // revoke or a denied/not-found attempt writes no domain event.
350
+ return await revokeKey(services, input, { id: revoker.id, permissions: revoker.permissions }, res.verifiedApp, {
351
+ requestId: input.requestId,
352
+ principalId: revoker.id,
353
+ principalLabel: auditLabelOf({ id: revoker.id, type: revoker.type, label: revoker.label }),
354
+ app: res.verifiedApp,
355
+ action: 'iam.credential.revoke',
356
+ resourceType: 'credential',
357
+ resourceId: input.id,
358
+ })
359
+ } catch (err) {
360
+ logError(`revokeKey failed for request '${input.requestId}'`, err)
361
+ ctx.waitUntil(
362
+ services.repositories.audit.writeAuthLog({
363
+ requestId: input.requestId,
364
+ app: input.app,
365
+ kind: 'authenticate',
366
+ principalId: null,
367
+ decision: 'deny',
368
+ reason: 'internal_error',
369
+ }),
370
+ )
371
+ return { ok: false, reason: 'unknown_principal' }
372
+ }
373
+ },
374
+
375
+ async issueKey(raw: IssueKeyInput): Promise<IssueKeyResult> {
376
+ const input = withAcceptedRequestId(raw)
377
+ try {
378
+ // Resolve the ISSUER from the forwarded native credential.
379
+ const res = await resolveCaller(services, env, { app: input.app, credential: input.credential, requestId: input.requestId })
380
+ if (!res.ok) {
381
+ return { ok: false, reason: res.reason }
382
+ }
383
+ if (res.caller.type === undefined || isApplicationCaller(services, res.verifiedApp)) {
384
+ // Delegation + audit require an accountable principal; an application issues no credentials.
385
+ return { ok: false, reason: 'not_allowed' }
386
+ }
387
+ const issuer = res.caller
388
+ const app = res.verifiedApp
389
+ // iam.credential.create, in the key's own transaction — issuer, label, binding + grants; NEVER the
390
+ // plaintext token. `principalId` is the freshly-created service principal (service mode) or the
391
+ // self-bound principal; null for an anonymous key.
392
+ const { result } = await issueKey(services, input, { id: issuer.id, permissions: issuer.permissions }, app, (issued) => ({
393
+ requestId: input.requestId,
394
+ principalId: issuer.id,
395
+ principalLabel: auditLabelOf({ id: issuer.id, type: issuer.type, label: issuer.label }),
396
+ app,
397
+ action: 'iam.credential.create',
398
+ resourceType: 'credential',
399
+ resourceId: issued.credentialId,
400
+ metadata: {
401
+ label: input.service?.label ?? input.label ?? null,
402
+ principalId: issued.principalId ?? null,
403
+ service: input.service !== undefined,
404
+ grants: input.service?.permissions ?? input.permissions ?? [],
405
+ },
406
+ }))
407
+ return result
408
+ } catch (err) {
409
+ logError(`issueKey failed for request '${input.requestId}'`, err)
410
+ ctx.waitUntil(
411
+ services.repositories.audit.writeAuthLog({
412
+ requestId: input.requestId,
413
+ app: input.app,
414
+ kind: 'authenticate',
415
+ principalId: null,
416
+ decision: 'deny',
417
+ reason: 'internal_error',
418
+ }),
419
+ )
420
+ return { ok: false, reason: 'unknown_principal' }
421
+ }
422
+ },
423
+ }
424
+ }
425
+
426
+ /**
427
+ * True when the verified app is an application rather than a platform audience. An application issues
428
+ * no credentials (ADR-0022 rule 5), so its token may not reach `issueKey` or `revokeKey` on any transport.
429
+ */
430
+ function isApplicationCaller(services: Services, verifiedApp: string): boolean {
431
+ return !services.config.platformAudiences.has(verifiedApp)
432
+ }
433
+
434
+ /**
435
+ * The caller's `requestId` held to the same rule as a header one (`src/request-id.ts`). A value that
436
+ * fails is replaced, not refused: `audit` is fire-and-forget, and refusing would drop the event.
437
+ */
438
+ function withAcceptedRequestId<T extends { requestId: string }>(input: T): T {
439
+ return { ...input, requestId: acceptRequestId(input.requestId) }
440
+ }
package/src/secret.ts ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Opaque-secret helpers shared by every stored credential (API keys, share links, SSO sessions):
3
+ * generate a high-entropy token and hash it for storage. Only the SHA-256 hash is ever persisted,
4
+ * so a DB leak yields no usable secret.
5
+ */
6
+
7
+ /** SHA-256 hex of a token. Only the hash is stored — a DB leak yields no usable token. */
8
+ export async function hashToken(token: string): Promise<string> {
9
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(token))
10
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')
11
+ }
12
+
13
+ /**
14
+ * Constant-time equality for two SHA-256 hex digests (`hashToken` output). Compares hashes, not raw
15
+ * secrets, and in constant time over equal-length inputs — so neither a length nor a per-character
16
+ * timing signal leaks how much of a presented token matched an expected one. Differing lengths are
17
+ * unequal (both are always 64-char hex here).
18
+ */
19
+ export function timingSafeEqualHex(a: string, b: string): boolean {
20
+ if (a.length !== b.length) {
21
+ return false
22
+ }
23
+ let diff = 0
24
+ for (let i = 0; i < a.length; i++) {
25
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i)
26
+ }
27
+ return diff === 0
28
+ }
29
+
30
+ /** A key IAM issued: `px_` and the 27 base64url characters `generateToken` writes. A public route refuses anything else before any lookup. */
31
+ export const ISSUED_KEY_FORMAT = /^px_[A-Za-z0-9_-]{27}$/
32
+
33
+ /**
34
+ * Generate a high-entropy random token (160 bits, > the 128-bit minimum) as
35
+ * URL-safe base64url. The plaintext is shown once at issue and never stored.
36
+ */
37
+ export function generateToken(): string {
38
+ const bytes = new Uint8Array(20)
39
+ crypto.getRandomValues(bytes)
40
+ let binary = ''
41
+ for (const b of bytes) {
42
+ binary += String.fromCharCode(b)
43
+ }
44
+ return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '')
45
+ }
package/src/service.ts ADDED
@@ -0,0 +1,59 @@
1
+ // IAM's service contract (ADR-0022 "Installation entries"): `createIamApp` serves it, and on Zerops the platform proxy
2
+ // decides from it. IAM's Cloudflare Worker stays unfronted; there the table is only its router.
3
+ //
4
+ // Every row is `protocol`: IAM authenticates each surface itself (its login, the JWKS, OAuth, `/admin/*` bearer-only,
5
+ // the shared secrets of `/rpc/*` and `/auth/mint/*`, an application's own key on `/membership/*`), so the proxy reads
6
+ // no credential here. This module imports only `@fabrika/app/service`, so strict consumers can import it without IAM's
7
+ // runtime.
8
+
9
+ import { defineServiceContract } from '@fabrika/app/service'
10
+
11
+ /** The composition switches of `IamAppOptions`; a switched-off surface has no row, so neither side serves it. */
12
+ export interface IamServiceOptions {
13
+ /** Process liveness (`health`). */
14
+ readonly health: boolean
15
+ /** The management transport `/rpc/*` (a non-empty `rpcKey`). */
16
+ readonly managementRpc: boolean
17
+ /** The proxy's mint transport `/auth/mint/*` (a non-empty `proxyKey`). */
18
+ readonly mintRpc: boolean
19
+ /** The applications' membership transport `/membership/<method>` (`membershipTransport`). */
20
+ readonly membershipTransport: boolean
21
+ }
22
+
23
+ export function iamServiceContract(options: IamServiceOptions) {
24
+ return defineServiceContract('iam', (s) => {
25
+ const mint = (path: string) => options.mintRpc ? s.protocol('*', path) : null
26
+ return {
27
+ endpoints: {
28
+ 'health': options.health ? s.health('*', '/healthz') : null,
29
+ 'jwks': s.protocol('*', '/.well-known/jwks.json'),
30
+ 'oauth-metadata': s.protocol('*', '/.well-known/oauth-authorization-server'),
31
+ 'oauth': s.protocol('*', '/oauth/*'),
32
+ 'auth-root': s.protocol('*', '/auth'),
33
+ 'auth': s.protocol('*', '/auth/*'),
34
+ 'mint-session': mint('/auth/mint/session'),
35
+ 'mint-key': mint('/auth/mint/key'),
36
+ 'mint-exchange': mint('/auth/mint/exchange'),
37
+ 'mint-delegation': mint('/auth/mint/delegation'),
38
+ 'admin-rpc': s.protocol('POST', '/admin/rpc'),
39
+ 'admin-root': s.protocol('*', '/admin'),
40
+ 'admin': s.protocol('*', '/admin/*'),
41
+ // Authenticated by the calling application's own transport key, per environment.
42
+ 'membership': options.membershipTransport ? s.protocol('*', '/membership/*') : null,
43
+ 'rpc-root': options.managementRpc ? s.protocol('*', '/rpc') : null,
44
+ 'rpc': options.managementRpc ? s.protocol('*', '/rpc/*') : null,
45
+ },
46
+ // A switched-off transport's paths reach no broader row: `/auth/mint/…` never falls to `/auth/*`.
47
+ reservedPrefixes: ['/auth/mint', '/rpc'],
48
+ }
49
+ })
50
+ }
51
+
52
+ /**
53
+ * What an installation's IAM process mounts, and so the table the platform proxy publishes: the Zerops topology always
54
+ * writes both transport keys. Zerops applications reach `/membership/*` and an operator's `fabrika control key issue`
55
+ * reaches `/rpc/*` at the public issuer; namespace proxies mint over `/auth/mint/*` there too.
56
+ */
57
+ export const IAM_INSTALLATION_SERVICE_OPTIONS: IamServiceOptions = { health: true, managementRpc: true, mintRpc: true, membershipTransport: true }
58
+
59
+ export type IamEndpointId = ReturnType<typeof iamServiceContract>['endpoints'][number]['id']