@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,291 @@
1
+ /**
2
+ * `/admin/*` — the MACHINE PROVISIONING surface, and the shared admission code `/admin/rpc` uses.
3
+ *
4
+ * It is not a second copy of the administration API. It used to be: about two dozen REST operations
5
+ * mirrored `/admin/rpc` procedure for procedure, and every one of them was a second place a gate
6
+ * could be forgotten (SEC-11) or an internal message could leak (CORR-4) — for operations that had
7
+ * no REST caller at all. They are gone. The console and every operator action go through
8
+ * `/admin/rpc`, so "policy, audit and hidden-object behaviour must not diverge by transport" is no
9
+ * longer a property anyone has to maintain for them; there is one transport.
10
+ *
11
+ * What is left is exactly what cannot be an RPC call from a browser:
12
+ * - `GET|PUT /admin/apps/:app/schema` — a deploy step reconciling an app's vocabulary
13
+ * (`reconcileSchema`, `@fabrika/auth`), which runs outside the installation over plain HTTPS;
14
+ * - `POST /admin/api-keys`, `DELETE /admin/api-keys/:principalId` — first-machine-caller bootstrap,
15
+ * which runs before a console exists.
16
+ * Adding a route here means proving no `/admin/rpc` procedure can serve the caller.
17
+ *
18
+ * **The whole surface is BEARER-ONLY.** The console reaches it through Control's gateway, which
19
+ * forwards the proxy-injected token as a bearer; machines present a `px_` key. No browser cookie is
20
+ * read, so there is no ambient authority and no CSRF check to keep.
21
+ *
22
+ * `extractCredentials` and `resolveAdmin` live here and are SHARED with `admin/rpc.ts`, so the
23
+ * caller is resolved in one place for both.
24
+ */
25
+
26
+ import { API_KEY_PREFIX, isWorkloadKind, type PermissionEntry, permits, type PrincipalType } from '@fabrika/auth-core'
27
+ import { IAM_ACTIONS, IAM_APP_ID } from '@fabrika/iam-contract'
28
+ import { resolveCaller } from '../auth'
29
+ import { principalStatus } from '../db'
30
+ import type { Env, RequestContext } from '../env'
31
+ import { logError } from '../log'
32
+ import { generateRequestId } from '../request-id'
33
+ import { resolvePermissionsAt } from '../resolve'
34
+ import type { Services } from '../services'
35
+ import { getSigner, verifyAccessToken } from '../signing'
36
+ import { recordAdminAccess } from './access'
37
+ import { type AdminContext, AdminUseCaseError, getAppSchema, provisionApiKey, putAppSchema, revokeApiKey } from './handlers'
38
+ import { error } from './http'
39
+
40
+ // The installation administrator's action. Scope-less → satisfied by a GLOBAL permission only.
41
+ export const ADMIN_ACTION = IAM_ACTIONS.ADMIN
42
+
43
+ // IAM's own app id — the audience the admin caller is resolved against (the SSO session is
44
+ // minted for it in auth/routes.ts). The built-in `admin` role is cross-app, so a global admin grant
45
+ // still resolves here regardless.
46
+ export const IAM_APP = IAM_APP_ID
47
+
48
+ /**
49
+ * The admin credential read off the request: an `Authorization: Bearer` holding a `px_` admin or
50
+ * provisioning key, or a proxy-injected access JWT forwarded by a first-party gateway.
51
+ */
52
+ export function extractCredentials(request: Request, requestId: string): { bearer: string | null; requestId: string } {
53
+ return { bearer: readBearer(request.headers.get('Authorization')), requestId }
54
+ }
55
+
56
+ /** Read the token out of an `Authorization: Bearer <token>` header. Null when absent/non-bearer. */
57
+ function readBearer(header: string | null): string | null {
58
+ if (header === null) {
59
+ return null
60
+ }
61
+ const match = /^Bearer\s+(.+)$/i.exec(header.trim())
62
+ return match ? (match[1]?.trim() ?? null) : null
63
+ }
64
+
65
+ /** The resolved admin (already authenticated; the `iam.admin` gate is applied by `handleAdmin`). */
66
+ export interface ResolvedAdmin {
67
+ id: string
68
+ type: PrincipalType
69
+ label: string | null
70
+ permissions: PermissionEntry[]
71
+ /** The app the admin's credential was verified for: a registered console gateway, or IAM itself for a `px_` key. */
72
+ audience: string
73
+ /** The credential is a signed-in session's token (`AccessTokenClaims.session`), not one a `px_` key minted. */
74
+ session: boolean
75
+ }
76
+
77
+ export type AdminResolution =
78
+ | { ok: true; admin: ResolvedAdmin }
79
+ | { ok: false; status: 401 | 403; reason: string }
80
+
81
+ /**
82
+ * Resolve the admin caller from its bearer:
83
+ * - a signed-in session's access JWT whose `aud` is a REGISTERED admin gateway → verify identity, then resolve IAM
84
+ * permissions;
85
+ * - a `px_<key>` machine credential (CI / provisioning) → `resolveCaller`.
86
+ * No bearer is 401. Returns the caller + permissions; `handleAdmin` then enforces `iam.admin`. An ANONYMOUS credential
87
+ * (a share link, no principal) is rejected — admin needs an accountable principal.
88
+ */
89
+ export async function resolveAdmin(
90
+ services: Services,
91
+ env: Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'FABRIKA_IAM_PROVISIONING_KEY' | 'ENVIRONMENT'>,
92
+ creds: { bearer: string | null; requestId: string },
93
+ ): Promise<AdminResolution> {
94
+ if (creds.bearer === null) {
95
+ return { ok: false, status: 401, reason: 'missing_token' }
96
+ }
97
+ // The control gateway receives a proxy-injected access JWT after the browser session has stopped
98
+ // at the proxy. Its signed audience names the calling app and MUST be a registered admin gateway:
99
+ // every app holds this token in cleartext, so an unpinned audience lets any of them replay it.
100
+ if (!creds.bearer.startsWith(API_KEY_PREFIX)) {
101
+ const signer = await getSigner(env)
102
+ const claims = await verifyAccessToken(signer, creds.bearer, { issuer: services.config.issuer })
103
+ if (claims === null) {
104
+ return { ok: false, status: 401, reason: 'invalid_token' }
105
+ }
106
+ if (!services.config.adminAudiences.has(claims.aud)) {
107
+ return { ok: false, status: 403, reason: 'not_allowed' }
108
+ }
109
+ // Refused before any permission is resolved: a workload token never administers (ADR-0022 "Principal kinds").
110
+ if (claims.ptype === undefined || isWorkloadKind(claims.ptype)) {
111
+ return { ok: false, status: 403, reason: 'not_allowed' }
112
+ }
113
+ // A token the proxy minted from a `px_` key carries that key's narrowed grants, not the person's live IAM permissions.
114
+ if (claims.session !== true) {
115
+ return { ok: false, status: 403, reason: 'not_allowed' }
116
+ }
117
+ // Nor does a person signed in at a terminal: this branch resolves the subject's own permissions, which would
118
+ // step past the terminal's ceiling (ADR-0067 §4).
119
+ if (claims.terminal !== undefined) {
120
+ return { ok: false, status: 403, reason: 'not_allowed' }
121
+ }
122
+ const principal = await services.repositories.principals.getPrincipalById(claims.sub)
123
+ if (principal === null) {
124
+ return { ok: false, status: 401, reason: 'invalid_token' }
125
+ }
126
+ if (principalStatus(principal) === 'disabled') {
127
+ return { ok: false, status: 403, reason: 'disabled' }
128
+ }
129
+ const permissions = await resolvePermissionsAt(services, principal, IAM_APP)
130
+ return {
131
+ ok: true,
132
+ admin: { id: principal.id, type: principal.type, label: principal.label, permissions, audience: claims.aud, session: true },
133
+ }
134
+ }
135
+
136
+ const res = await resolveCaller(services, env, { app: IAM_APP, credential: creds.bearer, requestId: creds.requestId })
137
+ if (!res.ok) {
138
+ const status = res.reason === 'missing_token' || res.reason === 'invalid_token' ? 401 : 403
139
+ return { ok: false, status, reason: res.reason }
140
+ }
141
+ // A credential bound to ANOTHER app never administers IAM. `resolveCredential` already refuses
142
+ // the mismatch, so this is the second lock on the same rule — and the one that reads as a rule
143
+ // rather than as a consequence of how a credential happens to resolve (SEC-7).
144
+ if (res.verifiedApp !== IAM_APP) {
145
+ return { ok: false, status: 403, reason: 'not_allowed' }
146
+ }
147
+ if (res.caller.type === undefined) {
148
+ return { ok: false, status: 403, reason: 'not_allowed' }
149
+ }
150
+ return {
151
+ ok: true,
152
+ admin: {
153
+ id: res.caller.id,
154
+ type: res.caller.type,
155
+ label: res.caller.label,
156
+ permissions: res.caller.permissions,
157
+ audience: res.verifiedApp,
158
+ session: false,
159
+ },
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Handle a `/admin/*` PROVISIONING request. The caller is resolved from its bearer and every handler runs only after `can('iam.admin')`
165
+ * passes in-Worker (scope-less → global only). Returns 401 when the caller can't be authenticated,
166
+ * 403 when authenticated but not an admin. `requestId` is the correlation id the composition root
167
+ * allowed (`src/request-id.ts`); a caller that supplies none gets a generated one.
168
+ */
169
+ export async function handleAdmin(
170
+ request: Request,
171
+ services: Services,
172
+ env: Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'FABRIKA_IAM_PROVISIONING_KEY' | 'ENVIRONMENT'>,
173
+ ctx: RequestContext,
174
+ requestId: string = generateRequestId(),
175
+ ): Promise<Response> {
176
+ const url = new URL(request.url)
177
+ const creds = extractCredentials(request, requestId)
178
+
179
+ // Backstop: resolution and the handlers touch D1, which can throw on a transient
180
+ // error. Map any unexpected throw to a 500 (never leak internals) so the admin
181
+ // surface degrades gracefully instead of surfacing a raw rejection.
182
+ try {
183
+ const resolution = await resolveAdmin(services, env, creds)
184
+ if (!resolution.ok) {
185
+ return error(resolution.status, resolution.reason)
186
+ }
187
+ if (!permits(resolution.admin.permissions, ADMIN_ACTION)) {
188
+ return error(403, 'admin permission required')
189
+ }
190
+
191
+ // Recorded whatever it then answers, a 404 or 405 included: the caller is an installation admin.
192
+ const operation = adminOperation(request.method, url)
193
+ const c: AdminContext = {
194
+ services,
195
+ request,
196
+ url,
197
+ admin: resolution.admin,
198
+ administration: { kind: 'installation' },
199
+ app: IAM_APP,
200
+ requestId: creds.requestId,
201
+ ctx,
202
+ }
203
+ try {
204
+ await recordAdminAccess(services, resolution.admin, creds.requestId, { method: request.method, route: operation.route })
205
+ } catch (err) {
206
+ logError('admin access could not be recorded', err)
207
+ return error(503, 'admin access could not be recorded')
208
+ }
209
+ return await operation.run(c)
210
+ } catch (err) {
211
+ if (err instanceof AdminUseCaseError) {
212
+ return error(err.httpStatus, err.message)
213
+ }
214
+ logError('admin request failed', err)
215
+ return error(500, 'internal error')
216
+ }
217
+ }
218
+
219
+ /**
220
+ * One `/admin/*` request's operation: its route template, which the access row records, and its handler. A path that
221
+ * names no operation is the fixed `UNMATCHED_ROUTE`, so no raw path value reaches the row, and its handler answers 404.
222
+ */
223
+ interface AdminOperation {
224
+ readonly route: string
225
+ run(c: AdminContext): Promise<Response>
226
+ }
227
+
228
+ const UNMATCHED_ROUTE = '/admin/*'
229
+
230
+ function refusal(route: string, response: Response): AdminOperation {
231
+ return { route, run: () => Promise.resolve(response) }
232
+ }
233
+
234
+ /**
235
+ * Path segments after `/admin/`. Returns the matched operation, or one that answers the 404/405.
236
+ *
237
+ * FOUR operations, and the list is closed. Anything an operator does — principals, grants, roles,
238
+ * policies, share links, sessions, audit — is `/admin/rpc` and only `/admin/rpc`.
239
+ */
240
+ function adminOperation(method: string, url: URL): AdminOperation {
241
+ const segments = decodedSegments(url.pathname.replace(/^\/admin\/?/, ''))
242
+ if (segments === null) {
243
+ return refusal(UNMATCHED_ROUTE, error(404, 'not found'))
244
+ }
245
+ const [resource, idOrSub, action] = segments
246
+
247
+ switch (resource) {
248
+ // GET|PUT /admin/apps/:app/schema — read / reconcile an app's vocabulary. The PUT is
249
+ // `reconcileSchema` in the app SDK, called from a DEPLOY: it runs outside the installation with
250
+ // nothing but a URL and a key, so a service binding is not available to it.
251
+ case 'apps': {
252
+ if (segments.length !== 3 || idOrSub === undefined || action !== 'schema') {
253
+ return refusal(UNMATCHED_ROUTE, error(404, 'not found'))
254
+ }
255
+ const route = '/admin/apps/:app/schema'
256
+ if (method === 'GET') return { route, run: (c) => getAppSchema(c, idOrSub) }
257
+ if (method === 'PUT') return { route, run: (c) => putAppSchema(c, idOrSub) }
258
+ return refusal(route, methodNotAllowed())
259
+ }
260
+
261
+ // POST /admin/api-keys, DELETE /admin/api-keys/:principalId — the first machine caller.
262
+ // Bootstrap runs before any console exists, from a shell script or a stack bring-up holding the
263
+ // provisioning key, so it cannot be a browser-shaped RPC call either.
264
+ case 'api-keys':
265
+ if (idOrSub === undefined) {
266
+ return method === 'POST' ? { route: '/admin/api-keys', run: provisionApiKey } : refusal('/admin/api-keys', methodNotAllowed())
267
+ }
268
+ if (segments.length !== 2) {
269
+ return refusal(UNMATCHED_ROUTE, error(404, 'not found'))
270
+ }
271
+ return method === 'DELETE'
272
+ ? { route: '/admin/api-keys/:principalId', run: (c) => revokeApiKey(c, idOrSub) }
273
+ : refusal('/admin/api-keys/:principalId', methodNotAllowed())
274
+
275
+ default:
276
+ return refusal(UNMATCHED_ROUTE, error(404, 'not found'))
277
+ }
278
+ }
279
+
280
+ /** The path's segments, percent-decoded: an app id `notes@prod` arrives as `notes%40prod`. Null for a malformed escape. */
281
+ function decodedSegments(path: string): string[] | null {
282
+ try {
283
+ return path.split('/').filter(Boolean).map((segment) => decodeURIComponent(segment))
284
+ } catch {
285
+ return null
286
+ }
287
+ }
288
+
289
+ function methodNotAllowed(): Response {
290
+ return error(405, 'method not allowed')
291
+ }
@@ -0,0 +1,387 @@
1
+ import { type AuthContext, ForbiddenError, initRpc, type RpcRouterFor, toErrorResponse, UnauthorizedError } from '@fabrika/app'
2
+ import { permits, scopedValues, WORKLOAD_KINDS } from '@fabrika/auth-core'
3
+ import { type IamAdminRpcContract, PASSWORD_MAX_LENGTH, PASSWORD_MIN_LENGTH_FLOOR } from '@fabrika/iam-contract'
4
+ import { installationBrandSchema } from '@fabrika/proxy-core/brand'
5
+ import { z } from 'zod'
6
+ import type { IamAppContext } from '../app'
7
+ import { logError } from '../log'
8
+ import { recordAdminAccess, rpcProcedureOf } from './access'
9
+ import { grantAppRole, listAdministeredApps, listAppPeople, revokeAppRole } from './app-people'
10
+ import { listConnections, revokeConnection } from './connections'
11
+ import type { AdminContext } from './handlers'
12
+ import { adminUseCases } from './handlers'
13
+ import { ADMIN_ACTION, extractCredentials, IAM_APP, resolveAdmin } from './router'
14
+ import { administrationOf } from './user-admin'
15
+
16
+ const t = initRpc<IamAppContext>()
17
+ const nonEmpty = z.string().min(1)
18
+ const optionalNullableString = z.string().nullable().optional()
19
+
20
+ const appInput = z.object({ app: nonEmpty })
21
+ const pageInput = { before: z.string().optional(), limit: z.number().finite().optional() }
22
+ const principalIdInput = z.object({ principalId: nonEmpty })
23
+ const shareLinkIdInput = z.object({ id: nonEmpty })
24
+ const authorization = {
25
+ roleKey: nonEmpty.optional(),
26
+ permissions: z.array(nonEmpty).optional(),
27
+ scopeType: optionalNullableString,
28
+ scopeValue: optionalNullableString,
29
+ app: optionalNullableString,
30
+ expiresAt: z.number().finite().optional().nullable(),
31
+ }
32
+ const policy = {
33
+ name: nonEmpty,
34
+ description: z.string().optional(),
35
+ permissions: z.array(nonEmpty),
36
+ }
37
+ const grantSchema = z.object({ principalId: nonEmpty, ...authorization })
38
+ const shareGrantSchema = z.object({
39
+ action: nonEmpty,
40
+ scope: z.object({ type: nonEmpty, value: nonEmpty }).nullable().optional(),
41
+ })
42
+
43
+ // A procedure without `.require(ADMIN_ACTION)` is open to a user administrator too (ADR-0058): `context` admits only a
44
+ // caller with an administration, and the use case applies the user-admin rules (`user-admin.ts`).
45
+ export const adminRpcRouter: RpcRouterFor<IamAppContext, IamAdminRpcContract> = t.router({
46
+ me: t.procedure.query(({ ctx }) => adminUseCases.me(context(ctx))),
47
+ principals: t.router({
48
+ list: t.procedure
49
+ .input(
50
+ z.object({
51
+ type: z.enum(['user', 'service']).optional(),
52
+ status: z.enum(['invited', 'active', 'disabled']).optional(),
53
+ q: z.string().optional(),
54
+ ...pageInput,
55
+ }).default({}),
56
+ )
57
+ .query(({ ctx, input }) => adminUseCases.listPrincipals(context(ctx), input)),
58
+ get: t.procedure.input(principalIdInput).query(({ ctx, input }) => adminUseCases.getPrincipal(context(ctx), input)),
59
+ invite: t.procedure
60
+ .input(z.object({ email: nonEmpty, affiliation: z.enum(['internal', 'external']).optional() }))
61
+ .mutation(({ ctx, input }) => adminUseCases.invitePrincipal(context(ctx), input)),
62
+ update: t.procedure
63
+ .input(z.object({ principalId: nonEmpty, disabled: z.boolean() }))
64
+ .mutation(({ ctx, input }) => adminUseCases.updatePrincipal(context(ctx), input)),
65
+ promote: t.procedure
66
+ .input(principalIdInput)
67
+ .require(ADMIN_ACTION)
68
+ .mutation(({ ctx, input }) => adminUseCases.promotePrincipal(context(ctx), input)),
69
+ }),
70
+ // Revoking a PARENT already cascades to every app session derived from it, so `revoke` is one
71
+ // call and never a sweep — see `SessionRepository.revokeSessionById`.
72
+ sessions: t.router({
73
+ list: t.procedure
74
+ .input(z.object({ principalId: nonEmpty, signInsOnly: z.boolean().optional(), ...pageInput }))
75
+ .query(({ ctx, input }) => adminUseCases.listSessions(context(ctx), input)),
76
+ revoke: t.procedure
77
+ .input(z.object({ id: nonEmpty }))
78
+ .mutation(({ ctx, input }) => adminUseCases.revokeSession(context(ctx), input)),
79
+ revokeAll: t.procedure
80
+ .input(principalIdInput)
81
+ .mutation(({ ctx, input }) => adminUseCases.revokeSessionsForPrincipal(context(ctx), input)),
82
+ }),
83
+ passwords: t.router({
84
+ issueEnrollment: t.procedure
85
+ .input(principalIdInput)
86
+ .mutation(({ ctx, input }) => adminUseCases.issuePasswordEnrollment(context(ctx), input)),
87
+ issueReset: t.procedure
88
+ .input(principalIdInput)
89
+ .mutation(({ ctx, input }) => adminUseCases.issuePasswordReset(context(ctx), input)),
90
+ disable: t.procedure
91
+ .input(principalIdInput)
92
+ .mutation(({ ctx, input }) => adminUseCases.disablePassword(context(ctx), input)),
93
+ }),
94
+ grants: t.router({
95
+ create: t.procedure.input(grantSchema).mutation(({ ctx, input }) => adminUseCases.createGrant(context(ctx), input)),
96
+ update: t.procedure.input(z.object({ id: nonEmpty, ...authorization }).omit({ app: true }))
97
+ .mutation(({ ctx, input }) => adminUseCases.updateGrant(context(ctx), input)),
98
+ delete: t.procedure.input(z.object({ id: nonEmpty })).mutation(({ ctx, input }) => adminUseCases.deleteGrant(context(ctx), input)),
99
+ }),
100
+ apps: t.router({
101
+ list: t.procedure.query(({ ctx }) => adminUseCases.listApps(context(ctx))),
102
+ getSchema: t.procedure.input(appInput).query(({ ctx, input }) => adminUseCases.getAppSchema(context(ctx), input)),
103
+ setReturnOrigins: t.procedure
104
+ .input(z.object({ app: nonEmpty, origins: z.array(nonEmpty) }))
105
+ .require(ADMIN_ACTION)
106
+ .mutation(({ ctx, input }) => adminUseCases.setReturnOrigins(context(ctx), input)),
107
+ }),
108
+ connections: t.router({
109
+ list: t.procedure.input(z.object({ principalId: nonEmpty, ...pageInput })).require(ADMIN_ACTION)
110
+ .query(({ ctx, input }) => listConnections(context(ctx), input)),
111
+ revoke: t.procedure.input(z.object({ id: nonEmpty })).require(ADMIN_ACTION)
112
+ .mutation(({ ctx, input }) => revokeConnection(context(ctx), input)),
113
+ }),
114
+ roles: t.router({
115
+ list: t.procedure
116
+ .input(z.object({ app: optionalNullableString }))
117
+ .query(({ ctx, input }) => adminUseCases.listRoles(context(ctx), input)),
118
+ }),
119
+ policies: t.router({
120
+ list: t.procedure.input(appInput).query(({ ctx, input }) => adminUseCases.listPolicies(context(ctx), input)),
121
+ create: t.procedure
122
+ .input(z.object({ app: nonEmpty, policy: z.object({ key: nonEmpty, ...policy }) }))
123
+ .require(ADMIN_ACTION)
124
+ .mutation(({ ctx, input }) => adminUseCases.createPolicy(context(ctx), input)),
125
+ update: t.procedure
126
+ .input(z.object({ app: nonEmpty, key: nonEmpty, policy: z.object(policy) }))
127
+ .require(ADMIN_ACTION)
128
+ .mutation(({ ctx, input }) => adminUseCases.updatePolicy(context(ctx), input)),
129
+ delete: t.procedure
130
+ .input(z.object({ app: nonEmpty, key: nonEmpty }))
131
+ .require(ADMIN_ACTION)
132
+ .mutation(({ ctx, input }) => adminUseCases.deletePolicy(context(ctx), input)),
133
+ }),
134
+ apiKeys: t.router({
135
+ list: t.procedure.input(z.object(pageInput).default({})).require(ADMIN_ACTION).query(({ ctx, input }) =>
136
+ adminUseCases.listApiKeys(context(ctx), input)
137
+ ),
138
+ get: t.procedure.input(principalIdInput).require(ADMIN_ACTION).query(({ ctx, input }) => adminUseCases.getApiKey(context(ctx), input)),
139
+ provision: t.procedure
140
+ .input(z.object({ label: nonEmpty, type: z.literal('service'), ...authorization }))
141
+ .require(ADMIN_ACTION)
142
+ .mutation(({ ctx, input }) => adminUseCases.provisionApiKey(context(ctx), input)),
143
+ rotate: t.procedure
144
+ .input(z.object({ principalId: nonEmpty, expiresAt: z.number().finite().nullable().optional() }))
145
+ .require(ADMIN_ACTION)
146
+ .mutation(({ ctx, input }) => adminUseCases.rotateApiKey(context(ctx), input)),
147
+ revoke: t.procedure.input(principalIdInput).require(ADMIN_ACTION).mutation(({ ctx, input }) => adminUseCases.revokeApiKey(context(ctx), input)),
148
+ }),
149
+ workloads: t.router({
150
+ issueKey: t.procedure
151
+ .input(
152
+ z.object({ app: nonEmpty, kind: z.enum(WORKLOAD_KINDS), name: nonEmpty, expiresAt: z.number().int(), keep: nonEmpty.nullable() }),
153
+ )
154
+ .require(ADMIN_ACTION)
155
+ .mutation(({ ctx, input }) => adminUseCases.issueWorkloadKey(context(ctx), input)),
156
+ revokeKeys: t.procedure
157
+ .input(z.object({ app: nonEmpty, kind: z.enum(WORKLOAD_KINDS), name: nonEmpty }))
158
+ .require(ADMIN_ACTION)
159
+ .mutation(({ ctx, input }) => adminUseCases.revokeWorkloadKeys(context(ctx), input)),
160
+ }),
161
+ membershipKeys: t.router({
162
+ issue: t.procedure
163
+ .input(z.object({ app: nonEmpty, expiresAt: z.number().int(), keep: nonEmpty.nullable() }))
164
+ .require(ADMIN_ACTION)
165
+ .mutation(({ ctx, input }) => adminUseCases.issueMembershipKey(context(ctx), input)),
166
+ }),
167
+ shareLinks: t.router({
168
+ list: t.procedure
169
+ .input(z.object({ app: nonEmpty.optional(), includeRevoked: z.boolean().optional(), ...pageInput }).default({}))
170
+ .require(ADMIN_ACTION)
171
+ .query(({ ctx, input }) => adminUseCases.listShareLinks(context(ctx), input)),
172
+ issue: t.procedure
173
+ .input(z.object({
174
+ app: nonEmpty,
175
+ grants: z.array(shareGrantSchema),
176
+ label: z.string().optional(),
177
+ expiresAt: z.number().finite(),
178
+ }))
179
+ .require(ADMIN_ACTION)
180
+ .mutation(({ ctx, input }) => adminUseCases.createShareLink(context(ctx), input)),
181
+ revoke: t.procedure.input(shareLinkIdInput).require(ADMIN_ACTION).mutation(({ ctx, input }) => adminUseCases.revokeShareLink(context(ctx), input)),
182
+ }),
183
+ audit: t.router({
184
+ list: t.procedure
185
+ .input(z.object({
186
+ resourceType: z.string().optional(),
187
+ resourceId: z.string().optional(),
188
+ principalId: z.string().optional(),
189
+ subjectPrincipalId: z.string().optional(),
190
+ action: z.string().optional(),
191
+ changesOnly: z.boolean().optional(),
192
+ requestId: z.string().optional(),
193
+ before: z.string().optional(),
194
+ limit: z.number().finite().optional(),
195
+ }))
196
+ .require(ADMIN_ACTION)
197
+ .query(({ ctx, input }) => adminUseCases.listAudit(context(ctx), input)),
198
+ listAuthLog: t.procedure
199
+ .input(z.object({
200
+ principalId: z.string().optional(),
201
+ requestId: z.string().optional(),
202
+ decision: z.enum(['allow', 'deny']).optional(),
203
+ before: z.string().optional(),
204
+ limit: z.number().finite().optional(),
205
+ }))
206
+ .require(ADMIN_ACTION)
207
+ .query(({ ctx, input }) => adminUseCases.listAuthLog(context(ctx), input)),
208
+ }),
209
+ terminals: t.router({
210
+ list: t.procedure
211
+ .input(z.object(pageInput).default({}))
212
+ .require(ADMIN_ACTION)
213
+ .query(({ ctx, input }) => adminUseCases.listTerminals(context(ctx), input)),
214
+ setProfile: t.procedure
215
+ .input(z.object({
216
+ terminalId: nonEmpty,
217
+ label: z.string(),
218
+ sessionTtl: z.number().int(),
219
+ asserters: z.array(z.object({ app: nonEmpty, ceiling: z.array(nonEmpty) })),
220
+ }))
221
+ .require(ADMIN_ACTION)
222
+ .mutation(({ ctx, input }) => adminUseCases.setTerminalProfile(context(ctx), input)),
223
+ revoke: t.procedure
224
+ .input(z.object({ terminalId: nonEmpty }))
225
+ .require(ADMIN_ACTION)
226
+ .mutation(({ ctx, input }) => adminUseCases.revokeTerminal(context(ctx), input)),
227
+ }),
228
+ // No `iam.admin` here: each use case authorizes the application's own `members.manage`, held globally there.
229
+ appPeople: t.router({
230
+ apps: t.procedure.query(({ ctx }) => listAdministeredApps(ctx)),
231
+ list: t.procedure.input(z.object({ app: nonEmpty, after: nonEmpty.optional() })).query(({ ctx, input }) => listAppPeople(ctx, input)),
232
+ grant: t.procedure
233
+ .input(z.object({ app: nonEmpty, role: nonEmpty, email: nonEmpty }))
234
+ .mutation(({ ctx, input }) => grantAppRole(ctx, input)),
235
+ revoke: t.procedure
236
+ .input(z.object({ app: nonEmpty, role: nonEmpty, principalId: nonEmpty }))
237
+ .mutation(({ ctx, input }) => revokeAppRole(ctx, input)),
238
+ }),
239
+ // The installation's own setting: `iam.admin` only, also to read it. Control reads it with the provisioning key.
240
+ brand: t.router({
241
+ get: t.procedure.require(ADMIN_ACTION).query(({ ctx }) => adminUseCases.getInstallationBrand(context(ctx))),
242
+ set: t.procedure
243
+ .input(z.object({ brand: installationBrandSchema }))
244
+ .require(ADMIN_ACTION)
245
+ .mutation(({ ctx, input }) => adminUseCases.setInstallationBrand(context(ctx), input)),
246
+ clear: t.procedure.require(ADMIN_ACTION).mutation(({ ctx }) => adminUseCases.clearInstallationBrand(context(ctx))),
247
+ }),
248
+ // The installation's own setting too: `iam.admin` only, also to read it. The use case holds it to the runtime's floor.
249
+ passwordPolicy: t.router({
250
+ get: t.procedure.require(ADMIN_ACTION).query(({ ctx }) => adminUseCases.getPasswordPolicy(context(ctx))),
251
+ set: t.procedure
252
+ .input(z.object({ minLength: z.number().int().min(PASSWORD_MIN_LENGTH_FLOOR).max(PASSWORD_MAX_LENGTH) }).strict())
253
+ .require(ADMIN_ACTION)
254
+ .mutation(({ ctx, input }) => adminUseCases.setPasswordPolicy(context(ctx), input)),
255
+ }),
256
+ })
257
+
258
+ /** Resolve the admin behind an `/admin/rpc` request, then run `next` with it on `ctx`; anyone else is refused. */
259
+ export const adminRpcAuth = async (request: Request, ctx: IamAppContext, next: () => Promise<Response>): Promise<Response> => {
260
+ try {
261
+ const credentials = extractCredentials(request, ctx.requestId)
262
+ const resolution = await resolveAdmin(ctx.services, ctx.env, credentials)
263
+ if (!resolution.ok) {
264
+ if (resolution.status === 401) {
265
+ const loginUrl = credentials.bearer === null ? createLoginUrl(ctx.services.config.issuer) : undefined
266
+ return toErrorResponse(new UnauthorizedError(resolution.reason, loginUrl === undefined ? undefined : { loginUrl }))
267
+ }
268
+ return toErrorResponse(new ForbiddenError(resolution.reason))
269
+ }
270
+
271
+ ctx.admin = resolution.admin
272
+ ctx.auth = authContext(resolution.admin)
273
+ // Every request of an administrator is recorded before it runs, reads included. A caller without an administration
274
+ // reaches no procedure but `appPeople.*`, so it used no privileged access.
275
+ if (administrationOf(resolution.admin) !== null) {
276
+ const access = { method: request.method, route: '/admin/rpc', procedure: await rpcProcedureOf(request) }
277
+ try {
278
+ await recordAdminAccess(ctx.services, resolution.admin, ctx.requestId, access)
279
+ } catch (err) {
280
+ logError('admin access could not be recorded', err)
281
+ return Response.json({ error: { type: 'unavailable', message: 'admin access could not be recorded' } }, { status: 503 })
282
+ }
283
+ }
284
+ return await scrubInternalErrors(await next())
285
+ } catch (err) {
286
+ logError('admin RPC request failed', err)
287
+ return internalError()
288
+ }
289
+ }
290
+
291
+ /**
292
+ * Mask an internal failure before it leaves the admin surface.
293
+ *
294
+ * TWO rules, because there are two ways an internal message can arrive. A 5xx response is replaced
295
+ * outright, as it always was. AND, INDEPENDENTLY OF STATUS, every `type: 'internal'` envelope in the
296
+ * body gets a fixed message — which is the half that was missing: a BATCHED call always answers 200
297
+ * with the per-call errors inside the body, so it returned verbatim what the single-call path
298
+ * carefully hid (CORR-4). `type: 'internal'` is precisely the branch the framework did NOT choose to
299
+ * expose, so a message that reaches it is by definition not one meant for a caller. Structured
300
+ * failures (`forbidden`, `not_found`, `conflict`, `validation`, …) are untouched.
301
+ */
302
+ async function scrubInternalErrors(response: Response): Promise<Response> {
303
+ if (response.status >= 500) {
304
+ return internalError()
305
+ }
306
+ if (response.headers.get('content-type')?.includes('application/json') !== true) {
307
+ return response
308
+ }
309
+ let body: unknown
310
+ try {
311
+ body = await response.clone().json()
312
+ } catch {
313
+ return response
314
+ }
315
+ const scrubbed = scrubEnvelope(body)
316
+ return scrubbed === null ? response : Response.json(scrubbed, { status: response.status, headers: response.headers })
317
+ }
318
+
319
+ /** Rewrite every `internal` error in a single or batched envelope; null when nothing changed. */
320
+ function scrubEnvelope(body: unknown): unknown {
321
+ if (!isRecord(body)) {
322
+ return null
323
+ }
324
+ const batch = body['batch']
325
+ if (Array.isArray(batch)) {
326
+ let changed = false
327
+ const results = batch.map((entry: unknown) => {
328
+ const masked = maskInternal(entry)
329
+ changed = changed || masked !== null
330
+ return masked ?? entry
331
+ })
332
+ return changed ? { ...body, batch: results } : null
333
+ }
334
+ return maskInternal(body)
335
+ }
336
+
337
+ /** `{ error: { type: 'internal', … } }` → the fixed message; null when the entry needs no change. */
338
+ function maskInternal(entry: unknown): unknown {
339
+ if (!isRecord(entry)) {
340
+ return null
341
+ }
342
+ const error = entry['error']
343
+ if (!isRecord(error) || error['type'] !== 'internal' || error['message'] === 'internal error') {
344
+ return null
345
+ }
346
+ return { ...entry, error: { type: 'internal', message: 'internal error' } }
347
+ }
348
+
349
+ function isRecord(value: unknown): value is Record<string, unknown> {
350
+ return value !== null && typeof value === 'object'
351
+ }
352
+
353
+ function authContext(admin: NonNullable<IamAppContext['admin']>): AuthContext {
354
+ return {
355
+ ok: true,
356
+ principal: { id: admin.id, type: admin.type, label: admin.label ?? admin.id },
357
+ can: (action, scope) => permits(admin.permissions, action, scope),
358
+ scopedTo: (action, dimension) => scopedValues(admin.permissions, action, dimension),
359
+ audit: () => Promise.resolve(),
360
+ }
361
+ }
362
+
363
+ /** The context of a caller with an administration; anyone else is refused before the use case runs. */
364
+ function context(ctx: IamAppContext): AdminContext {
365
+ if (ctx.admin === null) throw new UnauthorizedError()
366
+ const administration = administrationOf(ctx.admin)
367
+ if (administration === null) throw new ForbiddenError('admin permission required')
368
+ return {
369
+ services: ctx.services,
370
+ request: ctx.request,
371
+ url: new URL(ctx.request.url),
372
+ admin: ctx.admin,
373
+ administration,
374
+ app: IAM_APP,
375
+ requestId: ctx.requestId,
376
+ ctx: ctx.exec,
377
+ }
378
+ }
379
+
380
+ function internalError(): Response {
381
+ return Response.json({ error: { type: 'internal', message: 'internal error' } }, { status: 500 })
382
+ }
383
+
384
+ /** No `redirect`: a sign-in that names no destination lands on the installation's landing, not IAM's bare origin. */
385
+ function createLoginUrl(issuer: string): string {
386
+ return new URL('/auth/login', issuer).toString()
387
+ }