@fabrika/iam 0.0.1 → 0.9.0-dev.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (312) hide show
  1. package/fabrika.config.ts +267 -0
  2. package/migrations/0001_init.sql +316 -0
  3. package/migrations/0002_oauth.sql +38 -0
  4. package/migrations/0003_contract_apps.sql +11 -0
  5. package/migrations/0004_membership.sql +93 -0
  6. package/migrations/0005_workloads.sql +23 -0
  7. package/migrations/0006_membership_transport_keys.sql +16 -0
  8. package/migrations/0007_member_directory.sql +7 -0
  9. package/migrations/0008_durable_audit.sql +28 -0
  10. package/migrations/0009_member_lookups.sql +7 -0
  11. package/migrations/0010_workload_issues.sql +6 -0
  12. package/migrations/0011_app_presentation.sql +15 -0
  13. package/migrations/0012_external_principals.sql +10 -0
  14. package/migrations/0013_app_mail_templates.sql +14 -0
  15. package/migrations/0014_invitation_wording.sql +8 -0
  16. package/migrations/0015_app_schema_revisions.sql +15 -0
  17. package/migrations/0016_principal_grant_revision.sql +9 -0
  18. package/migrations/0017_app_sign_ins.sql +12 -0
  19. package/migrations/0018_app_members.sql +13 -0
  20. package/migrations/0019_app_mail_html.sql +7 -0
  21. package/migrations/0020_public_workloads.sql +34 -0
  22. package/migrations/0021_installation_brand.sql +19 -0
  23. package/migrations/0022_password_policy.sql +12 -0
  24. package/migrations/0023_terminals.sql +155 -0
  25. package/migrations/0024_app_terminals.sql +10 -0
  26. package/migrations/0025_terminal_completion.sql +10 -0
  27. package/migrations/0026_terminal_generation.sql +12 -0
  28. package/migrations/0027_application_exact_actions.sql +28 -0
  29. package/migrations/0028_oauth_client_assertions.sql +10 -0
  30. package/migrations/0029_role_via.sql +6 -0
  31. package/migrations/0030_membership_role_via.sql +12 -0
  32. package/migrations/0031_person_locale.sql +11 -0
  33. package/migrations-postgres/0001_init.sql +331 -0
  34. package/migrations-postgres/0002_oauth.sql +36 -0
  35. package/migrations-postgres/0003_contract_apps.sql +8 -0
  36. package/migrations-postgres/0004_membership.sql +92 -0
  37. package/migrations-postgres/0005_workloads.sql +18 -0
  38. package/migrations-postgres/0006_membership_transport_keys.sql +12 -0
  39. package/migrations-postgres/0007_member_directory.sql +7 -0
  40. package/migrations-postgres/0008_durable_audit.sql +8 -0
  41. package/migrations-postgres/0009_member_lookups.sql +7 -0
  42. package/migrations-postgres/0010_workload_issues.sql +6 -0
  43. package/migrations-postgres/0011_app_presentation.sql +15 -0
  44. package/migrations-postgres/0012_external_principals.sql +10 -0
  45. package/migrations-postgres/0013_app_mail_templates.sql +14 -0
  46. package/migrations-postgres/0014_invitation_wording.sql +8 -0
  47. package/migrations-postgres/0015_app_schema_revisions.sql +15 -0
  48. package/migrations-postgres/0016_principal_grant_revision.sql +9 -0
  49. package/migrations-postgres/0017_app_sign_ins.sql +12 -0
  50. package/migrations-postgres/0018_app_members.sql +13 -0
  51. package/migrations-postgres/0019_app_mail_html.sql +7 -0
  52. package/migrations-postgres/0020_public_workloads.sql +9 -0
  53. package/migrations-postgres/0021_installation_brand.sql +19 -0
  54. package/migrations-postgres/0022_password_policy.sql +12 -0
  55. package/migrations-postgres/0023_terminals.sql +70 -0
  56. package/migrations-postgres/0024_app_terminals.sql +10 -0
  57. package/migrations-postgres/0025_terminal_completion.sql +10 -0
  58. package/migrations-postgres/0026_terminal_generation.sql +12 -0
  59. package/migrations-postgres/0027_application_exact_actions.sql +28 -0
  60. package/migrations-postgres/0028_oauth_client_assertions.sql +9 -0
  61. package/migrations-postgres/0029_role_via.sql +4 -0
  62. package/migrations-postgres/0030_membership_role_via.sql +7 -0
  63. package/migrations-postgres/0031_person_locale.sql +11 -0
  64. package/package.json +69 -8
  65. package/src/admin/access.ts +47 -0
  66. package/src/admin/api-keys.ts +280 -0
  67. package/src/admin/app-people.ts +209 -0
  68. package/src/admin/app-schema.ts +308 -0
  69. package/src/admin/audit.ts +81 -0
  70. package/src/admin/brand.ts +54 -0
  71. package/src/admin/connections.ts +48 -0
  72. package/src/admin/context.ts +70 -0
  73. package/src/admin/grant-support.ts +192 -0
  74. package/src/admin/grants.ts +189 -0
  75. package/src/admin/handlers.ts +102 -0
  76. package/src/admin/http.ts +24 -0
  77. package/src/admin/membership-keys.ts +38 -0
  78. package/src/admin/pagination.ts +28 -0
  79. package/src/admin/password-policy.ts +48 -0
  80. package/src/admin/passwords.ts +78 -0
  81. package/src/admin/policies.ts +136 -0
  82. package/src/admin/principals.ts +226 -0
  83. package/src/admin/router.ts +291 -0
  84. package/src/admin/rpc.ts +387 -0
  85. package/src/admin/sessions.ts +115 -0
  86. package/src/admin/share-links.ts +127 -0
  87. package/src/admin/terminals.ts +115 -0
  88. package/src/admin/user-admin.ts +76 -0
  89. package/src/admin/workloads.ts +85 -0
  90. package/src/app-presentation.ts +178 -0
  91. package/src/app.ts +158 -0
  92. package/src/auth/cookies.ts +64 -0
  93. package/src/auth/failure.ts +25 -0
  94. package/src/auth/handoff.ts +136 -0
  95. package/src/auth/http.ts +88 -0
  96. package/src/auth/invitations.ts +220 -0
  97. package/src/auth/known-device.ts +44 -0
  98. package/src/auth/login.ts +162 -0
  99. package/src/auth/oidc-flight.ts +91 -0
  100. package/src/auth/oidc.ts +148 -0
  101. package/src/auth/password.ts +416 -0
  102. package/src/auth/routes.ts +108 -0
  103. package/src/auth/sessions.ts +249 -0
  104. package/src/auth/terminals.ts +284 -0
  105. package/src/auth.ts +193 -0
  106. package/src/binding-identity.ts +25 -0
  107. package/src/bounded-body.ts +35 -0
  108. package/src/catalog/cs.ts +147 -0
  109. package/src/catalog/en.ts +148 -0
  110. package/src/catalog/index.ts +122 -0
  111. package/src/catalog/uk.ts +164 -0
  112. package/src/client-address.ts +39 -0
  113. package/src/common-passwords.ts +37 -0
  114. package/src/contract-rules.ts +80 -0
  115. package/src/cron.ts +54 -0
  116. package/src/db.ts +128 -0
  117. package/src/delegation.ts +100 -0
  118. package/src/device-http.ts +39 -0
  119. package/src/device.ts +269 -0
  120. package/src/email-identity.ts +2 -0
  121. package/src/env.ts +132 -0
  122. package/src/handoff.ts +175 -0
  123. package/src/html.ts +4 -0
  124. package/src/human-admission.ts +40 -0
  125. package/src/identification.ts +185 -0
  126. package/src/index.ts +292 -0
  127. package/src/installation-brand.ts +82 -0
  128. package/src/issue.ts +265 -0
  129. package/src/json.ts +30 -0
  130. package/src/log.ts +26 -0
  131. package/src/membership-http.ts +135 -0
  132. package/src/membership.ts +1210 -0
  133. package/src/messages.ts +44 -0
  134. package/src/narrow-permissions.ts +26 -0
  135. package/src/node/browser-identity.ts +69 -0
  136. package/src/node/migrate.ts +52 -0
  137. package/src/node/prune.ts +34 -0
  138. package/src/node/runtime.ts +221 -0
  139. package/src/node/server.ts +104 -0
  140. package/src/oauth-client-auth.ts +93 -0
  141. package/src/oauth-client.ts +145 -0
  142. package/src/oauth-config.ts +72 -0
  143. package/src/oauth-http.ts +262 -0
  144. package/src/oauth.ts +272 -0
  145. package/src/oidc.ts +260 -0
  146. package/src/origin.ts +29 -0
  147. package/src/password-crypto.ts +148 -0
  148. package/src/password-db.ts +419 -0
  149. package/src/password-minimum.ts +44 -0
  150. package/src/password-pages.ts +397 -0
  151. package/src/password-policy.ts +79 -0
  152. package/src/password-service.ts +67 -0
  153. package/src/person-locale.ts +103 -0
  154. package/src/proxy-proof.ts +36 -0
  155. package/src/relay-mail.ts +64 -0
  156. package/src/repositories/app-schema.ts +550 -0
  157. package/src/repositories/audit.ts +405 -0
  158. package/src/repositories/brand.ts +66 -0
  159. package/src/repositories/credentials.ts +331 -0
  160. package/src/repositories/device.ts +137 -0
  161. package/src/repositories/grants.ts +404 -0
  162. package/src/repositories/handoff.ts +103 -0
  163. package/src/repositories/membership-transport.ts +49 -0
  164. package/src/repositories/membership.ts +875 -0
  165. package/src/repositories/oauth.ts +122 -0
  166. package/src/repositories/password-policy.ts +44 -0
  167. package/src/repositories/principals.ts +358 -0
  168. package/src/repositories/sessions.ts +339 -0
  169. package/src/repositories/sql.ts +23 -0
  170. package/src/repositories/terminals.ts +346 -0
  171. package/src/repositories/workloads.ts +134 -0
  172. package/src/request-id.ts +46 -0
  173. package/src/resolve.ts +396 -0
  174. package/src/retention.ts +34 -0
  175. package/src/roles.ts +54 -0
  176. package/src/rpc-http.ts +333 -0
  177. package/src/rpc-inputs.ts +110 -0
  178. package/src/rpc.ts +440 -0
  179. package/src/secret.ts +45 -0
  180. package/src/service.ts +59 -0
  181. package/src/services.ts +199 -0
  182. package/src/signing.ts +260 -0
  183. package/src/stored-chain.ts +23 -0
  184. package/src/stored-permissions.ts +34 -0
  185. package/src/terminals.ts +15 -0
  186. package/src/tokens.ts +506 -0
  187. package/src/workload-token.ts +130 -0
  188. package/types/fabrika.config.d.ts +11 -0
  189. package/types/src/admin/access.d.ts +19 -0
  190. package/types/src/admin/api-keys.d.ts +26 -0
  191. package/types/src/admin/app-people.d.ts +8 -0
  192. package/types/src/admin/app-schema.d.ts +32 -0
  193. package/types/src/admin/audit.d.ts +10 -0
  194. package/types/src/admin/brand.d.ts +10 -0
  195. package/types/src/admin/connections.d.ts +5 -0
  196. package/types/src/admin/context.d.ts +46 -0
  197. package/types/src/admin/grant-support.d.ts +59 -0
  198. package/types/src/admin/grants.d.ts +8 -0
  199. package/types/src/admin/handlers.d.ts +82 -0
  200. package/types/src/admin/http.d.ts +9 -0
  201. package/types/src/admin/membership-keys.d.ts +8 -0
  202. package/types/src/admin/pagination.d.ts +5 -0
  203. package/types/src/admin/password-policy.d.ts +9 -0
  204. package/types/src/admin/passwords.d.ts +5 -0
  205. package/types/src/admin/policies.d.ts +15 -0
  206. package/types/src/admin/principals.d.ts +15 -0
  207. package/types/src/admin/router.d.ts +75 -0
  208. package/types/src/admin/rpc.d.ts +6 -0
  209. package/types/src/admin/sessions.d.ts +14 -0
  210. package/types/src/admin/share-links.d.ts +21 -0
  211. package/types/src/admin/terminals.d.ts +13 -0
  212. package/types/src/admin/user-admin.d.ts +30 -0
  213. package/types/src/admin/workloads.d.ts +5 -0
  214. package/types/src/app-presentation.d.ts +86 -0
  215. package/types/src/app.d.ts +62 -0
  216. package/types/src/auth/cookies.d.ts +29 -0
  217. package/types/src/auth/failure.d.ts +47 -0
  218. package/types/src/auth/handoff.d.ts +66 -0
  219. package/types/src/auth/http.d.ts +29 -0
  220. package/types/src/auth/invitations.d.ts +18 -0
  221. package/types/src/auth/known-device.d.ts +12 -0
  222. package/types/src/auth/login.d.ts +10 -0
  223. package/types/src/auth/oidc-flight.d.ts +39 -0
  224. package/types/src/auth/oidc.d.ts +7 -0
  225. package/types/src/auth/password.d.ts +7 -0
  226. package/types/src/auth/routes.d.ts +15 -0
  227. package/types/src/auth/sessions.d.ts +60 -0
  228. package/types/src/auth/terminals.d.ts +47 -0
  229. package/types/src/auth.d.ts +70 -0
  230. package/types/src/binding-identity.d.ts +12 -0
  231. package/types/src/bounded-body.d.ts +12 -0
  232. package/types/src/catalog/cs.d.ts +2 -0
  233. package/types/src/catalog/en.d.ts +2 -0
  234. package/types/src/catalog/index.d.ts +112 -0
  235. package/types/src/catalog/uk.d.ts +2 -0
  236. package/types/src/client-address.d.ts +31 -0
  237. package/types/src/common-passwords.d.ts +2 -0
  238. package/types/src/contract-rules.d.ts +25 -0
  239. package/types/src/cron.d.ts +15 -0
  240. package/types/src/db.d.ts +58 -0
  241. package/types/src/delegation.d.ts +38 -0
  242. package/types/src/device-http.d.ts +2 -0
  243. package/types/src/device.d.ts +11 -0
  244. package/types/src/email-identity.d.ts +1 -0
  245. package/types/src/env.d.ts +127 -0
  246. package/types/src/handoff.d.ts +57 -0
  247. package/types/src/html.d.ts +2 -0
  248. package/types/src/human-admission.d.ts +22 -0
  249. package/types/src/identification.d.ts +30 -0
  250. package/types/src/index.d.ts +62 -0
  251. package/types/src/installation-brand.d.ts +22 -0
  252. package/types/src/issue.d.ts +62 -0
  253. package/types/src/json.d.ts +15 -0
  254. package/types/src/log.d.ts +15 -0
  255. package/types/src/membership-http.d.ts +8 -0
  256. package/types/src/membership.d.ts +156 -0
  257. package/types/src/messages.d.ts +20 -0
  258. package/types/src/narrow-permissions.d.ts +7 -0
  259. package/types/src/node/browser-identity.d.ts +1 -0
  260. package/types/src/node/migrate.d.ts +4 -0
  261. package/types/src/node/prune.d.ts +1 -0
  262. package/types/src/node/runtime.d.ts +51 -0
  263. package/types/src/node/server.d.ts +5 -0
  264. package/types/src/oauth-client-auth.d.ts +26 -0
  265. package/types/src/oauth-client.d.ts +17 -0
  266. package/types/src/oauth-config.d.ts +16 -0
  267. package/types/src/oauth-http.d.ts +7 -0
  268. package/types/src/oauth.d.ts +51 -0
  269. package/types/src/oidc.d.ts +81 -0
  270. package/types/src/origin.d.ts +9 -0
  271. package/types/src/password-crypto.d.ts +37 -0
  272. package/types/src/password-db.d.ts +134 -0
  273. package/types/src/password-minimum.d.ts +23 -0
  274. package/types/src/password-pages.d.ts +143 -0
  275. package/types/src/password-policy.d.ts +19 -0
  276. package/types/src/password-service.d.ts +24 -0
  277. package/types/src/person-locale.d.ts +50 -0
  278. package/types/src/proxy-proof.d.ts +21 -0
  279. package/types/src/relay-mail.d.ts +25 -0
  280. package/types/src/repositories/app-schema.d.ts +244 -0
  281. package/types/src/repositories/audit.d.ts +187 -0
  282. package/types/src/repositories/brand.d.ts +41 -0
  283. package/types/src/repositories/credentials.d.ts +148 -0
  284. package/types/src/repositories/device.d.ts +50 -0
  285. package/types/src/repositories/grants.d.ts +177 -0
  286. package/types/src/repositories/handoff.d.ts +52 -0
  287. package/types/src/repositories/membership-transport.d.ts +31 -0
  288. package/types/src/repositories/membership.d.ts +273 -0
  289. package/types/src/repositories/oauth.d.ts +55 -0
  290. package/types/src/repositories/password-policy.d.ts +25 -0
  291. package/types/src/repositories/principals.d.ts +159 -0
  292. package/types/src/repositories/sessions.d.ts +150 -0
  293. package/types/src/repositories/sql.d.ts +13 -0
  294. package/types/src/repositories/terminals.d.ts +144 -0
  295. package/types/src/repositories/workloads.d.ts +61 -0
  296. package/types/src/request-id.d.ts +25 -0
  297. package/types/src/resolve.d.ts +118 -0
  298. package/types/src/retention.d.ts +18 -0
  299. package/types/src/roles.d.ts +34 -0
  300. package/types/src/rpc-http.d.ts +53 -0
  301. package/types/src/rpc-inputs.d.ts +707 -0
  302. package/types/src/rpc.d.ts +4 -0
  303. package/types/src/secret.d.ts +21 -0
  304. package/types/src/service.d.ts +19 -0
  305. package/types/src/services.d.ts +72 -0
  306. package/types/src/signing.d.ts +72 -0
  307. package/types/src/stored-chain.d.ts +6 -0
  308. package/types/src/stored-permissions.d.ts +12 -0
  309. package/types/src/terminals.d.ts +7 -0
  310. package/types/src/tokens.d.ts +113 -0
  311. package/types/src/workload-token.d.ts +7 -0
  312. package/README.md +0 -3
@@ -0,0 +1,145 @@
1
+ import { type OAuthClientMetadataDocument, parseOAuthClientMetadata } from '@fabrika/iam-contract'
2
+ import type { JSONWebKeySet, JWK } from 'jose'
3
+ import { prop } from './json'
4
+ import type { ManagedOAuthClient } from './oauth-config'
5
+
6
+ const CACHE_TTL_MS = 300_000
7
+ const FAILURE_TTL_MS = 30_000
8
+ const CACHE_MAX_ENTRIES = 64
9
+ const FETCH_TIMEOUT_MS = 5_000
10
+ const MAX_DOCUMENT_BYTES = 16_384
11
+ const MAX_JWKS_BYTES = 65_536
12
+ const MAX_JWKS_KEYS = 32
13
+ /** An assertion naming an unknown `kid` refetches the key set, but at most this often per key set. */
14
+ const JWKS_REFETCH_INTERVAL_MS = 30_000
15
+
16
+ interface CacheEntry<T> {
17
+ fetchedAt: number
18
+ expiresAt: number
19
+ value: Promise<T | null>
20
+ }
21
+
22
+ /**
23
+ * One fetch per key at a time: concurrent callers share it, and a failure is remembered briefly so a
24
+ * burst of requests cannot turn into a burst of fetches.
25
+ */
26
+ class FetchCache<T> {
27
+ private readonly entries = new Map<string, CacheEntry<T>>()
28
+
29
+ constructor(private readonly ttlMs: number) {}
30
+
31
+ get(key: string, load: () => Promise<T | null>, options: { refetchAfterMs?: number } = {}): Promise<T | null> {
32
+ const now = Date.now()
33
+ const cached = this.entries.get(key)
34
+ const refetch = options.refetchAfterMs !== undefined && cached !== undefined && now - cached.fetchedAt >= options.refetchAfterMs
35
+ // On Workers a fetch belongs to the request that started it and never settles once that request is
36
+ // cancelled, so a caller sharing it waits no longer than the entry lives.
37
+ if (cached !== undefined && cached.expiresAt > now && !refetch) return withinDeadline(cached.value, cached.expiresAt - now)
38
+ if (this.entries.size >= CACHE_MAX_ENTRIES) this.entries.clear()
39
+ const value = load()
40
+ // An in-flight entry lives as long as its fetch may run; the outcome then sets how long it is kept.
41
+ const entry: CacheEntry<T> = { fetchedAt: now, expiresAt: now + FETCH_TIMEOUT_MS, value }
42
+ this.entries.set(key, entry)
43
+ void value.then((result) => {
44
+ entry.expiresAt = Date.now() + (result === null ? FAILURE_TTL_MS : this.ttlMs)
45
+ })
46
+ return value
47
+ }
48
+ }
49
+
50
+ /** The shared outcome, or `null` — a failed fetch — once `ms` have passed. */
51
+ function withinDeadline<T>(value: Promise<T | null>, ms: number): Promise<T | null> {
52
+ let timer: ReturnType<typeof setTimeout> | undefined
53
+ const deadline = new Promise<null>((resolve) => {
54
+ timer = setTimeout(() => resolve(null), ms)
55
+ })
56
+ return Promise.race([value, deadline]).finally(() => clearTimeout(timer))
57
+ }
58
+
59
+ const metadataCache = new FetchCache<OAuthClientMetadataDocument>(CACHE_TTL_MS)
60
+ const jwksCache = new FetchCache<JSONWebKeySet>(CACHE_TTL_MS)
61
+
62
+ /**
63
+ * The Client ID Metadata Document of an operator-registered client. Callers resolve the registration
64
+ * first, so an unregistered client id never causes a fetch. The key is the whole registration, so a
65
+ * config change is never answered from the old document.
66
+ */
67
+ export function clientMetadata(registration: ManagedOAuthClient): Promise<OAuthClientMetadataDocument | null> {
68
+ return metadataCache.get(JSON.stringify(registration), async () => {
69
+ const document = await fetchJson(registration.metadataUrl, MAX_DOCUMENT_BYTES)
70
+ return document === null ? null : parseOAuthClientMetadata(document, registration)
71
+ })
72
+ }
73
+
74
+ /**
75
+ * The public keys at a client's `jwks_uri`, which its parsed metadata document already confined to the
76
+ * client id's origin. `refetch` asks for a fresh copy (an assertion named an unknown `kid`); it is
77
+ * honoured once per `JWKS_REFETCH_INTERVAL_MS`, so assertions cannot drive fetches.
78
+ */
79
+ export function clientJwks(jwksUri: string, options: { refetch: boolean }): Promise<JSONWebKeySet | null> {
80
+ return jwksCache.get(jwksUri, async () => parseJwks(await fetchJson(jwksUri, MAX_JWKS_BYTES)), {
81
+ refetchAfterMs: options.refetch ? JWKS_REFETCH_INTERVAL_MS : undefined,
82
+ })
83
+ }
84
+
85
+ /** HTTPS GET of a JSON document: no redirects, a timeout, and a size bound enforced while reading. */
86
+ async function fetchJson(url: string, maxBytes: number): Promise<unknown> {
87
+ try {
88
+ // `manual` rather than `error`: Workers do not implement `error`, and a 3xx is refused below either way.
89
+ const response = await fetch(url, {
90
+ redirect: 'manual',
91
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
92
+ headers: { accept: 'application/json' },
93
+ })
94
+ if (response.status !== 200 || response.body === null || Number(response.headers.get('content-length') ?? '0') > maxBytes) {
95
+ await response.body?.cancel()
96
+ return null
97
+ }
98
+ const reader = response.body.getReader()
99
+ const decoder = new TextDecoder('utf-8', { fatal: true })
100
+ let bytes = 0
101
+ let body = ''
102
+ while (true) {
103
+ const chunk = await reader.read()
104
+ if (chunk.done) break
105
+ bytes += chunk.value.byteLength
106
+ if (bytes > maxBytes) {
107
+ await reader.cancel()
108
+ return null
109
+ }
110
+ body += decoder.decode(chunk.value, { stream: true })
111
+ }
112
+ body += decoder.decode()
113
+ const document: unknown = JSON.parse(body)
114
+ return document
115
+ } catch {
116
+ return null
117
+ }
118
+ }
119
+
120
+ /** RSA public keys only, the one key type the supported algorithms use; private members are never copied. */
121
+ function parseJwks(value: unknown): JSONWebKeySet | null {
122
+ const rawKeys = prop(value, 'keys')
123
+ if (!Array.isArray(rawKeys) || rawKeys.length > MAX_JWKS_KEYS) return null
124
+ const keys: JWK[] = []
125
+ for (const raw of rawKeys) {
126
+ const kty = text(raw, 'kty')
127
+ const n = text(raw, 'n')
128
+ const e = text(raw, 'e')
129
+ if (kty !== 'RSA' || n === undefined || e === undefined) continue
130
+ const key: JWK = { kty, n, e }
131
+ const kid = text(raw, 'kid')
132
+ const alg = text(raw, 'alg')
133
+ const use = text(raw, 'use')
134
+ if (kid !== undefined) key.kid = kid
135
+ if (alg !== undefined) key.alg = alg
136
+ if (use !== undefined) key.use = use
137
+ keys.push(key)
138
+ }
139
+ return keys.length === 0 ? null : { keys }
140
+ }
141
+
142
+ function text(value: unknown, name: string): string | undefined {
143
+ const member = prop(value, name)
144
+ return typeof member === 'string' && member.length > 0 ? member : undefined
145
+ }
@@ -0,0 +1,72 @@
1
+ import { type OAuthManagedClient, type OAuthResourceDto, parseOAuthManagedClient, parseOAuthResourceDto } from '@fabrika/iam-contract'
2
+ import { parseJsonOrNull, prop } from './json'
3
+
4
+ /** An operator-registered MCP client: its CIMD identity plus where IAM fetches that document. */
5
+ export interface ManagedOAuthClient extends OAuthManagedClient {
6
+ metadataUrl: string
7
+ }
8
+
9
+ /** `OAUTH_CONFIG`, parsed once. `null` from `parseOAuthConfig` means OAuth is off. */
10
+ export interface OAuthConfig {
11
+ clients: ManagedOAuthClient[]
12
+ resources: OAuthResourceDto[]
13
+ }
14
+
15
+ const MAX_CLIENTS = 16
16
+ const MAX_RESOURCES = 32
17
+ const CONFIG_KEYS = ['clients', 'resources']
18
+ const CLIENT_KEYS = ['provider', 'clientId', 'redirectUris', 'metadataUrl']
19
+ const RESOURCE_KEYS = ['app', 'resource', 'defaultScopes', 'scopeGrants']
20
+
21
+ /**
22
+ * Parse `OAUTH_CONFIG`. Absent or empty disables OAuth; anything malformed THROWS, so a typo fails the
23
+ * boot instead of quietly serving fewer clients or scopes than the operator wrote. Unknown keys are
24
+ * refused for the same reason.
25
+ */
26
+ export function parseOAuthConfig(raw: string | undefined): OAuthConfig | null {
27
+ if (raw === undefined || raw.trim() === '') return null
28
+ const value = parseJsonOrNull(raw)
29
+ const rawClients = prop(value, 'clients')
30
+ const rawResources = prop(value, 'resources')
31
+ if (
32
+ !hasOnlyKeys(value, CONFIG_KEYS) || !Array.isArray(rawClients) || rawClients.length === 0 || rawClients.length > MAX_CLIENTS
33
+ || !Array.isArray(rawResources)
34
+ || rawResources.length === 0 || rawResources.length > MAX_RESOURCES
35
+ ) {
36
+ throw new Error('OAUTH_CONFIG must be a JSON object { clients: [...], resources: [...] }')
37
+ }
38
+ const clients: ManagedOAuthClient[] = []
39
+ for (const entry of rawClients) {
40
+ const client = parseOAuthManagedClient(entry)
41
+ const metadataUrl = prop(entry, 'metadataUrl') ?? client?.clientId
42
+ if (
43
+ client === null || !hasOnlyKeys(entry, CLIENT_KEYS) || typeof metadataUrl !== 'string' || !isHttpsDocumentUrl(metadataUrl)
44
+ || clients.some((existing) => existing.clientId === client.clientId)
45
+ ) {
46
+ throw new Error(`OAUTH_CONFIG.clients[${clients.length}] is not a valid managed client`)
47
+ }
48
+ clients.push({ ...client, metadataUrl })
49
+ }
50
+ const resources: OAuthResourceDto[] = []
51
+ for (const entry of rawResources) {
52
+ const resource = parseOAuthResourceDto(entry)
53
+ if (resource === null || !hasOnlyKeys(entry, RESOURCE_KEYS) || resources.some((existing) => existing.resource === resource.resource)) {
54
+ throw new Error(`OAUTH_CONFIG.resources[${resources.length}] is not a valid resource`)
55
+ }
56
+ resources.push(resource)
57
+ }
58
+ return { clients, resources }
59
+ }
60
+
61
+ function hasOnlyKeys(value: unknown, allowed: readonly string[]): boolean {
62
+ return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.keys(value).every((key) => allowed.includes(key))
63
+ }
64
+
65
+ function isHttpsDocumentUrl(value: string): boolean {
66
+ try {
67
+ const url = new URL(value)
68
+ return url.protocol === 'https:' && url.username === '' && url.password === '' && url.hash === ''
69
+ } catch {
70
+ return false
71
+ }
72
+ }
@@ -0,0 +1,262 @@
1
+ import { DEFAULT_LOCALE } from '@fabrika/auth-core'
2
+ import {
3
+ OAUTH_CLIENT_ASSERTION_ALGORITHMS,
4
+ type OAuthAuthorizationRequest,
5
+ type OAuthAuthorizationServerMetadata,
6
+ type OAuthClientCredential,
7
+ type OAuthResourceDto,
8
+ parseOAuthAuthorizationAttempt,
9
+ parseOAuthClientCredential,
10
+ parseOAuthRevocationRequest,
11
+ parseOAuthTokenRequest,
12
+ resolveOAuthAuthorizationScopes,
13
+ } from '@fabrika/iam-contract'
14
+ import { decodeJwt } from 'jose'
15
+ import { readForm, redirectHeaders, sameOrigin } from './auth/http'
16
+ import { currentSession } from './auth/sessions'
17
+ import { principalStatus } from './db'
18
+ import type { Env } from './env'
19
+ import { escapeHtml } from './html'
20
+ import { installationBrand } from './installation-brand'
21
+ import { establishClient, type EstablishedClient, exchangeOAuthToken, grantAuthorization, revokeOAuthToken, scopeCeiling } from './oauth'
22
+ import { authenticateOAuthClient, authenticateRevokingClient } from './oauth-client-auth'
23
+ import type { OAuthConfig } from './oauth-config'
24
+ import { normalizeOrigin } from './origin'
25
+ import { htmlPage } from './password-pages'
26
+ import type { Services } from './services'
27
+
28
+ export const OAUTH_METADATA_PATH = '/.well-known/oauth-authorization-server'
29
+ const AUTHORIZE_PATH = '/oauth/authorize'
30
+ const TOKEN_PATH = '/oauth/token'
31
+ const REVOKE_PATH = '/oauth/revoke'
32
+
33
+ type SigningEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>
34
+
35
+ /** The OAuth authorization server's public surface. With `OAUTH_CONFIG` unset every path is 404. */
36
+ export async function handleOAuth(request: Request, services: Services, env: SigningEnv, requestId: string): Promise<Response> {
37
+ const config = services.config.oauth
38
+ if (config === null) return new Response('not found', { status: 404 })
39
+ const pathname = new URL(request.url).pathname
40
+ switch (pathname) {
41
+ case OAUTH_METADATA_PATH:
42
+ return request.method === 'GET' ? authorizationServerMetadata(services.config.issuer) : methodNotAllowed('GET')
43
+ case AUTHORIZE_PATH:
44
+ if (request.method === 'GET') return showConsent(request, services, config)
45
+ if (request.method === 'POST') return decideConsent(request, services, config, requestId)
46
+ return methodNotAllowed('GET, POST')
47
+ case TOKEN_PATH:
48
+ return request.method === 'POST' ? token(request, services, env, config, requestId) : methodNotAllowed('POST')
49
+ case REVOKE_PATH:
50
+ return request.method === 'POST' ? revoke(request, services, env, config, requestId) : methodNotAllowed('POST')
51
+ default:
52
+ return new Response('not found', { status: 404 })
53
+ }
54
+ }
55
+
56
+ function authorizationServerMetadata(issuer: string): Response {
57
+ const metadata: OAuthAuthorizationServerMetadata = {
58
+ issuer,
59
+ authorization_endpoint: `${issuer}${AUTHORIZE_PATH}`,
60
+ token_endpoint: `${issuer}${TOKEN_PATH}`,
61
+ revocation_endpoint: `${issuer}${REVOKE_PATH}`,
62
+ jwks_uri: `${issuer}/.well-known/jwks.json`,
63
+ response_types_supported: ['code'],
64
+ grant_types_supported: ['authorization_code', 'refresh_token'],
65
+ code_challenge_methods_supported: ['S256'],
66
+ token_endpoint_auth_methods_supported: ['none', 'private_key_jwt'],
67
+ token_endpoint_auth_signing_alg_values_supported: [...OAUTH_CLIENT_ASSERTION_ALGORITHMS],
68
+ revocation_endpoint_auth_methods_supported: ['none', 'private_key_jwt'],
69
+ revocation_endpoint_auth_signing_alg_values_supported: [...OAUTH_CLIENT_ASSERTION_ALGORITHMS],
70
+ authorization_response_iss_parameter_supported: true,
71
+ client_id_metadata_document_supported: true,
72
+ }
73
+ return Response.json(metadata, { headers: { 'cache-control': 'public, max-age=300', 'access-control-allow-origin': '*' } })
74
+ }
75
+
76
+ type AuthorizationCheck =
77
+ | { kind: 'refused'; message: string }
78
+ | { kind: 'redirect'; response: Response }
79
+ | { kind: 'valid'; request: OAuthAuthorizationRequest; client: EstablishedClient; resource: OAuthResourceDto; scopes: string[] }
80
+
81
+ /**
82
+ * Validate an authorization request in the order RFC 6749 §4.1.2.1 requires: until the client and its
83
+ * redirect URI are established an error is a page here, never a redirect to an unverified address.
84
+ */
85
+ async function checkAuthorization(issuer: string, config: OAuthConfig, input: Record<string, string> | null): Promise<AuthorizationCheck> {
86
+ const attempt = parseOAuthAuthorizationAttempt(input)
87
+ if (attempt.kind === 'invalid_request') return { kind: 'refused', message: 'The authorization request is malformed.' }
88
+ const coordinates = attempt.kind === 'valid' ? attempt.request : attempt.coordinates
89
+ const client = await establishClient(config, coordinates.client_id, coordinates.redirect_uri)
90
+ if (client === null) return { kind: 'refused', message: 'The client or its redirect URI is not registered.' }
91
+ if (attempt.kind === 'invalid_scope') return { kind: 'redirect', response: clientRedirect(issuer, coordinates, { error: 'invalid_scope' }) }
92
+ const resource = config.resources.find((entry) => entry.resource === coordinates.resource)
93
+ if (resource === undefined) return { kind: 'redirect', response: clientRedirect(issuer, coordinates, { error: 'invalid_target' }) }
94
+ const scopes = resolveOAuthAuthorizationScopes(attempt.request.scope, resource)
95
+ if (scopes === null) return { kind: 'redirect', response: clientRedirect(issuer, coordinates, { error: 'invalid_scope' }) }
96
+ return { kind: 'valid', request: attempt.request, client, resource, scopes }
97
+ }
98
+
99
+ async function showConsent(request: Request, services: Services, config: OAuthConfig): Promise<Response> {
100
+ const url = new URL(request.url)
101
+ const check = await checkAuthorization(services.config.issuer, config, singleValued(url.searchParams))
102
+ if (check.kind === 'refused') return errorPage(services, check.message, 400)
103
+ if (check.kind === 'redirect') return check.response
104
+ const session = await currentSession(request, services)
105
+ if (session === null) {
106
+ const back = `${services.config.issuer}${AUTHORIZE_PATH}${url.search}`
107
+ return new Response(null, { status: 302, headers: redirectHeaders(`${services.config.issuer}/auth/login?redirect=${encodeURIComponent(back)}`) })
108
+ }
109
+ const principal = await services.repositories.principals.getPrincipalById(session.principal_id)
110
+ if (principal === null || principal.type !== 'user' || principalStatus(principal) !== 'active') {
111
+ return errorPage(services, 'This account cannot authorize applications.', 403)
112
+ }
113
+ return consentPage(services, check, principal.label)
114
+ }
115
+
116
+ async function decideConsent(request: Request, services: Services, config: OAuthConfig, requestId: string): Promise<Response> {
117
+ if (!sameOrigin(request, services.config)) return errorPage(services, 'The consent was not submitted from this page.', 403)
118
+ const form = await readForm(request)
119
+ const fields = form === null ? null : singleValued(form)
120
+ const decision = fields?.['decision']
121
+ const issuer = services.config.issuer
122
+ const check = await checkAuthorization(issuer, config, fields)
123
+ if (check.kind === 'refused') return errorPage(services, check.message, 400)
124
+ if (check.kind === 'redirect') return check.response
125
+ if (decision === 'deny') return clientRedirect(issuer, check.request, { error: 'access_denied' })
126
+ if (decision !== 'approve') return errorPage(services, 'The consent decision is missing.', 400)
127
+ const session = await currentSession(request, services)
128
+ if (session === null) return errorPage(services, 'Your sign-in has ended. Start the authorization again.', 401)
129
+ const code = await grantAuthorization(services, { request: check.request, resource: check.resource, scopes: check.scopes, session, requestId })
130
+ return clientRedirect(issuer, check.request, { code })
131
+ }
132
+
133
+ async function token(request: Request, services: Services, env: SigningEnv, config: OAuthConfig, requestId: string): Promise<Response> {
134
+ const form = await readForm(request)
135
+ const fields = form === null ? null : singleValued(form)
136
+ const credential = parseOAuthClientCredential(fields)
137
+ if (credential === null) return protocolError('invalid_client', 401)
138
+ const input = parseOAuthTokenRequest(withAssertedClientId(fields, credential))
139
+ if (input === null) return protocolError('invalid_request', 400)
140
+ const issuer = services.config.issuer
141
+ const client = await authenticateOAuthClient(services, config, {
142
+ clientId: input.client_id,
143
+ credential,
144
+ audiences: [`${issuer}${TOKEN_PATH}`, issuer],
145
+ })
146
+ if (client === null) return protocolError('invalid_client', 401)
147
+ const outcome = await exchangeOAuthToken(services, env, client, input, requestId)
148
+ if (!outcome.ok) return protocolError(outcome.error, 400)
149
+ return Response.json(outcome.body, { headers: { 'cache-control': 'no-store', pragma: 'no-cache' } })
150
+ }
151
+
152
+ async function revoke(request: Request, services: Services, env: SigningEnv, config: OAuthConfig, requestId: string): Promise<Response> {
153
+ const form = await readForm(request)
154
+ const fields = form === null ? null : singleValued(form)
155
+ const credential = parseOAuthClientCredential(fields)
156
+ if (credential === null) return protocolError('invalid_client', 401)
157
+ const input = parseOAuthRevocationRequest(withAssertedClientId(fields, credential))
158
+ if (input === null) return protocolError('invalid_request', 400)
159
+ const issuer = services.config.issuer
160
+ const authenticated = await authenticateRevokingClient(services, config, {
161
+ clientId: input.client_id,
162
+ credential,
163
+ audiences: [`${issuer}${REVOKE_PATH}`, `${issuer}${TOKEN_PATH}`, issuer],
164
+ })
165
+ if (!authenticated) return protocolError('invalid_client', 401)
166
+ await revokeOAuthToken(services, env, input, requestId)
167
+ return new Response(null, { status: 200, headers: { 'cache-control': 'no-store' } })
168
+ }
169
+
170
+ /**
171
+ * RFC 7521 §4.2 lets a client that authenticates with an assertion omit `client_id`; the assertion's
172
+ * `sub` then names it. Nothing is trusted from it here: verification requires `iss` = `sub` = that id.
173
+ */
174
+ function withAssertedClientId(fields: Record<string, string> | null, credential: OAuthClientCredential): Record<string, string> | null {
175
+ if (fields === null || credential.method !== 'private_key_jwt' || Object.hasOwn(fields, 'client_id')) return fields
176
+ try {
177
+ const subject = decodeJwt(credential.assertion).sub
178
+ return subject === undefined ? fields : { ...fields, client_id: subject }
179
+ } catch {
180
+ return fields
181
+ }
182
+ }
183
+
184
+ async function consentPage(services: Services, check: Extract<AuthorizationCheck, { kind: 'valid' }>, signedInAs: string): Promise<Response> {
185
+ const { request, client, resource, scopes } = check
186
+ const clientName = client.metadata.client_name ?? client.registration.clientId
187
+ const permissions = (scopeCeiling(resource, scopes) ?? []).map((permission) => {
188
+ const scope = permission.scope == null ? 'everywhere' : `${permission.scope.type} ${permission.scope.value}`
189
+ return `<li><code>${escapeHtml(permission.action)}</code> — ${escapeHtml(scope)}</li>`
190
+ })
191
+ const fields: [string, string | undefined][] = [
192
+ ['response_type', request.response_type],
193
+ ['client_id', request.client_id],
194
+ ['redirect_uri', request.redirect_uri],
195
+ ['resource', request.resource],
196
+ ['scope', request.scope],
197
+ ['state', request.state],
198
+ ['code_challenge', request.code_challenge],
199
+ ['code_challenge_method', request.code_challenge_method],
200
+ ]
201
+ const hidden = fields.flatMap(([name, value]) => value === undefined ? [] : [`<input type="hidden" name="${name}" value="${escapeHtml(value)}">`])
202
+ return htmlPage({
203
+ locale: DEFAULT_LOCALE,
204
+ brand: await installationBrand(services),
205
+ title: 'Authorize application',
206
+ content: `<h1>Authorize ${escapeHtml(clientName)}</h1>
207
+ <p>Signed in as <strong>${escapeHtml(signedInAs)}</strong>.</p>
208
+ <p><strong>${escapeHtml(clientName)}</strong> asks to act as you in <strong>${escapeHtml(resource.app)}</strong>.</p>
209
+ <p>Client: <code>${escapeHtml(client.registration.clientId)}</code></p>
210
+ <p>Resource: <code>${escapeHtml(resource.resource)}</code></p>
211
+ <p>Scopes: <code>${escapeHtml(scopes.join(' '))}</code></p>
212
+ <p>At most these permissions, and only those you hold yourself:</p>
213
+ <ul>${permissions.join('')}</ul>
214
+ <p>Access ends when this sign-in ends or when it is revoked.</p>
215
+ <form method="post" action="${AUTHORIZE_PATH}">${hidden.join('')}
216
+ <button name="decision" value="approve">Allow</button>
217
+ <button name="decision" value="deny">Deny</button></form>`,
218
+ // Chromium applies `form-action` to the redirect a submission answers with (see CLAUDE.md).
219
+ formActionOrigin: normalizeOrigin(request.redirect_uri) ?? undefined,
220
+ })
221
+ }
222
+
223
+ /** Every authorization response names the issuer (RFC 9207), so a client can detect a mix-up of servers. */
224
+ function clientRedirect(
225
+ issuer: string,
226
+ target: Pick<OAuthAuthorizationRequest, 'redirect_uri' | 'state'>,
227
+ parameters: Record<string, string>,
228
+ ): Response {
229
+ const url = new URL(target.redirect_uri)
230
+ for (const [name, value] of Object.entries(parameters)) url.searchParams.set(name, value)
231
+ if (target.state !== undefined) url.searchParams.set('state', target.state)
232
+ url.searchParams.set('iss', issuer)
233
+ return new Response(null, { status: 302, headers: redirectHeaders(url.href) })
234
+ }
235
+
236
+ /** OAuth parameters must not repeat (RFC 6749 §3.1); a repeated one makes the whole request invalid. */
237
+ function singleValued(params: URLSearchParams): Record<string, string> | null {
238
+ const result: Record<string, string> = {}
239
+ for (const [name, value] of params) {
240
+ if (Object.hasOwn(result, name)) return null
241
+ result[name] = value
242
+ }
243
+ return result
244
+ }
245
+
246
+ async function errorPage(services: Services, message: string, status: number): Promise<Response> {
247
+ return htmlPage({
248
+ locale: DEFAULT_LOCALE,
249
+ brand: await installationBrand(services),
250
+ title: 'Authorization failed',
251
+ content: `<h1>Authorization failed</h1><p>${escapeHtml(message)}</p>`,
252
+ status,
253
+ })
254
+ }
255
+
256
+ function protocolError(error: string, status: number): Response {
257
+ return Response.json({ error }, { status, headers: { 'cache-control': 'no-store', pragma: 'no-cache' } })
258
+ }
259
+
260
+ function methodNotAllowed(allow: string): Response {
261
+ return new Response(null, { status: 405, headers: { allow, 'cache-control': 'no-store' } })
262
+ }