@fabrika/iam 0.0.1 → 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 +69 -8
  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
@@ -0,0 +1,333 @@
1
+ // `IamRpc` over HTTP — the transport a long-running process needs, because it has no service binding.
2
+ //
3
+ // WHAT THIS IS NOT: it is not a second implementation. `IamRpc` (@fabrika/auth-core) is unchanged and
4
+ // this file holds no policy — it decodes a JSON body into the method's input type, calls the SAME
5
+ // object `src/rpc.ts` builds, and encodes the result. Add a method to the contract and it must be
6
+ // added here too; nothing else moves.
7
+ //
8
+ // ── AUTHENTICATING THE SURFACE, and why it needs its own answer ───────────────────────────────────
9
+ //
10
+ // On Workers these methods sit behind a service binding, which is not addressable from outside the
11
+ // account: "who may call this" is answered by the topology, so three of the methods authenticate
12
+ // no caller at all. `issueKey`/`revokeKey`/`listPrincipals` resolve a caller from a
13
+ // forwarded credential and are safe on their own; `audit` takes its app from a verified token but
14
+ // trusts the rest of the event, so anyone holding an app's token could write that app's audit rows;
15
+ // and `mintToken`/`mintFromKey` are credential-checking oracles worth rate-limiting even though they
16
+ // fail closed. Over HTTP the topology guarantees nothing, so it has to be replaced,
17
+ // not assumed.
18
+ //
19
+ // The replacement is a SHARED SECRET on the transport: `Authorization: Bearer <rpcKey>`, compared as
20
+ // SHA-256 digests in constant time (`timingSafeEqualHex`), before the body is even parsed. Two
21
+ // properties of that choice are deliberate:
22
+ //
23
+ // * It is TRANSPORT auth, not caller identity. It says "this request came from inside the
24
+ // deployment", exactly as a service binding does, and nothing more — the per-caller authorization
25
+ // the management RPCs already do is untouched and still runs. Reusing
26
+ // `FABRIKA_IAM_PROVISIONING_KEY` here was rejected for precisely this reason: that key resolves to
27
+ // a synthetic global admin, so sharing it with every RPC client would hand every client admin.
28
+ // * NO KEY MEANS NO SURFACE. An unset key does not mean "open"; it means these routes 404 as if
29
+ // they were never mounted. A misconfigured deploy therefore loses RPC rather than publishing it,
30
+ // and there is no code path in which the check is skipped.
31
+ //
32
+ // Defence in depth on Zerops, not a substitute for the above: services are not publicly accessible
33
+ // until external access is opted into, so the IAM service exposes only its human-facing hostname and
34
+ // the RPC hop stays on the project's private network.
35
+ //
36
+ // ── TWO SURFACES, TWO KEYS ────────────────────────────────────────────────────────────────────────
37
+ //
38
+ // `/rpc/*` — the MANAGEMENT surface (`IamRpc` and `IamMembershipRpc`), gated by `rpcKey`.
39
+ // `/auth/mint/*` — the PROXY surface, gated by `proxyKey`: `mintToken`, `mintFromKey`,
40
+ // `exchangeAuthCode`, which redeems a cross-host handoff code for an app-bound
41
+ // session, and `requestDelegation`, a grant spent by the caller's token. Paths and
42
+ // wire shapes are fixed by `packages/proxy-core/src/iam.ts` (`HttpIamGateway`); that
43
+ // file is the contract.
44
+ //
45
+ // They are separate secrets on purpose, and the reason is least privilege rather than tidiness. The
46
+ // auth proxy is the ONLY publicly-routed component in the deployment, so it is the one most likely to
47
+ // be compromised — and it needs exactly those three IAM calls. Say the third one out loud, because it
48
+ // is the one that makes the split worth arguing about: a holder of `proxyKey` can turn a live,
49
+ // unconsumed handoff code into a SESSION. That is a real capability, and it is still the smaller
50
+ // grant — the code is single-use through a conditional UPDATE, stored only as a hash, bound to
51
+ // `(session, app, return URL)`, and dead after two minutes, so holding the key without also holding a
52
+ // fresh code buys nothing. Handing the proxy the MANAGEMENT key instead would hand it `audit`, which
53
+ // proves only the app (from a token) and takes the actor on the caller's word — and the proxy holds a
54
+ // token for every app it fronts, so a compromised proxy could forge audit rows for any of them. It could not escalate through
55
+ // `issueKey`/`revokeKey`/`listPrincipals` — those resolve a caller from a forwarded
56
+ // credential and enforce delegation regardless of the transport key — but the audit trail is exactly
57
+ // the thing that must survive a compromise of the edge. One extra env var buys that.
58
+ //
59
+ // Each key is independent, and each unset key 404s only its own surface: a deployment with a proxy
60
+ // and no control plane sets `proxyKey` alone, and vice versa.
61
+
62
+ import type { IamHandoffRpc, IamMembershipRpc, IamRpc } from '@fabrika/auth-core'
63
+ import { parseApproveDeviceAuthorizationInput, parseInspectDeviceAuthorizationInput, parseListOwnDeviceAuthorizationsInput } from '@fabrika/auth-core'
64
+ import {
65
+ assignMemberSchema,
66
+ auditSchema,
67
+ createScopeSchema,
68
+ exchangeAuthCodeSchema,
69
+ findMemberSchema,
70
+ issueKeySchema,
71
+ issueLinkSchema,
72
+ listAppMembersSchema,
73
+ listMembersSchema,
74
+ listPrincipalsSchema,
75
+ mintFromKeySchema,
76
+ mintTokenSchema,
77
+ requestDelegationSchema,
78
+ revokeKeySchema,
79
+ revokeLinkSchema,
80
+ revokeMemberSchema,
81
+ RpcInputError,
82
+ } from './rpc-inputs'
83
+ import { hashToken, timingSafeEqualHex } from './secret'
84
+
85
+ /** The path everything here is mounted under. `/rpc/<method>`, one segment, no nesting. */
86
+ export const RPC_PREFIX = '/rpc/'
87
+
88
+ /** True when `pathname` addresses the RPC surface — the mount check the server does before routing. */
89
+ export function isRpcPath(pathname: string): boolean {
90
+ return pathname === '/rpc' || pathname.startsWith(RPC_PREFIX)
91
+ }
92
+
93
+ /**
94
+ * Serve one RPC call. `rpcKey` is the shared secret; pass it exactly as configured — an empty or
95
+ * absent key disables the surface (404), which is the fail-closed default, not an error state.
96
+ *
97
+ * A method's own failure is a RESULT, not an HTTP error: a denied `issueKey` answers `200` with
98
+ * `{ ok: false, reason }`, because that is what the binding returns and callers must not have to
99
+ * distinguish "denied" from "unreachable". Only transport faults use status codes — 401 (bad key),
100
+ * 404 (no such method / surface disabled), 400 (undecodable body), 405 (not a POST).
101
+ */
102
+ export async function handleRpcHttp(request: Request, rpc: IamRpc & IamMembershipRpc, rpcKey: string): Promise<Response> {
103
+ if (rpcKey.trim() === '') {
104
+ return problem(404, 'not found')
105
+ }
106
+ if (request.method !== 'POST') {
107
+ return new Response(JSON.stringify({ error: 'method not allowed' }), {
108
+ status: 405,
109
+ headers: { 'content-type': 'application/json; charset=utf-8', allow: 'POST' },
110
+ })
111
+ }
112
+ if (!(await authorized(request, rpcKey))) {
113
+ // No `WWW-Authenticate` challenge: there is no interactive credential to prompt for, and the
114
+ // header would advertise the surface to a scanner that guessed the path.
115
+ return problem(401, 'unauthorized')
116
+ }
117
+
118
+ const method = new URL(request.url).pathname.slice(RPC_PREFIX.length)
119
+ const body: unknown = await readJsonBody(request)
120
+ if (body === MALFORMED) {
121
+ return problem(400, 'invalid JSON body')
122
+ }
123
+
124
+ try {
125
+ switch (method) {
126
+ case 'inspectDeviceAuthorization':
127
+ return json(await rpc.inspectDeviceAuthorization(parseInspectDeviceAuthorizationInput(body) ?? invalid('device input')))
128
+ case 'approveDeviceAuthorization':
129
+ return json(await rpc.approveDeviceAuthorization(parseApproveDeviceAuthorizationInput(body) ?? invalid('device input')))
130
+ case 'denyDeviceAuthorization':
131
+ return json(await rpc.denyDeviceAuthorization(parseInspectDeviceAuthorizationInput(body) ?? invalid('device input')))
132
+ case 'listOwnDeviceAuthorizations':
133
+ return json(await rpc.listOwnDeviceAuthorizations(parseListOwnDeviceAuthorizationsInput(body) ?? invalid('device input')))
134
+ case 'mintToken':
135
+ return json(await rpc.mintToken(mintTokenSchema.parse(body)))
136
+ case 'mintFromKey':
137
+ return json(await rpc.mintFromKey(mintFromKeySchema.parse(body)))
138
+ case 'issueKey':
139
+ return json(await rpc.issueKey(issueKeySchema.parse(body)))
140
+ case 'revokeKey':
141
+ return json(await rpc.revokeKey(revokeKeySchema.parse(body)))
142
+ case 'listPrincipals':
143
+ return json(await rpc.listPrincipals(listPrincipalsSchema.parse(body)))
144
+ case 'getJwks':
145
+ return json(await rpc.getJwks())
146
+ case 'audit':
147
+ await rpc.audit(auditSchema.parse(body))
148
+ // `audit` returns void over the binding, so there is no result to encode.
149
+ return new Response(null, { status: 204 })
150
+ case 'requestDelegation':
151
+ return json(await rpc.requestDelegation(requestDelegationSchema.parse(body)))
152
+ case 'createScope':
153
+ return json(await rpc.createScope(createScopeSchema.parse(body)))
154
+ case 'assignMember':
155
+ return json(await rpc.assignMember(assignMemberSchema.parse(body)))
156
+ case 'revokeMember':
157
+ return json(await rpc.revokeMember(revokeMemberSchema.parse(body)))
158
+ case 'listMembers':
159
+ return json(await rpc.listMembers(listMembersSchema.parse(body)))
160
+ case 'listAppMembers':
161
+ return json(await rpc.listAppMembers(listAppMembersSchema.parse(body)))
162
+ case 'findMember':
163
+ return json(await rpc.findMember(findMemberSchema.parse(body)))
164
+ case 'issueLink':
165
+ return json(await rpc.issueLink(issueLinkSchema.parse(body)))
166
+ case 'revokeLink':
167
+ return json(await rpc.revokeLink(revokeLinkSchema.parse(body)))
168
+ default:
169
+ return problem(404, 'not found')
170
+ }
171
+ } catch (err) {
172
+ if (err instanceof RpcInputError) {
173
+ return problem(400, err.message)
174
+ }
175
+ // The RPC methods fail closed and return a result rather than throwing; anything reaching here
176
+ // is unexpected. Log a message only — an error object can quote values that came off the wire.
177
+ console.error(`rpc '${method}' failed`, err instanceof Error ? err.message : 'unknown error')
178
+ return problem(500, 'internal error')
179
+ }
180
+ }
181
+
182
+ // ── The proxy surface: `/auth/mint/*` ─────────────────────────────────────────
183
+ //
184
+ // Four endpoints, fixed by `packages/proxy-core/src/iam.ts`: `mintToken`, `mintFromKey`,
185
+ // `exchangeAuthCode` and `requestDelegation`. They are the COLD PATH of every request the proxy handles — the first exchange
186
+ // of a browser session, a `px_` key, or an ADR-0022 handoff code for a short-lived signed token — and
187
+ // everything after that is a local JWKS verification inside the project. Do not change a
188
+ // path or a body shape here without changing `HttpIamGateway` in the same commit: a mismatch fails
189
+ // closed at runtime (the gateway maps any non-200 to `IamUnavailableError` → a 503 deny), which is
190
+ // safe but very hard to read from the outside.
191
+ //
192
+ // ALWAYS 200 ON A DECIDED OUTCOME, including a denial. That is not laxity — it is the distinction the
193
+ // proxy is built on: `{ ok: false, reason }` means "IAM answered: no", a non-200 means "IAM could not
194
+ // be consulted". Both deny, but only the second is an incident.
195
+
196
+ const MINT_PREFIX = '/auth/mint/'
197
+ /** Mint from the browser's SSO session cookie value. Body: `MintTokenInput`. */
198
+ export const MINT_SESSION_PATH = `${MINT_PREFIX}session`
199
+ /** Mint from an opaque `px_` credential (API key / share link). Body: `MintFromKeyInput`. */
200
+ export const MINT_KEY_PATH = `${MINT_PREFIX}key`
201
+ /** Redeem a cross-host handoff code for an app session (ADR-0022). Body: `ExchangeAuthCodeInput`. */
202
+ export const MINT_EXCHANGE_PATH = `${MINT_PREFIX}exchange`
203
+ /**
204
+ * A single-use delegation grant for one request to a membership or scope-creating endpoint (ADR-0022 rule 6).
205
+ * Body: `RequestDelegationInput`. On the proxy surface because the proxy obtains it for every such request; the
206
+ * authority is the caller's token in the body, so the proxy key adds none.
207
+ */
208
+ export const MINT_DELEGATION_PATH = `${MINT_PREFIX}delegation`
209
+
210
+ /** True when `pathname` addresses the proxy mint surface. Checked BEFORE the public `/auth/*` routes. */
211
+ export function isMintPath(pathname: string): boolean {
212
+ return pathname === MINT_SESSION_PATH || pathname === MINT_KEY_PATH || pathname === MINT_EXCHANGE_PATH || pathname === MINT_DELEGATION_PATH
213
+ }
214
+
215
+ /**
216
+ * Serve one mint call for the proxy. `proxyKey` is the shared secret; empty disables the surface.
217
+ *
218
+ * ON WHY THIS IS NOT PUBLIC. Minting confers nothing the caller does not already hold — you must
219
+ * present a valid session cookie value or a valid `px_` key, and the token you get back carries
220
+ * exactly that credential's resolved permissions for that app. So an open endpoint would not leak
221
+ * authority. What it WOULD do is publish an internet-facing oracle that answers "is this session/key
222
+ * still valid?" for unlimited guesses, and put a DB read, a permission resolution, an ES256 signature
223
+ * and an `auth_log` write behind every anonymous request to the platform's identity service. The
224
+ * credentials are 160/256-bit random so guessing is infeasible, but neither the oracle nor the
225
+ * amplification has any upside: the only intended caller is the proxy, and it can hold a key.
226
+ *
227
+ * ON RATE LIMITING — deliberately NOT done here. Requiring the key removes the anonymous attacker,
228
+ * which is the case that made this an oracle at all; what remains is per-client throttling, and this
229
+ * service cannot identify a client. Behind the project's L7 balancer the peer address is the
230
+ * balancer's, and the forwarded-header behaviour is not something this repo has verified; keying a
231
+ * limiter on a header a caller can set is worse than no limiter, because it looks like protection.
232
+ * The proxy does not limit either: it caches successful mints only, so every request with a present but
233
+ * unknown credential is one call here, and it holds no counter by design (ADR-0022). What bounds such a
234
+ * call is its cost: one or two indexed lookups and one `auth_log` deny row, less than a password attempt.
235
+ * Bounding raw request volume is the edge's job. The deny rows carry the app and the reason, so a
236
+ * burst is visible in the admin auth log.
237
+ */
238
+ export async function handleMintHttp(
239
+ request: Request,
240
+ rpc: IamRpc & IamHandoffRpc & Pick<IamMembershipRpc, 'requestDelegation'>,
241
+ proxyKey: string,
242
+ ): Promise<Response> {
243
+ if (proxyKey.trim() === '') {
244
+ return problem(404, 'not found')
245
+ }
246
+ if (request.method !== 'POST') {
247
+ return new Response(JSON.stringify({ error: 'method not allowed' }), {
248
+ status: 405,
249
+ headers: { 'content-type': 'application/json; charset=utf-8', allow: 'POST' },
250
+ })
251
+ }
252
+ if (!(await authorized(request, proxyKey))) {
253
+ return problem(401, 'unauthorized')
254
+ }
255
+
256
+ const body: unknown = await readJsonBody(request)
257
+ if (body === MALFORMED) {
258
+ return problem(400, 'invalid JSON body')
259
+ }
260
+
261
+ try {
262
+ const path = new URL(request.url).pathname
263
+ if (path === MINT_SESSION_PATH) {
264
+ return json(await rpc.mintToken(mintTokenSchema.parse(body)))
265
+ }
266
+ if (path === MINT_KEY_PATH) {
267
+ return json(await rpc.mintFromKey(mintFromKeySchema.parse(body)))
268
+ }
269
+ if (path === MINT_EXCHANGE_PATH) {
270
+ return json(await rpc.exchangeAuthCode(exchangeAuthCodeSchema.parse(body)))
271
+ }
272
+ if (path === MINT_DELEGATION_PATH) {
273
+ return json(await rpc.requestDelegation(requestDelegationSchema.parse(body)))
274
+ }
275
+ return problem(404, 'not found')
276
+ } catch (err) {
277
+ if (err instanceof RpcInputError) return problem(400, err.message)
278
+ // Both mint methods fail closed and return a result rather than throwing, so this is unreachable
279
+ // in practice. Log a message only — the body carried a credential.
280
+ console.error('mint failed', err instanceof Error ? err.message : 'unknown error')
281
+ return problem(500, 'internal error')
282
+ }
283
+ }
284
+
285
+ /** Constant-time bearer check against the configured key. Compares digests, never the raw secrets. */
286
+ async function authorized(request: Request, rpcKey: string): Promise<boolean> {
287
+ const header = request.headers.get('Authorization')
288
+ if (header === null) {
289
+ return false
290
+ }
291
+ const match = /^Bearer\s+(.+)$/i.exec(header.trim())
292
+ const presented = match?.[1]?.trim()
293
+ if (presented === undefined || presented === '') {
294
+ return false
295
+ }
296
+ // Hashing first makes the comparison fixed-width, so neither length nor prefix leaks by timing.
297
+ return timingSafeEqualHex(await hashToken(presented), await hashToken(rpcKey))
298
+ }
299
+
300
+ // ── Encoding ──────────────────────────────────────────────────────────────────
301
+
302
+ function json(body: unknown): Response {
303
+ return new Response(JSON.stringify(body), { headers: { 'content-type': 'application/json; charset=utf-8' } })
304
+ }
305
+
306
+ function problem(status: number, message: string): Response {
307
+ return new Response(JSON.stringify({ error: message }), {
308
+ status,
309
+ headers: { 'content-type': 'application/json; charset=utf-8' },
310
+ })
311
+ }
312
+
313
+ /** Distinguishes "the body was not JSON" from "the body decoded to something the decoders will reject". */
314
+ const MALFORMED = Symbol('malformed')
315
+
316
+ async function readJsonBody(request: Request): Promise<unknown> {
317
+ const text = await request.text()
318
+ // An EMPTY body is not an error: `getJwks` takes no input, so `POST /rpc/getJwks` with nothing
319
+ // attached is the natural call. It becomes `undefined`, which every other method's decoder then
320
+ // rejects by naming the field it wanted — a better answer than "invalid JSON".
321
+ if (text.trim() === '') {
322
+ return undefined
323
+ }
324
+ try {
325
+ return JSON.parse(text)
326
+ } catch {
327
+ return MALFORMED
328
+ }
329
+ }
330
+
331
+ function invalid(field: string): never {
332
+ throw new RpcInputError(`invalid or missing field '${field}'`)
333
+ }
@@ -0,0 +1,110 @@
1
+ import { LOCALES } from '@fabrika/auth-core'
2
+ import { z } from 'zod'
3
+
4
+ const optionalString = z.string().nullish().transform((value) => value ?? undefined)
5
+ const scopeSchema = z.object({ type: z.string(), value: z.string() }).nullish()
6
+ const grantSchema = z.object({ action: z.string(), scope: scopeSchema }).transform(({ action, scope }) => ({
7
+ action,
8
+ ...(scope === undefined ? {} : { scope }),
9
+ }))
10
+ const serviceSchema = z.object({ label: z.string(), permissions: z.array(z.string()), scope: scopeSchema })
11
+ .transform(({ label, permissions, scope }) => ({ label, permissions, ...(scope === undefined ? {} : { scope }) }))
12
+ const caller = { app: z.string(), credential: z.string().nullable(), requestId: z.string() }
13
+
14
+ // Field order preserves which error the HTTP transport reports first.
15
+ export const mintTokenSchema = z.object({ app: z.string(), session: z.string().nullable(), requestId: z.string() }).catch(rejectRpcInput)
16
+ export const mintFromKeySchema = z.object({ app: z.string(), key: z.string(), requestId: z.string() }).catch(rejectRpcInput)
17
+ export const exchangeAuthCodeSchema = z.object({ app: z.string(), code: z.string(), verifier: z.string(), requestId: z.string() }).catch(
18
+ rejectRpcInput,
19
+ )
20
+ export const issueKeySchema = z.object({
21
+ service: serviceSchema.nullish().transform((value) => value ?? undefined),
22
+ principalId: optionalString,
23
+ permissions: z.array(grantSchema).nullish().transform((value) => value ?? undefined),
24
+ label: optionalString,
25
+ expiresAt: z.number().finite(),
26
+ ...caller,
27
+ }).transform(({ app, credential, requestId, service, principalId, permissions, label, expiresAt }) => ({
28
+ app,
29
+ credential,
30
+ requestId,
31
+ ...(service === undefined ? {} : { service }),
32
+ ...(principalId === undefined ? {} : { principalId }),
33
+ ...(permissions === undefined ? {} : { permissions }),
34
+ ...(label === undefined ? {} : { label }),
35
+ expiresAt,
36
+ })).catch(rejectRpcInput)
37
+ export const revokeKeySchema = z.object({ ...caller, id: z.string() }).catch(rejectRpcInput)
38
+ export const listPrincipalsSchema = z.object(caller).catch(rejectRpcInput)
39
+ export const auditSchema = z.object({
40
+ credentialId: optionalString,
41
+ resourceId: optionalString,
42
+ credential: z.string(),
43
+ requestId: z.string(),
44
+ principalId: z.string().nullable(),
45
+ principalLabel: z.string(),
46
+ action: z.string(),
47
+ resourceType: z.string(),
48
+ diff: z.unknown(),
49
+ metadata: z.unknown(),
50
+ }).transform(({ credentialId, resourceId, diff, metadata, ...required }) => ({
51
+ ...required,
52
+ ...(credentialId === undefined ? {} : { credentialId }),
53
+ ...(resourceId === undefined ? {} : { resourceId }),
54
+ ...(diff === undefined ? {} : { diff }),
55
+ ...(metadata === undefined ? {} : { metadata }),
56
+ })).catch(rejectRpcInput)
57
+
58
+ const memberScopeSchema = z.object({ type: z.string(), value: z.string() })
59
+ export const requestDelegationSchema = z.object({ ...caller, endpoint: z.string() }).catch(rejectRpcInput)
60
+ export const createScopeSchema = z.object({ ...caller, delegation: z.string(), dimension: z.string() }).catch(rejectRpcInput)
61
+ export const assignMemberSchema = z.object({
62
+ ...caller,
63
+ delegation: z.string(),
64
+ scope: memberScopeSchema,
65
+ role: z.string(),
66
+ member: z.union([z.object({ principalId: z.string() }).strict(), z.object({ email: z.string() }).strict()]),
67
+ invitation: z
68
+ .object({ label: z.string().optional(), message: z.string().optional(), resend: z.boolean().optional(), locale: z.enum(LOCALES).optional() })
69
+ .strict()
70
+ .optional(),
71
+ }).catch(rejectRpcInput)
72
+ export const revokeMemberSchema = z.object({
73
+ ...caller,
74
+ delegation: z.string(),
75
+ scope: memberScopeSchema,
76
+ member: z.union([
77
+ z.object({ principalId: z.string(), role: z.string().nullish().transform((value) => value ?? null) }).strict(),
78
+ z.object({ invitationId: z.string() }).strict(),
79
+ ]),
80
+ }).catch(rejectRpcInput)
81
+ export const listMembersSchema = z.object({ ...caller, scope: memberScopeSchema }).catch(rejectRpcInput)
82
+ export const listAppMembersSchema = z.object({ ...caller, after: z.string().optional(), limit: z.number().finite().optional() }).catch(
83
+ rejectRpcInput,
84
+ )
85
+ export const findMemberSchema = z.object({
86
+ ...caller,
87
+ scope: memberScopeSchema,
88
+ principalId: z.string(),
89
+ action: z.string(),
90
+ }).catch(rejectRpcInput)
91
+ export const issueLinkSchema = z.object({ ...caller, mount: z.string(), chain: z.array(memberScopeSchema), days: z.number().finite() }).catch(
92
+ rejectRpcInput,
93
+ )
94
+ export const revokeLinkSchema = z.object({ ...caller, id: z.string() }).catch(rejectRpcInput)
95
+ export const inspectIdentificationSchema = z.object({ ...caller, id: z.string() }).catch(rejectRpcInput)
96
+ export const assertIdentitySchema = z.object({ ...caller, id: z.string(), principalId: z.string() }).catch(rejectRpcInput)
97
+ export const cancelIdentificationSchema = z.object({ ...caller, id: z.string() }).catch(rejectRpcInput)
98
+
99
+ export class RpcInputError extends Error {}
100
+
101
+ /** Preserve the transport's field-only errors without exposing submitted credentials. */
102
+ function rejectRpcInput({ error }: { error: z.ZodError }): never {
103
+ const path = error.issues[0]?.path ?? []
104
+ let field = String(path[0] ?? 'app')
105
+ if (field === 'service' && path[1] === 'scope') field = 'service.scope'
106
+ if (field === 'permissions' && typeof path[1] === 'number') {
107
+ field = path[2] === 'scope' ? 'permissions[].scope' : 'permissions[].action'
108
+ }
109
+ throw new RpcInputError(`invalid or missing field '${field}'`)
110
+ }