@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/env.ts ADDED
@@ -0,0 +1,132 @@
1
+ import type { EmailEnvironment, EmailProviderRegistry, EmailSender } from '@fabrika/email'
2
+ import type { SqlDatabase, WaitUntil } from '@fabrika/platform'
3
+ import type { IamRepositories } from './db'
4
+ import type { Pbkdf2Cost } from './password-crypto'
5
+
6
+ /**
7
+ * The IAM service's runtime surface: its two capability handles plus vars/secrets. Single source of
8
+ * truth — every other file imports from here, never re-declares the shape. JSON-typed vars
9
+ * (`HUMAN_EMAIL_DOMAINS`, `HUMAN_EMAILS`, `IAM_BOOTSTRAP_ADMINS`) are parsed once in `buildServices`.
10
+ *
11
+ * `DB` is a runtime port, not a Cloudflare binding, which lets one `Env` serve both entrypoints:
12
+ * on Workers a real `D1Database` satisfies it structurally, and the Bun entrypoint fills it with
13
+ * `PostgresDatabase`. Everything else here is a plain string, so it comes equally from `wrangler`
14
+ * vars or from `process.env`.
15
+ */
16
+ export interface Env {
17
+ /** Both policy tables and append-only audit tables (one database). D1 on Workers, Postgres on Bun. */
18
+ DB: SqlDatabase
19
+ /** Persistence capabilities selected by this runtime's composition root. */
20
+ REPOSITORIES: IamRepositories
21
+ /**
22
+ * JSON array of email domains admitted as a HUMAN at login (e.g. `["example.com","contember.com"]`).
23
+ * A `*` entry means admit anyone. IAM owns this centrally — the login-admission allowlist for
24
+ * self-provisioning a new identity. Consumed by `/auth/callback`.
25
+ */
26
+ HUMAN_EMAIL_DOMAINS: string
27
+ /** JSON array of specific emails admitted as a HUMAN, in ADDITION to the domains (a `*` = admit-all). */
28
+ HUMAN_EMAILS: string
29
+ /** JSON array of bootstrap-admin emails (normally empty). Always admitted; resolution-time only. */
30
+ IAM_BOOTSTRAP_ADMINS: string
31
+ /**
32
+ * Comma-separated app ids whose proxy-injected access token may administer `/admin/*` — the
33
+ * console gateway, and nothing else. Deploy var `FABRIKA_IAM_ADMIN_AUDIENCES`. Unset means the
34
+ * console's own app id; an explicitly empty value means no JWT may administer at all.
35
+ *
36
+ * A REGISTRY because every application in the installation receives the administrator's token in
37
+ * cleartext, so without a named audience any of them could replay it here.
38
+ */
39
+ ADMIN_AUDIENCES?: string
40
+ /**
41
+ * JSON: the OAuth 2.1 authorization server for MCP clients (`src/oauth-config.ts`). Absent or empty
42
+ * means OAuth is off and its routes 404. Deploy var `FABRIKA_IAM_OAUTH_CONFIG`. Malformed fails the boot.
43
+ */
44
+ OAUTH_CONFIG?: string
45
+ /**
46
+ * Days the maintenance cron keeps `auth_log` rows; unset means 30. Deploy var
47
+ * `FABRIKA_IAM_AUTH_LOG_RETENTION_DAYS`. A value that is not a whole number of days fails the boot.
48
+ */
49
+ AUTH_LOG_RETENTION_DAYS?: string
50
+ /**
51
+ * Days the maintenance cron keeps `audit_events` rows; unset keeps them all. Deploy var
52
+ * `FABRIKA_IAM_AUDIT_RETENTION_DAYS`. A value that is not a whole number of days fails the boot.
53
+ */
54
+ AUDIT_RETENTION_DAYS?: string
55
+ /** `local` / `stage` / `prod`. */
56
+ ENVIRONMENT: string
57
+ /** Explicit local-only human login bypass. Ignored unless `ENVIRONMENT=local`. */
58
+ LOCAL_DEV_LOGIN?: string
59
+ /** Independent authentication-method switches. Absent preserves the legacy OIDC-only mode. */
60
+ OIDC_ENABLED?: string
61
+ PASSWORD_ENABLED?: string
62
+ /** The installation's `FABRIKA_EMAIL_*` variables. An absent or `none` provider disables delivery. */
63
+ EMAIL_CONFIG?: EmailEnvironment
64
+ /** The providers `FABRIKA_EMAIL_PROVIDER` may name. Absent is an empty registry, which admits only `none`. */
65
+ EMAIL_PROVIDERS?: EmailProviderRegistry
66
+ /**
67
+ * A sender the composition root supplies in place of a configured provider: the local stack's mail capture. A port,
68
+ * not a variable, and refused by `buildServices` outside `ENVIRONMENT=local` or beside a configured provider.
69
+ */
70
+ EMAIL_SENDER?: EmailSender
71
+ /**
72
+ * The platform mail relay's sender: both compositions build it from `FABRIKA_CONTROL_URL` and the secret IAM's relay
73
+ * key derives from. `buildServices` sends through it while a provider is configured, and with that provider only when
74
+ * the relay refuses a message for good (`relayWithFallback`). Control then delivers through its own transport.
75
+ */
76
+ PLATFORM_EMAIL_SENDER?: EmailSender
77
+ /**
78
+ * The PBKDF2 cost this runtime can derive: a port the composition root sets, not a variable. Absent is the Bun cost,
79
+ * which production Workers refuse, so every Worker composition must pass `WORKERS_PBKDF2_COST`.
80
+ */
81
+ PASSWORD_COST?: Pbkdf2Cost
82
+
83
+ // ── IAM-native auth (IAM issues its own tokens; see token.ts / signing.ts) ──
84
+
85
+ /**
86
+ * IAM's OWN origin, e.g. `https://iam.example.com` — the `iss` of every minted
87
+ * token AND the base for the OIDC redirect URI. Derived from `FABRIKA_IAM_HOSTNAME` at
88
+ * deploy time; a localhost value locally.
89
+ */
90
+ ISSUER: string
91
+ /**
92
+ * **Secret.** JSON array of ES256 (EC P-256) PRIVATE JWKs. Index 0 is the active signer; all are
93
+ * published in the JWKS so a rotation key verifies before it signs. Empty locally → an ephemeral
94
+ * key is generated per isolate (dev only). Never placed in `vars` — provisioned as a Worker secret
95
+ * (`wrangler secret put` remote / `.dev.vars` local).
96
+ */
97
+ FABRIKA_IAM_SIGNING_KEYS: string
98
+ /**
99
+ * **Secret.** A single operator-generated provisioning `px_` key, or empty to disable (the default).
100
+ * Held ONLY here — never in the DB. A bearer whose hash matches it resolves a synthetic global-admin
101
+ * in `resolveCaller` (the machine analog of `IAM_BOOTSTRAP_ADMINS`): it lets a control plane bootstrap
102
+ * itself — reconcile app schemas / issue the first admin key — before any DB-backed admin credential
103
+ * exists. Provisioned as a Worker secret (`wrangler secret put` remote / `.dev.vars` local), never in
104
+ * `vars`. Rotate by changing the env value.
105
+ */
106
+ FABRIKA_IAM_PROVISIONING_KEY: string
107
+ /**
108
+ * OIDC provider issuer URL (e.g. `https://accounts.google.com`, an Auth0/Okta/Keycloak/Entra
109
+ * tenant). IAM discovers the endpoints from `${OIDC_ISSUER}/.well-known/openid-configuration`
110
+ * — so ANY OIDC provider works via config, no per-provider code.
111
+ */
112
+ OIDC_ISSUER?: string
113
+ /** OIDC client id (public). The SSO upstream — IAM federates here for human login. */
114
+ OIDC_CLIENT_ID?: string
115
+ /** **Secret.** OIDC client secret (the code-exchange credential). */
116
+ OIDC_CLIENT_SECRET?: string
117
+ /** Space-separated OIDC scopes; empty → `openid email profile`. */
118
+ OIDC_SCOPES?: string
119
+ /** `'false'` to accept logins whose `email_verified` claim is absent (an IdP that omits it); else verified is required. */
120
+ OIDC_REQUIRE_VERIFIED_EMAIL?: string
121
+ }
122
+
123
+ /**
124
+ * The slice of a request's runtime context the service actually uses: keeping work alive past the
125
+ * response. Deliberately NOT `ExecutionContext` — that type only exists on Workers, and a handler
126
+ * typed against it could not be called from a Bun process without inventing the rest of it. A real
127
+ * `ExecutionContext` satisfies this structurally, so the Worker entrypoint passes `this.ctx`
128
+ * unchanged; the Bun entrypoint passes `createBackgroundTasks()` from `@fabrika/platform-node`.
129
+ */
130
+ export interface RequestContext {
131
+ readonly waitUntil: WaitUntil
132
+ }
package/src/handoff.ts ADDED
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Cross-host session handoff ([ADR-0022](../../../docs/decisions/0022-the-proxy-is-the-only-enforcement-point.md)).
3
+ *
4
+ * IAM authenticates on ITS host and the app lives on another, where no cookie of IAM's can be read.
5
+ * So IAM issues a single-use code bound to `(session, app, return URL)`, the browser carries it to
6
+ * the app's own host, and the proxy there redeems it for an app-bound child session it CAN set.
7
+ *
8
+ * Two rules carry the security of the whole exchange:
9
+ *
10
+ * 1. **A return URL is validated against the app's registered origins, never trusted.** Whoever
11
+ * can ask for a code decides where the browser goes next, so an unregistered origin is refused
12
+ * outright — not quietly rewritten to the issuer, which would hide a misconfiguration behind a
13
+ * redirect loop.
14
+ * 2. **The child session is bound to one app.** The cookie is host-only, so another app cannot
15
+ * read it; the binding is the second lock, so a value that leaks anyway cannot buy a token for
16
+ * anything else (`mintToken` enforces it).
17
+ */
18
+
19
+ import { AUTH_CODE_TTL_SECONDS, type ExchangeAuthCodeInput, type ExchangeAuthCodeResult } from '@fabrika/auth-core'
20
+ import { principalStatus, type SessionTerminal, sessionTerminal } from './db'
21
+ import { pkceChallenge, randomToken } from './oidc'
22
+ import { normalizeOrigin } from './origin'
23
+ import { hashToken } from './secret'
24
+ import type { Services } from './services'
25
+
26
+ /** An issued code and when it dies. The plaintext is returned once and never stored. */
27
+ export interface IssuedAuthCode {
28
+ code: string
29
+ expiresAt: number
30
+ }
31
+
32
+ export { normalizeOrigin }
33
+
34
+ /**
35
+ * Check a proposed return URL against the app's registered origins and return it normalized, or null.
36
+ *
37
+ * The whole URL is rebuilt from its parts rather than echoed: the stored value is what a later
38
+ * redemption redirects the browser to, and reconstructing it means a caller cannot smuggle anything
39
+ * past the origin check in a component we never looked at.
40
+ */
41
+ export async function resolveReturnUrl(services: Services, app: string, rawUrl: string): Promise<string | null> {
42
+ let url: URL
43
+ try {
44
+ url = new URL(rawUrl)
45
+ } catch {
46
+ return null
47
+ }
48
+ const origin = normalizeOrigin(url.toString())
49
+ if (origin === null) {
50
+ return null
51
+ }
52
+ const registered = await services.repositories.handoff.listReturnOrigins(app)
53
+ if (!registered.includes(origin)) {
54
+ return null
55
+ }
56
+ return `${origin}${url.pathname}${url.search}`
57
+ }
58
+
59
+ /** Issue a single-use code for a validated return URL. */
60
+ export async function issueAuthCode(
61
+ services: Services,
62
+ input: { app: string; parentSessionId: string; returnUrl: string; challenge: string },
63
+ ): Promise<IssuedAuthCode> {
64
+ if (!validChallenge(input.challenge)) throw new Error('invalid handoff challenge')
65
+ // The stored hash integrity-binds the public challenge without adding a second persistence field.
66
+ const code = `${randomToken(32)}.${input.challenge}`
67
+ const expiresAt = Math.floor(Date.now() / 1000) + AUTH_CODE_TTL_SECONDS
68
+ await services.repositories.handoff.issueCode({
69
+ codeHash: await hashToken(code),
70
+ app: input.app,
71
+ parentSessionId: input.parentSessionId,
72
+ returnUrl: input.returnUrl,
73
+ expiresAt,
74
+ })
75
+ return { code, expiresAt }
76
+ }
77
+
78
+ /** The principal and the login's terminal are surfaced so the caller can write the `auth_log` row of a refusal. */
79
+ export interface ExchangeOutcome {
80
+ result: ExchangeAuthCodeResult
81
+ principalId: string | null
82
+ terminal: SessionTerminal | null
83
+ }
84
+
85
+ /**
86
+ * Redeem a code for an app-bound child session. Consumption is atomic and happens FIRST: a code that
87
+ * fails any later check is still spent, because a code that survives a failed redemption is a code an
88
+ * attacker can keep trying.
89
+ *
90
+ * The child inherits the parent's absolute expiry, so an app session can never outlive the login it
91
+ * came from, and `getActiveSessionByHash` re-checks the parent on every use so revocation reaches it.
92
+ */
93
+ export async function exchangeAuthCode(services: Services, input: ExchangeAuthCodeInput): Promise<ExchangeOutcome> {
94
+ const codeHash = await hashToken(input.code)
95
+ const now = Math.floor(Date.now() / 1000)
96
+ const consumed = await services.repositories.handoff.consumeCode(codeHash, now)
97
+ if (consumed === null) {
98
+ // Tell "never existed" from "too late" for the operator's benefit; the caller sees a deny either
99
+ // way, and neither answer confirms anything about a code the caller did not already hold.
100
+ const existing = await services.repositories.handoff.findCode(codeHash)
101
+ const reason = existing === null ? 'invalid_code' : 'expired_code'
102
+ return { result: { ok: false, reason }, principalId: null, terminal: null }
103
+ }
104
+ if (consumed.app !== input.app) {
105
+ return { result: { ok: false, reason: 'wrong_app' }, principalId: null, terminal: null }
106
+ }
107
+ const challenge = challengeFromCode(input.code)
108
+ if (challenge === null || !validVerifier(input.verifier) || await pkceChallenge(input.verifier) !== challenge) {
109
+ return { result: { ok: false, reason: 'invalid_verifier' }, principalId: null, terminal: null }
110
+ }
111
+
112
+ // The login must still be usable: a code outliving a logout would resurrect the session it came from.
113
+ const parent = await services.repositories.sessions.getActiveSessionById(consumed.parent_session_id)
114
+ if (parent === null) {
115
+ return { result: { ok: false, reason: 'invalid_code' }, principalId: null, terminal: null }
116
+ }
117
+ const terminal = sessionTerminal(parent)
118
+ // A login asserted at a terminal reaches only the application that asserted it (ADR-0067 §4).
119
+ if (terminal !== null && terminal.assertedBy !== consumed.app) {
120
+ return { result: { ok: false, reason: 'wrong_app' }, principalId: parent.principal_id, terminal }
121
+ }
122
+ const principal = await services.repositories.principals.getPrincipalById(parent.principal_id)
123
+ if (principal === null) {
124
+ return { result: { ok: false, reason: 'unknown_principal' }, principalId: null, terminal }
125
+ }
126
+ if (principalStatus(principal) === 'disabled') {
127
+ return { result: { ok: false, reason: 'disabled' }, principalId: principal.id, terminal }
128
+ }
129
+
130
+ const session = randomToken(32)
131
+ // The child session and its `auth_log` row are one batch: a session nobody logged is never handed out.
132
+ await services.repositories.sessions.createSession({
133
+ tokenHash: await hashToken(session),
134
+ principalId: principal.id,
135
+ idpSub: parent.idp_sub,
136
+ email: parent.email,
137
+ authenticationMethod: parent.authentication_method,
138
+ expiresAt: parent.expires_at,
139
+ app: consumed.app,
140
+ parentSessionId: parent.id,
141
+ terminal,
142
+ terminalGeneration: parent.terminal_generation,
143
+ }, {
144
+ requestId: input.requestId,
145
+ app: input.app,
146
+ kind: 'authenticate',
147
+ principalId: principal.id,
148
+ decision: 'allow',
149
+ reason: 'handoff',
150
+ terminal,
151
+ })
152
+ return {
153
+ result: { ok: true, session, returnUrl: consumed.return_url, expiresAt: parent.expires_at },
154
+ principalId: principal.id,
155
+ terminal,
156
+ }
157
+ }
158
+
159
+ const CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/
160
+ const VERIFIER_PATTERN = /^[A-Za-z0-9_-]{43,128}$/
161
+
162
+ function validChallenge(value: string): boolean {
163
+ return CHALLENGE_PATTERN.test(value)
164
+ }
165
+
166
+ function validVerifier(value: string): boolean {
167
+ return VERIFIER_PATTERN.test(value)
168
+ }
169
+
170
+ function challengeFromCode(code: string): string | null {
171
+ const separator = code.lastIndexOf('.')
172
+ if (separator === -1) return null
173
+ const challenge = code.slice(separator + 1)
174
+ return validChallenge(challenge) ? challenge : null
175
+ }
package/src/html.ts ADDED
@@ -0,0 +1,4 @@
1
+ /** Escape a value for HTML text and a quoted attribute. Every value a page or an e-mail inserts passes through it. */
2
+ export function escapeHtml(value: string): string {
3
+ return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#39;')
4
+ }
@@ -0,0 +1,40 @@
1
+ import { normalizeEmailIdentity } from './email-identity'
2
+ import type { Config } from './services'
3
+
4
+ /**
5
+ * Whether the installation names `email` as one of the organization's own: a bootstrap admin, an exact entry of
6
+ * `HUMAN_EMAILS`, or an address in a `HUMAN_EMAIL_DOMAINS` domain. A `*` entry names nobody: it admits everyone, and
7
+ * is no statement about who belongs to the organization. IAM never creates such a mailbox as an external principal.
8
+ */
9
+ export function organizationMailbox(email: string, config: Pick<Config, 'human' | 'bootstrapAdmins'>): boolean {
10
+ const { emailDomains, emails } = config.human
11
+ const mailbox = normalizeEmailIdentity(email)
12
+ if (emails.some((allowed) => normalizeEmailIdentity(allowed) === mailbox)) {
13
+ return true
14
+ }
15
+ const at = mailbox.lastIndexOf('@')
16
+ const domain = at === -1 ? '' : mailbox.slice(at + 1)
17
+ if (domain !== '' && emailDomains.some((d) => d.toLowerCase() === domain)) {
18
+ return true
19
+ }
20
+ return config.bootstrapAdmins.has(mailbox)
21
+ }
22
+
23
+ /**
24
+ * The human-admission allowlist for self-provisioning a brand-new identity. IAM owns this
25
+ * centrally (the deploy vars `FABRIKA_IAM_HUMAN_EMAIL_DOMAINS` / `FABRIKA_IAM_HUMAN_EMAILS`):
26
+ * - a `*` entry in EITHER list = admit anyone (allow-all);
27
+ * - an exact email match in `emails`;
28
+ * - the email's domain in `emailDomains` (case-insensitive);
29
+ * - a bootstrap admin.
30
+ * Returns false otherwise — an empty allowlist with no `*` means only known/invited principals and
31
+ * bootstrap admins may log in (fail-closed). Matching uses ONLY the IdP-verified email.
32
+ *
33
+ * Both sides of every comparison are normalized. Entra and Okta both preserve directory casing, so a
34
+ * `FABRIKA_IAM_HUMAN_EMAILS` entry spelled `Vip@Example.com` used to be a control that simply never
35
+ * matched, with nothing said about it either way.
36
+ */
37
+ export function admitted(email: string, config: Pick<Config, 'human' | 'bootstrapAdmins'>): boolean {
38
+ const { emailDomains, emails } = config.human
39
+ return emailDomains.includes('*') || emails.includes('*') || organizationMailbox(email, config)
40
+ }
@@ -0,0 +1,185 @@
1
+ // The identification of a person at an enrolled terminal (ADR-0067 §2, §3): what an application asks IAM about an
2
+ // identification that `/auth/login` opened for a terminal's browser, and its word about who stands there. IAM takes the
3
+ // asserting application from the caller's verified token, never from the input. The code of the handoff the
4
+ // application's proxy started is issued only at the completion, to the terminal's own browser (`auth/terminals.ts`).
5
+
6
+ import {
7
+ type AssertIdentityInput,
8
+ type AssertIdentityResult,
9
+ type CancelIdentificationInput,
10
+ type CancelIdentificationResult,
11
+ IDENTIFICATION_QUERY_PARAMETER,
12
+ type InspectIdentificationInput,
13
+ type InspectIdentificationResult,
14
+ type TerminalCaller,
15
+ type TerminalFailure,
16
+ } from '@fabrika/auth-core'
17
+ import { uuidv7 } from '@fabrika/platform'
18
+ import { IAM_APP } from './admin/router'
19
+ import { administersIam } from './auth/sessions'
20
+ import { type PrincipalRow, principalStatus, type SessionTerminal, type TerminalIdentificationRow, type TerminalRow } from './db'
21
+ import type { Env } from './env'
22
+ import { randomToken } from './oidc'
23
+ import { unixNow } from './repositories/sql'
24
+ import { hashToken } from './secret'
25
+ import type { Services } from './services'
26
+ import { getSigner, verifyAccessToken } from './signing'
27
+
28
+ /** How long the person at a terminal has to identify before the sign-in starts over. */
29
+ export const IDENTIFICATION_TTL_SECONDS = 120
30
+
31
+ /** How long the terminal's browser has, after an assertion, to complete the identification at IAM. */
32
+ export const COMPLETION_TTL_SECONDS = 60
33
+
34
+ /** Where an application sends the terminal's browser after its assertion; IAM issues the code there. */
35
+ export const TERMINAL_COMPLETE_PATH = '/auth/terminals/complete'
36
+
37
+ /** The longest identification id or principal id IAM looks up; its own are far shorter. */
38
+ const MAX_ID_LENGTH = 128
39
+
40
+ const NOT_FOUND: TerminalFailure = { ok: false, reason: 'not_found' }
41
+ const INVALID_PRINCIPAL: TerminalFailure = { ok: false, reason: 'invalid_principal' }
42
+
43
+ type CallerEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>
44
+
45
+ /**
46
+ * The application asking: the `app` the transport already pinned (the membership key, or the binding's props), which the
47
+ * caller's token must also verify for. The token's audience alone is no proof of the caller.
48
+ */
49
+ async function askingApp(services: Services, env: CallerEnv, caller: TerminalCaller): Promise<{ ok: true; app: string } | TerminalFailure> {
50
+ if (caller.credential === null) {
51
+ return { ok: false, reason: 'missing_token' }
52
+ }
53
+ const claims = await verifyAccessToken(await getSigner(env), caller.credential, { issuer: services.config.issuer, audience: caller.app })
54
+ return claims === null ? { ok: false, reason: 'invalid_token' } : { ok: true, app: claims.aud }
55
+ }
56
+
57
+ interface OpenIdentification {
58
+ readonly identification: TerminalIdentificationRow
59
+ readonly terminal: TerminalRow
60
+ }
61
+
62
+ /**
63
+ * The identification `id` of `app` while it is open: unexpired, unconsumed, on an enrolled terminal not released since
64
+ * it was opened, with an enabled principal that still lists `app` as an asserter. Null for anything else, so an id reveals nothing.
65
+ */
66
+ async function openIdentification(services: Services, app: string, id: string, now: number): Promise<OpenIdentification | null> {
67
+ if (id.length === 0 || id.length > MAX_ID_LENGTH) {
68
+ return null
69
+ }
70
+ const { terminals, principals } = services.repositories
71
+ const identification = await terminals.getIdentification(await hashToken(id))
72
+ if (identification === null || identification.app !== app || identification.consumed_at !== null || identification.expires_at <= now) {
73
+ return null
74
+ }
75
+ const terminal = await terminals.getById(identification.terminal_id)
76
+ if (
77
+ terminal === null || terminal.revoked_at !== null || terminal.generation !== identification.generation
78
+ || await terminals.getAsserter(terminal.principal_id, app) === null
79
+ ) {
80
+ return null
81
+ }
82
+ const principal = await principals.getPrincipalById(terminal.principal_id)
83
+ if (principal === null || principalStatus(principal) !== 'active') {
84
+ return null
85
+ }
86
+ return { identification, terminal }
87
+ }
88
+
89
+ /** The terminal an open identification belongs to and when it expires; the application keys its throttle on the terminal. */
90
+ export async function inspectIdentification(
91
+ services: Services,
92
+ env: CallerEnv,
93
+ input: InspectIdentificationInput,
94
+ ): Promise<InspectIdentificationResult> {
95
+ const asking = await askingApp(services, env, input)
96
+ if (!asking.ok) {
97
+ return asking
98
+ }
99
+ const open = await openIdentification(services, asking.app, input.id, unixNow())
100
+ if (open === null) {
101
+ return NOT_FOUND
102
+ }
103
+ return { ok: true, terminal: { id: open.terminal.principal_id, label: open.terminal.label }, expiresAt: open.identification.expires_at }
104
+ }
105
+
106
+ /** The answer of an assertion, with the principal and terminal its `auth_log` row of a refusal names. */
107
+ export interface AssertOutcome {
108
+ result: AssertIdentityResult
109
+ principalId: string | null
110
+ terminal: SessionTerminal | null
111
+ }
112
+
113
+ /**
114
+ * The application's word that `principalId` stands at the identification's terminal. In one batch, IAM consumes the
115
+ * identification and opens a login for the person that no browser holds (the parent of the application session), with
116
+ * its `auth_log` row. It answers IAM's completion URL, never a code: only the terminal's own browser completes the
117
+ * identification there, and only then does IAM issue the code of the handoff the identification carries. A refused
118
+ * principal leaves the identification open, so the person can try again within its two minutes.
119
+ */
120
+ export async function assertIdentity(services: Services, env: CallerEnv, input: AssertIdentityInput): Promise<AssertOutcome> {
121
+ const asking = await askingApp(services, env, input)
122
+ if (!asking.ok) {
123
+ return { result: asking, principalId: null, terminal: null }
124
+ }
125
+ const now = unixNow()
126
+ const open = await openIdentification(services, asking.app, input.id, now)
127
+ if (open === null) {
128
+ return { result: NOT_FOUND, principalId: null, terminal: null }
129
+ }
130
+ const terminal: SessionTerminal = { terminalId: open.terminal.principal_id, assertedBy: asking.app }
131
+ const person = input.principalId.length > MAX_ID_LENGTH ? null : await services.repositories.principals.getPrincipalById(input.principalId)
132
+ if (person === null || !signsInAtTerminal(person)) {
133
+ return { result: INVALID_PRINCIPAL, principalId: person?.id ?? null, terminal }
134
+ }
135
+ const { terminals, sessions } = services.repositories
136
+ const idHash = open.identification.id_hash
137
+ const loginId = uuidv7()
138
+ const login = sessions.createSessionStatements(loginId, {
139
+ tokenHash: await hashToken(randomToken(32)),
140
+ principalId: person.id,
141
+ authenticationMethod: 'terminal_assertion',
142
+ terminal,
143
+ terminalGeneration: open.identification.generation,
144
+ expiresAt: now + open.terminal.session_ttl,
145
+ }, {
146
+ requestId: input.requestId,
147
+ app: IAM_APP,
148
+ kind: 'authenticate',
149
+ principalId: person.id,
150
+ decision: 'allow',
151
+ reason: 'terminal_assertion',
152
+ privileged: await administersIam(services, person.id),
153
+ terminal,
154
+ }, terminals.consumedFor(idHash, loginId))
155
+ // Single use: a concurrent assertion of the same id consumes nothing, opens no login and is refused here.
156
+ const consumed = await terminals.consumeIdentification({ idHash, sessionId: loginId, now, completeBy: now + COMPLETION_TTL_SECONDS }, login)
157
+ if (consumed === null) {
158
+ return { result: NOT_FOUND, principalId: person.id, terminal }
159
+ }
160
+ const completion = new URL(TERMINAL_COMPLETE_PATH, services.config.issuer)
161
+ completion.searchParams.set(IDENTIFICATION_QUERY_PARAMETER, input.id)
162
+ return { result: { ok: true, completionUrl: completion.toString() }, principalId: person.id, terminal }
163
+ }
164
+
165
+ /** An active internal person. A service never signs in, and an external principal never on a terminal (ADR-0051). */
166
+ function signsInAtTerminal(principal: PrincipalRow): boolean {
167
+ return principal.type === 'user' && principal.affiliation === 'internal' && principalStatus(principal) === 'active'
168
+ }
169
+
170
+ /** End an identification of the asking application that the person abandoned. */
171
+ export async function cancelIdentification(
172
+ services: Services,
173
+ env: CallerEnv,
174
+ input: CancelIdentificationInput,
175
+ ): Promise<CancelIdentificationResult> {
176
+ const asking = await askingApp(services, env, input)
177
+ if (!asking.ok) {
178
+ return asking
179
+ }
180
+ if (input.id.length === 0 || input.id.length > MAX_ID_LENGTH) {
181
+ return NOT_FOUND
182
+ }
183
+ const cancelled = await services.repositories.terminals.cancelIdentification(await hashToken(input.id), asking.app)
184
+ return cancelled ? { ok: true } : NOT_FOUND
185
+ }