@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
package/src/index.ts ADDED
@@ -0,0 +1,292 @@
1
+ import type {
2
+ ApproveDeviceAuthorizationInput,
3
+ ApproveDeviceAuthorizationResult,
4
+ AssertIdentityInput,
5
+ AssertIdentityResult,
6
+ AssignMemberInput,
7
+ AssignMemberResult,
8
+ AuditInput,
9
+ CancelIdentificationInput,
10
+ CancelIdentificationResult,
11
+ CreateScopeInput,
12
+ CreateScopeResult,
13
+ DenyDeviceAuthorizationResult,
14
+ ExchangeAuthCodeInput,
15
+ ExchangeAuthCodeResult,
16
+ FindMemberInput,
17
+ FindMemberResult,
18
+ IamHandoffRpc,
19
+ IamMembershipRpc,
20
+ IamRpc,
21
+ IamTerminalRpc,
22
+ InspectDeviceAuthorizationInput,
23
+ InspectDeviceAuthorizationResult,
24
+ InspectIdentificationInput,
25
+ InspectIdentificationResult,
26
+ IssueKeyInput,
27
+ IssueKeyResult,
28
+ IssueLinkInput,
29
+ IssueLinkResult,
30
+ Jwks,
31
+ ListAppMembersInput,
32
+ ListAppMembersResult,
33
+ ListMembersInput,
34
+ ListMembersResult,
35
+ ListOwnDeviceAuthorizationsInput,
36
+ ListOwnDeviceAuthorizationsResult,
37
+ ListPrincipalsInput,
38
+ ListPrincipalsResult,
39
+ MembershipFailure,
40
+ MintFromKeyInput,
41
+ MintFromKeyResult,
42
+ MintTokenInput,
43
+ MintTokenResult,
44
+ RequestDelegationInput,
45
+ RequestDelegationResult,
46
+ RevokeKeyInput,
47
+ RevokeKeyResult,
48
+ RevokeLinkInput,
49
+ RevokeLinkResult,
50
+ RevokeMemberInput,
51
+ RevokeMemberResult,
52
+ TerminalFailure,
53
+ } from '@fabrika/auth-core'
54
+ import { EmailDeliveryError, type EmailSender, pickEmailEnvironment } from '@fabrika/email'
55
+ import { installationMailSender, PLATFORM_MAIL_CAPABILITIES } from '@fabrika/email/platform'
56
+ import { builtinEmailProviders } from '@fabrika/email/providers'
57
+ import { WorkerEntrypoint } from 'cloudflare:workers'
58
+ import { createIamApp } from './app'
59
+ import { bindingApp, isApplicationWorkerBinding } from './binding-identity'
60
+ import { runIamMaintenance } from './cron'
61
+ import { createIamRepositories } from './db'
62
+ import type { Env } from './env'
63
+ import { WORKERS_PBKDF2_COST } from './password-crypto'
64
+ import { createIamRpc } from './rpc'
65
+
66
+ /**
67
+ * The IAM Worker — the CLOUDFLARE entrypoint, and nothing more. Two `WorkerEntrypoint`s, reached over
68
+ * `env.IAM` service bindings, which do not traverse any public edge: `PropustkaApplication`, the
69
+ * subset an application calls, and the default export `Propustka`, which adds key issuing, device
70
+ * approval, `fetch()` (`/admin/*` + `/auth/*`) and the cron for platform components.
71
+ *
72
+ * There is no logic here. Every method delegates: the RPC surface to `createIamRpc` (src/rpc.ts),
73
+ * `fetch` to `workerApp`, `scheduled` to `runIamMaintenance` (src/cron.ts) — the same
74
+ * three functions the Bun entrypoint (src/node/server.ts) calls. This file's whole job is to bind
75
+ * `cloudflare:workers` to them, and it is the ONLY file in the package that imports it: the Bun
76
+ * process must never load this module, and it must never load `bun:*`/`node:*`.
77
+ * `src/__tests__/entrypoint-isolation.test.ts` walks both import graphs and enforces exactly that.
78
+ *
79
+ * `this.ctx` (an `ExecutionContext`) satisfies `RequestContext` structurally, so it is passed
80
+ * straight through with no adapter.
81
+ */
82
+
83
+ /**
84
+ * The composition facts this root supplies: which headers carry the client address and the request id.
85
+ *
86
+ * IAM's Worker holds its OWN Custom Domain — it is not behind a proxy Worker — so the hop in front of
87
+ * it is Cloudflare's edge, which writes `CF-Connecting-IP` and `cf-ray` on every request and replaces
88
+ * a caller's. No proxy strips `X-Request-Id` here, so it is caller-chosen and never trusted. See
89
+ * `src/client-address.ts` and `src/request-id.ts` for why IAM refuses to pick either itself.
90
+ */
91
+ const workerApp = createIamApp({ clientAddressHeader: 'CF-Connecting-IP', requestIdHeader: 'cf-ray' })
92
+ export interface WorkerBindings extends
93
+ Omit<
94
+ Env,
95
+ 'DB' | 'REPOSITORIES' | 'FABRIKA_IAM_SIGNING_KEYS' | 'FABRIKA_IAM_PROVISIONING_KEY' | 'EMAIL_CONFIG' | 'EMAIL_PROVIDERS' | 'PASSWORD_COST'
96
+ >
97
+ {
98
+ DB: D1Database
99
+ FABRIKA_IAM_SIGNING_KEYS?: string
100
+ FABRIKA_IAM_PROVISIONING_KEY?: string
101
+ /** Control's public origin: with a provider and the provisioning key, IAM's mail goes through Control's relay. */
102
+ FABRIKA_CONTROL_URL?: string
103
+ /** The mail transport's vars and secrets, whichever provider they name. */
104
+ [emailVariable: `FABRIKA_EMAIL_${string}`]: string | undefined
105
+ }
106
+
107
+ /** IAM's relay sender per bindings object, built once; absent where IAM sends with its own provider. */
108
+ const relayByBindings = new WeakMap<WorkerBindings, EmailSender | undefined>()
109
+
110
+ /**
111
+ * The sender to Control's mail relay, when IAM knows Control's origin and holds the provisioning key; `buildServices`
112
+ * uses it only while a provider is configured, as on Zerops. The relay knows IAM by `installationMailKey` of the
113
+ * provisioning key, the secret both Workers hold (Zerops derives it from `FABRIKA_IAM_RPC_KEY`, which a Cloudflare
114
+ * installation has none of).
115
+ */
116
+ function relaySender(bindings: WorkerBindings): EmailSender | undefined {
117
+ if (relayByBindings.has(bindings)) return relayByBindings.get(bindings)
118
+ const url = bindings.FABRIKA_CONTROL_URL?.trim() ?? ''
119
+ const secret = bindings.FABRIKA_IAM_PROVISIONING_KEY?.trim() ?? ''
120
+ const sender = url === '' || secret === '' ? undefined : url.startsWith('https://') ? installationMailSender({ url, secret }) : cleartextRelay
121
+ relayByBindings.set(bindings, sender)
122
+ return sender
123
+ }
124
+
125
+ /**
126
+ * What a Worker does with an `http:` Control origin (the deploy refuses one; a var edited by hand can still be one): it
127
+ * never sends the relay key in cleartext across the internet, and the refusal sends the message with IAM's own provider.
128
+ */
129
+ const cleartextRelay: EmailSender = {
130
+ capabilities: PLATFORM_MAIL_CAPABILITIES,
131
+ send: () => Promise.reject(new EmailDeliveryError('Platform mail URL is not an https origin', { code: 'invalid_configuration' })),
132
+ }
133
+
134
+ /** Present native Worker bindings as the runtime-neutral IAM environment. */
135
+ export function iamEnv(bindings: WorkerBindings): Env {
136
+ const relay = relaySender(bindings)
137
+ return {
138
+ ...bindings,
139
+ DB: bindings.DB,
140
+ REPOSITORIES: createIamRepositories(bindings.DB),
141
+ FABRIKA_IAM_SIGNING_KEYS: bindings.FABRIKA_IAM_SIGNING_KEYS ?? '',
142
+ FABRIKA_IAM_PROVISIONING_KEY: bindings.FABRIKA_IAM_PROVISIONING_KEY ?? '',
143
+ EMAIL_CONFIG: pickEmailEnvironment(bindings),
144
+ EMAIL_PROVIDERS: builtinEmailProviders,
145
+ PASSWORD_COST: WORKERS_PBKDF2_COST,
146
+ ...(relay === undefined ? {} : { PLATFORM_EMAIL_SENDER: relay }),
147
+ }
148
+ }
149
+
150
+ const NOT_ALLOWED: TerminalFailure = { ok: false, reason: 'not_allowed' }
151
+ const DELEGATION_NOT_ALLOWED: MembershipFailure = { ok: false, reason: 'not_allowed' }
152
+
153
+ /** Every call builds its surface from the Worker's own bindings; see `PropustkaApplication` for why it is no getter. */
154
+ function iamRpc(bindings: WorkerBindings, ctx: ExecutionContext): IamRpc & IamHandoffRpc & IamMembershipRpc & IamTerminalRpc {
155
+ return createIamRpc(iamEnv(bindings), ctx)
156
+ }
157
+
158
+ /**
159
+ * What an application's Workers call over `IAM`: the proxy mints and redeems, the SDK verifies, lists and
160
+ * audits, and the framework requests membership operations on its caller's behalf and identifies people at terminals.
161
+ * An identification operation is pinned to the application named by the binding's `props` (`binding-identity.ts`).
162
+ */
163
+ export type IamApplicationRpc =
164
+ & Pick<IamRpc, 'getJwks' | 'mintToken' | 'mintFromKey' | 'listPrincipals' | 'audit'>
165
+ & IamHandoffRpc
166
+ & IamMembershipRpc
167
+ & IamTerminalRpc
168
+
169
+ /**
170
+ * The entrypoint every application Worker and its proxy bind (`@fabrika/provider-cloudflare` refuses any
171
+ * other). It holds no getter or field: workerd serves every prototype member over RPC, and a getter
172
+ * returning the env or the RPC object would hand a caller IAM's secrets and every method withheld here.
173
+ */
174
+ export class PropustkaApplication extends WorkerEntrypoint<WorkerBindings> implements IamApplicationRpc {
175
+ mintToken(input: MintTokenInput): Promise<MintTokenResult> {
176
+ return iamRpc(this.env, this.ctx).mintToken(input)
177
+ }
178
+
179
+ mintFromKey(input: MintFromKeyInput): Promise<MintFromKeyResult> {
180
+ return iamRpc(this.env, this.ctx).mintFromKey(input)
181
+ }
182
+
183
+ /** Cross-host handoff redemption (ADR-0022), absent from `IamRpc`: the proxy Worker narrows this binding structurally. */
184
+ exchangeAuthCode(input: ExchangeAuthCodeInput): Promise<ExchangeAuthCodeResult> {
185
+ return iamRpc(this.env, this.ctx).exchangeAuthCode(input)
186
+ }
187
+
188
+ getJwks(): Promise<Jwks> {
189
+ return iamRpc(this.env, this.ctx).getJwks()
190
+ }
191
+
192
+ audit(event: AuditInput): Promise<void> {
193
+ return iamRpc(this.env, this.ctx).audit(event)
194
+ }
195
+
196
+ listPrincipals(input: ListPrincipalsInput): Promise<ListPrincipalsResult> {
197
+ return iamRpc(this.env, this.ctx).listPrincipals(input)
198
+ }
199
+
200
+ // The method stays for every framework release's binding check; only the proxy obtains a grant (ADR-0022 rule 6).
201
+ requestDelegation(input: RequestDelegationInput): Promise<RequestDelegationResult> {
202
+ return isApplicationWorkerBinding(this.ctx) ? Promise.resolve(DELEGATION_NOT_ALLOWED) : iamRpc(this.env, this.ctx).requestDelegation(input)
203
+ }
204
+
205
+ createScope(input: CreateScopeInput): Promise<CreateScopeResult> {
206
+ return iamRpc(this.env, this.ctx).createScope(input)
207
+ }
208
+
209
+ assignMember(input: AssignMemberInput): Promise<AssignMemberResult> {
210
+ return iamRpc(this.env, this.ctx).assignMember(input)
211
+ }
212
+
213
+ revokeMember(input: RevokeMemberInput): Promise<RevokeMemberResult> {
214
+ return iamRpc(this.env, this.ctx).revokeMember(input)
215
+ }
216
+
217
+ listMembers(input: ListMembersInput): Promise<ListMembersResult> {
218
+ return iamRpc(this.env, this.ctx).listMembers(input)
219
+ }
220
+
221
+ listAppMembers(input: ListAppMembersInput): Promise<ListAppMembersResult> {
222
+ return iamRpc(this.env, this.ctx).listAppMembers(input)
223
+ }
224
+
225
+ findMember(input: FindMemberInput): Promise<FindMemberResult> {
226
+ return iamRpc(this.env, this.ctx).findMember(input)
227
+ }
228
+
229
+ issueLink(input: IssueLinkInput): Promise<IssueLinkResult> {
230
+ return iamRpc(this.env, this.ctx).issueLink(input)
231
+ }
232
+
233
+ revokeLink(input: RevokeLinkInput): Promise<RevokeLinkResult> {
234
+ return iamRpc(this.env, this.ctx).revokeLink(input)
235
+ }
236
+
237
+ // The identification operations are pinned to the application whose deployment holds the binding, as the membership
238
+ // transport pins its key's (ADR-0067 §3): a credential's audience proves nothing about who calls.
239
+ inspectIdentification(input: InspectIdentificationInput): Promise<InspectIdentificationResult> {
240
+ return bindingApp(this.ctx) === input.app ? iamRpc(this.env, this.ctx).inspectIdentification(input) : Promise.resolve(NOT_ALLOWED)
241
+ }
242
+
243
+ assertIdentity(input: AssertIdentityInput): Promise<AssertIdentityResult> {
244
+ return bindingApp(this.ctx) === input.app ? iamRpc(this.env, this.ctx).assertIdentity(input) : Promise.resolve(NOT_ALLOWED)
245
+ }
246
+
247
+ cancelIdentification(input: CancelIdentificationInput): Promise<CancelIdentificationResult> {
248
+ return bindingApp(this.ctx) === input.app ? iamRpc(this.env, this.ctx).cancelIdentification(input) : Promise.resolve(NOT_ALLOWED)
249
+ }
250
+ }
251
+
252
+ /** The default export: the whole `IamRpc`, `/admin/*` + `/auth/*`, and the cron. Only platform components bind it. */
253
+ export class Propustka extends PropustkaApplication implements IamRpc, IamHandoffRpc {
254
+ inspectDeviceAuthorization(input: InspectDeviceAuthorizationInput): Promise<InspectDeviceAuthorizationResult> {
255
+ return iamRpc(this.env, this.ctx).inspectDeviceAuthorization(input)
256
+ }
257
+
258
+ approveDeviceAuthorization(input: ApproveDeviceAuthorizationInput): Promise<ApproveDeviceAuthorizationResult> {
259
+ return iamRpc(this.env, this.ctx).approveDeviceAuthorization(input)
260
+ }
261
+
262
+ denyDeviceAuthorization(input: InspectDeviceAuthorizationInput): Promise<DenyDeviceAuthorizationResult> {
263
+ return iamRpc(this.env, this.ctx).denyDeviceAuthorization(input)
264
+ }
265
+
266
+ listOwnDeviceAuthorizations(input: ListOwnDeviceAuthorizationsInput): Promise<ListOwnDeviceAuthorizationsResult> {
267
+ return iamRpc(this.env, this.ctx).listOwnDeviceAuthorizations(input)
268
+ }
269
+
270
+ revokeKey(input: RevokeKeyInput): Promise<RevokeKeyResult> {
271
+ return iamRpc(this.env, this.ctx).revokeKey(input)
272
+ }
273
+
274
+ issueKey(input: IssueKeyInput): Promise<IssueKeyResult> {
275
+ return iamRpc(this.env, this.ctx).issueKey(input)
276
+ }
277
+
278
+ override fetch(request: Request): Promise<Response> {
279
+ return workerApp.fetch(request, iamEnv(this.env), this.ctx)
280
+ }
281
+
282
+ /**
283
+ * Daily cron (see `triggers.crons`): prune old auth-log and password-transient rows.
284
+ * `WorkerEntrypoint.scheduled` receives only the controller; `env`/`ctx` come from `this`.
285
+ */
286
+ override scheduled(_controller: ScheduledController): Promise<void> {
287
+ runIamMaintenance(iamEnv(this.env), this.ctx)
288
+ return Promise.resolve()
289
+ }
290
+ }
291
+
292
+ export default Propustka
@@ -0,0 +1,82 @@
1
+ import { type InstallationBrand, installationBrandSchema } from '@fabrika/proxy-core/brand'
2
+ import { logWarn } from './log'
3
+ import type { InstallationBrandImages, InstallationBrandRow } from './repositories/brand'
4
+ import type { Services } from './services'
5
+
6
+ type StoredImages = Pick<InstallationBrandRow, 'light_type' | 'light_base64' | 'dark_type' | 'dark_base64'>
7
+
8
+ /** The images last checked, what the check made of them, and when a refusal of them was last logged (`storedBrand`). */
9
+ interface CheckedImages {
10
+ readonly row: StoredImages
11
+ readonly brand: InstallationBrand | null
12
+ readonly warnedAt: number
13
+ }
14
+
15
+ /**
16
+ * One entry for the process (the isolate, on Cloudflare). Not one per repository: the Worker builds its repositories
17
+ * for every request (`iamEnv`), so an entry kept on one would never be read again. Two IAM compositions in one process,
18
+ * which only tests run, share it: one's images then replace the other's, which costs a check and never a wrong answer.
19
+ */
20
+ let lastChecked: CheckedImages | null = null
21
+
22
+ /** How often a stored logo the check refuses is logged again, so the reason the pages lost it stays in the logs. */
23
+ export const REFUSED_BRAND_WARN_INTERVAL_MS = 60 * 60 * 1000
24
+
25
+ /**
26
+ * The brand a stored row holds, checked again as every reader of a brand checks it (`@fabrika/proxy-core/brand`), or
27
+ * null: for no row, for a cleared one, and for one the check now refuses, which then draws the fabrika mark.
28
+ *
29
+ * Every page reads the row, and it changes only with `brand.set` and `brand.clear`, so the check of the images last
30
+ * read is kept and a row with the same images takes its answer: comparing the stored strings is far cheaper than
31
+ * decoding them again. The key is the images themselves, never a time, so a change is checked whichever instance made it.
32
+ * A refused logo is logged when it is checked and again every `REFUSED_BRAND_WARN_INTERVAL_MS` while pages read it.
33
+ */
34
+ export function storedBrand(row: InstallationBrandRow | null, now: number = Date.now()): InstallationBrand | null {
35
+ if (row === null || row.light_type === null || row.light_base64 === null) {
36
+ lastChecked = null
37
+ return null
38
+ }
39
+ const checked = lastChecked
40
+ if (checked !== null && sameImages(checked.row, row)) {
41
+ // A clock stepped back would otherwise hold the next line off until it passes the last one again.
42
+ const elapsed = now - checked.warnedAt
43
+ if (checked.brand === null && (elapsed >= REFUSED_BRAND_WARN_INTERVAL_MS || elapsed < 0)) {
44
+ warnRefused()
45
+ lastChecked = { ...checked, warnedAt: now }
46
+ }
47
+ return checked.brand
48
+ }
49
+ const light = { type: row.light_type, base64: row.light_base64 }
50
+ const dark = row.dark_type === null || row.dark_base64 === null ? {} : { dark: { type: row.dark_type, base64: row.dark_base64 } }
51
+ const parsed = installationBrandSchema.safeParse({ light, ...dark })
52
+ if (!parsed.success) warnRefused()
53
+ const brand = parsed.success ? parsed.data : null
54
+ lastChecked = { row, brand, warnedAt: now }
55
+ return brand
56
+ }
57
+
58
+ function warnRefused(): void {
59
+ console.warn('installation brand: the stored logo fails the brand check, so the pages draw the fabrika mark')
60
+ }
61
+
62
+ function sameImages(a: StoredImages, b: StoredImages): boolean {
63
+ return a.light_type === b.light_type && a.light_base64 === b.light_base64 && a.dark_type === b.dark_type && a.dark_base64 === b.dark_base64
64
+ }
65
+
66
+ /** The images of `brand` as the repository stores them. */
67
+ export function brandImages(brand: InstallationBrand): InstallationBrandImages {
68
+ return { light: brand.light, dark: brand.dark ?? null }
69
+ }
70
+
71
+ /**
72
+ * The brand every IAM page draws, read once per render. A logo is decoration: a read that fails draws the fabrika mark
73
+ * and logs the failure's message, never the row, so a page that would otherwise render never fails for its logo.
74
+ */
75
+ export async function installationBrand(services: Services): Promise<InstallationBrand | null> {
76
+ try {
77
+ return storedBrand(await services.repositories.brand.get())
78
+ } catch (err) {
79
+ logWarn('installation brand could not be read, the page draws the fabrika mark', err)
80
+ return null
81
+ }
82
+ }
package/src/issue.ts ADDED
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Issuing credentials: `issueKey` writes an opaque, stored, revocable `px_` credential (API key /
3
+ * share link). The token's EFFECTIVE permissions are resolved at use time (`mintFromKey`); this just
4
+ * persists the row.
5
+ *
6
+ * Issuance is DELEGATED: the issuer (resolved server-side from the forwarded credentials, never
7
+ * self-asserted) may only grant what it itself holds — the same `permits` rule `can()` uses. The
8
+ * Worker entrypoint resolves the issuer and writes the audit row; this module is the pure-ish core.
9
+ */
10
+
11
+ import {
12
+ API_KEY_PREFIX,
13
+ isReservedScopeType,
14
+ type IssueKeyInput,
15
+ type IssueKeyResult,
16
+ type KeyGrant,
17
+ MAX_KEY_LIFETIME_SECONDS,
18
+ type PermissionEntry,
19
+ permits,
20
+ type RevokeKeyInput,
21
+ type RevokeKeyResult,
22
+ } from '@fabrika/auth-core'
23
+ import { uuidv7 } from '@fabrika/platform'
24
+ import type { AuditEventInput, CredentialGrantRow } from './db'
25
+ import { issuerAuthority } from './delegation'
26
+ import { unixNow } from './repositories/sql'
27
+ import { generateToken, hashToken } from './secret'
28
+ import type { Services } from './services'
29
+
30
+ /** The resolved caller (issuer), as `index.ts` resolves it from the forwarded JWT. */
31
+ interface Issuer {
32
+ id: string
33
+ permissions: PermissionEntry[]
34
+ }
35
+
36
+ /**
37
+ * What `issueKey` decided. A refusal with a `problem` was a malformed request (expiry, catalog), not a
38
+ * lack of authority: the admin path answers it with a 400 that names the problem, and the RPC still
39
+ * answers `not_allowed`, its only refusal reason.
40
+ */
41
+ export interface IssueOutcome {
42
+ result: IssueKeyResult
43
+ auditLabel?: string
44
+ problem?: string
45
+ }
46
+
47
+ /** The record of an issued key, given the ids the issuance generated; written in the key's own transaction. */
48
+ export type IssueRecord = (issued: { credentialId: string; principalId: string | undefined }) => AuditEventInput
49
+
50
+ const NOT_ALLOWED: IssueOutcome = { result: { ok: false, reason: 'not_allowed' } }
51
+
52
+ function refused(problem: string): IssueOutcome {
53
+ return { ...NOT_ALLOWED, problem }
54
+ }
55
+
56
+ /**
57
+ * Delegation check (pure): every requested grant must be covered by the issuer's permissions on its
58
+ * scope, using the same `permits` matching as `can()`. Returns the first uncovered grant, or null.
59
+ */
60
+ export function findUncoveredGrant(issuerPermissions: PermissionEntry[], grants: KeyGrant[]): KeyGrant | null {
61
+ for (const grant of grants) {
62
+ // A relation entry is derived from a role's via at every mint, never frozen into a key.
63
+ if (
64
+ (grant.scope !== null && grant.scope !== undefined && isReservedScopeType(grant.scope.type))
65
+ || !permits(issuerPermissions, grant.action, grant.scope ?? undefined)
66
+ ) {
67
+ return grant
68
+ }
69
+ }
70
+ return null
71
+ }
72
+
73
+ /**
74
+ * The expiry of a key that delegates `grants`: the requested one, or earlier when the issuer's grants behind them end
75
+ * first (S8). Null when the issuer no longer holds them live, or they end now.
76
+ */
77
+ async function delegatedExpiry(services: Services, issuer: Issuer, app: string, grants: KeyGrant[], requested: number): Promise<number | null> {
78
+ const required = grants.map((grant) => ({ action: grant.action, on: [grant.scope ?? null] }))
79
+ const authority = await issuerAuthority(services, issuer.id, app, null, required)
80
+ if (!authority.ok) {
81
+ return null
82
+ }
83
+ const expiresAt = authority.expiresAt === null ? requested : Math.min(requested, authority.expiresAt)
84
+ return expiresAt > unixNow() ? expiresAt : null
85
+ }
86
+
87
+ /** Why `expiresAt` is not an acceptable key expiry at `now` (both unix seconds), or null when it is. */
88
+ export function keyExpiryProblem(expiresAt: number, now: number): string | null {
89
+ if (!Number.isSafeInteger(expiresAt) || expiresAt <= now) {
90
+ return 'expiresAt must be a future unix time in seconds'
91
+ }
92
+ if (expiresAt - now > MAX_KEY_LIFETIME_SECONDS) {
93
+ return `expiresAt must be at most ${MAX_KEY_LIFETIME_SECONDS} seconds (30 days) ahead`
94
+ }
95
+ return null
96
+ }
97
+
98
+ /**
99
+ * Why a requested action may not go on a key, or null when every one may. A key lists EXACT catalog
100
+ * actions: a wildcard would also cover actions the app declares later, or never declares at all.
101
+ */
102
+ async function actionProblem(services: Services, app: string, actions: string[]): Promise<string | null> {
103
+ const wildcard = actions.find((action) => action.includes('*'))
104
+ if (wildcard !== undefined) {
105
+ return `a key lists exact actions, not the wildcard: ${wildcard}`
106
+ }
107
+ const catalog = new Set(await services.repositories.appSchema.listActionCatalog(app))
108
+ const unknown = actions.find((action) => !catalog.has(action))
109
+ return unknown === undefined ? null : `unknown action: ${unknown}`
110
+ }
111
+
112
+ // ── issueKey ──────────────────────────────────────────────────────────────────
113
+
114
+ /**
115
+ * Issue an opaque `px_` credential.
116
+ *
117
+ * `app` is the issuer's VERIFIED app, and every credential this function writes is bound to it. That
118
+ * binding is what makes delegation mean anything: the grants below are checked against the issuer's
119
+ * permissions *for this app*, so a credential that could be spent at another one would convert
120
+ * app-scoped authority into installation-wide authority (SEC-2). For the same reason every granted
121
+ * action must be an exact action of that app's catalog, and every key must expire within
122
+ * `MAX_KEY_LIFETIME_SECONDS`.
123
+ */
124
+ export async function issueKey(services: Services, input: IssueKeyInput, issuer: Issuer, app: string, record?: IssueRecord): Promise<IssueOutcome> {
125
+ // Every mode: a self-bound key is a standing copy of a 300-second token, a service key a new
126
+ // principal, a share link frozen authority — none of them may outlive the bound (SEC-7).
127
+ const expiryProblem = keyExpiryProblem(input.expiresAt, unixNow())
128
+ if (expiryProblem !== null) {
129
+ return refused(expiryProblem)
130
+ }
131
+ // An external principal's authority is its live external roles (ADR-0051): it issues only a key bound to itself,
132
+ // which resolves those live. A service or standalone key would freeze a copy that outlives them.
133
+ const selfBound = input.service === undefined && input.principalId === issuer.id
134
+ if (!selfBound && (await services.repositories.principals.getPrincipalById(issuer.id))?.affiliation !== 'internal') {
135
+ return NOT_ALLOWED
136
+ }
137
+
138
+ // Service mode: create a NEW machine principal + grant and bind the key to it (the folded
139
+ // issueServiceToken). The grant is scoped to the issuer's verified `app`; the issuer must hold
140
+ // every requested action on `scope` (the same delegation rule as a grant).
141
+ if (input.service !== undefined) {
142
+ const svc = input.service
143
+ const grants = svc.permissions.map((action) => ({ action, scope: svc.scope ?? null }))
144
+ if (grants.length === 0) {
145
+ return NOT_ALLOWED
146
+ }
147
+ const problem = await actionProblem(services, app, svc.permissions)
148
+ if (problem !== null) {
149
+ return refused(problem)
150
+ }
151
+ if (findUncoveredGrant(issuer.permissions, grants) !== null) {
152
+ return NOT_ALLOWED
153
+ }
154
+ const expiresAt = await delegatedExpiry(services, issuer, app, grants, input.expiresAt)
155
+ if (expiresAt === null) {
156
+ return NOT_ALLOWED
157
+ }
158
+ const token = `${API_KEY_PREFIX}${generateToken()}`
159
+ const principalId = uuidv7()
160
+ const id = uuidv7()
161
+ const { principals, grants: grantRepository, credentials, audit } = services.repositories
162
+ // The principal, its grant, its key and the record are one transaction: no half-issued service survives.
163
+ await audit.commit([
164
+ principals.createServiceStatement(principalId, svc.label),
165
+ grantRepository.grantStatement(uuidv7(), {
166
+ principalId,
167
+ app,
168
+ permissions: svc.permissions,
169
+ scopeType: svc.scope?.type ?? null,
170
+ scopeValue: svc.scope?.value ?? null,
171
+ grantedBy: issuer.id,
172
+ expiresAt,
173
+ }),
174
+ ...credentials.credentialStatements(id, {
175
+ tokenHash: await hashToken(token),
176
+ label: svc.label,
177
+ principalId,
178
+ app,
179
+ issuedBy: issuer.id,
180
+ expiresAt,
181
+ grants: [],
182
+ }),
183
+ ...(record === undefined ? [] : [audit.eventStatement(record({ credentialId: id, principalId }))]),
184
+ ])
185
+ return { result: { ok: true, token, id, principalId }, auditLabel: svc.label }
186
+ }
187
+
188
+ // v1: binding is only to the issuer's OWN principal (a personal token). A standalone credential
189
+ // needs grants.
190
+ if (input.principalId !== undefined && input.principalId !== issuer.id) {
191
+ return NOT_ALLOWED
192
+ }
193
+ const grants = input.permissions ?? []
194
+ if (input.principalId === undefined && grants.length === 0) {
195
+ return NOT_ALLOWED
196
+ }
197
+ const problem = await actionProblem(services, app, grants.map((grant) => grant.action))
198
+ if (problem !== null) {
199
+ return refused(problem)
200
+ }
201
+ // Delegation: the issuer must hold every inline grant (trivially true for a self-bound downscope).
202
+ if (findUncoveredGrant(issuer.permissions, grants) !== null) {
203
+ return NOT_ALLOWED
204
+ }
205
+ // A self-bound key resolves its principal live at every mint; an anonymous one freezes what the issuer delegates.
206
+ const expiresAt = input.principalId === undefined ? await delegatedExpiry(services, issuer, app, grants, input.expiresAt) : input.expiresAt
207
+ if (expiresAt === null) {
208
+ return NOT_ALLOWED
209
+ }
210
+
211
+ const token = `${API_KEY_PREFIX}${generateToken()}`
212
+ const id = await services.repositories.credentials.createCredential({
213
+ tokenHash: await hashToken(token),
214
+ label: input.label ?? null,
215
+ principalId: input.principalId ?? null,
216
+ app,
217
+ issuedBy: issuer.id,
218
+ expiresAt,
219
+ grants: grants.map((g) => ({ action: g.action, scopeType: g.scope?.type ?? null, scopeValue: g.scope?.value ?? null })),
220
+ }, record === undefined ? undefined : (credentialId) => record({ credentialId, principalId: input.principalId }))
221
+ return { result: { ok: true, token, id, principalId: input.principalId }, auditLabel: input.label }
222
+ }
223
+
224
+ // ── revokeKey ───────────────────────────────────────────────────────────────────
225
+
226
+ /** A `credential_grants` row → a delegation-check `KeyGrant` (both scope cols null = global); a reserved `~` row grants nothing. */
227
+ function credentialGrantToKeyGrant(row: CredentialGrantRow): KeyGrant[] {
228
+ if (row.scope_type !== null && isReservedScopeType(row.scope_type)) return []
229
+ const scope = row.scope_type === null || row.scope_value === null ? null : { type: row.scope_type, value: row.scope_value }
230
+ return [{ action: row.action, scope }]
231
+ }
232
+
233
+ /**
234
+ * Revoke an opaque `px_` credential by id, for the caller's VERIFIED `app`. A credential bound to any
235
+ * other app — or to none, a cross-app key — is `not_found`, the same answer as an unknown id, so one
236
+ * app cannot probe or end another app's keys. Within the app, authorization mirrors the old capability
237
+ * revoke: the original issuer may always revoke; otherwise, for an ANONYMOUS credential (a share
238
+ * link), the caller must be able to re-issue its grants — hold every granted action, checked with the
239
+ * same `findUncoveredGrant` as issue. A principal-bound credential is managed through the principal
240
+ * path (the api-keys page), so a non-issuer caller cannot revoke it by id here. Idempotent — a second
241
+ * revoke returns `{ ok: true, revoked: false }`.
242
+ */
243
+ export async function revokeKey(
244
+ services: Services,
245
+ input: RevokeKeyInput,
246
+ revoker: Issuer,
247
+ app: string,
248
+ record?: AuditEventInput,
249
+ ): Promise<RevokeKeyResult> {
250
+ const cred = await services.repositories.credentials.getCredentialById(input.id)
251
+ if (!cred || cred.app !== app) {
252
+ return { ok: false, reason: 'not_found' }
253
+ }
254
+ if (cred.issued_by !== revoker.id) {
255
+ if (cred.principal_id !== null) {
256
+ return { ok: false, reason: 'not_allowed' }
257
+ }
258
+ const grants = (await services.repositories.credentials.getCredentialGrants(cred.id)).flatMap(credentialGrantToKeyGrant)
259
+ if (findUncoveredGrant(revoker.permissions, grants) !== null) {
260
+ return { ok: false, reason: 'not_allowed' }
261
+ }
262
+ }
263
+ const revoked = await services.repositories.credentials.revokeCredential(cred.id, record)
264
+ return { ok: true, revoked }
265
+ }
package/src/json.ts ADDED
@@ -0,0 +1,30 @@
1
+ /** `JSON.parse` typed to return `unknown` (the built-in returns `any`). */
2
+ export function parseJson(text: string): unknown {
3
+ return JSON.parse(text)
4
+ }
5
+
6
+ /**
7
+ * `parseJson` that yields `null` instead of throwing on malformed text.
8
+ *
9
+ * The JSON-bearing TEXT columns (`audit_events.diff`/`metadata`, `roles.permissions`,
10
+ * `grants.permissions`) used to carry a `CHECK (json_valid(...))`, which let read paths parse
11
+ * without a guard. That check is SQLite-only (Postgres has no equivalent inside the common
12
+ * subset), so it is gone from the migrations and the guarantee now lives at the two ends: the
13
+ * only writer JSON-encodes, and every reader goes through here. A hand-written or out-of-band
14
+ * row can therefore no longer 500 the admin API or break an authenticate().
15
+ */
16
+ export function parseJsonOrNull(text: string): unknown {
17
+ try {
18
+ return JSON.parse(text)
19
+ } catch {
20
+ return null
21
+ }
22
+ }
23
+
24
+ /** Read a property off an unknown value (undefined when absent / not an object). */
25
+ export function prop(value: unknown, key: string): unknown {
26
+ if (typeof value !== 'object' || value === null) {
27
+ return undefined
28
+ }
29
+ return Object.hasOwn(value, key) ? Reflect.get(value, key) : undefined
30
+ }