@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,209 @@
1
+ // An application's own people, administered by the application's own administrator: a person
2
+ // holding the application's `members.manage` globally there grants and revokes the application's global roles through
3
+ // IAM's administration API, without being an installation admin. Every change writes its audit row under the
4
+ // application, in the change's own transaction. This is authorization, never an enforcement decision (ADR-0022).
5
+
6
+ import { MAX_APP_MEMBERS_PAGE, normalizeEmailIdentity, type PermissionEntry, permits } from '@fabrika/auth-core'
7
+ import type {
8
+ AdministeredAppDto,
9
+ AppPeopleDto,
10
+ AppPeopleInput,
11
+ GrantAppRoleRequest,
12
+ GrantAppRoleResponse,
13
+ RevokeAppRoleRequest,
14
+ RevokeAppRoleResponse,
15
+ } from '@fabrika/iam-contract'
16
+ import type { IamAppContext } from '../app'
17
+ import { contractGrantProblem } from '../contract-rules'
18
+ import {
19
+ type AppMembersRow,
20
+ type AuditEventInput,
21
+ auditLabelOf,
22
+ type DelegatedAuthority,
23
+ ExternalGrantError,
24
+ type PrincipalRow,
25
+ principalStatus,
26
+ type RoleRow,
27
+ } from '../db'
28
+ import { appMemberPage } from '../membership'
29
+ import { unixNow } from '../repositories/sql'
30
+ import { authorityDeadline, type HeldEntry, resolveAuthorityAt } from '../resolve'
31
+ import { BUILTIN_ROLES } from '../roles'
32
+ import type { Services } from '../services'
33
+ import { delegatedActions, parseStoredPermissions } from '../stored-permissions'
34
+ import { fail } from './context'
35
+ import { IAM_APP } from './router'
36
+
37
+ /** The person administering, as the console's token names it. */
38
+ interface PeopleAdministrator {
39
+ readonly services: Services
40
+ readonly principal: PrincipalRow
41
+ readonly requestId: string
42
+ }
43
+
44
+ /**
45
+ * An application the administrator holds `members.manage` of, globally, with its permissions there, and the authority
46
+ * a change writes under: the administrator's grant revision and the app's schema revision, read before the check.
47
+ */
48
+ interface AdministeredApp {
49
+ readonly app: string
50
+ readonly people: AppMembersRow
51
+ readonly permissions: PermissionEntry[]
52
+ readonly supports: readonly HeldEntry[]
53
+ readonly authority: DelegatedAuthority
54
+ }
55
+
56
+ /**
57
+ * The person behind the request. Only a person administers an application's people, and only through a signed-in
58
+ * session: a `px_` key is refused, presented directly or exchanged by the proxy for a console token, because a key's own
59
+ * grants narrow what it carries and these checks resolve the person's.
60
+ */
61
+ async function administrator(ctx: IamAppContext): Promise<PeopleAdministrator> {
62
+ const admin = ctx.admin
63
+ if (admin === null) return fail(401, 'missing_token')
64
+ if (admin.type !== 'user' || admin.audience === IAM_APP || !admin.session) {
65
+ return fail(403, 'an application administrator is a person signed in to the console')
66
+ }
67
+ const principal = await ctx.services.repositories.principals.getPrincipalById(admin.id)
68
+ if (principal === null || principalStatus(principal) === 'disabled') return fail(403, 'not_allowed')
69
+ return { services: ctx.services, principal, requestId: ctx.requestId }
70
+ }
71
+
72
+ /** The application, when it declares its people and the administrator holds its `members.manage` globally there. */
73
+ async function administeredApp(admin: PeopleAdministrator, app: string): Promise<AdministeredApp | null> {
74
+ const schemaRevision = await admin.services.repositories.appSchema.getSchemaRevision(app)
75
+ const people = await admin.services.repositories.appSchema.getAppMembers(app)
76
+ if (people === null) return null
77
+ const live = await resolveAuthorityAt(admin.services, admin.principal, app)
78
+ const permissions = live.permissions
79
+ const authority = { administratorId: admin.principal.id, app, grantRevision: admin.principal.grant_revision, schemaRevision }
80
+ return permits(permissions, people.manage) ? { app, people, permissions, supports: live.supports, authority } : null
81
+ }
82
+
83
+ /** A delegated change that wrote nothing because the authority its check read changed meanwhile. */
84
+ async function refuseIfStale(admin: PeopleAdministrator, administered: AdministeredApp): Promise<void> {
85
+ if (!(await admin.services.repositories.grants.delegatedAuthorityHolds(administered.authority))) {
86
+ fail(409, 'your authority over the application changed meanwhile; try again')
87
+ }
88
+ }
89
+
90
+ /** One answer for an unknown application and one the caller does not administer, so neither is told apart. */
91
+ async function requireAdministered(admin: PeopleAdministrator, app: string): Promise<AdministeredApp> {
92
+ return (await administeredApp(admin, app)) ?? fail(404, 'no application whose people you administer')
93
+ }
94
+
95
+ /**
96
+ * The application's global roles the administrator may give and take: declared by the application (never a custom
97
+ * policy or a built-in), not a membership role, and granting nothing the administrator lacks globally there.
98
+ */
99
+ async function grantableRoles(admin: PeopleAdministrator, administered: AdministeredApp): Promise<RoleRow[]> {
100
+ const roles = await admin.services.repositories.appSchema.listRolesByOrigin(administered.app, 'app')
101
+ return roles.filter((role) =>
102
+ role.member_scope === null && !Object.hasOwn(BUILTIN_ROLES, role.role_key)
103
+ && delegatedActions(role).every((action) => permits(administered.permissions, action))
104
+ )
105
+ }
106
+
107
+ async function grantableRole(admin: PeopleAdministrator, administered: AdministeredApp, roleKey: string): Promise<RoleRow> {
108
+ const role = (await grantableRoles(admin, administered)).find((candidate) => candidate.role_key === roleKey)
109
+ if (role === undefined) {
110
+ return fail(403, `'${roleKey}' is not a global role of the application whose every action you hold`)
111
+ }
112
+ return role
113
+ }
114
+
115
+ /** The record of a change the administrator made, filed under the application. A user's audit label is its id. */
116
+ function peopleEvent(admin: PeopleAdministrator, app: string, event: { action: string; resourceId: string; metadata: unknown }): AuditEventInput {
117
+ return {
118
+ requestId: admin.requestId,
119
+ principalId: admin.principal.id,
120
+ principalLabel: auditLabelOf(admin.principal),
121
+ app,
122
+ resourceType: 'grant',
123
+ ...event,
124
+ }
125
+ }
126
+
127
+ export async function listAdministeredApps(ctx: IamAppContext): Promise<{ items: AdministeredAppDto[] }> {
128
+ const admin = await administrator(ctx)
129
+ const items: AdministeredAppDto[] = []
130
+ for (const row of await admin.services.repositories.appSchema.listAppMembers()) {
131
+ const administered = await administeredApp(admin, row.app)
132
+ if (administered === null) continue
133
+ const presentation = await admin.services.repositories.appSchema.getPresentation(row.app)
134
+ items.push({
135
+ app: row.app,
136
+ displayName: presentation?.display_name ?? null,
137
+ roles: (await grantableRoles(admin, administered)).map((role) => ({
138
+ key: role.role_key,
139
+ name: role.name,
140
+ permissions: parseStoredPermissions(role.permissions),
141
+ })),
142
+ })
143
+ }
144
+ return { items }
145
+ }
146
+
147
+ export async function listAppPeople(ctx: IamAppContext, input: AppPeopleInput): Promise<AppPeopleDto> {
148
+ const admin = await administrator(ctx)
149
+ const administered = await requireAdministered(admin, input.app)
150
+ const page = await appMemberPage(admin.services, administered.app, administered.people, true, input.after ?? null, MAX_APP_MEMBERS_PAGE)
151
+ return { app: administered.app, ...page }
152
+ }
153
+
154
+ export async function grantAppRole(ctx: IamAppContext, input: GrantAppRoleRequest): Promise<GrantAppRoleResponse> {
155
+ const admin = await administrator(ctx)
156
+ const administered = await requireAdministered(admin, input.app)
157
+ const role = await grantableRole(admin, administered, input.role)
158
+ const { principals, grants, appSchema } = admin.services.repositories
159
+ const target = await principals.getUserByEmail(normalizeEmailIdentity(input.email))
160
+ if (target === null || target.type !== 'user') {
161
+ return fail(404, 'IAM knows no person by that address; an IAM administrator invites people')
162
+ }
163
+ const contract = await contractGrantProblem(appSchema, administered.app, { roleKey: role.role_key, permissions: null, scopeType: null })
164
+ if (contract !== null) return fail(400, contract)
165
+ try {
166
+ // S8: the grant ends no later than the administrator's own grants of `manage` and of every action the role carries.
167
+ const carried = [administered.people.manage, ...delegatedActions(role)].map(
168
+ (action): PermissionEntry => ({ action, scope: null, source: 'grant' }),
169
+ )
170
+ const expiresAt = authorityDeadline(administered, carried, unixNow())
171
+ const granted = await grants.createDelegatedRoleGrant(
172
+ { principalId: target.id, roleKey: role.role_key, grantedBy: admin.principal.id, expiresAt },
173
+ administered.authority,
174
+ (grantId) =>
175
+ peopleEvent(admin, administered.app, {
176
+ action: 'iam.grant.create',
177
+ resourceId: grantId,
178
+ metadata: { principalId: target.id, roleKey: role.role_key, scopeType: null, scopeValue: null, delegated: true },
179
+ }),
180
+ )
181
+ if (granted === null) await refuseIfStale(admin, administered)
182
+ return { principalId: target.id, role: role.role_key, granted: granted !== null }
183
+ } catch (cause) {
184
+ if (cause instanceof ExternalGrantError) return fail(409, cause.message)
185
+ throw cause
186
+ }
187
+ }
188
+
189
+ export async function revokeAppRole(ctx: IamAppContext, input: RevokeAppRoleRequest): Promise<RevokeAppRoleResponse> {
190
+ const admin = await administrator(ctx)
191
+ const administered = await requireAdministered(admin, input.app)
192
+ const role = await grantableRole(admin, administered, input.role)
193
+ const { grants } = admin.services.repositories
194
+ const held = (await grants.listGrants(input.principalId)).find((grant) =>
195
+ grant.app === administered.app && grant.role_key === role.role_key && grant.scope_type === null && grant.scope_value === null
196
+ )
197
+ if (held === undefined) return { revoked: false }
198
+ const revoked = await grants.deleteDelegatedGrant(
199
+ held,
200
+ administered.authority,
201
+ peopleEvent(admin, administered.app, {
202
+ action: 'iam.grant.revoke',
203
+ resourceId: held.id,
204
+ metadata: { principalId: input.principalId, roleKey: role.role_key, scopeType: null, scopeValue: null, delegated: true },
205
+ }),
206
+ )
207
+ if (!revoked) await refuseIfStale(admin, administered)
208
+ return { revoked }
209
+ }
@@ -0,0 +1,308 @@
1
+ import { appSchemaSchema } from '@fabrika/auth'
2
+ import { type AppDelegationDef, type AppLinkMountDef, LOCALES, type RoleDef } from '@fabrika/auth-core'
3
+
4
+ import {
5
+ type AppDto,
6
+ type AppInput,
7
+ type AppSchemaDto,
8
+ type ListRolesInput,
9
+ type ReturnOriginsDto,
10
+ type RoleDto,
11
+ type SetReturnOriginsRequest,
12
+ } from '@fabrika/iam-contract'
13
+ import type { z } from 'zod'
14
+ import { parsePresentation } from '../app-presentation'
15
+ import { normalizeOrigin } from '../handoff'
16
+ import { BUILTIN_ROLES } from '../roles'
17
+ import { parseStoredPermissions } from '../stored-permissions'
18
+ import { type AdminContext, adminEvent, fail } from './context'
19
+ import { dbRoleToDef, knownApps } from './grant-support'
20
+ import { error, json, readJson } from './http'
21
+
22
+ /** The app ids a grant can be scoped to — the apps that have registered a vocabulary — with their display names. */
23
+ export async function listAppsUseCase(c: AdminContext): Promise<{ items: AppDto[] }> {
24
+ const items = await Promise.all((await knownApps(c)).map(async (id): Promise<AppDto> => {
25
+ const { displayName } = parsePresentation(await c.services.repositories.appSchema.getPresentation(id))
26
+ return { id, displayName, installation: c.services.config.platformAudiences.has(id) }
27
+ }))
28
+ return { items }
29
+ }
30
+
31
+ /**
32
+ * The roles available to grant for an app: the built-ins (cross-app, e.g. `admin`)
33
+ * plus the app's DB roles (origin 'app' + 'custom'). Without an app, only built-ins are
34
+ * listed. Built-ins win on a key collision so an app cannot shadow the cross-app `admin`.
35
+ */
36
+ export async function listRolesUseCase(c: AdminContext, input: ListRolesInput): Promise<{ items: RoleDto[] }> {
37
+ const items: RoleDto[] = []
38
+ const appParam = input.app ?? null
39
+ const app = appParam !== null && (await knownApps(c)).includes(appParam) ? appParam : null
40
+ const builtinKeys = new Set(Object.keys(BUILTIN_ROLES))
41
+ if (app !== null) {
42
+ for (const row of await c.services.repositories.appSchema.listRoles(app)) {
43
+ if (builtinKeys.has(row.role_key)) {
44
+ continue // a built-in shadows any same-key DB row in the grantable list
45
+ }
46
+ items.push({
47
+ key: row.role_key,
48
+ ...dbRoleToDef(row),
49
+ origin: row.origin,
50
+ })
51
+ }
52
+ }
53
+ for (const [key, role] of Object.entries(BUILTIN_ROLES)) {
54
+ items.push({
55
+ key,
56
+ name: role.name,
57
+ ...(role.description ? { description: role.description } : {}),
58
+ permissions: role.permissions,
59
+ origin: 'builtin',
60
+ })
61
+ }
62
+ return { items }
63
+ }
64
+
65
+ /** The 400 message for a refused vocabulary, naming the envelope field or the role at fault. */
66
+ function appSchemaError(issues: readonly z.ZodIssue[]): string {
67
+ // A wrong envelope is the more useful report than the first bad element inside it.
68
+ const issue = issues.find((candidate) => candidate.path.length === 1) ?? issues[0]
69
+ const [field, key] = issue?.path ?? []
70
+ // A cross-reference refusal names its own problem; only a malformed shape gets the generic message.
71
+ if (issue?.code === 'custom' && issue.path.length > 2) return issue.message
72
+ if (field === 'roles') {
73
+ if (typeof key !== 'string') return 'roles must be an object (role_key -> def)'
74
+ return `role '${key}' needs a non-empty name and a permissions array, and a usable key`
75
+ }
76
+ if (field === 'links') {
77
+ return typeof key === 'string'
78
+ ? `link mount '${key}' needs a dimension, exact grants, an issuedBy action and maxDays from 1 to 365, and a usable key`
79
+ : 'links must be an object (mount -> def)'
80
+ }
81
+ if (field === 'delegations') {
82
+ return typeof key === 'string'
83
+ ? `endpoint '${key}' needs an action, a dimension and a purpose of 'members' or 'creates', and a usable key`
84
+ : 'delegations must be an object (endpoint -> def)'
85
+ }
86
+ if (field === 'workloads') {
87
+ return typeof key === 'number'
88
+ ? "each workload needs a kind of 'job', 'webhook', 'public' or 'app', a name and an array of exact actions"
89
+ : 'workloads must be an array'
90
+ }
91
+ if (field === 'members' || field === 'directory') {
92
+ return issue?.code === 'custom' ? issue.message : "members must be { manage, list } of exact actions, and directory 'labels'"
93
+ }
94
+ if (field === 'locale') return `locale must be one of ${LOCALES.map((locale) => `'${locale}'`).join(', ')}`
95
+ if (field === 'displayName') return issue?.code === 'custom' ? issue.message : 'displayName must be a string'
96
+ if (field === 'terminal') return issue?.code === 'custom' ? issue.message : "terminal must be { identify: '/path' }"
97
+ if (key === undefined) return 'scopes and actions must be arrays'
98
+ return field === 'scopes'
99
+ ? 'each scope needs a non-empty `type` and, when present, a non-empty `label`, `in`, `creator` and `members`'
100
+ : 'each action needs a non-empty `action` and, when present, a non-empty `description`'
101
+ }
102
+
103
+ /**
104
+ * Reconcile an app's declared vocabulary (idempotent): upsert its scopes/actions and
105
+ * origin='app' roles, delete app-origin rows absent from the body, and NEVER touch
106
+ * origin='custom' roles. Every role's patterns are validated against the body's own
107
+ * action catalog. The `:app` path segment is the app id this vocabulary belongs to.
108
+ */
109
+ export async function putAppSchema(c: AdminContext, app: string): Promise<Response> {
110
+ // No knownApps gate: an app's FIRST schema reconcile is how it REGISTERS itself (this endpoint is
111
+ // admin-gated). After this, `db.listKnownApps()` surfaces the app id across the schema tables.
112
+ const body = await readJson(c.request)
113
+ const parsed = appSchemaSchema.safeParse(body)
114
+ if (!parsed.success) {
115
+ return error(400, appSchemaError(parsed.error.issues))
116
+ }
117
+ const schema = parsed.data
118
+ // A role key an admin already owns as a custom policy is a CONFLICT, not something to overwrite.
119
+ // The rule was one-directional: `createPolicyUseCase` 409s on an existing key so an admin can never
120
+ // clobber an app role, but a deploy silently flipped a custom policy to origin='app' — after which
121
+ // update and delete both 404 and the policy is unmanageable (SEC-3). Refused here, loudly, so the
122
+ // deploy fails with the collision named rather than quietly rewriting somebody's policy.
123
+ const collisions: string[] = []
124
+ for (const row of await c.services.repositories.appSchema.listRoles(app)) {
125
+ if (row.origin === 'custom' && Object.hasOwn(schema.roles, row.role_key)) {
126
+ collisions.push(row.role_key)
127
+ }
128
+ }
129
+ if (collisions.length > 0) {
130
+ return error(
131
+ 409,
132
+ `the app declares role ${collisions.map((key) => `'${key}'`).join(', ')}, which already exists as an admin-composed custom policy. `
133
+ + 'Rename the declared role or delete the policy; a deploy never overwrites one.',
134
+ )
135
+ }
136
+ // A role newly declared a membership role would turn its existing global grants into global
137
+ // membership grants. Resolution ignores such a grant anyway; refusing names the grants to fix.
138
+ const outside: string[] = []
139
+ for (const [roleKey, def] of Object.entries(schema.roles)) {
140
+ if (def.member === undefined) continue
141
+ for (const grant of await c.services.repositories.grants.listRoleGrantsOutsideScope(app, roleKey, def.member.scope)) {
142
+ outside.push(`${grant.id} (role '${roleKey}')`)
143
+ }
144
+ }
145
+ if (outside.length > 0) {
146
+ return error(
147
+ 409,
148
+ `the app declares a membership role whose existing grants are not in a value of its scope: ${outside.join(', ')}. `
149
+ + 'Delete or re-scope those grants first.',
150
+ )
151
+ }
152
+ // An external principal holds only roles declared external (ADR-0051): a schema that narrows a role one holds, or
153
+ // declares an internal role under a key one still holds, is refused with the grants named.
154
+ const externalHeld: string[] = []
155
+ for (const [roleKey, def] of Object.entries(schema.roles)) {
156
+ if (def.external === true) continue
157
+ for (const grant of await c.services.repositories.grants.listExternalHoldersOfRole(app, roleKey)) {
158
+ externalHeld.push(`${grant.id} (role '${roleKey}')`)
159
+ }
160
+ }
161
+ if (externalHeld.length > 0) {
162
+ return error(
163
+ 409,
164
+ `the app declares a role that is not external while external principals hold it: ${externalHeld.join(', ')}. `
165
+ + 'Delete those grants first, or keep the role external.',
166
+ )
167
+ }
168
+ await c.services.repositories.appSchema.reconcileAppSchema(
169
+ {
170
+ app,
171
+ scopes: schema.scopes.map((s) => ({
172
+ scopeType: s.type,
173
+ label: s.label ?? null,
174
+ parentScope: s.in ?? null,
175
+ creatorRole: s.creator ?? null,
176
+ members: s.members ?? null,
177
+ directory: s.directory ?? null,
178
+ lookups: s.lookups ?? null,
179
+ })),
180
+ actions: schema.actions.map((a) => ({ action: a.action, description: a.description ?? null })),
181
+ roles: Object.entries(schema.roles).map(([roleKey, def]) => ({
182
+ roleKey,
183
+ name: def.name,
184
+ description: def.description ?? null,
185
+ permissions: def.permissions,
186
+ memberScope: def.member?.scope ?? null,
187
+ assignableBy: def.member?.assignableBy ?? null,
188
+ external: def.external === true,
189
+ via: def.via ?? null,
190
+ })),
191
+ contract: schema.contract === true,
192
+ links: Object.entries(schema.links ?? {}).map(([mount, link]) => ({ mount, ...link })),
193
+ delegations: Object.entries(schema.delegations ?? {}).map(([endpoint, delegation]) => ({ endpoint, ...delegation })),
194
+ workloads: schema.workloads ?? [],
195
+ presentation: { locale: schema.locale ?? null, displayName: schema.displayName ?? null },
196
+ mail: Object.entries(schema.mail ?? {}).flatMap(([kind, byLocale]) =>
197
+ Object.entries(byLocale ?? {}).flatMap(([locale, template]) => (template === undefined ? [] : [{ kind, locale, ...template }]))
198
+ ),
199
+ members: schema.members === undefined ? null : { ...schema.members, directory: schema.directory ?? null },
200
+ terminal: schema.terminal ?? null,
201
+ },
202
+ adminEvent(c, {
203
+ action: 'iam.app.schema.reconcile',
204
+ resourceType: 'app',
205
+ resourceId: app,
206
+ metadata: {
207
+ scopes: schema.scopes.length,
208
+ actions: schema.actions.length,
209
+ roles: Object.keys(schema.roles),
210
+ contract: schema.contract === true,
211
+ links: Object.keys(schema.links ?? {}),
212
+ delegations: Object.keys(schema.delegations ?? {}),
213
+ workloads: (schema.workloads ?? []).map((workload) => `${workload.kind}:${workload.name}`),
214
+ locale: schema.locale ?? null,
215
+ displayName: schema.displayName ?? null,
216
+ mail: Object.entries(schema.mail ?? {}).flatMap(([kind, byLocale]) => Object.keys(byLocale ?? {}).map((locale) => `${kind}.${locale}`)),
217
+ members: schema.members ?? null,
218
+ terminal: schema.terminal ?? null,
219
+ },
220
+ }),
221
+ )
222
+ return json(await readAppSchemaDto(c, app))
223
+ }
224
+
225
+ /** Read the app's scopes, actions, and origin='app' roles into a DTO (no auth gate). */
226
+ async function readAppSchemaDto(c: AdminContext, app: string): Promise<AppSchemaDto> {
227
+ const scopeRows = await c.services.repositories.appSchema.listAppScopes(app)
228
+ const actionRows = await c.services.repositories.appSchema.listAppActions(app)
229
+ const roleRows = await c.services.repositories.appSchema.listRolesByOrigin(app, 'app')
230
+ const roles: Record<string, RoleDef> = {}
231
+ for (const row of roleRows) {
232
+ roles[row.role_key] = dbRoleToDef(row)
233
+ }
234
+ const links: Record<string, AppLinkMountDef> = {}
235
+ for (const row of await c.services.repositories.appSchema.listLinkMounts(app)) {
236
+ links[row.mount] = { dimension: row.dimension, grants: parseStoredPermissions(row.grants), issuedBy: row.issued_by, maxDays: row.max_days }
237
+ }
238
+ const delegations: Record<string, AppDelegationDef> = {}
239
+ for (const row of await c.services.repositories.appSchema.listDelegatedEndpoints(app)) {
240
+ delegations[row.endpoint] = { action: row.action, dimension: row.dimension, purpose: row.purpose }
241
+ }
242
+ const presentation = parsePresentation(await c.services.repositories.appSchema.getPresentation(app))
243
+ const members = await c.services.repositories.appSchema.getAppMembers(app)
244
+ const identify = await c.services.repositories.appSchema.getTerminalIdentifyPath(app)
245
+ return {
246
+ app,
247
+ scopes: scopeRows.map((r) => ({
248
+ type: r.scope_type,
249
+ ...(r.label !== null ? { label: r.label } : {}),
250
+ ...(r.parent_scope !== null ? { in: r.parent_scope } : {}),
251
+ ...(r.creator_role !== null ? { creator: r.creator_role } : {}),
252
+ ...(r.members_manage !== null && r.members_list !== null ? { members: { manage: r.members_manage, list: r.members_list } } : {}),
253
+ ...(r.members_directory === 'labels' ? { directory: 'labels' } : {}),
254
+ ...(r.members_lookup === null ? {} : { lookups: parseStoredPermissions(r.members_lookup) }),
255
+ })),
256
+ actions: actionRows.map((r) => ({ action: r.action, ...(r.description !== null ? { description: r.description } : {}) })),
257
+ roles,
258
+ ...(Object.keys(links).length > 0 ? { links } : {}),
259
+ ...(Object.keys(delegations).length > 0 ? { delegations } : {}),
260
+ ...(presentation.locale === null ? {} : { locale: presentation.locale }),
261
+ ...(presentation.displayName === null ? {} : { displayName: presentation.displayName }),
262
+ ...(members === null ? {} : { members: { manage: members.manage, list: members.list } }),
263
+ ...(members?.directory === 'labels' ? { directory: 'labels' } : {}),
264
+ ...(identify === null ? {} : { terminal: { identify } }),
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Replace an app's registered return origins (ADR-0022). Every value is canonicalized before it is
270
+ * stored, so the comparison at issue time is against one spelling and an operator cannot register
271
+ * `https://App.Example.com/` and then wonder why `https://app.example.com` is refused.
272
+ *
273
+ * The app is validated FIRST, so a typo in the app id is reported as a typo in the app id rather than
274
+ * as an origin problem. An EMPTY set is refused as a caller error: it is indistinguishable from an
275
+ * app that never registered, and reaching that state through this endpoint is always a mistake.
276
+ */
277
+ export async function setReturnOriginsUseCase(c: AdminContext, input: SetReturnOriginsRequest): Promise<ReturnOriginsDto> {
278
+ if (!(await knownApps(c)).includes(input.app)) {
279
+ return fail(404, 'unknown app')
280
+ }
281
+ if (input.origins.length === 0) {
282
+ return fail(400, 'at least one origin is required')
283
+ }
284
+ const origins: string[] = []
285
+ for (const raw of input.origins) {
286
+ const normalized = normalizeOrigin(raw)
287
+ if (normalized === null) {
288
+ return fail(400, `not an absolute http(s) origin: ${raw}`)
289
+ }
290
+ if (!origins.includes(normalized)) {
291
+ origins.push(normalized)
292
+ }
293
+ }
294
+ await c.services.repositories.handoff.setReturnOrigins(
295
+ input.app,
296
+ origins,
297
+ adminEvent(c, { action: 'iam.app.return-origins.set', resourceType: 'app', resourceId: input.app, metadata: { origins } }),
298
+ )
299
+ return { app: input.app, origins }
300
+ }
301
+
302
+ export async function getAppSchemaUseCase(c: AdminContext, input: AppInput): Promise<AppSchemaDto> {
303
+ const app = input.app
304
+ if (!(await knownApps(c)).includes(app)) {
305
+ return fail(404, 'unknown app')
306
+ }
307
+ return readAppSchemaDto(c, app)
308
+ }
@@ -0,0 +1,81 @@
1
+ import { type AuditEventDto, type AuthLogDto, type ListAuditInput, type ListAuthLogInput } from '@fabrika/iam-contract'
2
+ import { type AuditEventRow, type AuthLogRow } from '../db'
3
+
4
+ import { parseJsonOrNull } from '../json'
5
+ import { ADMIN_ACCESS_ACTION } from './access'
6
+
7
+ import { type AdminContext } from './context'
8
+
9
+ import { normalizeLimit } from './pagination'
10
+
11
+ function toAuditEventDto(row: AuditEventRow): AuditEventDto {
12
+ return {
13
+ id: row.id,
14
+ requestId: row.request_id,
15
+ principalId: row.principal_id,
16
+ principalLabel: row.principal_label,
17
+ credentialId: row.credential_id,
18
+ app: row.app,
19
+ action: row.action,
20
+ resourceType: row.resource_type,
21
+ resourceId: row.resource_id,
22
+ // Unparseable JSON reads as null rather than throwing — the DB no longer guarantees
23
+ // validity (the `json_valid` CHECK was SQLite-only; see `parseJsonOrNull`).
24
+ diff: row.diff === null ? null : parseJsonOrNull(row.diff),
25
+ metadata: row.metadata === null ? null : parseJsonOrNull(row.metadata),
26
+ createdAt: row.created_at,
27
+ }
28
+ }
29
+
30
+ function toAuthLogDto(row: AuthLogRow): AuthLogDto {
31
+ return {
32
+ // The one backend-dependent column: a `number` on D1, a `string` on Postgres (a BIGINT identity,
33
+ // which Bun decodes by column OID). Normalised HERE, once, so the DTO stays a plain number for
34
+ // the SPA and for the `before=` cursor. Precision holds to 2^53 rows, far past any real auth log.
35
+ id: typeof row.id === 'string' ? Number(row.id) : row.id,
36
+ requestId: row.request_id,
37
+ app: row.app,
38
+ kind: row.kind,
39
+ principalId: row.principal_id,
40
+ credentialId: row.credential_id,
41
+ decision: row.decision,
42
+ reason: row.reason,
43
+ privileged: row.privileged === 1,
44
+ createdAt: row.created_at,
45
+ }
46
+ }
47
+
48
+ export async function listAuditUseCase(c: AdminContext, input: ListAuditInput): Promise<{ items: AuditEventDto[]; nextCursor: string | null }> {
49
+ const limit = normalizeLimit(input.limit)
50
+ const rows = await c.services.repositories.audit.listAuditEvents({
51
+ ...(input.resourceType ? { resourceType: input.resourceType } : {}),
52
+ ...(input.resourceId ? { resourceId: input.resourceId } : {}),
53
+ ...(input.principalId ? { principalId: input.principalId } : {}),
54
+ ...(input.subjectPrincipalId ? { subjectPrincipalId: input.subjectPrincipalId } : {}),
55
+ ...(input.action ? { action: input.action } : {}),
56
+ ...(input.changesOnly === true ? { excludeActions: [ADMIN_ACCESS_ACTION] } : {}),
57
+ ...(input.requestId ? { requestId: input.requestId } : {}),
58
+ ...(input.before ? { before: input.before } : {}),
59
+ limit,
60
+ })
61
+ const items = rows.map(toAuditEventDto)
62
+ const last = items.at(-1)
63
+ const nextCursor = items.length === limit && last ? last.id : null
64
+ return { items, nextCursor }
65
+ }
66
+
67
+ export async function listAuthLogUseCase(c: AdminContext, input: ListAuthLogInput): Promise<{ items: AuthLogDto[]; nextCursor: string | null }> {
68
+ const limit = normalizeLimit(input.limit)
69
+ const before = input.before ? Number.parseInt(input.before, 10) : undefined
70
+ const rows = await c.services.repositories.audit.listAuthLog({
71
+ ...(input.principalId ? { principalId: input.principalId } : {}),
72
+ ...(input.requestId ? { requestId: input.requestId } : {}),
73
+ ...(input.decision ? { decision: input.decision } : {}),
74
+ ...(before !== undefined && Number.isFinite(before) ? { before } : {}),
75
+ limit,
76
+ })
77
+ const items = rows.map(toAuthLogDto)
78
+ const last = items.at(-1)
79
+ const nextCursor = items.length === limit && last ? String(last.id) : null
80
+ return { items, nextCursor }
81
+ }
@@ -0,0 +1,54 @@
1
+ // The installation's client logo (ADR-0066): an installation administrator's to read and to change. Control reads it
2
+ // with the provisioning key, which resolves to a synthetic installation administrator, and carries it to the proxy.
3
+
4
+ import type { InstallationBrandDto, SetInstallationBrandRequest } from '@fabrika/iam-contract'
5
+ import { installationBrandSchema } from '@fabrika/proxy-core/brand'
6
+ import { type AuditEventInput, type InstallationBrandRow } from '../db'
7
+ import { brandImages, storedBrand } from '../installation-brand'
8
+ import { type AdminContext, adminEvent, fail } from './context'
9
+
10
+ export async function getInstallationBrandUseCase(c: AdminContext): Promise<InstallationBrandDto> {
11
+ requireInstallationAdmin(c)
12
+ return brandDto(await c.services.repositories.brand.get())
13
+ }
14
+
15
+ /**
16
+ * Store the brand, checked here again whatever the console checked: every reader trusts what IAM stored no more than
17
+ * this, and checks it again too. The record names the types of the images it stored, never their bytes.
18
+ */
19
+ export async function setInstallationBrandUseCase(c: AdminContext, input: SetInstallationBrandRequest): Promise<InstallationBrandDto> {
20
+ requireInstallationAdmin(c)
21
+ const parsed = installationBrandSchema.safeParse(input.brand)
22
+ if (!parsed.success) {
23
+ return fail(400, `not an installation brand: ${parsed.error.issues.map((issue) => issue.message).join('; ')}`)
24
+ }
25
+ const brand = parsed.data
26
+ const row = await c.services.repositories.brand.set(
27
+ brandImages(brand),
28
+ brandEvent(c, { light: brand.light.type, dark: brand.dark?.type ?? null }),
29
+ )
30
+ return brandDto(row)
31
+ }
32
+
33
+ /** Clear the brand, so every page draws the fabrika mark again. Clearing an absent brand changes and records nothing. */
34
+ export async function clearInstallationBrandUseCase(c: AdminContext): Promise<InstallationBrandDto> {
35
+ requireInstallationAdmin(c)
36
+ const cleared = await c.services.repositories.brand.clear(brandEvent(c, { light: null, dark: null }))
37
+ return brandDto(cleared ?? await c.services.repositories.brand.get())
38
+ }
39
+
40
+ function brandEvent(c: AdminContext, images: { light: string | null; dark: string | null }): AuditEventInput {
41
+ return adminEvent(c, { action: 'iam.brand.update', resourceType: 'installation_brand', metadata: images })
42
+ }
43
+
44
+ /** The brand as the pages draw it: a stored row the check now refuses answers null, like no brand. */
45
+ function brandDto(row: InstallationBrandRow | null): InstallationBrandDto {
46
+ return { brand: storedBrand(row), updatedAt: row?.updated_at ?? null }
47
+ }
48
+
49
+ /** `.require(iam.admin)` gates these procedures already; a direct caller of a use case meets the same rule. */
50
+ function requireInstallationAdmin(c: AdminContext): void {
51
+ if (c.administration.kind !== 'installation') {
52
+ return fail(403, "the installation's brand is changed and read only by an installation administrator")
53
+ }
54
+ }