@fabrika/iam 0.0.1 → 0.9.0-dev.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (312) hide show
  1. package/fabrika.config.ts +267 -0
  2. package/migrations/0001_init.sql +316 -0
  3. package/migrations/0002_oauth.sql +38 -0
  4. package/migrations/0003_contract_apps.sql +11 -0
  5. package/migrations/0004_membership.sql +93 -0
  6. package/migrations/0005_workloads.sql +23 -0
  7. package/migrations/0006_membership_transport_keys.sql +16 -0
  8. package/migrations/0007_member_directory.sql +7 -0
  9. package/migrations/0008_durable_audit.sql +28 -0
  10. package/migrations/0009_member_lookups.sql +7 -0
  11. package/migrations/0010_workload_issues.sql +6 -0
  12. package/migrations/0011_app_presentation.sql +15 -0
  13. package/migrations/0012_external_principals.sql +10 -0
  14. package/migrations/0013_app_mail_templates.sql +14 -0
  15. package/migrations/0014_invitation_wording.sql +8 -0
  16. package/migrations/0015_app_schema_revisions.sql +15 -0
  17. package/migrations/0016_principal_grant_revision.sql +9 -0
  18. package/migrations/0017_app_sign_ins.sql +12 -0
  19. package/migrations/0018_app_members.sql +13 -0
  20. package/migrations/0019_app_mail_html.sql +7 -0
  21. package/migrations/0020_public_workloads.sql +34 -0
  22. package/migrations/0021_installation_brand.sql +19 -0
  23. package/migrations/0022_password_policy.sql +12 -0
  24. package/migrations/0023_terminals.sql +155 -0
  25. package/migrations/0024_app_terminals.sql +10 -0
  26. package/migrations/0025_terminal_completion.sql +10 -0
  27. package/migrations/0026_terminal_generation.sql +12 -0
  28. package/migrations/0027_application_exact_actions.sql +28 -0
  29. package/migrations/0028_oauth_client_assertions.sql +10 -0
  30. package/migrations/0029_role_via.sql +6 -0
  31. package/migrations/0030_membership_role_via.sql +12 -0
  32. package/migrations/0031_person_locale.sql +11 -0
  33. package/migrations-postgres/0001_init.sql +331 -0
  34. package/migrations-postgres/0002_oauth.sql +36 -0
  35. package/migrations-postgres/0003_contract_apps.sql +8 -0
  36. package/migrations-postgres/0004_membership.sql +92 -0
  37. package/migrations-postgres/0005_workloads.sql +18 -0
  38. package/migrations-postgres/0006_membership_transport_keys.sql +12 -0
  39. package/migrations-postgres/0007_member_directory.sql +7 -0
  40. package/migrations-postgres/0008_durable_audit.sql +8 -0
  41. package/migrations-postgres/0009_member_lookups.sql +7 -0
  42. package/migrations-postgres/0010_workload_issues.sql +6 -0
  43. package/migrations-postgres/0011_app_presentation.sql +15 -0
  44. package/migrations-postgres/0012_external_principals.sql +10 -0
  45. package/migrations-postgres/0013_app_mail_templates.sql +14 -0
  46. package/migrations-postgres/0014_invitation_wording.sql +8 -0
  47. package/migrations-postgres/0015_app_schema_revisions.sql +15 -0
  48. package/migrations-postgres/0016_principal_grant_revision.sql +9 -0
  49. package/migrations-postgres/0017_app_sign_ins.sql +12 -0
  50. package/migrations-postgres/0018_app_members.sql +13 -0
  51. package/migrations-postgres/0019_app_mail_html.sql +7 -0
  52. package/migrations-postgres/0020_public_workloads.sql +9 -0
  53. package/migrations-postgres/0021_installation_brand.sql +19 -0
  54. package/migrations-postgres/0022_password_policy.sql +12 -0
  55. package/migrations-postgres/0023_terminals.sql +70 -0
  56. package/migrations-postgres/0024_app_terminals.sql +10 -0
  57. package/migrations-postgres/0025_terminal_completion.sql +10 -0
  58. package/migrations-postgres/0026_terminal_generation.sql +12 -0
  59. package/migrations-postgres/0027_application_exact_actions.sql +28 -0
  60. package/migrations-postgres/0028_oauth_client_assertions.sql +9 -0
  61. package/migrations-postgres/0029_role_via.sql +4 -0
  62. package/migrations-postgres/0030_membership_role_via.sql +7 -0
  63. package/migrations-postgres/0031_person_locale.sql +11 -0
  64. package/package.json +69 -8
  65. package/src/admin/access.ts +47 -0
  66. package/src/admin/api-keys.ts +280 -0
  67. package/src/admin/app-people.ts +209 -0
  68. package/src/admin/app-schema.ts +308 -0
  69. package/src/admin/audit.ts +81 -0
  70. package/src/admin/brand.ts +54 -0
  71. package/src/admin/connections.ts +48 -0
  72. package/src/admin/context.ts +70 -0
  73. package/src/admin/grant-support.ts +192 -0
  74. package/src/admin/grants.ts +189 -0
  75. package/src/admin/handlers.ts +102 -0
  76. package/src/admin/http.ts +24 -0
  77. package/src/admin/membership-keys.ts +38 -0
  78. package/src/admin/pagination.ts +28 -0
  79. package/src/admin/password-policy.ts +48 -0
  80. package/src/admin/passwords.ts +78 -0
  81. package/src/admin/policies.ts +136 -0
  82. package/src/admin/principals.ts +226 -0
  83. package/src/admin/router.ts +291 -0
  84. package/src/admin/rpc.ts +387 -0
  85. package/src/admin/sessions.ts +115 -0
  86. package/src/admin/share-links.ts +127 -0
  87. package/src/admin/terminals.ts +115 -0
  88. package/src/admin/user-admin.ts +76 -0
  89. package/src/admin/workloads.ts +85 -0
  90. package/src/app-presentation.ts +178 -0
  91. package/src/app.ts +158 -0
  92. package/src/auth/cookies.ts +64 -0
  93. package/src/auth/failure.ts +25 -0
  94. package/src/auth/handoff.ts +136 -0
  95. package/src/auth/http.ts +88 -0
  96. package/src/auth/invitations.ts +220 -0
  97. package/src/auth/known-device.ts +44 -0
  98. package/src/auth/login.ts +162 -0
  99. package/src/auth/oidc-flight.ts +91 -0
  100. package/src/auth/oidc.ts +148 -0
  101. package/src/auth/password.ts +416 -0
  102. package/src/auth/routes.ts +108 -0
  103. package/src/auth/sessions.ts +249 -0
  104. package/src/auth/terminals.ts +284 -0
  105. package/src/auth.ts +193 -0
  106. package/src/binding-identity.ts +25 -0
  107. package/src/bounded-body.ts +35 -0
  108. package/src/catalog/cs.ts +147 -0
  109. package/src/catalog/en.ts +148 -0
  110. package/src/catalog/index.ts +122 -0
  111. package/src/catalog/uk.ts +164 -0
  112. package/src/client-address.ts +39 -0
  113. package/src/common-passwords.ts +37 -0
  114. package/src/contract-rules.ts +80 -0
  115. package/src/cron.ts +54 -0
  116. package/src/db.ts +128 -0
  117. package/src/delegation.ts +100 -0
  118. package/src/device-http.ts +39 -0
  119. package/src/device.ts +269 -0
  120. package/src/email-identity.ts +2 -0
  121. package/src/env.ts +132 -0
  122. package/src/handoff.ts +175 -0
  123. package/src/html.ts +4 -0
  124. package/src/human-admission.ts +40 -0
  125. package/src/identification.ts +185 -0
  126. package/src/index.ts +292 -0
  127. package/src/installation-brand.ts +82 -0
  128. package/src/issue.ts +265 -0
  129. package/src/json.ts +30 -0
  130. package/src/log.ts +26 -0
  131. package/src/membership-http.ts +135 -0
  132. package/src/membership.ts +1210 -0
  133. package/src/messages.ts +44 -0
  134. package/src/narrow-permissions.ts +26 -0
  135. package/src/node/browser-identity.ts +69 -0
  136. package/src/node/migrate.ts +52 -0
  137. package/src/node/prune.ts +34 -0
  138. package/src/node/runtime.ts +221 -0
  139. package/src/node/server.ts +104 -0
  140. package/src/oauth-client-auth.ts +93 -0
  141. package/src/oauth-client.ts +145 -0
  142. package/src/oauth-config.ts +72 -0
  143. package/src/oauth-http.ts +262 -0
  144. package/src/oauth.ts +272 -0
  145. package/src/oidc.ts +260 -0
  146. package/src/origin.ts +29 -0
  147. package/src/password-crypto.ts +148 -0
  148. package/src/password-db.ts +419 -0
  149. package/src/password-minimum.ts +44 -0
  150. package/src/password-pages.ts +397 -0
  151. package/src/password-policy.ts +79 -0
  152. package/src/password-service.ts +67 -0
  153. package/src/person-locale.ts +103 -0
  154. package/src/proxy-proof.ts +36 -0
  155. package/src/relay-mail.ts +64 -0
  156. package/src/repositories/app-schema.ts +550 -0
  157. package/src/repositories/audit.ts +405 -0
  158. package/src/repositories/brand.ts +66 -0
  159. package/src/repositories/credentials.ts +331 -0
  160. package/src/repositories/device.ts +137 -0
  161. package/src/repositories/grants.ts +404 -0
  162. package/src/repositories/handoff.ts +103 -0
  163. package/src/repositories/membership-transport.ts +49 -0
  164. package/src/repositories/membership.ts +875 -0
  165. package/src/repositories/oauth.ts +122 -0
  166. package/src/repositories/password-policy.ts +44 -0
  167. package/src/repositories/principals.ts +358 -0
  168. package/src/repositories/sessions.ts +339 -0
  169. package/src/repositories/sql.ts +23 -0
  170. package/src/repositories/terminals.ts +346 -0
  171. package/src/repositories/workloads.ts +134 -0
  172. package/src/request-id.ts +46 -0
  173. package/src/resolve.ts +396 -0
  174. package/src/retention.ts +34 -0
  175. package/src/roles.ts +54 -0
  176. package/src/rpc-http.ts +333 -0
  177. package/src/rpc-inputs.ts +110 -0
  178. package/src/rpc.ts +440 -0
  179. package/src/secret.ts +45 -0
  180. package/src/service.ts +59 -0
  181. package/src/services.ts +199 -0
  182. package/src/signing.ts +260 -0
  183. package/src/stored-chain.ts +23 -0
  184. package/src/stored-permissions.ts +34 -0
  185. package/src/terminals.ts +15 -0
  186. package/src/tokens.ts +506 -0
  187. package/src/workload-token.ts +130 -0
  188. package/types/fabrika.config.d.ts +11 -0
  189. package/types/src/admin/access.d.ts +19 -0
  190. package/types/src/admin/api-keys.d.ts +26 -0
  191. package/types/src/admin/app-people.d.ts +8 -0
  192. package/types/src/admin/app-schema.d.ts +32 -0
  193. package/types/src/admin/audit.d.ts +10 -0
  194. package/types/src/admin/brand.d.ts +10 -0
  195. package/types/src/admin/connections.d.ts +5 -0
  196. package/types/src/admin/context.d.ts +46 -0
  197. package/types/src/admin/grant-support.d.ts +59 -0
  198. package/types/src/admin/grants.d.ts +8 -0
  199. package/types/src/admin/handlers.d.ts +82 -0
  200. package/types/src/admin/http.d.ts +9 -0
  201. package/types/src/admin/membership-keys.d.ts +8 -0
  202. package/types/src/admin/pagination.d.ts +5 -0
  203. package/types/src/admin/password-policy.d.ts +9 -0
  204. package/types/src/admin/passwords.d.ts +5 -0
  205. package/types/src/admin/policies.d.ts +15 -0
  206. package/types/src/admin/principals.d.ts +15 -0
  207. package/types/src/admin/router.d.ts +75 -0
  208. package/types/src/admin/rpc.d.ts +6 -0
  209. package/types/src/admin/sessions.d.ts +14 -0
  210. package/types/src/admin/share-links.d.ts +21 -0
  211. package/types/src/admin/terminals.d.ts +13 -0
  212. package/types/src/admin/user-admin.d.ts +30 -0
  213. package/types/src/admin/workloads.d.ts +5 -0
  214. package/types/src/app-presentation.d.ts +86 -0
  215. package/types/src/app.d.ts +62 -0
  216. package/types/src/auth/cookies.d.ts +29 -0
  217. package/types/src/auth/failure.d.ts +47 -0
  218. package/types/src/auth/handoff.d.ts +66 -0
  219. package/types/src/auth/http.d.ts +29 -0
  220. package/types/src/auth/invitations.d.ts +18 -0
  221. package/types/src/auth/known-device.d.ts +12 -0
  222. package/types/src/auth/login.d.ts +10 -0
  223. package/types/src/auth/oidc-flight.d.ts +39 -0
  224. package/types/src/auth/oidc.d.ts +7 -0
  225. package/types/src/auth/password.d.ts +7 -0
  226. package/types/src/auth/routes.d.ts +15 -0
  227. package/types/src/auth/sessions.d.ts +60 -0
  228. package/types/src/auth/terminals.d.ts +47 -0
  229. package/types/src/auth.d.ts +70 -0
  230. package/types/src/binding-identity.d.ts +12 -0
  231. package/types/src/bounded-body.d.ts +12 -0
  232. package/types/src/catalog/cs.d.ts +2 -0
  233. package/types/src/catalog/en.d.ts +2 -0
  234. package/types/src/catalog/index.d.ts +112 -0
  235. package/types/src/catalog/uk.d.ts +2 -0
  236. package/types/src/client-address.d.ts +31 -0
  237. package/types/src/common-passwords.d.ts +2 -0
  238. package/types/src/contract-rules.d.ts +25 -0
  239. package/types/src/cron.d.ts +15 -0
  240. package/types/src/db.d.ts +58 -0
  241. package/types/src/delegation.d.ts +38 -0
  242. package/types/src/device-http.d.ts +2 -0
  243. package/types/src/device.d.ts +11 -0
  244. package/types/src/email-identity.d.ts +1 -0
  245. package/types/src/env.d.ts +127 -0
  246. package/types/src/handoff.d.ts +57 -0
  247. package/types/src/html.d.ts +2 -0
  248. package/types/src/human-admission.d.ts +22 -0
  249. package/types/src/identification.d.ts +30 -0
  250. package/types/src/index.d.ts +62 -0
  251. package/types/src/installation-brand.d.ts +22 -0
  252. package/types/src/issue.d.ts +62 -0
  253. package/types/src/json.d.ts +15 -0
  254. package/types/src/log.d.ts +15 -0
  255. package/types/src/membership-http.d.ts +8 -0
  256. package/types/src/membership.d.ts +156 -0
  257. package/types/src/messages.d.ts +20 -0
  258. package/types/src/narrow-permissions.d.ts +7 -0
  259. package/types/src/node/browser-identity.d.ts +1 -0
  260. package/types/src/node/migrate.d.ts +4 -0
  261. package/types/src/node/prune.d.ts +1 -0
  262. package/types/src/node/runtime.d.ts +51 -0
  263. package/types/src/node/server.d.ts +5 -0
  264. package/types/src/oauth-client-auth.d.ts +26 -0
  265. package/types/src/oauth-client.d.ts +17 -0
  266. package/types/src/oauth-config.d.ts +16 -0
  267. package/types/src/oauth-http.d.ts +7 -0
  268. package/types/src/oauth.d.ts +51 -0
  269. package/types/src/oidc.d.ts +81 -0
  270. package/types/src/origin.d.ts +9 -0
  271. package/types/src/password-crypto.d.ts +37 -0
  272. package/types/src/password-db.d.ts +134 -0
  273. package/types/src/password-minimum.d.ts +23 -0
  274. package/types/src/password-pages.d.ts +143 -0
  275. package/types/src/password-policy.d.ts +19 -0
  276. package/types/src/password-service.d.ts +24 -0
  277. package/types/src/person-locale.d.ts +50 -0
  278. package/types/src/proxy-proof.d.ts +21 -0
  279. package/types/src/relay-mail.d.ts +25 -0
  280. package/types/src/repositories/app-schema.d.ts +244 -0
  281. package/types/src/repositories/audit.d.ts +187 -0
  282. package/types/src/repositories/brand.d.ts +41 -0
  283. package/types/src/repositories/credentials.d.ts +148 -0
  284. package/types/src/repositories/device.d.ts +50 -0
  285. package/types/src/repositories/grants.d.ts +177 -0
  286. package/types/src/repositories/handoff.d.ts +52 -0
  287. package/types/src/repositories/membership-transport.d.ts +31 -0
  288. package/types/src/repositories/membership.d.ts +273 -0
  289. package/types/src/repositories/oauth.d.ts +55 -0
  290. package/types/src/repositories/password-policy.d.ts +25 -0
  291. package/types/src/repositories/principals.d.ts +159 -0
  292. package/types/src/repositories/sessions.d.ts +150 -0
  293. package/types/src/repositories/sql.d.ts +13 -0
  294. package/types/src/repositories/terminals.d.ts +144 -0
  295. package/types/src/repositories/workloads.d.ts +61 -0
  296. package/types/src/request-id.d.ts +25 -0
  297. package/types/src/resolve.d.ts +118 -0
  298. package/types/src/retention.d.ts +18 -0
  299. package/types/src/roles.d.ts +34 -0
  300. package/types/src/rpc-http.d.ts +53 -0
  301. package/types/src/rpc-inputs.d.ts +707 -0
  302. package/types/src/rpc.d.ts +4 -0
  303. package/types/src/secret.d.ts +21 -0
  304. package/types/src/service.d.ts +19 -0
  305. package/types/src/services.d.ts +72 -0
  306. package/types/src/signing.d.ts +72 -0
  307. package/types/src/stored-chain.d.ts +6 -0
  308. package/types/src/stored-permissions.d.ts +12 -0
  309. package/types/src/terminals.d.ts +7 -0
  310. package/types/src/tokens.d.ts +113 -0
  311. package/types/src/workload-token.d.ts +7 -0
  312. package/README.md +0 -3
@@ -0,0 +1,48 @@
1
+ import type { CursorList, GrantIdInput, ListSessionsInput, OkResponse, UserConnectionDto } from '@fabrika/iam-contract'
2
+ import { grantAuthority } from '../oauth'
3
+ import { parseStoredPermissions } from '../stored-permissions'
4
+ import { type AdminContext, adminEvent, fail } from './context'
5
+ import { cursorOf, normalizeLimit } from './pagination'
6
+
7
+ /** OAuth consents are installation administration, like the audit and credentials pages. */
8
+ export async function listConnections(c: AdminContext, input: ListSessionsInput): Promise<CursorList<UserConnectionDto>> {
9
+ const principal = await c.services.repositories.principals.getPrincipalById(input.principalId)
10
+ if (principal === null) return fail(404, 'principal not found')
11
+ const limit = normalizeLimit(input.limit)
12
+ const rows = await c.services.repositories.oauth.listForPrincipal(principal.id, input.before, limit)
13
+ const now = Math.floor(Date.now() / 1000)
14
+ const items = await Promise.all(rows.map(async (row): Promise<UserConnectionDto> => {
15
+ const authority = await grantAuthority(c.services, row, now)
16
+ return {
17
+ id: row.id,
18
+ clientId: row.client_id,
19
+ app: row.app,
20
+ resource: row.resource,
21
+ scopes: parseStoredPermissions(row.scopes),
22
+ createdAt: row.created_at,
23
+ expiresAt: row.expires_at,
24
+ status: row.revoked_at !== null ? 'revoked' : row.expires_at <= now
25
+ ? 'expired'
26
+ : authority === null
27
+ ? 'unavailable'
28
+ : 'active',
29
+ }
30
+ }))
31
+ return { items, nextCursor: cursorOf(items, limit, (item) => item.id) }
32
+ }
33
+
34
+ export async function revokeConnection(c: AdminContext, input: GrantIdInput): Promise<OkResponse> {
35
+ const grant = await c.services.repositories.oauth.grant(input.id)
36
+ if (grant === null) return fail(404, 'connection not found')
37
+ await c.services.repositories.oauth.revokeGrant(
38
+ grant.id,
39
+ Math.floor(Date.now() / 1000),
40
+ adminEvent(c, {
41
+ action: 'iam.oauth.grant.revoke',
42
+ resourceType: 'oauth_grant',
43
+ resourceId: grant.id,
44
+ metadata: { principalId: grant.principal_id, clientId: grant.client_id, app: grant.app, reason: 'administrator' },
45
+ }),
46
+ )
47
+ return { ok: true }
48
+ }
@@ -0,0 +1,70 @@
1
+ import { type PermissionEntry, type PrincipalType } from '@fabrika/auth-core'
2
+ import { type AuditEventInput, auditLabelOf } from '../db'
3
+ import { type RequestContext } from '../env'
4
+ import { type Services } from '../services'
5
+ import { type Administration } from './user-admin'
6
+
7
+ /**
8
+ * Context every admin handler receives: the resolved admin caller (already gated on its administration), the
9
+ * request, parsed URL, and the verified app id for audit labeling.
10
+ */
11
+ export interface AdminContext {
12
+ services: Services
13
+ request: Request
14
+ url: URL
15
+ /** The resolved admin caller (already gated on its administration). `label` is null for a label-less key. */
16
+ admin: { id: string; type: PrincipalType; label: string | null; permissions: PermissionEntry[] }
17
+ /** The installation, or the people of some applications (ADR-0058); every user-admin rule reads it. */
18
+ administration: Administration
19
+ /** IAM's own app id — the audience the admin was resolved against; used for audit labeling. */
20
+ app: string
21
+ /** Correlation id supplied by the proxy/edge or generated at IAM. */
22
+ requestId: string
23
+ ctx: RequestContext
24
+ }
25
+
26
+ /** Structural domain failure shared by REST adapters and the RPC dispatcher. */
27
+ export class AdminUseCaseError extends Error {
28
+ readonly httpStatus: number
29
+ readonly type: string
30
+
31
+ constructor(httpStatus: number, message: string) {
32
+ super(message)
33
+ this.name = 'AdminUseCaseError'
34
+ this.httpStatus = httpStatus
35
+ this.type = httpStatus === 400
36
+ ? 'bad_request'
37
+ : httpStatus === 404
38
+ ? 'not_found'
39
+ : httpStatus === 409
40
+ ? 'conflict'
41
+ : httpStatus === 403
42
+ ? 'forbidden'
43
+ : 'error'
44
+ }
45
+ }
46
+
47
+ export function fail(status: number, message: string): never {
48
+ throw new AdminUseCaseError(status, message)
49
+ }
50
+
51
+ /**
52
+ * The record of a change the admin made. A use case hands it to the repository that makes the change, which writes it
53
+ * in the change's own transaction, so a committed change always has its row and a failed write fails the change.
54
+ */
55
+ export function adminEvent(
56
+ c: AdminContext,
57
+ event: { action: string; resourceType: string; resourceId?: string | null; diff?: unknown; metadata?: unknown },
58
+ ): AuditEventInput {
59
+ return {
60
+ requestId: c.requestId,
61
+ principalId: c.admin.id,
62
+ principalLabel: auditLabelOf(c.admin),
63
+ app: c.app,
64
+ action: event.action,
65
+ resourceType: event.resourceType,
66
+ resourceId: event.resourceId ?? null,
67
+ diff: event.diff,
68
+ metadata: event.metadata,
69
+ }
70
+ }
@@ -0,0 +1,192 @@
1
+ import { isActionAllowed, isReservedScopeType, parseJsonStringArray, type RoleDef } from '@fabrika/auth-core'
2
+ import { type CreateGrantRequest, type GrantDto } from '@fabrika/iam-contract'
3
+ import { type GrantRow, type RoleRow } from '../db'
4
+ import { BUILTIN_ROLES, isKnownRole } from '../roles'
5
+ import { type Services } from '../services'
6
+ import { parseStoredPermissions } from '../stored-permissions'
7
+ import { type AdminContext } from './context'
8
+
9
+ /** Parse a `roles` row's JSON permissions into a string array (fail-closed on junk, incl. unparseable text). */
10
+ export function rolePermissions(json: string): string[] {
11
+ return parseStoredPermissions(json)
12
+ }
13
+
14
+ /**
15
+ * Loads (and memoizes) an app's role_key set on demand so DTO mappers can flag
16
+ * dangling role grants without re-querying per row. A grant/mapping with `app = null`
17
+ * (cross-app) is checked against the built-ins only — there is no per-app row set.
18
+ */
19
+ export class RoleKnownCache {
20
+ private readonly perApp = new Map<string, Set<string>>()
21
+
22
+ constructor(private readonly services: Services) {}
23
+
24
+ private async appRoleKeys(app: string): Promise<Set<string>> {
25
+ const cached = this.perApp.get(app)
26
+ if (cached) {
27
+ return cached
28
+ }
29
+ const rows = await this.services.repositories.appSchema.listRoles(app)
30
+ const keys = new Set(rows.map((r) => r.role_key))
31
+ this.perApp.set(app, keys)
32
+ return keys
33
+ }
34
+
35
+ /** True iff `roleKey` resolves for `app` — a built-in, or a row in the app's roles. */
36
+ async isKnown(roleKey: string, app: string | null): Promise<boolean> {
37
+ if (Object.hasOwn(BUILTIN_ROLES, roleKey)) {
38
+ return true
39
+ }
40
+ if (app === null) {
41
+ return false
42
+ }
43
+ return (await this.appRoleKeys(app)).has(roleKey)
44
+ }
45
+ }
46
+
47
+ export async function toGrantDto(row: GrantRow, roleCache: RoleKnownCache): Promise<GrantDto> {
48
+ const dangling = row.role_key !== null && !(await roleCache.isKnown(row.role_key, row.app))
49
+ return {
50
+ id: row.id,
51
+ principalId: row.principal_id,
52
+ roleKey: row.role_key,
53
+ permissions: row.permissions === null ? null : rolePermissions(row.permissions),
54
+ scopeType: row.scope_type,
55
+ scopeValue: row.scope_value,
56
+ app: row.app,
57
+ grantedBy: row.granted_by,
58
+ expiresAt: row.expires_at,
59
+ createdAt: row.created_at,
60
+ dangling,
61
+ }
62
+ }
63
+
64
+ /** Map a list of grant rows to DTOs sharing one role-known cache (one query per app). */
65
+ export async function toGrantDtos(rows: GrantRow[], services: Services, cache: RoleKnownCache = new RoleKnownCache(services)): Promise<GrantDto[]> {
66
+ const out: GrantDto[] = []
67
+ for (const row of rows) {
68
+ out.push(await toGrantDto(row, cache))
69
+ }
70
+ return out
71
+ }
72
+
73
+ /** The set of app ids IAM knows about — the live registry derived from the schema tables. */
74
+ export function knownApps(c: AdminContext): Promise<string[]> {
75
+ return c.services.repositories.appSchema.listKnownApps()
76
+ }
77
+
78
+ /** Validate an admin-supplied `app`: null (all apps) or a known (registered) app. */
79
+ export async function appField(c: AdminContext, body: Pick<CreateGrantRequest, 'app'>): Promise<{ ok: true; app: string | null } | { ok: false }> {
80
+ const app = body.app ?? null
81
+ if (app !== null && !(await knownApps(c)).includes(app)) {
82
+ return { ok: false }
83
+ }
84
+ return { ok: true, app }
85
+ }
86
+
87
+ /** A `roles` row → core `RoleDef` for resolution. */
88
+ export function dbRoleToDef(row: RoleRow): RoleDef {
89
+ return {
90
+ name: row.name,
91
+ ...(row.description !== null ? { description: row.description } : {}),
92
+ permissions: rolePermissions(row.permissions),
93
+ ...(row.member_scope !== null
94
+ ? { member: { scope: row.member_scope, ...(row.assignable_by === null ? {} : { assignableBy: parseJsonStringArray(row.assignable_by) }) } }
95
+ : {}),
96
+ ...(row.external === 1 ? { external: true } : {}),
97
+ }
98
+ }
99
+
100
+ /** Load an app's DB roles into a role_key -> RoleDef map (empty for app=null). */
101
+ async function loadAppRoleMap(c: AdminContext, app: string | null): Promise<Record<string, RoleDef>> {
102
+ const map: Record<string, RoleDef> = {}
103
+ if (app !== null) {
104
+ for (const row of await c.services.repositories.appSchema.listRoles(app)) {
105
+ map[row.role_key] = dbRoleToDef(row)
106
+ }
107
+ }
108
+ return map
109
+ }
110
+
111
+ /**
112
+ * Validate the scope coordinate on a grant/key request: `scopeType`/`scopeValue` are
113
+ * both-or-neither (both null = global). A half-set pair is a 400.
114
+ */
115
+ export function parseScope(
116
+ body: Pick<CreateGrantRequest, 'scopeType' | 'scopeValue'>,
117
+ ): { ok: true; scopeType: string | null; scopeValue: string | null } | { ok: false } {
118
+ const scopeType = body.scopeType ?? null
119
+ const scopeValue = body.scopeValue ?? null
120
+ if ((scopeType === null) !== (scopeValue === null)) {
121
+ return { ok: false }
122
+ }
123
+ // A `~` scope type is IAM's derived pseudo-scope (`~rel`); a stored grant never names one.
124
+ if (scopeType !== null && isReservedScopeType(scopeType)) {
125
+ return { ok: false }
126
+ }
127
+ return { ok: true, scopeType, scopeValue }
128
+ }
129
+
130
+ /**
131
+ * Validate the role-or-inline choice for a grant/key against the app: EXACTLY one of
132
+ * `roleKey` / `permissions`. A `roleKey` must be a known role for the app (built-in
133
+ * `admin` OR a `roles` row). Inline `permissions` must each be a pattern the relevant
134
+ * action catalog knows. Returns a normalized result or an error message for a 400.
135
+ */
136
+ export async function parseRoleOrInline(
137
+ c: AdminContext,
138
+ body: Pick<CreateGrantRequest, 'roleKey' | 'permissions'>,
139
+ app: string | null,
140
+ ): Promise<{ ok: true; roleKey: string | null; permissions: string[] | null } | { ok: false; message: string }> {
141
+ const { roleKey, permissions } = body
142
+ if ((roleKey === undefined) === (permissions === undefined)) {
143
+ return { ok: false, message: 'exactly one of roleKey or permissions is required' }
144
+ }
145
+ if (roleKey !== undefined) {
146
+ if (!isKnownRole(roleKey, await loadAppRoleMap(c, app))) {
147
+ return { ok: false, message: `unknown role: ${roleKey}` }
148
+ }
149
+ return { ok: true, roleKey, permissions: null }
150
+ }
151
+ // Inline permissions: validate each pattern against the app's action catalog.
152
+ if (permissions === undefined || permissions.length === 0) {
153
+ return { ok: false, message: 'permissions must be a non-empty array of action patterns' }
154
+ }
155
+ const catalog = await actionCatalog(c, app)
156
+ for (const pattern of permissions) {
157
+ if (!isActionAllowed(pattern, catalog)) {
158
+ return {
159
+ ok: false,
160
+ message: app === null
161
+ ? `no registered app declares the action pattern '${pattern}'. This check catches typos, it is not a security boundary — `
162
+ + 'a cross-app grant is matched by pattern at request time, so it also covers an app registered later.'
163
+ : `unknown action pattern: ${pattern}`,
164
+ }
165
+ }
166
+ }
167
+ return { ok: true, roleKey: null, permissions }
168
+ }
169
+
170
+ /**
171
+ * The catalog an inline pattern is validated against: one app's actions, or — for a CROSS-APP grant —
172
+ * the union of every registered app's catalog.
173
+ *
174
+ * A cross-app grant has no single catalog, and the previous code substituted an empty one, which made
175
+ * `isActionAllowed` refuse everything except `*`. That inverted least privilege: an operator who
176
+ * wanted `deploy.read` everywhere had to grant everything instead (CORR-10). The union is the right
177
+ * comparison and it is honest about what it is — a TYPO CHECK, not a boundary. `permits()` matches
178
+ * patterns at request time and never pre-expands them, so an app registered tomorrow is covered by a
179
+ * cross-app grant written today whatever this function said.
180
+ */
181
+ async function actionCatalog(c: AdminContext, app: string | null): Promise<string[]> {
182
+ if (app !== null) {
183
+ return c.services.repositories.appSchema.listActionCatalog(app)
184
+ }
185
+ const catalog = new Set<string>()
186
+ for (const known of await knownApps(c)) {
187
+ for (const action of await c.services.repositories.appSchema.listActionCatalog(known)) {
188
+ catalog.add(action)
189
+ }
190
+ }
191
+ return [...catalog]
192
+ }
@@ -0,0 +1,189 @@
1
+ import { type CreateGrantRequest, type GrantDto, type OkResponse, type UpdateGrantInput } from '@fabrika/iam-contract'
2
+ import { contractGrantProblem, externalGrantProblem } from '../contract-rules'
3
+ import { ExternalGrantError, type GrantRow } from '../db'
4
+ import { type AdminContext, adminEvent, fail } from './context'
5
+ import { appField, parseRoleOrInline, parseScope, RoleKnownCache, toGrantDto } from './grant-support'
6
+ import { requireGrantablePrincipal, requireManagedApp } from './user-admin'
7
+
8
+ export async function createGrantUseCase(c: AdminContext, input: CreateGrantRequest): Promise<GrantDto> {
9
+ const principalId = input.principalId
10
+ if (principalId.trim() === '') return fail(400, 'principalId required')
11
+ if (await c.services.repositories.grants.isWorkloadPrincipal(principalId)) {
12
+ return fail(409, 'a job, a webhook or a connector holds no grant: its actions come from the application schema')
13
+ }
14
+ const appResult = await appField(c, input)
15
+ if (!appResult.ok) {
16
+ return fail(400, 'unknown app')
17
+ }
18
+ const app = appResult.app
19
+ requireManagedApp(c, app)
20
+ const roleOrInline = await parseRoleOrInline(c, input, app)
21
+ if (!roleOrInline.ok) {
22
+ return fail(400, roleOrInline.message)
23
+ }
24
+ const scope = parseScope(input)
25
+ if (!scope.ok) {
26
+ return fail(400, 'scopeType and scopeValue must be both set or both omitted')
27
+ }
28
+ const contractProblem = await contractGrantProblem(c.services.repositories.appSchema, app, { ...roleOrInline, scopeType: scope.scopeType })
29
+ if (contractProblem !== null) {
30
+ return fail(400, contractProblem)
31
+ }
32
+ const expiresAt = Number.isFinite(input.expiresAt) ? input.expiresAt ?? null : null
33
+ const principal = await c.services.repositories.principals.getPrincipalById(principalId)
34
+ if (!principal) {
35
+ return fail(404, 'principal not found')
36
+ }
37
+ requireGrantablePrincipal(c, principal)
38
+ const external = await externalGrantProblem(c.services.repositories.appSchema, principal, app, roleOrInline)
39
+ if (external !== null) {
40
+ return fail(409, external)
41
+ }
42
+ const values = { principalId, app, scopeType: scope.scopeType, scopeValue: scope.scopeValue, grantedBy: c.admin.id, expiresAt }
43
+ const roleKey = roleOrInline.roleKey
44
+ const record = (grantId: string) =>
45
+ adminEvent(c, {
46
+ action: 'iam.grant.create',
47
+ resourceType: 'grant',
48
+ resourceId: grantId,
49
+ metadata: {
50
+ principalId,
51
+ roleKey: roleOrInline.roleKey,
52
+ permissions: roleOrInline.permissions,
53
+ scopeType: scope.scopeType,
54
+ scopeValue: scope.scopeValue,
55
+ app,
56
+ },
57
+ })
58
+ let grant: GrantRow
59
+ try {
60
+ if (roleKey === null) {
61
+ grant = await c.services.repositories.grants.createGrant({ ...values, permissions: roleOrInline.permissions }, record)
62
+ } else {
63
+ const created = await c.services.repositories.grants.createRoleGrantUnlessHeld({ ...values, roleKey }, record)
64
+ if (created === null) {
65
+ const held = await findHeldRoleGrant(c, { ...values, roleKey }).catch(() => undefined)
66
+ const naming = held === undefined ? '' : `: ${held.id}`
67
+ return fail(409, `principal ${principalId} already holds this grant${naming}`)
68
+ }
69
+ grant = created
70
+ }
71
+ } catch (cause) {
72
+ // A reconcile narrowed the role between the check above and the write, which carries the condition itself.
73
+ if (cause instanceof ExternalGrantError) return fail(409, cause.message)
74
+ throw cause
75
+ }
76
+ const cache = new RoleKnownCache(c.services)
77
+ return toGrantDto(grant, cache)
78
+ }
79
+
80
+ export async function deleteGrantUseCase(c: AdminContext, input: { id: string }): Promise<OkResponse> {
81
+ const id = input.id
82
+ const grant = await c.services.repositories.grants.getGrantById(id)
83
+ if (!grant) {
84
+ return fail(404, 'grant not found')
85
+ }
86
+ requireManagedApp(c, grant.app)
87
+ const principal = await c.services.repositories.principals.getPrincipalById(grant.principal_id)
88
+ if (!principal) {
89
+ return fail(404, 'grant not found')
90
+ }
91
+ requireGrantablePrincipal(c, principal)
92
+ await c.services.repositories.grants.deleteGrant(
93
+ id,
94
+ adminEvent(c, {
95
+ action: 'iam.grant.revoke',
96
+ resourceType: 'grant',
97
+ resourceId: id,
98
+ metadata: {
99
+ principalId: grant.principal_id,
100
+ roleKey: grant.role_key,
101
+ scopeType: grant.scope_type,
102
+ scopeValue: grant.scope_value,
103
+ },
104
+ }),
105
+ )
106
+ return { ok: true }
107
+ }
108
+
109
+ /** Edit a grant in place within its original application. Both paths use the same role, scope and external-person rules. */
110
+ export async function updateGrantUseCase(c: AdminContext, input: UpdateGrantInput): Promise<GrantDto> {
111
+ const grant = await c.services.repositories.grants.getGrantById(input.id)
112
+ if (grant === null) return fail(404, 'grant not found')
113
+ requireManagedApp(c, grant.app)
114
+ const principal = await c.services.repositories.principals.getPrincipalById(grant.principal_id)
115
+ if (principal === null) return fail(404, 'principal not found')
116
+ requireGrantablePrincipal(c, principal)
117
+ const authorization = await parseRoleOrInline(c, input, grant.app)
118
+ if (!authorization.ok) return fail(400, authorization.message)
119
+ const scope = parseScope(input)
120
+ if (!scope.ok) return fail(400, 'scopeType and scopeValue must be both set or both omitted')
121
+ const problem = await contractGrantProblem(c.services.repositories.appSchema, grant.app, { ...authorization, scopeType: scope.scopeType })
122
+ ?? await externalGrantProblem(c.services.repositories.appSchema, principal, grant.app, authorization)
123
+ if (problem !== null) return fail(409, problem)
124
+ const expiresAt = input.expiresAt ?? null
125
+ if (expiresAt !== null && expiresAt <= Math.floor(Date.now() / 1000)) return fail(400, 'Choose an expiration in the future, or no expiration.')
126
+ const values = { principalId: principal.id, app: grant.app, ...authorization, ...scope, expiresAt }
127
+ if (
128
+ grant.role_key === authorization.roleKey
129
+ && grant.permissions === (authorization.permissions === null ? null : JSON.stringify(authorization.permissions))
130
+ && grant.scope_type === scope.scopeType && grant.scope_value === scope.scopeValue && grant.expires_at === expiresAt
131
+ ) {
132
+ return toGrantDto(grant, new RoleKnownCache(c.services))
133
+ }
134
+ const duplicate = async () =>
135
+ authorization.roleKey !== null
136
+ && (await c.services.repositories.grants.listGrants(principal.id)).some((other) =>
137
+ other.id !== grant.id && other.app === grant.app && other.role_key === authorization.roleKey
138
+ && other.scope_type === scope.scopeType && other.scope_value === scope.scopeValue
139
+ )
140
+ if (await duplicate()) return fail(409, 'This user already has that role in this scope. Edit the existing access instead.')
141
+ let updated: GrantRow | null
142
+ try {
143
+ updated = await c.services.repositories.grants.updateGrant(
144
+ grant,
145
+ values,
146
+ adminEvent(c, {
147
+ action: 'iam.grant.update',
148
+ resourceType: 'grant',
149
+ resourceId: grant.id,
150
+ metadata: { principalId: principal.id, app: grant.app },
151
+ diff: {
152
+ before: {
153
+ roleKey: grant.role_key,
154
+ permissions: grant.permissions === null ? null : JSON.parse(grant.permissions),
155
+ scopeType: grant.scope_type,
156
+ scopeValue: grant.scope_value,
157
+ expiresAt: grant.expires_at,
158
+ },
159
+ after: {
160
+ roleKey: authorization.roleKey,
161
+ permissions: authorization.permissions,
162
+ scopeType: scope.scopeType,
163
+ scopeValue: scope.scopeValue,
164
+ expiresAt,
165
+ },
166
+ },
167
+ }),
168
+ )
169
+ } catch (cause) {
170
+ if (await duplicate()) return fail(409, 'This user already has that role in this scope. Edit the existing access instead.')
171
+ throw cause
172
+ }
173
+ if (updated === null) return fail(409, 'The access changed or is no longer allowed. Refresh and try again.')
174
+ return toGrantDto(updated, new RoleKnownCache(c.services))
175
+ }
176
+
177
+ /** The held grant a refused role grant duplicates, to name it in the 409; it may be gone by the time this reads. */
178
+ async function findHeldRoleGrant(
179
+ c: AdminContext,
180
+ candidate: { principalId: string; app: string | null; roleKey: string; scopeType: string | null; scopeValue: string | null },
181
+ ): Promise<GrantRow | undefined> {
182
+ const held = await c.services.repositories.grants.listGrants(candidate.principalId)
183
+ return held.find((row) =>
184
+ row.role_key === candidate.roleKey
185
+ && row.app === candidate.app
186
+ && row.scope_type === candidate.scopeType
187
+ && row.scope_value === candidate.scopeValue
188
+ )
189
+ }
@@ -0,0 +1,102 @@
1
+ import {
2
+ getApiKeyUseCase,
3
+ listApiKeysUseCase,
4
+ parseProvisionApiKeyRequest,
5
+ provisionApiKeyUseCase,
6
+ revokeApiKeyUseCase,
7
+ rotateApiKeyUseCase,
8
+ } from './api-keys'
9
+ import { getAppSchemaUseCase, listAppsUseCase, listRolesUseCase, setReturnOriginsUseCase } from './app-schema'
10
+ import { listAuditUseCase, listAuthLogUseCase } from './audit'
11
+ import { clearInstallationBrandUseCase, getInstallationBrandUseCase, setInstallationBrandUseCase } from './brand'
12
+ import { type AdminContext } from './context'
13
+ import { createGrantUseCase, deleteGrantUseCase, updateGrantUseCase } from './grants'
14
+ import { json, readJson } from './http'
15
+ import { issueMembershipKeyUseCase } from './membership-keys'
16
+ import { getPasswordPolicyUseCase, setPasswordPolicyUseCase } from './password-policy'
17
+ import { disablePasswordUseCase, issuePasswordEnrollmentUseCase, issuePasswordResetUseCase } from './passwords'
18
+ import { createPolicyUseCase, deletePolicyUseCase, listPoliciesUseCase, updatePolicyUseCase } from './policies'
19
+ import { getPrincipalUseCase, invitePrincipalUseCase, listPrincipalsUseCase, me, promotePrincipalUseCase, updatePrincipalUseCase } from './principals'
20
+ import { listSessionsUseCase, revokeSessionsForPrincipalUseCase, revokeSessionUseCase } from './sessions'
21
+ import { createShareLinkUseCase, listShareLinksUseCase, revokeShareLinkUseCase } from './share-links'
22
+ import { listTerminalsUseCase, revokeTerminalUseCase, setTerminalProfileUseCase } from './terminals'
23
+ import { issueWorkloadKeyUseCase, revokeWorkloadKeysUseCase } from './workloads'
24
+
25
+ /** Return the app's scopes, actions, and origin='app' roles (the reconciled vocabulary). */
26
+ export async function getAppSchema(c: AdminContext, app: string): Promise<Response> {
27
+ return json(await adminUseCases.getAppSchema(c, { app }))
28
+ }
29
+
30
+ /**
31
+ * Provision an API key: create a native service principal + grant and mint a `px_`
32
+ * credential bound to it — resolved by the IAM-native path (`mintFromKey`), no
33
+ * Cloudflare Access in front. The plaintext `px_` token is returned ONCE.
34
+ *
35
+ * There is no distributed transaction; the writes are local D1 (principal → grant →
36
+ * credential). A failure partway leaves an orphan principal at worst — harmless (it
37
+ * holds no live credential) and revocable from this page.
38
+ */
39
+ export async function provisionApiKey(c: AdminContext): Promise<Response> {
40
+ const body = await readJson(c.request)
41
+ return json(await adminUseCases.provisionApiKey(c, parseProvisionApiKeyRequest(body)), { status: 201 })
42
+ }
43
+
44
+ /**
45
+ * Revoke an API key: hard-delete its grants, soft-disable the service principal, and
46
+ * revoke its `px_` credentials so they stop minting immediately. Revocation is
47
+ * effective at once — `mintFromKey` re-resolves the credential on every mint.
48
+ */
49
+ export async function revokeApiKey(c: AdminContext, principalId: string): Promise<Response> {
50
+ return json(await adminUseCases.revokeApiKey(c, { principalId }))
51
+ }
52
+
53
+ /** The typed application operations. `/admin/rpc` serves all of them; REST serves four. */
54
+ export const adminUseCases = {
55
+ me,
56
+ listPrincipals: listPrincipalsUseCase,
57
+ getPrincipal: getPrincipalUseCase,
58
+ invitePrincipal: invitePrincipalUseCase,
59
+ updatePrincipal: updatePrincipalUseCase,
60
+ promotePrincipal: promotePrincipalUseCase,
61
+ listSessions: listSessionsUseCase,
62
+ revokeSession: revokeSessionUseCase,
63
+ revokeSessionsForPrincipal: revokeSessionsForPrincipalUseCase,
64
+ issuePasswordEnrollment: issuePasswordEnrollmentUseCase,
65
+ issuePasswordReset: issuePasswordResetUseCase,
66
+ disablePassword: disablePasswordUseCase,
67
+ createGrant: createGrantUseCase,
68
+ updateGrant: updateGrantUseCase,
69
+ deleteGrant: deleteGrantUseCase,
70
+ listApps: listAppsUseCase,
71
+ listRoles: listRolesUseCase,
72
+ getAppSchema: getAppSchemaUseCase,
73
+ setReturnOrigins: setReturnOriginsUseCase,
74
+ listPolicies: listPoliciesUseCase,
75
+ createPolicy: createPolicyUseCase,
76
+ updatePolicy: updatePolicyUseCase,
77
+ deletePolicy: deletePolicyUseCase,
78
+ listApiKeys: listApiKeysUseCase,
79
+ getApiKey: getApiKeyUseCase,
80
+ provisionApiKey: provisionApiKeyUseCase,
81
+ rotateApiKey: rotateApiKeyUseCase,
82
+ revokeApiKey: revokeApiKeyUseCase,
83
+ listShareLinks: listShareLinksUseCase,
84
+ createShareLink: createShareLinkUseCase,
85
+ revokeShareLink: revokeShareLinkUseCase,
86
+ listAudit: listAuditUseCase,
87
+ listAuthLog: listAuthLogUseCase,
88
+ issueWorkloadKey: issueWorkloadKeyUseCase,
89
+ revokeWorkloadKeys: revokeWorkloadKeysUseCase,
90
+ issueMembershipKey: issueMembershipKeyUseCase,
91
+ getInstallationBrand: getInstallationBrandUseCase,
92
+ setInstallationBrand: setInstallationBrandUseCase,
93
+ clearInstallationBrand: clearInstallationBrandUseCase,
94
+ getPasswordPolicy: getPasswordPolicyUseCase,
95
+ setPasswordPolicy: setPasswordPolicyUseCase,
96
+ listTerminals: listTerminalsUseCase,
97
+ setTerminalProfile: setTerminalProfileUseCase,
98
+ revokeTerminal: revokeTerminalUseCase,
99
+ }
100
+
101
+ export { putAppSchema } from './app-schema'
102
+ export { type AdminContext, AdminUseCaseError } from './context'
@@ -0,0 +1,24 @@
1
+ /** JSON response helper for the admin API. */
2
+ export function json(body: unknown, init?: ResponseInit): Response {
3
+ return new Response(JSON.stringify(body), {
4
+ ...init,
5
+ headers: { 'content-type': 'application/json; charset=utf-8', ...init?.headers },
6
+ })
7
+ }
8
+
9
+ /** A structured JSON error with an HTTP status. */
10
+ export function error(status: number, message: string): Response {
11
+ return json({ error: message }, { status })
12
+ }
13
+
14
+ /**
15
+ * Parse a JSON request body as `unknown` (undefined on parse failure). Callers
16
+ * narrow fields with the readers in `../json` — no `as` casts on untrusted input.
17
+ */
18
+ export async function readJson(request: Request): Promise<unknown> {
19
+ try {
20
+ return await request.json()
21
+ } catch {
22
+ return undefined
23
+ }
24
+ }
@@ -0,0 +1,38 @@
1
+ import { API_KEY_PREFIX, parseAppEnvironmentId } from '@fabrika/auth-core'
2
+ import type { IssueMembershipKeyRequest, IssueMembershipKeyResponse } from '@fabrika/iam-contract'
3
+ import { keyExpiryProblem } from '../issue'
4
+ import { unixNow } from '../repositories/sql'
5
+ import { generateToken, hashToken } from '../secret'
6
+ import { type AdminContext, adminEvent, fail } from './context'
7
+
8
+ /**
9
+ * Issue a fresh membership transport key for one application environment (`src/membership-http.ts`). The key the caller
10
+ * recorded as active (`keep`) stays valid, so the version still running keeps working until the caller has recorded the
11
+ * new one; every other key of the environment is an orphan of an attempt whose record failed, and is deleted.
12
+ */
13
+ export async function issueMembershipKeyUseCase(c: AdminContext, input: IssueMembershipKeyRequest): Promise<IssueMembershipKeyResponse> {
14
+ if (parseAppEnvironmentId(input.app) === null) {
15
+ return fail(400, 'a membership transport key belongs to one application environment, <app>@<env>')
16
+ }
17
+ const now = unixNow()
18
+ const expiryProblem = keyExpiryProblem(input.expiresAt, now)
19
+ if (expiryProblem !== null) {
20
+ return fail(400, expiryProblem)
21
+ }
22
+ // `px_`, like every key IAM issues, so the redaction of `px_` patterns covers it in every log.
23
+ const key = `${API_KEY_PREFIX}${generateToken()}`
24
+ const id = await c.services.repositories.membershipTransport.issue({
25
+ app: input.app,
26
+ keyHash: await hashToken(key),
27
+ expiresAt: input.expiresAt,
28
+ keep: input.keep,
29
+ now,
30
+ }, (keyId) =>
31
+ adminEvent(c, {
32
+ action: 'iam.membership-key.issue',
33
+ resourceType: 'membership_transport_key',
34
+ resourceId: keyId,
35
+ metadata: { app: input.app, expiresAt: input.expiresAt, kept: input.keep },
36
+ }))
37
+ return { key, id, expiresAt: input.expiresAt }
38
+ }