@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,28 @@
1
+ /** Group rows by a key, preserving order — how a single page-wide query becomes per-row lists. */
2
+ export function groupBy<T>(rows: readonly T[], key: (row: T) => string): Map<string, T[]> {
3
+ const out = new Map<string, T[]>()
4
+ for (const row of rows) {
5
+ const bucket = out.get(key(row))
6
+ if (bucket === undefined) {
7
+ out.set(key(row), [row])
8
+ } else {
9
+ bucket.push(row)
10
+ }
11
+ }
12
+ return out
13
+ }
14
+
15
+ /** The `before` value for the next page, or null when this page is the last one. */
16
+ export function cursorOf<T>(items: readonly T[], limit: number, id: (item: T) => string): string | null {
17
+ const last = items.at(-1)
18
+ return items.length === limit && last !== undefined ? id(last) : null
19
+ }
20
+
21
+ const DEFAULT_LIMIT = 50
22
+
23
+ const MAX_LIMIT = 200
24
+
25
+ export function normalizeLimit(limit: number | undefined): number {
26
+ if (limit === undefined || !Number.isFinite(limit) || limit <= 0) return DEFAULT_LIMIT
27
+ return Math.min(Math.floor(limit), MAX_LIMIT)
28
+ }
@@ -0,0 +1,48 @@
1
+ // The installation's minimum password length (ADR-0020): an installation administrator's to read and to change. One
2
+ // value for every principal of the installation; IAM's set-password and invitation pages read it at every render.
3
+
4
+ import { PASSWORD_DEFAULT_MIN_LENGTH, PASSWORD_MAX_LENGTH, type PasswordPolicyDto, type SetPasswordPolicyRequest } from '@fabrika/iam-contract'
5
+ import { minLengthProblem, storedMinLength } from '../password-minimum'
6
+ import type { PasswordPolicyRow } from '../repositories/password-policy'
7
+ import { type AdminContext, adminEvent, fail } from './context'
8
+
9
+ export async function getPasswordPolicyUseCase(c: AdminContext): Promise<PasswordPolicyDto> {
10
+ requireInstallationAdmin(c)
11
+ return policyDto(c, await c.services.repositories.passwordPolicy.get())
12
+ }
13
+
14
+ /**
15
+ * Store the minimum, held here to this runtime's floor whatever the console checked. It applies to the next password
16
+ * chosen; a stored verifier is never re-judged, so raising it asks nobody to change a password and lowering it weakens
17
+ * none. Setting the minimum already stored changes and records nothing.
18
+ */
19
+ export async function setPasswordPolicyUseCase(c: AdminContext, input: SetPasswordPolicyRequest): Promise<PasswordPolicyDto> {
20
+ requireInstallationAdmin(c)
21
+ const problem = minLengthProblem(input.minLength, c.services.config.authentication.password.minLengthFloor)
22
+ if (problem !== null) return fail(400, problem)
23
+ const repository = c.services.repositories.passwordPolicy
24
+ const changed = await repository.setMinLength(
25
+ input.minLength,
26
+ adminEvent(c, { action: 'iam.password_policy.update', resourceType: 'password_policy', metadata: { minLength: input.minLength } }),
27
+ )
28
+ return policyDto(c, changed ?? await repository.get())
29
+ }
30
+
31
+ function policyDto(c: AdminContext, row: PasswordPolicyRow | null): PasswordPolicyDto {
32
+ const { enabled, minLengthFloor } = c.services.config.authentication.password
33
+ return {
34
+ minLength: storedMinLength(row, minLengthFloor),
35
+ defaultMinLength: PASSWORD_DEFAULT_MIN_LENGTH,
36
+ minLengthFloor,
37
+ maxLength: PASSWORD_MAX_LENGTH,
38
+ passwordEnabled: enabled,
39
+ updatedAt: row?.updated_at ?? null,
40
+ }
41
+ }
42
+
43
+ /** `.require(iam.admin)` gates these procedures already; a direct caller of a use case meets the same rule. */
44
+ function requireInstallationAdmin(c: AdminContext): void {
45
+ if (c.administration.kind !== 'installation') {
46
+ return fail(403, "the installation's password policy is changed and read only by an installation administrator")
47
+ }
48
+ }
@@ -0,0 +1,78 @@
1
+ import { type OkResponse, type PasswordActionDelivery, type PrincipalIdInput } from '@fabrika/iam-contract'
2
+
3
+ import { INSTALLATION_PRESENTATION } from '../app-presentation'
4
+ import { type PrincipalRow } from '../db'
5
+ import { deliverPasswordAction, issuePasswordAction } from '../password-service'
6
+ import { type AdminContext, adminEvent, fail } from './context'
7
+ import { requireActableTarget } from './user-admin'
8
+
9
+ async function passwordUser(c: AdminContext, id: string, requireActive: boolean = true): Promise<PrincipalRow> {
10
+ if (!c.services.config.authentication.password.enabled) {
11
+ return fail(409, 'password authentication is not available')
12
+ }
13
+ const principal = await c.services.repositories.principals.getPrincipalById(id)
14
+ if (!principal) return fail(404, 'principal not found')
15
+ if (principal.type !== 'user') return fail(400, 'password authentication is available only for users')
16
+ if (principal.email === null) return fail(409, 'user has no email address')
17
+ if (requireActive && principal.disabled_at !== null) return fail(409, 'principal is disabled')
18
+ await requireActableTarget(c, principal)
19
+ return principal
20
+ }
21
+
22
+ async function passwordDelivery(
23
+ c: AdminContext,
24
+ principal: PrincipalRow,
25
+ purpose: 'enrollment' | 'reset',
26
+ ): Promise<PasswordActionDelivery> {
27
+ const delivery = c.services.email === null ? 'manual' : 'email'
28
+ // A manual URL lets its holder set the person's password, which outlives a later OIDC claim of that row (ADR-0058).
29
+ if (delivery === 'manual' && c.administration.kind === 'users') {
30
+ return fail(403, `without an email sender, only an installation administrator receives a password ${purpose} link`)
31
+ }
32
+ // The token, the enrollment opt-in and the record commit together; the email is an effect after that.
33
+ // An administrator's action belongs to the installation: its page and mail speak the person's language, else IAM's default.
34
+ const action = await issuePasswordAction(c.services, { principal, purpose, issuedBy: c.admin.id, presentation: INSTALLATION_PRESENTATION }, {
35
+ audit: adminEvent(c, { action: `iam.password.${purpose}.issue`, resourceType: 'principal', resourceId: principal.id, metadata: { delivery } }),
36
+ enableEnrollment: purpose === 'enrollment',
37
+ })
38
+ if (c.services.email === null) {
39
+ return { delivery: 'manual', url: action.url, expiresAt: action.expiresAt }
40
+ }
41
+ if (action.message === null || principal.email === null) {
42
+ return fail(409, 'user has no email address')
43
+ }
44
+ try {
45
+ await deliverPasswordAction(c.services, action)
46
+ } catch {
47
+ console.error('Password action email delivery failed')
48
+ // The outcome of an effect, not a change of IAM's: the token was recorded when it was issued.
49
+ await c.services.repositories.audit.writeAuditEvent(
50
+ adminEvent(c, { action: `iam.password.${purpose}.delivery_failed`, resourceType: 'principal', resourceId: principal.id }),
51
+ )
52
+ return fail(502, 'password action email delivery failed')
53
+ }
54
+ return { delivery: 'email', email: principal.email, expiresAt: action.expiresAt }
55
+ }
56
+
57
+ export async function issuePasswordEnrollmentUseCase(c: AdminContext, input: PrincipalIdInput): Promise<PasswordActionDelivery> {
58
+ const principal = await passwordUser(c, input.principalId)
59
+ const account = await c.services.repositories.passwords.getAccount(principal.id)
60
+ if (account?.state === 'enabled') return fail(409, 'password authentication is already enabled')
61
+ return passwordDelivery(c, principal, 'enrollment')
62
+ }
63
+
64
+ export async function issuePasswordResetUseCase(c: AdminContext, input: PrincipalIdInput): Promise<PasswordActionDelivery> {
65
+ const principal = await passwordUser(c, input.principalId)
66
+ const account = await c.services.repositories.passwords.getAccount(principal.id)
67
+ if (account?.state !== 'enabled') return fail(409, 'password authentication is not enabled')
68
+ return passwordDelivery(c, principal, 'reset')
69
+ }
70
+
71
+ export async function disablePasswordUseCase(c: AdminContext, input: PrincipalIdInput): Promise<OkResponse> {
72
+ const principal = await passwordUser(c, input.principalId, false)
73
+ await c.services.repositories.passwords.disableCredential(
74
+ principal.id,
75
+ adminEvent(c, { action: 'iam.password.disable', resourceType: 'principal', resourceId: principal.id }),
76
+ )
77
+ return { ok: true }
78
+ }
@@ -0,0 +1,136 @@
1
+ import { isActionAllowed } from '@fabrika/auth-core'
2
+
3
+ import { type AppInput, type CreatePolicyInput, type OkResponse, type PolicyDto, type UpdatePolicyInput } from '@fabrika/iam-contract'
4
+ import { contractPatternsProblem } from '../contract-rules'
5
+ import { type RoleRow } from '../db'
6
+ import { BUILTIN_ROLES } from '../roles'
7
+ import { type AdminContext, adminEvent, fail } from './context'
8
+ import { knownApps, rolePermissions } from './grant-support'
9
+
10
+ function toPolicyDto(row: RoleRow): PolicyDto {
11
+ return {
12
+ app: row.app,
13
+ key: row.role_key,
14
+ name: row.name,
15
+ ...(row.description !== null ? { description: row.description } : {}),
16
+ permissions: rolePermissions(row.permissions),
17
+ createdAt: row.created_at,
18
+ }
19
+ }
20
+
21
+ /** List an app's custom policies (origin='custom' role rows). */
22
+ export async function listPoliciesUseCase(c: AdminContext, input: AppInput): Promise<{ items: PolicyDto[] }> {
23
+ const app = input.app
24
+ if (!(await knownApps(c)).includes(app)) {
25
+ return fail(404, 'unknown app')
26
+ }
27
+ const rows = await c.services.repositories.appSchema.listRolesByOrigin(app, 'custom')
28
+ return { items: rows.map(toPolicyDto) }
29
+ }
30
+
31
+ /**
32
+ * Validate a policy body's action patterns against the app's catalog (`app_actions`),
33
+ * returning normalized fields or an error message. Shared by create + update.
34
+ */
35
+ async function parsePolicyBody(
36
+ c: AdminContext,
37
+ app: string,
38
+ body: UpdatePolicyInput['policy'] & { key?: string },
39
+ requireKey: boolean,
40
+ ): Promise<{ ok: true; key: string | undefined; name: string; description: string | null; permissions: string[] } | { ok: false; message: string }> {
41
+ const { key, name, permissions } = body
42
+ if (requireKey && key === undefined) {
43
+ return { ok: false, message: 'key required' }
44
+ }
45
+ if (permissions.length === 0) {
46
+ return { ok: false, message: 'permissions must be a non-empty array of action patterns' }
47
+ }
48
+ // A custom policy must not collide with a built-in role key.
49
+ if (key !== undefined && Object.hasOwn(BUILTIN_ROLES, key)) {
50
+ return { ok: false, message: `'${key}' is a reserved built-in role key` }
51
+ }
52
+ const catalog = await c.services.repositories.appSchema.listActionCatalog(app)
53
+ for (const pattern of permissions) {
54
+ if (!isActionAllowed(pattern, catalog)) {
55
+ return { ok: false, message: `unknown action pattern: ${pattern}` }
56
+ }
57
+ }
58
+ const contractProblem = await contractPatternsProblem(c.services.repositories.appSchema, app, permissions)
59
+ if (contractProblem !== null) {
60
+ return { ok: false, message: contractProblem }
61
+ }
62
+ const description = body.description ?? null
63
+ return { ok: true, key, name, description, permissions }
64
+ }
65
+
66
+ /** Create a custom policy (origin='custom' role). Rejects a key that already exists. */
67
+ export async function createPolicyUseCase(c: AdminContext, input: CreatePolicyInput): Promise<PolicyDto> {
68
+ const { app, policy: body } = input
69
+ if (!(await knownApps(c)).includes(app)) return fail(404, 'unknown app')
70
+ const parsed = await parsePolicyBody(c, app, body, true)
71
+ if (!parsed.ok) {
72
+ return fail(400, parsed.message)
73
+ }
74
+ const key = parsed.key
75
+ if (key === undefined) {
76
+ return fail(400, 'key required')
77
+ }
78
+ const existing = await c.services.repositories.appSchema.getRole(app, key)
79
+ if (existing) {
80
+ return fail(409, `a role with key '${key}' already exists`)
81
+ }
82
+ const row = await c.services.repositories.appSchema.upsertRole(
83
+ { app, roleKey: key, name: parsed.name, description: parsed.description, permissions: parsed.permissions, origin: 'custom' },
84
+ adminEvent(c, {
85
+ action: 'iam.policy.create',
86
+ resourceType: 'policy',
87
+ resourceId: `${app}/${key}`,
88
+ metadata: { app, key, permissions: parsed.permissions },
89
+ }),
90
+ )
91
+ return toPolicyDto(row)
92
+ }
93
+
94
+ /** Update a custom policy. Rejects if the key is missing or is an origin='app' role. */
95
+ export async function updatePolicyUseCase(c: AdminContext, input: UpdatePolicyInput): Promise<PolicyDto> {
96
+ const { app, key, policy: body } = input
97
+ if (!(await knownApps(c)).includes(app)) {
98
+ return fail(404, 'unknown app')
99
+ }
100
+ const existing = await c.services.repositories.appSchema.getRole(app, key)
101
+ if (existing?.origin !== 'custom') {
102
+ return fail(404, 'custom policy not found')
103
+ }
104
+ const parsed = await parsePolicyBody(c, app, body, false)
105
+ if (!parsed.ok) {
106
+ return fail(400, parsed.message)
107
+ }
108
+ const row = await c.services.repositories.appSchema.upsertRole(
109
+ { app, roleKey: key, name: parsed.name, description: parsed.description, permissions: parsed.permissions, origin: 'custom' },
110
+ adminEvent(c, {
111
+ action: 'iam.policy.update',
112
+ resourceType: 'policy',
113
+ resourceId: `${app}/${key}`,
114
+ metadata: { app, key, permissions: parsed.permissions },
115
+ }),
116
+ )
117
+ return toPolicyDto(row)
118
+ }
119
+
120
+ /** Delete a custom policy. Refuses to delete an origin='app' (reconciled) role. */
121
+ export async function deletePolicyUseCase(c: AdminContext, input: { app: string; key: string }): Promise<OkResponse> {
122
+ const { app, key } = input
123
+ if (!(await knownApps(c)).includes(app)) {
124
+ return fail(404, 'unknown app')
125
+ }
126
+ const existing = await c.services.repositories.appSchema.getRole(app, key)
127
+ if (existing?.origin !== 'custom') {
128
+ return fail(404, 'custom policy not found')
129
+ }
130
+ await c.services.repositories.appSchema.deleteRole(
131
+ app,
132
+ key,
133
+ adminEvent(c, { action: 'iam.policy.delete', resourceType: 'policy', resourceId: `${app}/${key}`, metadata: { app, key } }),
134
+ )
135
+ return { ok: true }
136
+ }
@@ -0,0 +1,226 @@
1
+ import {
2
+ type CursorList,
3
+ type InviteRequest,
4
+ type ListPrincipalsInput,
5
+ type MeDto,
6
+ type PrincipalDetail,
7
+ type PrincipalGrantDto,
8
+ type PrincipalIdInput,
9
+ type PrincipalListItem,
10
+ type UpdatePrincipalInput,
11
+ } from '@fabrika/iam-contract'
12
+ import { type PrincipalRow, principalStatus } from '../db'
13
+ import { normalizeEmailIdentity } from '../email-identity'
14
+ import { resolvePermissionsAt } from '../resolve'
15
+ import { listRolesUseCase } from './app-schema'
16
+ import { type AdminContext, adminEvent, fail } from './context'
17
+ import { toGrantDtos } from './grant-support'
18
+ import { cursorOf, normalizeLimit } from './pagination'
19
+ import { canManagePrincipal, managesApp, requireActableTarget, requireInvitableMailbox } from './user-admin'
20
+
21
+ function toPrincipalListItem(row: PrincipalRow): PrincipalListItem {
22
+ return {
23
+ id: row.id,
24
+ type: row.type,
25
+ label: row.label,
26
+ email: row.email,
27
+ externalId: row.external_id,
28
+ status: principalStatus(row),
29
+ affiliation: row.affiliation,
30
+ createdAt: row.created_at,
31
+ }
32
+ }
33
+
34
+ export function me(c: AdminContext): MeDto {
35
+ const me: MeDto = {
36
+ id: c.admin.id,
37
+ type: c.admin.type,
38
+ label: c.admin.label ?? c.admin.id,
39
+ permissions: c.admin.permissions,
40
+ }
41
+ return me
42
+ }
43
+
44
+ export async function listPrincipalsUseCase(c: AdminContext, input: ListPrincipalsInput): Promise<CursorList<PrincipalListItem>> {
45
+ const limit = normalizeLimit(input.limit)
46
+ const rows = await c.services.repositories.principals.listPrincipals({
47
+ ...(input.type !== undefined ? { type: input.type } : {}),
48
+ ...(input.status !== undefined ? { status: input.status } : {}),
49
+ ...(input.q ? { q: input.q } : {}),
50
+ ...(input.before ? { before: input.before } : {}),
51
+ limit,
52
+ })
53
+ const items = rows.map(toPrincipalListItem)
54
+ return { items, nextCursor: cursorOf(items, limit, (item) => item.id) }
55
+ }
56
+
57
+ export async function getPrincipalUseCase(c: AdminContext, input: PrincipalIdInput): Promise<PrincipalDetail> {
58
+ const id = input.principalId
59
+ const row = await c.services.repositories.principals.getPrincipalById(id)
60
+ if (!row) {
61
+ return fail(404, 'principal not found')
62
+ }
63
+ const grants = await c.services.repositories.grants.listGrants(id)
64
+
65
+ const permissions = row.disabled_at === null ? await resolvePermissionsAt(c.services, row, c.app) : []
66
+ const canManage = await canManagePrincipal(c, row)
67
+ const lastSignIns = await c.services.repositories.sessions.lastAppSignIns(id)
68
+ const apps = new Set([...grants.flatMap((grant) => grant.app === null ? [] : [grant.app]), ...lastSignIns.map((login) => login.app)])
69
+ if (grants.some((grant) => grant.app === null) || (bootstrapMailbox(c, row) && row.affiliation === 'internal')) {
70
+ for (const app of c.services.config.platformAudiences) apps.add(app)
71
+ }
72
+ const access = await Promise.all(
73
+ [...apps].sort().map(async (app) => ({
74
+ app,
75
+ permissions: row.disabled_at === null ? await resolvePermissionsAt(c.services, row, app) : [],
76
+ lastSignInAt: lastSignIns.find((login) => login.app === app)?.signed_in_at ?? null,
77
+ })),
78
+ )
79
+ const roles = new Map(
80
+ await Promise.all([...new Set(grants.map((grant) => grant.app))].map(async (app) => [app, (await listRolesUseCase(c, { app })).items] as const)),
81
+ )
82
+ const authors = new Map(
83
+ await Promise.all([...new Set(grants.flatMap((grant) => grant.granted_by === null ? [] : [grant.granted_by]))]
84
+ .map(async (author) => [author, (await c.services.repositories.principals.getPrincipalById(author))?.label ?? author] as const)),
85
+ )
86
+ const grantDetails: PrincipalGrantDto[] = (await toGrantDtos(grants, c.services)).map((grant) => {
87
+ const role = roles.get(grant.app)?.find((role) => role.key === grant.roleKey)
88
+ return {
89
+ ...grant,
90
+ roleName: role?.name ?? null,
91
+ rolePermissions: role?.permissions ?? [],
92
+ grantedByLabel: grant.grantedBy === null ? null : authors.get(grant.grantedBy) ?? grant.grantedBy,
93
+ canManage: (c.administration.kind === 'installation' || row.type === 'user') && managesApp(c.services, c.administration, grant.app),
94
+ }
95
+ })
96
+ const latestAction = await c.services.repositories.passwords.latestAction(id)
97
+ const passwordAccount = row.type === 'user' && c.services.config.authentication.password.enabled
98
+ ? await c.services.repositories.passwords.getAccount(row.id)
99
+ : null
100
+
101
+ const detail: PrincipalDetail = {
102
+ ...toPrincipalListItem(row),
103
+ bootstrapMailbox: bootstrapMailbox(c, row),
104
+ grants: grantDetails,
105
+ permissions,
106
+ access,
107
+ management: {
108
+ account: canManage,
109
+ passwordLinks: canManage && (c.services.email !== null || c.administration.kind === 'installation'),
110
+ audit: c.administration.kind === 'installation',
111
+ },
112
+ activatedAt: row.activated_at,
113
+ disabledAt: row.disabled_at,
114
+ authentication: {
115
+ oidc: {
116
+ state: !c.services.config.authentication.oidc.enabled
117
+ ? 'unavailable'
118
+ : row.type === 'user' && row.external_id !== null
119
+ ? 'linked'
120
+ : 'unlinked',
121
+ },
122
+ password: {
123
+ delivery: c.services.email === null ? 'manual' : 'email',
124
+ latestAction: latestAction === null ? null : {
125
+ purpose: latestAction.purpose,
126
+ createdAt: latestAction.created_at,
127
+ expiresAt: latestAction.expires_at,
128
+ closedAt: latestAction.consumed_at,
129
+ },
130
+ state: !c.services.config.authentication.password.enabled
131
+ ? 'unavailable'
132
+ : row.type !== 'user'
133
+ ? 'disabled'
134
+ : passwordAccount?.state ?? 'disabled',
135
+ },
136
+ },
137
+ }
138
+ return detail
139
+ }
140
+
141
+ export async function invitePrincipalUseCase(c: AdminContext, input: InviteRequest): Promise<PrincipalListItem> {
142
+ const email = input.email.trim()
143
+ if (email === '') return fail(400, 'email required')
144
+ const normalizedEmail = normalizeEmailIdentity(email)
145
+ requireInvitableMailbox(c, normalizedEmail)
146
+ const existing = await c.services.repositories.passwords.lookupActionUser(normalizedEmail)
147
+ if (existing.status !== 'missing') {
148
+ return fail(409, 'a user with this email already exists')
149
+ }
150
+ let principal: PrincipalRow
151
+ try {
152
+ // The mailbox is what identifies the human; the spelling the admin typed survives as the label.
153
+ const affiliation = input.affiliation ?? 'internal'
154
+ principal = await c.services.repositories.principals.inviteUser(
155
+ normalizedEmail,
156
+ email,
157
+ (principalId) => adminEvent(c, { action: 'iam.principal.invite', resourceType: 'principal', resourceId: principalId, metadata: { affiliation } }),
158
+ affiliation,
159
+ )
160
+ } catch (cause) {
161
+ if ((await c.services.repositories.passwords.lookupActionUser(normalizedEmail)).status !== 'missing') {
162
+ return fail(409, 'a user with this email already exists')
163
+ }
164
+ throw cause
165
+ }
166
+ return toPrincipalListItem(principal)
167
+ }
168
+
169
+ export async function updatePrincipalUseCase(c: AdminContext, input: UpdatePrincipalInput): Promise<PrincipalListItem> {
170
+ const { principalId: id, disabled } = input
171
+ const row = await c.services.repositories.principals.getPrincipalById(id)
172
+ if (!row) {
173
+ return fail(404, 'principal not found')
174
+ }
175
+ await requireActableTarget(c, row)
176
+ // Recorded only when it changes something: disabling a disabled principal is not a change.
177
+ if (disabled) {
178
+ await c.services.repositories.principals.disablePrincipal(
179
+ id,
180
+ adminEvent(c, { action: 'iam.principal.disable', resourceType: 'principal', resourceId: id }),
181
+ )
182
+ } else {
183
+ await c.services.repositories.principals.enablePrincipal(
184
+ id,
185
+ adminEvent(c, { action: 'iam.principal.enable', resourceType: 'principal', resourceId: id }),
186
+ )
187
+ }
188
+ const updated = await c.services.repositories.principals.getPrincipalById(id)
189
+ if (!updated) return fail(404, 'principal not found')
190
+ return toPrincipalListItem(updated)
191
+ }
192
+
193
+ /**
194
+ * Make an external user internal (ADR-0051). Its grant rows stay as they are, but what it may reach widens: it may then
195
+ * hold any role, an OIDC login presenting its address may claim it, and a mailbox listed in `IAM_BOOTSTRAP_ADMINS`
196
+ * becomes an installation admin at once. So the promotion revokes every session of the user and spends its pending
197
+ * password actions in the same transaction, and its record says whether the mailbox is a bootstrap admin. There is no
198
+ * demotion.
199
+ */
200
+ export async function promotePrincipalUseCase(c: AdminContext, input: PrincipalIdInput): Promise<PrincipalListItem> {
201
+ const id = input.principalId
202
+ const row = await c.services.repositories.principals.getPrincipalById(id)
203
+ if (!row) {
204
+ return fail(404, 'principal not found')
205
+ }
206
+ const promoted = await c.services.repositories.principals.promoteToInternal(
207
+ id,
208
+ adminEvent(c, {
209
+ action: 'iam.principal.promote',
210
+ resourceType: 'principal',
211
+ resourceId: id,
212
+ metadata: { bootstrapAdmin: bootstrapMailbox(c, row) },
213
+ }),
214
+ )
215
+ if (!promoted) {
216
+ return fail(409, 'the principal is not external')
217
+ }
218
+ const updated = await c.services.repositories.principals.getPrincipalById(id)
219
+ if (!updated) return fail(404, 'principal not found')
220
+ return toPrincipalListItem(updated)
221
+ }
222
+
223
+ /** Whether the user's mailbox is listed in `IAM_BOOTSTRAP_ADMINS`: internal, it is an installation admin. */
224
+ function bootstrapMailbox(c: AdminContext, row: PrincipalRow): boolean {
225
+ return row.type === 'user' && row.email !== null && c.services.config.bootstrapAdmins.has(normalizeEmailIdentity(row.email))
226
+ }