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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (312) hide show
  1. package/fabrika.config.ts +267 -0
  2. package/migrations/0001_init.sql +316 -0
  3. package/migrations/0002_oauth.sql +38 -0
  4. package/migrations/0003_contract_apps.sql +11 -0
  5. package/migrations/0004_membership.sql +93 -0
  6. package/migrations/0005_workloads.sql +23 -0
  7. package/migrations/0006_membership_transport_keys.sql +16 -0
  8. package/migrations/0007_member_directory.sql +7 -0
  9. package/migrations/0008_durable_audit.sql +28 -0
  10. package/migrations/0009_member_lookups.sql +7 -0
  11. package/migrations/0010_workload_issues.sql +6 -0
  12. package/migrations/0011_app_presentation.sql +15 -0
  13. package/migrations/0012_external_principals.sql +10 -0
  14. package/migrations/0013_app_mail_templates.sql +14 -0
  15. package/migrations/0014_invitation_wording.sql +8 -0
  16. package/migrations/0015_app_schema_revisions.sql +15 -0
  17. package/migrations/0016_principal_grant_revision.sql +9 -0
  18. package/migrations/0017_app_sign_ins.sql +12 -0
  19. package/migrations/0018_app_members.sql +13 -0
  20. package/migrations/0019_app_mail_html.sql +7 -0
  21. package/migrations/0020_public_workloads.sql +34 -0
  22. package/migrations/0021_installation_brand.sql +19 -0
  23. package/migrations/0022_password_policy.sql +12 -0
  24. package/migrations/0023_terminals.sql +155 -0
  25. package/migrations/0024_app_terminals.sql +10 -0
  26. package/migrations/0025_terminal_completion.sql +10 -0
  27. package/migrations/0026_terminal_generation.sql +12 -0
  28. package/migrations/0027_application_exact_actions.sql +28 -0
  29. package/migrations/0028_oauth_client_assertions.sql +10 -0
  30. package/migrations/0029_role_via.sql +6 -0
  31. package/migrations/0030_membership_role_via.sql +12 -0
  32. package/migrations/0031_person_locale.sql +11 -0
  33. package/migrations-postgres/0001_init.sql +331 -0
  34. package/migrations-postgres/0002_oauth.sql +36 -0
  35. package/migrations-postgres/0003_contract_apps.sql +8 -0
  36. package/migrations-postgres/0004_membership.sql +92 -0
  37. package/migrations-postgres/0005_workloads.sql +18 -0
  38. package/migrations-postgres/0006_membership_transport_keys.sql +12 -0
  39. package/migrations-postgres/0007_member_directory.sql +7 -0
  40. package/migrations-postgres/0008_durable_audit.sql +8 -0
  41. package/migrations-postgres/0009_member_lookups.sql +7 -0
  42. package/migrations-postgres/0010_workload_issues.sql +6 -0
  43. package/migrations-postgres/0011_app_presentation.sql +15 -0
  44. package/migrations-postgres/0012_external_principals.sql +10 -0
  45. package/migrations-postgres/0013_app_mail_templates.sql +14 -0
  46. package/migrations-postgres/0014_invitation_wording.sql +8 -0
  47. package/migrations-postgres/0015_app_schema_revisions.sql +15 -0
  48. package/migrations-postgres/0016_principal_grant_revision.sql +9 -0
  49. package/migrations-postgres/0017_app_sign_ins.sql +12 -0
  50. package/migrations-postgres/0018_app_members.sql +13 -0
  51. package/migrations-postgres/0019_app_mail_html.sql +7 -0
  52. package/migrations-postgres/0020_public_workloads.sql +9 -0
  53. package/migrations-postgres/0021_installation_brand.sql +19 -0
  54. package/migrations-postgres/0022_password_policy.sql +12 -0
  55. package/migrations-postgres/0023_terminals.sql +70 -0
  56. package/migrations-postgres/0024_app_terminals.sql +10 -0
  57. package/migrations-postgres/0025_terminal_completion.sql +10 -0
  58. package/migrations-postgres/0026_terminal_generation.sql +12 -0
  59. package/migrations-postgres/0027_application_exact_actions.sql +28 -0
  60. package/migrations-postgres/0028_oauth_client_assertions.sql +9 -0
  61. package/migrations-postgres/0029_role_via.sql +4 -0
  62. package/migrations-postgres/0030_membership_role_via.sql +7 -0
  63. package/migrations-postgres/0031_person_locale.sql +11 -0
  64. package/package.json +70 -5
  65. package/src/admin/access.ts +47 -0
  66. package/src/admin/api-keys.ts +280 -0
  67. package/src/admin/app-people.ts +209 -0
  68. package/src/admin/app-schema.ts +308 -0
  69. package/src/admin/audit.ts +81 -0
  70. package/src/admin/brand.ts +54 -0
  71. package/src/admin/connections.ts +48 -0
  72. package/src/admin/context.ts +70 -0
  73. package/src/admin/grant-support.ts +192 -0
  74. package/src/admin/grants.ts +189 -0
  75. package/src/admin/handlers.ts +102 -0
  76. package/src/admin/http.ts +24 -0
  77. package/src/admin/membership-keys.ts +38 -0
  78. package/src/admin/pagination.ts +28 -0
  79. package/src/admin/password-policy.ts +48 -0
  80. package/src/admin/passwords.ts +78 -0
  81. package/src/admin/policies.ts +136 -0
  82. package/src/admin/principals.ts +226 -0
  83. package/src/admin/router.ts +291 -0
  84. package/src/admin/rpc.ts +387 -0
  85. package/src/admin/sessions.ts +115 -0
  86. package/src/admin/share-links.ts +127 -0
  87. package/src/admin/terminals.ts +115 -0
  88. package/src/admin/user-admin.ts +76 -0
  89. package/src/admin/workloads.ts +85 -0
  90. package/src/app-presentation.ts +178 -0
  91. package/src/app.ts +158 -0
  92. package/src/auth/cookies.ts +64 -0
  93. package/src/auth/failure.ts +25 -0
  94. package/src/auth/handoff.ts +136 -0
  95. package/src/auth/http.ts +88 -0
  96. package/src/auth/invitations.ts +220 -0
  97. package/src/auth/known-device.ts +44 -0
  98. package/src/auth/login.ts +162 -0
  99. package/src/auth/oidc-flight.ts +91 -0
  100. package/src/auth/oidc.ts +148 -0
  101. package/src/auth/password.ts +416 -0
  102. package/src/auth/routes.ts +108 -0
  103. package/src/auth/sessions.ts +249 -0
  104. package/src/auth/terminals.ts +284 -0
  105. package/src/auth.ts +193 -0
  106. package/src/binding-identity.ts +25 -0
  107. package/src/bounded-body.ts +35 -0
  108. package/src/catalog/cs.ts +147 -0
  109. package/src/catalog/en.ts +148 -0
  110. package/src/catalog/index.ts +122 -0
  111. package/src/catalog/uk.ts +164 -0
  112. package/src/client-address.ts +39 -0
  113. package/src/common-passwords.ts +37 -0
  114. package/src/contract-rules.ts +80 -0
  115. package/src/cron.ts +54 -0
  116. package/src/db.ts +128 -0
  117. package/src/delegation.ts +100 -0
  118. package/src/device-http.ts +39 -0
  119. package/src/device.ts +269 -0
  120. package/src/email-identity.ts +2 -0
  121. package/src/env.ts +132 -0
  122. package/src/handoff.ts +175 -0
  123. package/src/html.ts +4 -0
  124. package/src/human-admission.ts +40 -0
  125. package/src/identification.ts +185 -0
  126. package/src/index.ts +292 -0
  127. package/src/installation-brand.ts +82 -0
  128. package/src/issue.ts +265 -0
  129. package/src/json.ts +30 -0
  130. package/src/log.ts +26 -0
  131. package/src/membership-http.ts +135 -0
  132. package/src/membership.ts +1210 -0
  133. package/src/messages.ts +44 -0
  134. package/src/narrow-permissions.ts +26 -0
  135. package/src/node/browser-identity.ts +69 -0
  136. package/src/node/migrate.ts +52 -0
  137. package/src/node/prune.ts +34 -0
  138. package/src/node/runtime.ts +221 -0
  139. package/src/node/server.ts +104 -0
  140. package/src/oauth-client-auth.ts +93 -0
  141. package/src/oauth-client.ts +145 -0
  142. package/src/oauth-config.ts +72 -0
  143. package/src/oauth-http.ts +262 -0
  144. package/src/oauth.ts +272 -0
  145. package/src/oidc.ts +260 -0
  146. package/src/origin.ts +29 -0
  147. package/src/password-crypto.ts +148 -0
  148. package/src/password-db.ts +419 -0
  149. package/src/password-minimum.ts +44 -0
  150. package/src/password-pages.ts +397 -0
  151. package/src/password-policy.ts +79 -0
  152. package/src/password-service.ts +67 -0
  153. package/src/person-locale.ts +103 -0
  154. package/src/proxy-proof.ts +36 -0
  155. package/src/relay-mail.ts +64 -0
  156. package/src/repositories/app-schema.ts +550 -0
  157. package/src/repositories/audit.ts +405 -0
  158. package/src/repositories/brand.ts +66 -0
  159. package/src/repositories/credentials.ts +331 -0
  160. package/src/repositories/device.ts +137 -0
  161. package/src/repositories/grants.ts +404 -0
  162. package/src/repositories/handoff.ts +103 -0
  163. package/src/repositories/membership-transport.ts +49 -0
  164. package/src/repositories/membership.ts +875 -0
  165. package/src/repositories/oauth.ts +122 -0
  166. package/src/repositories/password-policy.ts +44 -0
  167. package/src/repositories/principals.ts +358 -0
  168. package/src/repositories/sessions.ts +339 -0
  169. package/src/repositories/sql.ts +23 -0
  170. package/src/repositories/terminals.ts +346 -0
  171. package/src/repositories/workloads.ts +134 -0
  172. package/src/request-id.ts +46 -0
  173. package/src/resolve.ts +396 -0
  174. package/src/retention.ts +34 -0
  175. package/src/roles.ts +54 -0
  176. package/src/rpc-http.ts +333 -0
  177. package/src/rpc-inputs.ts +110 -0
  178. package/src/rpc.ts +440 -0
  179. package/src/secret.ts +45 -0
  180. package/src/service.ts +59 -0
  181. package/src/services.ts +199 -0
  182. package/src/signing.ts +260 -0
  183. package/src/stored-chain.ts +23 -0
  184. package/src/stored-permissions.ts +34 -0
  185. package/src/terminals.ts +15 -0
  186. package/src/tokens.ts +506 -0
  187. package/src/workload-token.ts +130 -0
  188. package/types/fabrika.config.d.ts +11 -0
  189. package/types/src/admin/access.d.ts +19 -0
  190. package/types/src/admin/api-keys.d.ts +26 -0
  191. package/types/src/admin/app-people.d.ts +8 -0
  192. package/types/src/admin/app-schema.d.ts +32 -0
  193. package/types/src/admin/audit.d.ts +10 -0
  194. package/types/src/admin/brand.d.ts +10 -0
  195. package/types/src/admin/connections.d.ts +5 -0
  196. package/types/src/admin/context.d.ts +46 -0
  197. package/types/src/admin/grant-support.d.ts +59 -0
  198. package/types/src/admin/grants.d.ts +8 -0
  199. package/types/src/admin/handlers.d.ts +82 -0
  200. package/types/src/admin/http.d.ts +9 -0
  201. package/types/src/admin/membership-keys.d.ts +8 -0
  202. package/types/src/admin/pagination.d.ts +5 -0
  203. package/types/src/admin/password-policy.d.ts +9 -0
  204. package/types/src/admin/passwords.d.ts +5 -0
  205. package/types/src/admin/policies.d.ts +15 -0
  206. package/types/src/admin/principals.d.ts +15 -0
  207. package/types/src/admin/router.d.ts +75 -0
  208. package/types/src/admin/rpc.d.ts +6 -0
  209. package/types/src/admin/sessions.d.ts +14 -0
  210. package/types/src/admin/share-links.d.ts +21 -0
  211. package/types/src/admin/terminals.d.ts +13 -0
  212. package/types/src/admin/user-admin.d.ts +30 -0
  213. package/types/src/admin/workloads.d.ts +5 -0
  214. package/types/src/app-presentation.d.ts +86 -0
  215. package/types/src/app.d.ts +62 -0
  216. package/types/src/auth/cookies.d.ts +29 -0
  217. package/types/src/auth/failure.d.ts +47 -0
  218. package/types/src/auth/handoff.d.ts +66 -0
  219. package/types/src/auth/http.d.ts +29 -0
  220. package/types/src/auth/invitations.d.ts +18 -0
  221. package/types/src/auth/known-device.d.ts +12 -0
  222. package/types/src/auth/login.d.ts +10 -0
  223. package/types/src/auth/oidc-flight.d.ts +39 -0
  224. package/types/src/auth/oidc.d.ts +7 -0
  225. package/types/src/auth/password.d.ts +7 -0
  226. package/types/src/auth/routes.d.ts +15 -0
  227. package/types/src/auth/sessions.d.ts +60 -0
  228. package/types/src/auth/terminals.d.ts +47 -0
  229. package/types/src/auth.d.ts +70 -0
  230. package/types/src/binding-identity.d.ts +12 -0
  231. package/types/src/bounded-body.d.ts +12 -0
  232. package/types/src/catalog/cs.d.ts +2 -0
  233. package/types/src/catalog/en.d.ts +2 -0
  234. package/types/src/catalog/index.d.ts +112 -0
  235. package/types/src/catalog/uk.d.ts +2 -0
  236. package/types/src/client-address.d.ts +31 -0
  237. package/types/src/common-passwords.d.ts +2 -0
  238. package/types/src/contract-rules.d.ts +25 -0
  239. package/types/src/cron.d.ts +15 -0
  240. package/types/src/db.d.ts +58 -0
  241. package/types/src/delegation.d.ts +38 -0
  242. package/types/src/device-http.d.ts +2 -0
  243. package/types/src/device.d.ts +11 -0
  244. package/types/src/email-identity.d.ts +1 -0
  245. package/types/src/env.d.ts +127 -0
  246. package/types/src/handoff.d.ts +57 -0
  247. package/types/src/html.d.ts +2 -0
  248. package/types/src/human-admission.d.ts +22 -0
  249. package/types/src/identification.d.ts +30 -0
  250. package/types/src/index.d.ts +62 -0
  251. package/types/src/installation-brand.d.ts +22 -0
  252. package/types/src/issue.d.ts +62 -0
  253. package/types/src/json.d.ts +15 -0
  254. package/types/src/log.d.ts +15 -0
  255. package/types/src/membership-http.d.ts +8 -0
  256. package/types/src/membership.d.ts +156 -0
  257. package/types/src/messages.d.ts +20 -0
  258. package/types/src/narrow-permissions.d.ts +7 -0
  259. package/types/src/node/browser-identity.d.ts +1 -0
  260. package/types/src/node/migrate.d.ts +4 -0
  261. package/types/src/node/prune.d.ts +1 -0
  262. package/types/src/node/runtime.d.ts +51 -0
  263. package/types/src/node/server.d.ts +5 -0
  264. package/types/src/oauth-client-auth.d.ts +26 -0
  265. package/types/src/oauth-client.d.ts +17 -0
  266. package/types/src/oauth-config.d.ts +16 -0
  267. package/types/src/oauth-http.d.ts +7 -0
  268. package/types/src/oauth.d.ts +51 -0
  269. package/types/src/oidc.d.ts +81 -0
  270. package/types/src/origin.d.ts +9 -0
  271. package/types/src/password-crypto.d.ts +37 -0
  272. package/types/src/password-db.d.ts +134 -0
  273. package/types/src/password-minimum.d.ts +23 -0
  274. package/types/src/password-pages.d.ts +143 -0
  275. package/types/src/password-policy.d.ts +19 -0
  276. package/types/src/password-service.d.ts +24 -0
  277. package/types/src/person-locale.d.ts +50 -0
  278. package/types/src/proxy-proof.d.ts +21 -0
  279. package/types/src/relay-mail.d.ts +25 -0
  280. package/types/src/repositories/app-schema.d.ts +244 -0
  281. package/types/src/repositories/audit.d.ts +187 -0
  282. package/types/src/repositories/brand.d.ts +41 -0
  283. package/types/src/repositories/credentials.d.ts +148 -0
  284. package/types/src/repositories/device.d.ts +50 -0
  285. package/types/src/repositories/grants.d.ts +177 -0
  286. package/types/src/repositories/handoff.d.ts +52 -0
  287. package/types/src/repositories/membership-transport.d.ts +31 -0
  288. package/types/src/repositories/membership.d.ts +273 -0
  289. package/types/src/repositories/oauth.d.ts +55 -0
  290. package/types/src/repositories/password-policy.d.ts +25 -0
  291. package/types/src/repositories/principals.d.ts +159 -0
  292. package/types/src/repositories/sessions.d.ts +150 -0
  293. package/types/src/repositories/sql.d.ts +13 -0
  294. package/types/src/repositories/terminals.d.ts +144 -0
  295. package/types/src/repositories/workloads.d.ts +61 -0
  296. package/types/src/request-id.d.ts +25 -0
  297. package/types/src/resolve.d.ts +118 -0
  298. package/types/src/retention.d.ts +18 -0
  299. package/types/src/roles.d.ts +34 -0
  300. package/types/src/rpc-http.d.ts +53 -0
  301. package/types/src/rpc-inputs.d.ts +707 -0
  302. package/types/src/rpc.d.ts +4 -0
  303. package/types/src/secret.d.ts +21 -0
  304. package/types/src/service.d.ts +19 -0
  305. package/types/src/services.d.ts +72 -0
  306. package/types/src/signing.d.ts +72 -0
  307. package/types/src/stored-chain.d.ts +6 -0
  308. package/types/src/stored-permissions.d.ts +12 -0
  309. package/types/src/terminals.d.ts +7 -0
  310. package/types/src/tokens.d.ts +113 -0
  311. package/types/src/workload-token.d.ts +7 -0
  312. package/README.md +0 -3
@@ -0,0 +1,199 @@
1
+ import { LOCAL_ENVIRONMENT, parseJsonStringArray, readEnvironmentName } from '@fabrika/auth-core'
2
+ import { type EmailSender, emailSenderFromEnv, readEmailTransportConfig } from '@fabrika/email'
3
+ import { uuidv7 } from '@fabrika/platform'
4
+ import type { IamRepositories } from './db'
5
+ import { normalizeEmailIdentity } from './email-identity'
6
+ import type { Env } from './env'
7
+ import { type OAuthConfig, parseOAuthConfig } from './oauth-config'
8
+ import { OidcClient } from './oidc'
9
+ import { BUN_PBKDF2_COST, type PasswordHasher, WebCryptoPasswordHasher } from './password-crypto'
10
+ import { passwordMinLengthFloor } from './password-minimum'
11
+ import { relayFallbackEvent, relayWithFallback } from './relay-mail'
12
+ import { parseRetention, type Retention } from './retention'
13
+
14
+ /**
15
+ * Pre-wired services + parsed config for every request. Handlers take `Services`
16
+ * (or pick what they need off it) instead of reaching into `env` directly —
17
+ * keeps them decoupled from the CF binding shape and easier to test.
18
+ */
19
+ export interface Services {
20
+ readonly repositories: IamRepositories
21
+ /** OIDC relying-party client. Null when the method is disabled. */
22
+ readonly oidc: OidcClient | null
23
+ readonly passwordHasher: PasswordHasher
24
+ readonly email: EmailSender | null
25
+ readonly config: Config
26
+ }
27
+
28
+ export interface Config {
29
+ /**
30
+ * The central human-admission allowlist — who may self-provision as a HUMAN at login. A `*` entry
31
+ * in either list means admit-all; otherwise an exact email or matching domain. Owned by IAM
32
+ * (deploy vars `FABRIKA_IAM_HUMAN_EMAIL_DOMAINS` / `FABRIKA_IAM_HUMAN_EMAILS`).
33
+ */
34
+ readonly human: {
35
+ readonly emailDomains: readonly string[]
36
+ readonly emails: readonly string[]
37
+ }
38
+ /** Bootstrap-admin emails (normally empty). Always admitted; resolve to the global `admin` role. */
39
+ readonly bootstrapAdmins: ReadonlySet<string>
40
+ /**
41
+ * App ids whose proxy-injected access token may administer `/admin/*` (`ADMIN_AUDIENCES`).
42
+ * EMPTY means no JWT may administer at all, which is the fail-closed end of the same registry.
43
+ */
44
+ readonly adminAudiences: ReadonlySet<string>
45
+ /**
46
+ * App ids of the installation's own services. Only a token for one of them carries cross-app grants
47
+ * and the bootstrap `admin`; an application token carries the grants of its own app id and nothing else.
48
+ */
49
+ readonly platformAudiences: ReadonlySet<string>
50
+ readonly environment: string
51
+ /** Create a real local admin session without contacting an external OIDC provider. */
52
+ readonly localDevLogin: boolean
53
+ readonly authentication: {
54
+ readonly oidc: { readonly enabled: boolean }
55
+ readonly password: {
56
+ readonly enabled: boolean
57
+ /** The lowest minimum length an administrator may set here (`passwordMinLengthFloor` of the hasher's cost). */
58
+ readonly minLengthFloor: number
59
+ }
60
+ }
61
+ /** The OAuth authorization server for MCP clients; null = off. */
62
+ readonly oauth: OAuthConfig | null
63
+ /** How long the maintenance cron keeps `auth_log` and `audit_events`. */
64
+ readonly retention: Retention
65
+ // ── IAM-native auth ──
66
+ /** IAM's own origin — the `iss` of minted tokens and the OIDC redirect base. */
67
+ readonly issuer: string
68
+ }
69
+
70
+ /**
71
+ * The console gateway's app id — the only first-party holder of a JWT that administers IAM, and so
72
+ * the audience an installation gets when it names none.
73
+ */
74
+ export const DEFAULT_ADMIN_AUDIENCES: ReadonlySet<string> = new Set(['vozka'])
75
+
76
+ /** IAM itself, the console (Control's app id) and Operations — the services every installation runs. */
77
+ export const DEFAULT_PLATFORM_AUDIENCES: ReadonlySet<string> = new Set(['propustka', 'vozka', 'operations'])
78
+
79
+ /** An admin audience is a console gateway, so it is a platform service too, whatever it is named. */
80
+ export function platformAudiencesFor(adminAudiences: ReadonlySet<string>): ReadonlySet<string> {
81
+ return new Set([...DEFAULT_PLATFORM_AUDIENCES, ...adminAudiences])
82
+ }
83
+
84
+ /** An app id as every fabrika config writes one — the shape an `aud` claim can actually carry. */
85
+ const APP_ID = /^[a-z0-9][a-z0-9-]*$/
86
+
87
+ /**
88
+ * Parse `ADMIN_AUDIENCES` (comma-separated app ids). Unset = `DEFAULT_ADMIN_AUDIENCES`; explicitly
89
+ * empty = no JWT may administer. A malformed entry is REFUSED rather than skipped: an entry no `aud`
90
+ * can ever equal would otherwise read as a registry while admitting nobody.
91
+ */
92
+ function parseAdminAudiences(raw: string | undefined): ReadonlySet<string> {
93
+ if (raw === undefined) {
94
+ return DEFAULT_ADMIN_AUDIENCES
95
+ }
96
+ if (raw.trim() === '') {
97
+ return new Set()
98
+ }
99
+ const audiences = new Set<string>()
100
+ for (const entry of raw.split(',')) {
101
+ const app = entry.trim()
102
+ if (!APP_ID.test(app)) {
103
+ throw new Error(`ADMIN_AUDIENCES holds a value that is not an app id: ${entry}`)
104
+ }
105
+ audiences.add(app)
106
+ }
107
+ return audiences
108
+ }
109
+
110
+ function parseBootstrapAdmins(raw: string): Set<string> {
111
+ return new Set(parseJsonStringArray(raw).map(normalizeEmailIdentity).filter((value) => value !== ''))
112
+ }
113
+
114
+ export function buildServices(env: Env): Services {
115
+ // This root's public origin IS `ISSUER`, so `local` cannot survive an IAM that mints tokens for a
116
+ // public name. Enforced here rather than per entrypoint because both engines pass through this
117
+ // function — the same reason `buildOidc` lives here.
118
+ const environment = readEnvironmentName(env.ENVIRONMENT, env.ISSUER)
119
+ const oidcEnabled = parseBooleanSwitch('OIDC_ENABLED', env.OIDC_ENABLED, true)
120
+ const passwordEnabled = parseBooleanSwitch('PASSWORD_ENABLED', env.PASSWORD_ENABLED, false)
121
+ if (!oidcEnabled && !passwordEnabled) {
122
+ throw new Error('At least one authentication method must be enabled')
123
+ }
124
+ const oidc = oidcEnabled ? buildOidc(env) : null
125
+ const adminAudiences = parseAdminAudiences(env.ADMIN_AUDIENCES)
126
+ const passwordCost = env.PASSWORD_COST ?? BUN_PBKDF2_COST
127
+ return {
128
+ repositories: env.REPOSITORIES,
129
+ oidc,
130
+ passwordHasher: new WebCryptoPasswordHasher(passwordCost),
131
+ email: buildEmailSender(env, environment),
132
+ config: {
133
+ human: {
134
+ emailDomains: parseJsonStringArray(env.HUMAN_EMAIL_DOMAINS),
135
+ emails: parseJsonStringArray(env.HUMAN_EMAILS),
136
+ },
137
+ bootstrapAdmins: parseBootstrapAdmins(env.IAM_BOOTSTRAP_ADMINS),
138
+ adminAudiences,
139
+ platformAudiences: platformAudiencesFor(adminAudiences),
140
+ environment,
141
+ localDevLogin: environment === LOCAL_ENVIRONMENT && env.LOCAL_DEV_LOGIN === 'true',
142
+ authentication: {
143
+ oidc: { enabled: oidcEnabled },
144
+ password: { enabled: passwordEnabled, minLengthFloor: passwordMinLengthFloor(passwordCost) },
145
+ },
146
+ oauth: parseOAuthConfig(env.OAUTH_CONFIG),
147
+ retention: parseRetention({ authLogDays: env.AUTH_LOG_RETENTION_DAYS, auditDays: env.AUDIT_RETENTION_DAYS }),
148
+ issuer: env.ISSUER,
149
+ },
150
+ }
151
+ }
152
+
153
+ function parseBooleanSwitch(name: string, raw: string | undefined, fallback: boolean): boolean {
154
+ if (raw === undefined || raw === '') return fallback
155
+ if (raw === 'true') return true
156
+ if (raw === 'false') return false
157
+ throw new Error(`${name} must be 'true' or 'false'`)
158
+ }
159
+
160
+ function required(name: string, value: string | undefined): string {
161
+ if (value === undefined || value.trim() === '') throw new Error(`${name} is required`)
162
+ return value
163
+ }
164
+
165
+ /**
166
+ * Build the relying-party client, REFUSING an incomplete configuration.
167
+ *
168
+ * The Bun composition has always failed the boot on a missing `OIDC_*`; the Worker used to substitute
169
+ * empty strings and serve an OIDC method that could only fail at the redirect. Two engines, two
170
+ * answers to one misconfiguration — the surviving one is the loud one, on the same reasoning as the
171
+ * proxy's key check and the signing-key refusal: refusing to boot beats booting misconfigured.
172
+ */
173
+ function buildOidc(env: Env): OidcClient {
174
+ return new OidcClient({
175
+ issuer: required('OIDC_ISSUER', env.OIDC_ISSUER),
176
+ clientId: required('OIDC_CLIENT_ID', env.OIDC_CLIENT_ID),
177
+ clientSecret: required('OIDC_CLIENT_SECRET', env.OIDC_CLIENT_SECRET),
178
+ redirectUri: `${env.ISSUER}/auth/callback`,
179
+ scopes: env.OIDC_SCOPES ?? '',
180
+ requireVerifiedEmail: env.OIDC_REQUIRE_VERIFIED_EMAIL !== 'false',
181
+ })
182
+ }
183
+
184
+ function buildEmailSender(env: Env, environment: string): EmailSender | null {
185
+ const config = env.EMAIL_CONFIG ?? {}
186
+ const providers = env.EMAIL_PROVIDERS ?? {}
187
+ if (env.EMAIL_SENDER !== undefined) {
188
+ if (environment !== LOCAL_ENVIRONMENT) throw new Error('A composition email sender is local-only; set ENVIRONMENT=local or remove it')
189
+ if (readEmailTransportConfig(config, providers).kind !== 'none') {
190
+ throw new Error('A composition email sender replaces FABRIKA_EMAIL_PROVIDER, which must then be none')
191
+ }
192
+ return env.EMAIL_SENDER
193
+ }
194
+ const direct = emailSenderFromEnv(config, providers)
195
+ // The provider stays the switch for delivery on both runtimes, and the relay's fallback for a refused message.
196
+ if (direct === null || env.PLATFORM_EMAIL_SENDER === undefined) return direct
197
+ const audit = env.REPOSITORIES.audit
198
+ return relayWithFallback(env.PLATFORM_EMAIL_SENDER, direct, (refusal) => audit.writeAuditEvent(relayFallbackEvent(uuidv7(), refusal)))
199
+ }
package/src/signing.ts ADDED
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Token signing key custody for IAM-issued tokens. The Worker is now an ISSUER: it signs
3
+ * per-app permission tokens (and capability tokens) with its own ES256 (EC P-256) key, and
4
+ * publishes the public half so the SDK verifies locally — no per-request round-trip.
5
+ *
6
+ * Keys come from the `FABRIKA_IAM_SIGNING_KEYS` secret (a JSON array of private JWKs). Index 0 is the
7
+ * ACTIVE signer; every key is published in the JWKS, so a freshly-added rotation key can be verified
8
+ * (it's in the public set) before it's promoted to index 0 to sign. Locally, with no keys
9
+ * configured, an EPHEMERAL key is generated per isolate — fine for dev (sessions reset on restart),
10
+ * refused on stage/prod (a real deploy must provision durable keys).
11
+ *
12
+ * One Signer per isolate, memoised like the `JwtValidator` (jose imports the key once).
13
+ */
14
+
15
+ import { type AccessTokenClaims, type Jwks, parseAccessClaims, type PublicJwk, RESOURCE_ACCESS_TOKEN_TYP, TOKEN_ALG } from '@fabrika/auth-core'
16
+ import {
17
+ calculateJwkThumbprint,
18
+ createLocalJWKSet,
19
+ exportJWK,
20
+ generateKeyPair,
21
+ importJWK,
22
+ type JWK,
23
+ type JWTPayload,
24
+ jwtVerify,
25
+ type KeyLike,
26
+ SignJWT,
27
+ } from 'jose'
28
+ import { z } from 'zod'
29
+ import type { Env } from './env'
30
+
31
+ /** A key jose can sign with (a CryptoKey-like `KeyLike` or a raw secret). */
32
+ type SignKey = KeyLike | Uint8Array
33
+
34
+ interface LoadedKey {
35
+ kid: string
36
+ /** Private key material, for signing. */
37
+ key: SignKey
38
+ /** Public half, for the JWKS. */
39
+ publicJwk: PublicJwk
40
+ }
41
+
42
+ export class Signer {
43
+ private constructor(private readonly keys: LoadedKey[]) {}
44
+
45
+ /**
46
+ * Sign a claims object with the ACTIVE key. The `kid` goes in the protected header so the SDK
47
+ * picks the matching public JWK. The claims already carry `iss`/`aud`/`exp` (built in core).
48
+ */
49
+ sign(claims: AccessTokenClaims): Promise<string> {
50
+ const active = this.keys[0]
51
+ if (!active) {
52
+ throw new Error('Signer has no keys')
53
+ }
54
+ return new SignJWT({ ...claims })
55
+ .setProtectedHeader({ alg: TOKEN_ALG, kid: active.kid })
56
+ .sign(active.key)
57
+ }
58
+
59
+ /**
60
+ * Sign an OAuth resource access token (`buildResourceAccessClaims`). `typ: at+jwt` (RFC 9068) is what
61
+ * keeps it from passing as a native app token, whose header carries no `typ`.
62
+ */
63
+ signResourceToken(claims: Record<string, unknown>): Promise<string> {
64
+ const active = this.keys[0]
65
+ if (!active) {
66
+ throw new Error('Signer has no keys')
67
+ }
68
+ return new SignJWT(claims)
69
+ .setProtectedHeader({ alg: TOKEN_ALG, kid: active.kid, typ: RESOURCE_ACCESS_TOKEN_TYP })
70
+ .sign(active.key)
71
+ }
72
+
73
+ /**
74
+ * Sign a short-lived INTERNAL payload — state IAM hands to a browser and expects back unaltered,
75
+ * such as the OIDC flight cookie. Not an access token: no `iss`, no `perms`, and an `aud` that is
76
+ * never an app id, so the two can never be mistaken for each other in either direction.
77
+ */
78
+ signInternal(payload: JWTPayload, audience: string, ttlSeconds: number): Promise<string> {
79
+ const active = this.keys[0]
80
+ if (!active) {
81
+ throw new Error('Signer has no keys')
82
+ }
83
+ return new SignJWT(payload)
84
+ .setProtectedHeader({ alg: TOKEN_ALG, kid: active.kid })
85
+ .setAudience(audience)
86
+ .setIssuedAt()
87
+ .setExpirationTime(`${ttlSeconds}s`)
88
+ .sign(active.key)
89
+ }
90
+
91
+ /** The public key set — active key first, then any rotation keys. */
92
+ jwks(): Jwks {
93
+ return { keys: this.keys.map((k) => k.publicJwk) }
94
+ }
95
+
96
+ /** Import the configured private JWKs (index 0 = active signer). */
97
+ static async fromPrivateJwks(jwks: JWK[]): Promise<Signer> {
98
+ const keys: LoadedKey[] = []
99
+ for (const jwk of jwks) {
100
+ const key = await importJWK(jwk, TOKEN_ALG)
101
+ const kid = jwk.kid ?? (await calculateJwkThumbprint(jwk))
102
+ keys.push({ kid, key, publicJwk: toPublicJwk(jwk, kid) })
103
+ }
104
+ if (keys.length === 0) {
105
+ throw new Error('No signing keys configured')
106
+ }
107
+ return new Signer(keys)
108
+ }
109
+
110
+ /** Generate an ephemeral signer — LOCAL DEV ONLY (rotates on isolate restart; sessions reset). */
111
+ static async ephemeral(): Promise<Signer> {
112
+ const { publicKey, privateKey } = await generateKeyPair(TOKEN_ALG, { extractable: true })
113
+ const publicJwk = await exportJWK(publicKey)
114
+ const kid = await calculateJwkThumbprint(publicJwk)
115
+ return new Signer([{ kid, key: privateKey, publicJwk: toPublicJwk(publicJwk, kid) }])
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Verify an IAM-issued NATIVE access token (`px_token`) against THIS signer's own public keys and
121
+ * narrow it to access claims; null on any failure. The server-side mirror of the SDK's local verify
122
+ * (`session.ts`) — IAM issued the token, so it trusts the `perms`/`ptype`/`aud` it signed. The
123
+ * signer already holds the current + rotation public keys, so there is no JWKS fetch or kid-miss retry.
124
+ *
125
+ * An OAuth resource token is REFUSED here: it was minted for an MCP client and one resource, and must
126
+ * never act as a native credential for IAM itself (`verifyResourceAccessToken` is its only reader).
127
+ */
128
+ export async function verifyAccessToken(
129
+ signer: Signer,
130
+ token: string,
131
+ opts: VerifyOptions & { audience?: string },
132
+ ): Promise<AccessTokenClaims | null> {
133
+ const verified = await verifySigned(signer, token, opts)
134
+ if (verified === null || verified.typ !== undefined || verified.claims.oauth !== undefined) return null
135
+ return verified.claims
136
+ }
137
+
138
+ /** Verify an OAuth resource token (`typ: at+jwt`, OAuth claims present); null for anything else. */
139
+ export async function verifyResourceAccessToken(signer: Signer, token: string, opts: VerifyOptions): Promise<AccessTokenClaims | null> {
140
+ const verified = await verifySigned(signer, token, opts)
141
+ if (verified === null || verified.typ !== RESOURCE_ACCESS_TOKEN_TYP || verified.claims.oauth === undefined) return null
142
+ return verified.claims
143
+ }
144
+
145
+ interface VerifyOptions {
146
+ issuer: string
147
+ /** Accept a token this many seconds past its `exp`. Only a caller that records, never authorizes, may pass it. */
148
+ expiryGraceSeconds?: number
149
+ }
150
+
151
+ async function verifySigned(
152
+ signer: Signer,
153
+ token: string,
154
+ opts: VerifyOptions & { audience?: string },
155
+ ): Promise<{ claims: AccessTokenClaims; typ: string | undefined } | null> {
156
+ try {
157
+ const { payload, protectedHeader } = await jwtVerify(token, createLocalJWKSet(signer.jwks()), {
158
+ algorithms: [TOKEN_ALG],
159
+ issuer: opts.issuer,
160
+ ...(opts.audience === undefined ? {} : { audience: opts.audience }),
161
+ ...(opts.expiryGraceSeconds === undefined ? {} : { clockTolerance: opts.expiryGraceSeconds }),
162
+ })
163
+ const claims = parseAccessClaims(payload)
164
+ return claims === null ? null : { claims, typ: protectedHeader.typ }
165
+ } catch {
166
+ return null
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Verify a payload `signInternal` produced, against this signer's own keys; null on any failure
172
+ * (bad signature, wrong audience, expired). The counterpart of `verifyAccessToken`, and deliberately
173
+ * separate: it demands the internal audience, so an access token never verifies here.
174
+ */
175
+ export async function verifyInternal(signer: Signer, token: string, audience: string): Promise<JWTPayload | null> {
176
+ try {
177
+ const { payload } = await jwtVerify(token, createLocalJWKSet(signer.jwks()), { audience })
178
+ return payload
179
+ } catch {
180
+ return null
181
+ }
182
+ }
183
+
184
+ /** Pick the public members of a JWK (drop the private `d`); stamp our alg/use/kid. */
185
+ function toPublicJwk(jwk: JWK, kid: string): PublicJwk {
186
+ return {
187
+ kty: jwk.kty ?? 'EC',
188
+ crv: jwk.crv,
189
+ x: jwk.x,
190
+ y: jwk.y,
191
+ kid,
192
+ alg: TOKEN_ALG,
193
+ use: 'sig',
194
+ }
195
+ }
196
+
197
+ /** Parse `FABRIKA_IAM_SIGNING_KEYS` into private JWKs. Throws loudly on malformed config (fail the deploy). */
198
+ export function parseSigningKeys(raw: string): JWK[] {
199
+ if (raw.trim() === '') {
200
+ return []
201
+ }
202
+ let parsed: unknown
203
+ try {
204
+ parsed = JSON.parse(raw)
205
+ } catch {
206
+ throw new Error('FABRIKA_IAM_SIGNING_KEYS is not valid JSON')
207
+ }
208
+ const keys = signingKeysSchema.safeParse(parsed)
209
+ if (!keys.success) {
210
+ const index = keys.error.issues[0]?.path[0]
211
+ if (typeof index !== 'number') throw new Error('FABRIKA_IAM_SIGNING_KEYS must be a JSON array of private JWKs')
212
+ throw new Error(`FABRIKA_IAM_SIGNING_KEYS[${index}] must be an EC P-256 private JWK (kty=EC, crv=P-256, x, y, d)`)
213
+ }
214
+ return keys.data
215
+ }
216
+
217
+ /** Build a typed EC P-256 private JWK from an untrusted object (no `as`); reject anything else. */
218
+ const privateJwkSchema = z.object({
219
+ kty: z.literal('EC'),
220
+ crv: z.literal('P-256'),
221
+ x: z.string(),
222
+ y: z.string(),
223
+ d: z.string(),
224
+ kid: z.string().optional().catch(undefined),
225
+ }).transform(({ kid, ...key }) => ({ ...key, alg: TOKEN_ALG, use: 'sig', ...(kid === undefined ? {} : { kid }) }))
226
+
227
+ const signingKeysSchema = z.array(privateJwkSchema)
228
+
229
+ // ── Per-isolate memoisation ────────────────────────────────────────────────────
230
+
231
+ let cached: { key: string; signer: Promise<Signer> } | undefined
232
+
233
+ /** The isolate-cached Signer for this env. Returns a promise (key import is async). */
234
+ export function getSigner(env: Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>): Promise<Signer> {
235
+ const raw = env.FABRIKA_IAM_SIGNING_KEYS ?? ''
236
+ const cacheKey = `${env.ENVIRONMENT}::${raw}`
237
+ if (cached && cached.key === cacheKey) {
238
+ return cached.signer
239
+ }
240
+ const signer = buildSigner(env.ENVIRONMENT, raw).catch((err: unknown) => {
241
+ // Don't cache a rejected promise — a fixed config should be retried, not poisoned.
242
+ if (cached?.key === cacheKey) {
243
+ cached = undefined
244
+ }
245
+ throw err
246
+ })
247
+ cached = { key: cacheKey, signer }
248
+ return signer
249
+ }
250
+
251
+ async function buildSigner(environment: string, raw: string): Promise<Signer> {
252
+ const jwks = parseSigningKeys(raw)
253
+ if (jwks.length > 0) {
254
+ return Signer.fromPrivateJwks(jwks)
255
+ }
256
+ if (environment === 'local') {
257
+ return Signer.ephemeral()
258
+ }
259
+ throw new Error('FABRIKA_IAM_SIGNING_KEYS is empty — provide an ES256 private JWK array for stage/prod.')
260
+ }
@@ -0,0 +1,23 @@
1
+ import type { Scope } from '@fabrika/auth-core'
2
+ import { parseJsonOrNull, prop } from './json'
3
+
4
+ /**
5
+ * A share link's stored containment chain (`credentials.link_chain`), or null when the column does not
6
+ * hold a non-empty array of `{type, value}`. A key whose chain does not parse resolves to nothing.
7
+ */
8
+ export function parseStoredChain(json: string): Scope[] | null {
9
+ const value = parseJsonOrNull(json)
10
+ if (!Array.isArray(value) || value.length === 0) {
11
+ return null
12
+ }
13
+ const chain: Scope[] = []
14
+ for (const item of value) {
15
+ const type = prop(item, 'type')
16
+ const scopeValue = prop(item, 'value')
17
+ if (typeof type !== 'string' || typeof scopeValue !== 'string') {
18
+ return null
19
+ }
20
+ chain.push({ type, value: scopeValue })
21
+ }
22
+ return chain
23
+ }
@@ -0,0 +1,34 @@
1
+ import { parseJsonStringArray } from '@fabrika/auth-core'
2
+
3
+ /** A role's stored `via`: relation → actions. A malformed row contributes nothing, as an unparseable grant does. */
4
+ export function parseStoredVia(json: string | null): Record<string, string[]> {
5
+ if (json === null) return {}
6
+ let value: unknown
7
+ try {
8
+ value = JSON.parse(json)
9
+ } catch {
10
+ return {}
11
+ }
12
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return {}
13
+ const via: Record<string, string[]> = {}
14
+ for (const [relation, actions] of Object.entries(value)) {
15
+ const parsed = parseJsonStringArray(JSON.stringify(actions))
16
+ if (relation.length > 0 && parsed.length > 0) via[relation] = parsed
17
+ }
18
+ return via
19
+ }
20
+
21
+ /** Legacy rows retain valid patterns even when other entries are malformed. */
22
+ export function parseStoredPermissions(json: string): string[] {
23
+ return parseJsonStringArray(json)
24
+ }
25
+
26
+ /**
27
+ * Every action a grant of a role carries: its own, and each one it holds through a relation (`via`). Whoever gives the
28
+ * role must hold each of them, by a grant of the action itself: a relation it holds them through does not count.
29
+ */
30
+ export function delegatedActions(role: { readonly permissions: string; readonly via: string | null }): string[] {
31
+ const actions = parseStoredPermissions(role.permissions)
32
+ for (const held of Object.values(parseStoredVia(role.via))) actions.push(...held)
33
+ return actions
34
+ }
@@ -0,0 +1,15 @@
1
+ /** The longest label an administrator may give a terminal, in code points. */
2
+ export const MAX_TERMINAL_LABEL_LENGTH = 100
3
+
4
+ /**
5
+ * A terminal's label as stored, or null when it may not be one: trimmed, 1 to `MAX_TERMINAL_LABEL_LENGTH` code points,
6
+ * no control character. It reaches a person's token as `terminal.label` and every page that names the terminal.
7
+ */
8
+ export function terminalLabel(raw: string): string | null {
9
+ const label = raw.trim()
10
+ const length = [...label].length
11
+ if (length === 0 || length > MAX_TERMINAL_LABEL_LENGTH || /\p{Cc}/u.test(label)) {
12
+ return null
13
+ }
14
+ return label
15
+ }