@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,44 @@
1
+ import { iamMessageTemplate, type MailTemplate, type MessageKind, type MessageValues, type RenderedMessage } from '@fabrika/auth-core'
2
+ import { type EmailMessage, MAX_EMAIL_SUBJECT_LENGTH } from '@fabrika/email'
3
+ import { type AppPresentation, landingUrl } from './app-presentation'
4
+ import type { Services } from './services'
5
+
6
+ /** How long one send may take. IAM has no request-scoped signal that outlives `waitUntil`, so each send carries its own. */
7
+ export const EMAIL_SEND_DEADLINE_MS = 30_000
8
+
9
+ /**
10
+ * The template IAM renders a presentation's `kind` e-mail with: the application's own wording in the presentation's
11
+ * language when it declares one, else the catalog's (`iamMessageTemplate`, which `fabrika app dev`'s stand-in IAM
12
+ * renders with too).
13
+ */
14
+ export async function messageTemplateFor<K extends MessageKind>(
15
+ services: Services,
16
+ presentation: AppPresentation,
17
+ kind: K,
18
+ ): Promise<(values: MessageValues[K]) => RenderedMessage> {
19
+ const app = presentation.app
20
+ const row = app === null ? null : await services.repositories.appSchema.getMailTemplate(app, kind, presentation.locale)
21
+ const template: MailTemplate | null = row === null
22
+ ? null
23
+ : { subject: row.subject, text: row.body, ...(row.html === null ? {} : { html: row.html }) }
24
+ return iamMessageTemplate(kind, {
25
+ locale: presentation.locale,
26
+ template,
27
+ displayName: presentation.displayName ?? app ?? '',
28
+ appUrl: landingUrl(presentation),
29
+ maxSubjectLength: MAX_EMAIL_SUBJECT_LENGTH,
30
+ })
31
+ }
32
+
33
+ /** One IAM e-mail: the template of its kind rendered from the closed values, to one mailbox. */
34
+ export async function renderEmail<K extends MessageKind>(services: Services, input: {
35
+ readonly to: string
36
+ readonly presentation: AppPresentation
37
+ readonly kind: K
38
+ readonly values: MessageValues[K]
39
+ readonly idempotencyKey: string
40
+ }): Promise<EmailMessage> {
41
+ const template = await messageTemplateFor(services, input.presentation, input.kind)
42
+ const rendered = template(input.values)
43
+ return { to: input.to, subject: rendered.subject, text: rendered.text, html: rendered.html, idempotencyKey: input.idempotencyKey }
44
+ }
@@ -0,0 +1,26 @@
1
+ import { type KeyGrant, matchAction, type PermissionEntry, type Scope, uniquePermissions } from '@fabrika/auth-core'
2
+
3
+ /**
4
+ * Intersect live permissions with a ceiling: an OAuth scope's grants, or a terminal's patterns for an application. The
5
+ * ceiling never adds anything: each result is the narrower action and the narrower scope of one held entry and one
6
+ * ceiling entry that overlap, so a held `*` under a ceiling `a.read` yields `a.read`.
7
+ */
8
+ export function narrowPermissions(live: readonly PermissionEntry[], ceiling: readonly KeyGrant[]): PermissionEntry[] {
9
+ const result: PermissionEntry[] = []
10
+ for (const held of live) {
11
+ for (const limit of ceiling) {
12
+ const action = matchAction(limit.action, held.action) ? held.action : matchAction(held.action, limit.action) ? limit.action : null
13
+ const scope = narrowerScope(held.scope, limit.scope ?? null)
14
+ if (action === null || scope === undefined) continue
15
+ result.push({ action, scope, source: held.source })
16
+ }
17
+ }
18
+ return uniquePermissions(result)
19
+ }
20
+
21
+ /** `null` is global; `undefined` means the two scopes do not overlap. */
22
+ function narrowerScope(held: Scope | null, limit: Scope | null): Scope | null | undefined {
23
+ if (held === null) return limit
24
+ if (limit === null) return held
25
+ return held.type === limit.type && held.value === limit.value ? held : undefined
26
+ }
@@ -0,0 +1,69 @@
1
+ /** Local browser-test identity seeding. This file is not mounted as an HTTP route. */
2
+ import { chmodSync, mkdirSync } from 'node:fs'
3
+ import { resolve } from 'node:path'
4
+ import { generateToken, hashToken } from '../secret'
5
+ import { createRuntime } from './runtime'
6
+
7
+ const OUTPUT_DIR = resolve(import.meta.dir, '..', '..', '..', 'local-stack', '.state', 'browser-identities')
8
+ const SESSION_TTL_SECONDS = 60 * 60
9
+
10
+ export type BrowserIdentityRole = 'admin' | 'operations-notes'
11
+
12
+ function parseRole(value: string | undefined): BrowserIdentityRole {
13
+ if (value === 'admin' || value === 'operations-notes') return value
14
+ throw new Error('role must be admin or operations-notes')
15
+ }
16
+
17
+ function parseOutputId(value: string | undefined): string {
18
+ if (value === undefined || !/^[0-9a-f-]{36}$/.test(value)) throw new Error('output id must be a UUID')
19
+ return value
20
+ }
21
+
22
+ async function createBrowserIdentity(role: BrowserIdentityRole, outputId: string): Promise<void> {
23
+ // The local IAM's provider is registered only by its server (`local-stack/src/iam-server.ts`); seeding sends no mail.
24
+ const runtime = await createRuntime({ ...process.env, FABRIKA_EMAIL_PROVIDER: 'none' })
25
+ try {
26
+ const email = `browser-${role}-${outputId}@fabrika.local`
27
+ const principal = await runtime.env.REPOSITORIES.principals.createUser(`browser-${outputId}`, email)
28
+ await runtime.env.REPOSITORIES.grants.createGrant({
29
+ principalId: principal.id,
30
+ app: role === 'admin' ? null : 'vozka',
31
+ permissions: role === 'admin' ? ['*'] : ['operations.*'],
32
+ ...(role === 'operations-notes' ? { scopeType: 'app', scopeValue: 'browser-notes' } : {}),
33
+ })
34
+ if (role === 'admin') {
35
+ // An application's token carries no cross-app grant (ADR-0022 rule 6), so the local Notes example, whose SPA
36
+ // admits a member only and lists the notes it may read, needs a grant of its own.
37
+ await runtime.env.REPOSITORIES.grants.createGrant({ principalId: principal.id, app: 'notes@prod', permissions: ['notes.read'] })
38
+ }
39
+
40
+ const session = generateToken()
41
+ const expiresAt = Math.floor(Date.now() / 1000) + SESSION_TTL_SECONDS
42
+ // A session is refused once its method is disabled, and this stack runs password-only (OIDC off),
43
+ // so the seeded login has to be a password one — which also means no IdP subject.
44
+ await runtime.env.REPOSITORIES.sessions.createSession({
45
+ tokenHash: await hashToken(session),
46
+ principalId: principal.id,
47
+ email,
48
+ authenticationMethod: 'password',
49
+ expiresAt,
50
+ })
51
+
52
+ mkdirSync(OUTPUT_DIR, { recursive: true, mode: 0o700 })
53
+ chmodSync(OUTPUT_DIR, 0o700)
54
+ const output = resolve(OUTPUT_DIR, `${outputId}.json`)
55
+ await Bun.write(output, `${JSON.stringify({ role, principalId: principal.id, label: email, session, expiresAt })}\n`)
56
+ chmodSync(output, 0o600)
57
+ } finally {
58
+ await runtime.shutdown()
59
+ }
60
+ }
61
+
62
+ if (import.meta.main) {
63
+ try {
64
+ await createBrowserIdentity(parseRole(Bun.argv[2]), parseOutputId(Bun.argv[3]))
65
+ } catch (error) {
66
+ console.error(error instanceof Error ? error.message : 'browser identity setup failed')
67
+ process.exit(1)
68
+ }
69
+ }
@@ -0,0 +1,52 @@
1
+ import {
2
+ definePostgresServiceMigrations,
3
+ PostgresDatabase,
4
+ type PostgresMigration,
5
+ type PostgresMigrationPlan,
6
+ postgresMigrationResultMessage,
7
+ } from '@fabrika/platform-node'
8
+ import { join } from 'node:path'
9
+
10
+ const MIGRATION_LOCK_KEY = 7214839201
11
+ const MIGRATIONS_DIR = join(import.meta.dir, '..', '..', 'migrations-postgres')
12
+ const serviceMigrations = definePostgresServiceMigrations({
13
+ name: 'iam',
14
+ directory: MIGRATIONS_DIR,
15
+ ledgerTable: 'iam_schema_migrations',
16
+ lockKey: MIGRATION_LOCK_KEY,
17
+ })
18
+
19
+ export function postgresMigrations(dir: string = MIGRATIONS_DIR): PostgresMigration[] {
20
+ return serviceMigrations.read(dir)
21
+ }
22
+
23
+ export function postgresMigrationPlan(migrations: readonly PostgresMigration[] = postgresMigrations()): PostgresMigrationPlan {
24
+ return serviceMigrations.plan(migrations)
25
+ }
26
+
27
+ export async function applyMigrations(
28
+ db: PostgresDatabase,
29
+ migrations: readonly PostgresMigration[] = postgresMigrations(),
30
+ ): Promise<string[]> {
31
+ return serviceMigrations.apply(db, migrations)
32
+ }
33
+
34
+ async function main(): Promise<void> {
35
+ const url = process.env['FABRIKA_IAM_DATABASE_URL']
36
+ if (url === undefined || url.trim() === '') throw new Error('FABRIKA_IAM_DATABASE_URL is required')
37
+ const db = PostgresDatabase.connect(url, { max: 1 })
38
+ try {
39
+ const applied = await applyMigrations(db)
40
+ console.info(postgresMigrationResultMessage(applied))
41
+ } finally {
42
+ await db.close()
43
+ }
44
+ }
45
+
46
+ if (import.meta.main) {
47
+ main().catch(() => {
48
+ // Driver errors may contain the credential-bearing connection URL.
49
+ console.error('migration failed')
50
+ process.exit(1)
51
+ })
52
+ }
@@ -0,0 +1,34 @@
1
+ // The cron command — the process-side equivalent of the Worker's `scheduled` handler.
2
+ //
3
+ // On Cloudflare `triggers.crons` wakes the Worker and calls `scheduled()`. There is no such trigger
4
+ // for a plain container, so the platform cron (`zerops.yaml` → `run.crontab`) runs THIS file, which
5
+ // calls the same `runIamMaintenance` the Worker's handler calls. Nothing about retention or queries
6
+ // lives here.
7
+ //
8
+ // It is a one-shot process, not a timer inside the server: a timer fires once per container (so it
9
+ // multiplies with horizontal scale) and its schedule silently resets on every redeploy. The
10
+ // operation is an idempotent DELETE by cutoff, so an overlapping run is harmless regardless.
11
+ //
12
+ // Run it: `bun src/node/prune.ts`.
13
+
14
+ import { runIamMaintenance } from '../cron'
15
+ import { createRuntime } from './runtime'
16
+
17
+ async function main(): Promise<void> {
18
+ const runtime = await createRuntime()
19
+ try {
20
+ // Maintenance registers the deletes through `waitUntil`; `shutdown()` drains them before the pool
21
+ // closes, so the process exits only once the prune has actually finished.
22
+ runIamMaintenance(runtime.env, runtime.ctx)
23
+ } finally {
24
+ await runtime.shutdown()
25
+ }
26
+ console.info('IAM maintenance complete')
27
+ }
28
+
29
+ if (import.meta.main) {
30
+ main().catch((err: unknown) => {
31
+ console.error('IAM maintenance failed:', err instanceof Error ? err.message : 'unknown error')
32
+ process.exit(1)
33
+ })
34
+ }
@@ -0,0 +1,221 @@
1
+ // Runtime assembly for a LONG-RUNNING BUN PROCESS — the other half of what `wrangler` does for the
2
+ // Worker: fill the `Env` ports and hand back a request context.
3
+ //
4
+ // Everything under `src/node/` is Bun/Node-only and is the ONLY part of this package allowed to be.
5
+ // It imports `@fabrika/platform-node`; `src/index.ts` (the Worker) imports `cloudflare:workers`; the
6
+ // shared layer between them (`app.ts`, `rpc.ts`, `cron.ts`, everything they reach) imports
7
+ // neither. `src/__tests__/entrypoint-isolation.test.ts` walks both graphs and fails if that stops
8
+ // being true.
9
+ //
10
+ // SqlDatabase → PostgresDatabase (D1's place)
11
+ // WaitUntil → createBackgroundTasks (ctx.waitUntil's place — supervised, never process-fatal)
12
+
13
+ import { IAM_PROXY_SECRET_VARIABLE, LOCAL_ENVIRONMENT, readEnvironmentName } from '@fabrika/auth-core'
14
+ import { type EmailProviderRegistry, type EmailSender, emailSenderFromEnv, pickEmailEnvironment, readEmailTransportConfig } from '@fabrika/email'
15
+ import { installationMailSender, isHttpOrigin } from '@fabrika/email/platform'
16
+ import { builtinEmailProviders } from '@fabrika/email/providers'
17
+ import { createBackgroundTasks, PostgresDatabase } from '@fabrika/platform-node'
18
+ import { createPostgresIamRepositories } from '../db'
19
+ import type { Env, RequestContext } from '../env'
20
+ import { parseOAuthConfig } from '../oauth-config'
21
+ import { BUN_PBKDF2_COST } from '../password-crypto'
22
+ import { parseRetention } from '../retention'
23
+
24
+ /** Config that exists ONLY off Workers — the process's own knobs, not part of the service's `Env`. */
25
+ export interface ProcessConfig {
26
+ /** TCP port to listen on. */
27
+ port: number
28
+ /**
29
+ * Shared secret gating the HTTP MANAGEMENT surface (`/rpc/*`). EMPTY DISABLES IT — see
30
+ * `rpc-http.ts`. Never logged.
31
+ */
32
+ rpcKey: string
33
+ /**
34
+ * Shared secret gating the PROXY mint surface (`/auth/mint/*`), which the auth proxy calls on the
35
+ * cold path. Separate from `rpcKey` by least privilege — the proxy is the only publicly-routed
36
+ * component and needs only three IAM calls: `mintToken`, `mintFromKey`, and `exchangeAuthCode`
37
+ * (ADR-0022), which redeems a live handoff code for an app-bound session. That third one is a real
38
+ * capability rather than a read, and the split is still worth it: the code is single-use,
39
+ * hash-only, bound to `(session, app, return URL)` and dead in two minutes, whereas the management
40
+ * key would additionally let a compromised edge forge audit rows for any app. EMPTY DISABLES IT.
41
+ * Never logged.
42
+ */
43
+ proxyKey: string
44
+ /**
45
+ * The secret the platform proxy sends on IAM's route (`IAM_PROXY_SECRET_VARIABLE`), proving it wrote the client-address
46
+ * and request-id headers. EMPTY READS THOSE HEADERS UNPROVEN, as before the deploy that writes it. Never logged.
47
+ */
48
+ proxySecret: string
49
+ }
50
+
51
+ /** What a composition root hands the process besides `process.env` — never an environment variable. */
52
+ export interface RuntimeOverrides {
53
+ /** Replaces `FABRIKA_EMAIL_PROVIDER`'s sender, only with `ENVIRONMENT=local`: the local stack's mail capture. */
54
+ readonly emailSender?: EmailSender
55
+ /** The providers `FABRIKA_EMAIL_PROVIDER` may name. Defaults to the built-in ones. */
56
+ readonly emailProviders?: EmailProviderRegistry
57
+ }
58
+
59
+ export interface Runtime {
60
+ env: Env
61
+ ctx: RequestContext
62
+ config: ProcessConfig
63
+ /** Wait for in-flight background work, then close the connection pool. */
64
+ shutdown(): Promise<void>
65
+ }
66
+
67
+ /** Minimum length for the RPC shared secret. 32 chars of a generated token is ~190 bits at base64url. */
68
+ const MIN_RPC_KEY_LENGTH = 32
69
+
70
+ /**
71
+ * Read `process.env`, open the Postgres pool, mount the asset directory, and return the pair of
72
+ * handles every shared entrypoint function takes. Everything that can refuse the boot runs before the pool opens.
73
+ *
74
+ * Fails LOUDLY and early on missing required configuration: a service that boots half-configured and
75
+ * then refuses logins at 3am is strictly worse than one that never came up. Nothing here ever logs a
76
+ * value — the database URL and the RPC key are credentials, and only their absence is reportable.
77
+ */
78
+ export async function createRuntime(source: Record<string, string | undefined> = process.env, overrides: RuntimeOverrides = {}): Promise<Runtime> {
79
+ const databaseUrl = required(source, 'FABRIKA_IAM_DATABASE_URL')
80
+ const issuer = required(source, 'ISSUER')
81
+ // Checked at BOOT as well as in `buildServices`: a process that comes up and then throws per request
82
+ // still answers `/healthz`, so the readiness probe would pass a deployment that serves nothing.
83
+ const environment = readEnvironmentName(required(source, 'ENVIRONMENT'), issuer)
84
+ const oidcEnabled = booleanValue(source, 'FABRIKA_IAM_OIDC_ENABLED', true)
85
+ const passwordEnabled = booleanValue(source, 'FABRIKA_IAM_PASSWORD_ENABLED', false)
86
+ if (!oidcEnabled && !passwordEnabled) {
87
+ throw new Error('At least one IAM authentication method must be enabled')
88
+ }
89
+ const oidcIssuer = oidcEnabled ? required(source, 'OIDC_ISSUER') : source['OIDC_ISSUER'] ?? ''
90
+ const oidcClientId = oidcEnabled ? required(source, 'OIDC_CLIENT_ID') : source['OIDC_CLIENT_ID'] ?? ''
91
+ const oidcClientSecret = oidcEnabled ? required(source, 'OIDC_CLIENT_SECRET') : source['OIDC_CLIENT_SECRET'] ?? ''
92
+ const emailConfig = pickEmailEnvironment(source)
93
+ const emailProviders = overrides.emailProviders ?? builtinEmailProviders
94
+ const emailConfigured = readEmailTransportConfig(emailConfig, emailProviders).kind !== 'none'
95
+ if (overrides.emailSender !== undefined && (environment !== LOCAL_ENVIRONMENT || emailConfigured)) {
96
+ throw new Error('A composition email sender needs ENVIRONMENT=local and FABRIKA_EMAIL_PROVIDER=none')
97
+ }
98
+ // Built once here as well as per request in `buildServices`, for the same readiness-probe reason as above.
99
+ emailSenderFromEnv(emailConfig, emailProviders)
100
+ const controlUrl = httpOrigin(source, 'FABRIKA_CONTROL_URL')
101
+
102
+ // Parsed here as well as per request in `buildServices`, for the same readiness-probe reason as above.
103
+ parseOAuthConfig(source['FABRIKA_IAM_OAUTH_CONFIG'])
104
+ const authLogRetentionDays = source['FABRIKA_IAM_AUTH_LOG_RETENTION_DAYS']
105
+ const auditRetentionDays = source['FABRIKA_IAM_AUDIT_RETENTION_DAYS']
106
+ parseRetention(
107
+ { authLogDays: authLogRetentionDays, auditDays: auditRetentionDays },
108
+ { authLogDays: 'FABRIKA_IAM_AUTH_LOG_RETENTION_DAYS', auditDays: 'FABRIKA_IAM_AUDIT_RETENTION_DAYS' },
109
+ )
110
+
111
+ const config: ProcessConfig = {
112
+ port: parsePort(source['PORT']),
113
+ rpcKey: sharedSecret(source, 'FABRIKA_IAM_RPC_KEY'),
114
+ proxyKey: sharedSecret(source, 'FABRIKA_IAM_PROXY_KEY'),
115
+ proxySecret: sharedSecret(source, IAM_PROXY_SECRET_VARIABLE),
116
+ }
117
+ // IAM keeps its provider's configuration as the switch for delivery; Control holds the transport that delivers.
118
+ const platformEmailSender = controlUrl !== undefined && emailConfigured ? relaySender(controlUrl, config.rpcKey) : undefined
119
+
120
+ const db = PostgresDatabase.connect(databaseUrl)
121
+ const tasks = createBackgroundTasks({ label: 'iam background task' })
122
+
123
+ const env: Env = {
124
+ DB: db,
125
+ REPOSITORIES: createPostgresIamRepositories(db),
126
+ HUMAN_EMAIL_DOMAINS: source['HUMAN_EMAIL_DOMAINS'] ?? '[]',
127
+ HUMAN_EMAILS: source['HUMAN_EMAILS'] ?? '[]',
128
+ IAM_BOOTSTRAP_ADMINS: source['IAM_BOOTSTRAP_ADMINS'] ?? '[]',
129
+ // Which app's proxy token may administer. Passed through undefined so "unset" (the console
130
+ // gateway default) stays distinguishable from an explicit empty value (no JWT may administer).
131
+ ADMIN_AUDIENCES: source['FABRIKA_IAM_ADMIN_AUDIENCES'],
132
+ OAUTH_CONFIG: source['FABRIKA_IAM_OAUTH_CONFIG'] ?? '',
133
+ AUTH_LOG_RETENTION_DAYS: authLogRetentionDays,
134
+ AUDIT_RETENTION_DAYS: auditRetentionDays,
135
+ ENVIRONMENT: environment,
136
+ LOCAL_DEV_LOGIN: source['LOCAL_DEV_LOGIN'] ?? '',
137
+ ISSUER: issuer,
138
+ // Empty off-local is refused by `getSigner`, not here — one owner for that rule.
139
+ FABRIKA_IAM_SIGNING_KEYS: source['FABRIKA_IAM_SIGNING_KEYS'] ?? '',
140
+ FABRIKA_IAM_PROVISIONING_KEY: source['FABRIKA_IAM_PROVISIONING_KEY'] ?? '',
141
+ OIDC_ENABLED: String(oidcEnabled),
142
+ PASSWORD_ENABLED: String(passwordEnabled),
143
+ OIDC_ISSUER: oidcIssuer,
144
+ OIDC_CLIENT_ID: oidcClientId,
145
+ OIDC_CLIENT_SECRET: oidcClientSecret,
146
+ OIDC_SCOPES: source['OIDC_SCOPES'] ?? '',
147
+ OIDC_REQUIRE_VERIFIED_EMAIL: source['OIDC_REQUIRE_VERIFIED_EMAIL'] ?? 'true',
148
+ EMAIL_CONFIG: emailConfig,
149
+ EMAIL_PROVIDERS: emailProviders,
150
+ PASSWORD_COST: BUN_PBKDF2_COST,
151
+ ...(overrides.emailSender === undefined ? {} : { EMAIL_SENDER: overrides.emailSender }),
152
+ ...(platformEmailSender === undefined ? {} : { PLATFORM_EMAIL_SENDER: platformEmailSender }),
153
+ }
154
+
155
+ return {
156
+ env,
157
+ ctx: { waitUntil: tasks.waitUntil },
158
+ config,
159
+ async shutdown(): Promise<void> {
160
+ // Drain BEFORE closing the pool: the auth-log and audit writes registered through `waitUntil`
161
+ // are the reason the port exists, and closing under them would lose exactly the records an
162
+ // audit trail must not lose.
163
+ await tasks.drain()
164
+ await db.close()
165
+ },
166
+ }
167
+ }
168
+
169
+ function booleanValue(source: Record<string, string | undefined>, name: string, fallback: boolean): boolean {
170
+ const raw = source[name]
171
+ if (raw === undefined || raw === '') return fallback
172
+ if (raw === 'true') return true
173
+ if (raw === 'false') return false
174
+ throw new Error(`${name} must be true or false`)
175
+ }
176
+
177
+ /**
178
+ * Read a transport shared secret. Absent is legal and means "that surface is off"; a SHORT one is
179
+ * not, and fails the boot — a guessable secret in front of an internet-reachable surface is worse
180
+ * than no surface at all, and it would look configured.
181
+ */
182
+ function sharedSecret(source: Record<string, string | undefined>, name: string): string {
183
+ const value = source[name] ?? ''
184
+ if (value !== '' && value.length < MIN_RPC_KEY_LENGTH) {
185
+ throw new Error(`${name} must be at least ${MIN_RPC_KEY_LENGTH} characters (it is the only thing guarding its HTTP surface)`)
186
+ }
187
+ return value
188
+ }
189
+
190
+ /** The relay authenticates IAM by a key derived from the secret both hold, so the relay needs that secret set. */
191
+ function relaySender(controlUrl: string, rpcKey: string): EmailSender {
192
+ if (rpcKey === '') throw new Error('FABRIKA_CONTROL_URL needs FABRIKA_IAM_RPC_KEY, which the mail relay authenticates IAM by')
193
+ return installationMailSender({ url: controlUrl, secret: rpcKey })
194
+ }
195
+
196
+ /** An optional http(s) origin: no path, no trailing slash. Absent or empty is undefined. */
197
+ function httpOrigin(source: Record<string, string | undefined>, name: string): string | undefined {
198
+ const raw = source[name]
199
+ if (raw === undefined || raw === '') return undefined
200
+ if (!isHttpOrigin(raw)) throw new Error(`${name} must be an http(s) origin, such as http://control:3000`)
201
+ return raw
202
+ }
203
+
204
+ function required(source: Record<string, string | undefined>, name: string): string {
205
+ const value = source[name]
206
+ if (value === undefined || value.trim() === '') {
207
+ throw new Error(`${name} is required`)
208
+ }
209
+ return value
210
+ }
211
+
212
+ function parsePort(raw: string | undefined): number {
213
+ if (raw === undefined || raw.trim() === '') {
214
+ return 3000
215
+ }
216
+ const port = Number.parseInt(raw, 10)
217
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
218
+ throw new Error('PORT must be an integer between 1 and 65535')
219
+ }
220
+ return port
221
+ }
@@ -0,0 +1,104 @@
1
+ // The BUN entrypoint — the IAM service as a long-running process.
2
+ //
3
+ // The sibling of `src/index.ts`, not a fork of it. Both use the same application and jobs:
4
+ //
5
+ // createIamApp (src/app.ts) — `/auth/*`, the JWKS, `/admin/*`, and optional Bun transports.
6
+ // createIamRpc (src/rpc.ts) — the `IamRpc` object. A service binding on Workers; here it is
7
+ // reached over HTTP via `handleRpcHttp`, which authenticates the
8
+ // transport with a shared secret because HTTP has no equivalent of
9
+ // a binding's unreachability. See the header of `rpc-http.ts`.
10
+ // runIamMaintenance (src/cron.ts) — the `scheduled` handler's work. NOT scheduled from in here: the
11
+ // platform cron drives it (`run.crontab` → `node/prune.ts`), which
12
+ // is the same shape as `triggers.crons` driving `scheduled`.
13
+ //
14
+ // The shared application owns route order, including optional `/rpc/*` and `/healthz` routes.
15
+ //
16
+ // Run it: `bun src/node/server.ts` (see `zerops.yaml` → `run.start`).
17
+
18
+ import { createBunHandler } from '@fabrika/app/bun'
19
+ import { createIamApp } from '../app'
20
+ import { createRuntime, type Runtime } from './runtime'
21
+
22
+ /** Build the server's fetch handler for an assembled runtime. Exported so a test can drive it directly. */
23
+ export function createFetchHandler(runtime: Runtime): (request: Request) => Promise<Response> {
24
+ const app = createIamApp({
25
+ rpcKey: runtime.config.rpcKey,
26
+ proxyKey: runtime.config.proxyKey,
27
+ // An application on Zerops has no IAM binding; its membership operations arrive here, each with its own key.
28
+ membershipTransport: true,
29
+ health: true,
30
+ // No `clientAddressHeader`: behind the Zerops balancer the proxy's client address is the balancer for every
31
+ // client, so a per-client bucket would be one installation-wide bucket (`src/client-address.ts`).
32
+ // `REQUEST_ID_HEADER` in `@fabrika/proxy-core`: the proxy deletes a caller's copy at ingress and injects its own.
33
+ requestIdHeader: 'X-Request-Id',
34
+ // The private network reaches this port too, so the header above counts only beside the proxy's secret.
35
+ proxySecret: runtime.config.proxySecret,
36
+ })
37
+ return createBunHandler(app, runtime.env, { executionContext: runtime.ctx }).fetch
38
+ }
39
+
40
+ /** Serve an assembled runtime until SIGTERM or SIGINT. A composition root with its own overrides starts here. */
41
+ export function startIamServer(runtime: Runtime): void {
42
+ const server = Bun.serve({
43
+ port: runtime.config.port,
44
+ // Bun closes an idle socket after 10s by default, and a handler that is still working counts as
45
+ // idle — a slow upstream answered as an unattributable 502 instead of its own error.
46
+ idleTimeout: 255,
47
+ // The project's L7 balancer terminates TLS and forwards plain HTTP on the private network, so
48
+ // this listener speaks HTTP and holds no certificates. The session cookie is still marked
49
+ // `Secure`: the auth handler decides that from the configured public origin (`ISSUER`), not from
50
+ // the socket, precisely because behind a terminating balancer the socket is the wrong signal.
51
+ fetch: createFetchHandler(runtime),
52
+ // Backstop for anything raised outside the handler. The handler already catches its own throws
53
+ // (see `createFetchHandler`); without this, Bun's default page would answer with source lines.
54
+ error(err: unknown): Response {
55
+ console.error('server error:', err instanceof Error ? err.message : 'unknown error')
56
+ return new Response('internal error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
57
+ },
58
+ })
59
+
60
+ // Which surfaces are live, never the keys themselves — an operator needs to see that a missing
61
+ // secret turned something off, which is otherwise only visible as a 404 at 3am.
62
+ const state = (key: string): string => (key === '' ? 'disabled' : 'enabled')
63
+ console.info(
64
+ `iam listening on :${server.port} (env=${runtime.env.ENVIRONMENT}, rpc=${state(runtime.config.rpcKey)}, mint=${
65
+ state(runtime.config.proxyKey)
66
+ }, proxy-proof=${state(runtime.config.proxySecret)})`,
67
+ )
68
+
69
+ // SIGTERM is what the platform sends on redeploy/scale-down. Stop accepting, let in-flight requests
70
+ // finish, then drain the supervised audit/auth-log writes before the pool closes.
71
+ let stopping = false
72
+ const stop = (signal: string): void => {
73
+ if (stopping) {
74
+ return
75
+ }
76
+ stopping = true
77
+ console.info(`iam shutting down (${signal})`)
78
+ void server.stop(false)
79
+ .then(() => runtime.shutdown())
80
+ .then(() => process.exit(0))
81
+ .catch((err: unknown) => {
82
+ console.error('shutdown failed:', err instanceof Error ? err.message : 'unknown error')
83
+ process.exit(1)
84
+ })
85
+ }
86
+ process.on('SIGTERM', () => {
87
+ stop('SIGTERM')
88
+ })
89
+ process.on('SIGINT', () => {
90
+ stop('SIGINT')
91
+ })
92
+ }
93
+
94
+ async function main(): Promise<void> {
95
+ startIamServer(await createRuntime())
96
+ }
97
+
98
+ if (import.meta.main) {
99
+ // Never log the error object: configuration errors can quote a connection string.
100
+ main().catch((err: unknown) => {
101
+ console.error('iam failed to start:', err instanceof Error ? err.message : 'unknown error')
102
+ process.exit(1)
103
+ })
104
+ }
@@ -0,0 +1,93 @@
1
+ import type { OAuthClientCredential, OAuthClientMetadataDocument } from '@fabrika/iam-contract'
2
+ import { createLocalJWKSet, errors, type JSONWebKeySet, type JWTPayload, jwtVerify } from 'jose'
3
+ import type { EstablishedClient } from './oauth'
4
+ import { clientJwks, clientMetadata } from './oauth-client'
5
+ import type { OAuthConfig } from './oauth-config'
6
+ import { unixNow } from './repositories/sql'
7
+ import type { Services } from './services'
8
+
9
+ const CLOCK_TOLERANCE_SECONDS = 60
10
+ /** The common ceiling for a client assertion's lifetime; client libraries default to it. */
11
+ const MAX_ASSERTION_LIFETIME_SECONDS = 3600
12
+ const MAX_JTI_LENGTH = 256
13
+
14
+ type PrivateKeyJwtClient = Extract<OAuthClientMetadataDocument, { token_endpoint_auth_method: 'private_key_jwt' }>
15
+
16
+ /**
17
+ * Authenticate the client of a token or revocation request (RFC 6749 §2.3). The method is the one the
18
+ * client's own metadata document declares, never the one the request picks: a `private_key_jwt` client
19
+ * that sends no assertion is refused, and a public client that sends one is refused too.
20
+ * `audiences` are the values an assertion's `aud` may name.
21
+ */
22
+ export async function authenticateOAuthClient(
23
+ services: Services,
24
+ config: OAuthConfig,
25
+ input: { clientId: string; credential: OAuthClientCredential; audiences: string[] },
26
+ ): Promise<EstablishedClient | null> {
27
+ const registration = config.clients.find((client) => client.clientId === input.clientId)
28
+ if (registration === undefined) return null
29
+ const metadata = await clientMetadata(registration)
30
+ if (metadata === null) return null
31
+ if (metadata.token_endpoint_auth_method === 'none') return input.credential.method === 'none' ? { registration, metadata } : null
32
+ if (input.credential.method !== 'private_key_jwt') return null
33
+ const accepted = await verifyClientAssertion(services, metadata, input.credential.assertion, input.audiences)
34
+ return accepted ? { registration, metadata } : null
35
+ }
36
+
37
+ /**
38
+ * Whether a revocation request comes from its client (RFC 7009 §2.1). A confidential client authenticates as at the
39
+ * token endpoint. A request without an assertion only names a registered client: the token's own client binding is
40
+ * enough for a public client, so an unreachable metadata document never keeps a token alive. It is refused only when
41
+ * the document is known and declares `private_key_jwt`.
42
+ */
43
+ export async function authenticateRevokingClient(
44
+ services: Services,
45
+ config: OAuthConfig,
46
+ input: { clientId: string; credential: OAuthClientCredential; audiences: string[] },
47
+ ): Promise<boolean> {
48
+ if (input.credential.method !== 'none') return await authenticateOAuthClient(services, config, input) !== null
49
+ const registration = config.clients.find((client) => client.clientId === input.clientId)
50
+ if (registration === undefined) return false
51
+ const metadata = await clientMetadata(registration)
52
+ return metadata?.token_endpoint_auth_method !== 'private_key_jwt'
53
+ }
54
+
55
+ /** RFC 7523 §3: signed by a key of the client's JWKS, `iss` = `sub` = client id, an IAM `aud`, a short `exp`, a fresh `jti`. */
56
+ async function verifyClientAssertion(services: Services, client: PrivateKeyJwtClient, assertion: string, audiences: string[]): Promise<boolean> {
57
+ const cached = await clientJwks(client.jwks_uri, { refetch: false })
58
+ if (cached === null) return false
59
+ let payload = await verifyWith(cached, client, assertion, audiences)
60
+ if (payload === 'unknown_key') {
61
+ // The client may have rotated its keys since the set was cached.
62
+ const refetched = await clientJwks(client.jwks_uri, { refetch: true })
63
+ payload = refetched === null ? null : await verifyWith(refetched, client, assertion, audiences)
64
+ }
65
+ if (payload === null || payload === 'unknown_key') return false
66
+ const now = unixNow()
67
+ const { exp, jti } = payload
68
+ if (exp === undefined || exp > now + MAX_ASSERTION_LIFETIME_SECONDS + CLOCK_TOLERANCE_SECONDS) return false
69
+ if (typeof jti !== 'string' || jti.length === 0 || jti.length > MAX_JTI_LENGTH) return false
70
+ // Kept past `exp` by the tolerance, which is how long the verifier still accepts the assertion.
71
+ return services.repositories.oauth.recordClientAssertion(client.client_id, jti, exp + CLOCK_TOLERANCE_SECONDS)
72
+ }
73
+
74
+ async function verifyWith(
75
+ jwks: JSONWebKeySet,
76
+ client: PrivateKeyJwtClient,
77
+ assertion: string,
78
+ audiences: string[],
79
+ ): Promise<JWTPayload | 'unknown_key' | null> {
80
+ try {
81
+ const { payload } = await jwtVerify(assertion, createLocalJWKSet(jwks), {
82
+ algorithms: [client.token_endpoint_auth_signing_alg],
83
+ issuer: client.client_id,
84
+ subject: client.client_id,
85
+ audience: audiences,
86
+ requiredClaims: ['exp', 'jti'],
87
+ clockTolerance: CLOCK_TOLERANCE_SECONDS,
88
+ })
89
+ return payload
90
+ } catch (error) {
91
+ return error instanceof errors.JWKSNoMatchingKey ? 'unknown_key' : null
92
+ }
93
+ }