@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,1210 @@
1
+ /**
2
+ * The membership operations of a multi-tenant application (ADR-0012 §6; ADR-0022
3
+ * rule 6): delegation grants, scope creation, membership, invitations and share links.
4
+ *
5
+ * Every operation resolves the caller from its own credential and evaluates it against the caller's LIVE
6
+ * permissions at the credential's verified app. The application names no actor and writes no grant: IAM
7
+ * generates every value, writes every grant and issues every key. Scopes stay flat — a value is checked as
8
+ * itself; only a share link names its containment chain, and the framework re-checks that chain per request.
9
+ */
10
+
11
+ import {
12
+ API_KEY_PREFIX,
13
+ type AppMemberItem,
14
+ type AssignMemberInput,
15
+ type AssignMemberResult,
16
+ type CreateScopeInput,
17
+ type CreateScopeResult,
18
+ DELEGATION_GRANT_TTL_SECONDS,
19
+ type FindMemberInput,
20
+ type FindMemberResult,
21
+ type InvitationAcceptance,
22
+ type InvitationOptions,
23
+ invitationOptionsProblem,
24
+ invitedAddress,
25
+ type IssueLinkInput,
26
+ type IssueLinkResult,
27
+ type ListAppMembersInput,
28
+ type ListAppMembersResult,
29
+ type ListMembersInput,
30
+ type ListMembersResult,
31
+ matchAction,
32
+ MAX_APP_MEMBERS_PAGE,
33
+ MAX_LINK_CHAIN_LENGTH,
34
+ MAX_MEMBERSHIP_SCOPE_PART_LENGTH,
35
+ type MemberItem,
36
+ type MembershipCaller,
37
+ type MembershipFailure,
38
+ membershipScopeProblem,
39
+ parseJsonStringArray,
40
+ type PermissionEntry,
41
+ permits,
42
+ type RequestDelegationInput,
43
+ type RequestDelegationResult,
44
+ type RevokeLinkInput,
45
+ type RevokeLinkResult,
46
+ type RevokeMemberInput,
47
+ type RevokeMemberResult,
48
+ type Scope,
49
+ } from '@fabrika/auth-core'
50
+ import { EmailDeliveryError, type EmailMessage } from '@fabrika/email'
51
+ import { uuidv7 } from '@fabrika/platform'
52
+ import { appQuery, presentationFor } from './app-presentation'
53
+ import { type CallerResolution, resolveCaller, resolveLinkCaller } from './auth'
54
+ import { contractGrantProblem, externalGrantProblem } from './contract-rules'
55
+ import {
56
+ type AppMembersRow,
57
+ type AppScopeRow,
58
+ type AuditEventInput,
59
+ auditLabelOf,
60
+ type DelegatedEndpointRow,
61
+ type InvitationRow,
62
+ type InviterCheck,
63
+ type PrincipalRow,
64
+ principalStatus,
65
+ type RoleRow,
66
+ } from './db'
67
+ import { issuerAuthority } from './delegation'
68
+ import type { Env, RequestContext } from './env'
69
+ import { admitted, organizationMailbox } from './human-admission'
70
+ import { logError } from './log'
71
+ import { EMAIL_SEND_DEADLINE_MS, renderEmail } from './messages'
72
+ import { randomToken } from './oidc'
73
+ import type { StoredPasswordHash } from './password-crypto'
74
+ import { parseLocale } from './person-locale'
75
+ import { unixNow } from './repositories/sql'
76
+ import { authorityDeadline, type HeldEntry, resolveAuthorityAt } from './resolve'
77
+ import { BUILTIN_ROLES } from './roles'
78
+ import { generateToken, hashToken } from './secret'
79
+ import type { Services } from './services'
80
+ import { parseStoredChain } from './stored-chain'
81
+ import { delegatedActions, parseStoredPermissions } from './stored-permissions'
82
+ import { authorityOnTerminal } from './tokens'
83
+
84
+ /** How long an invitation may wait for its addressee. */
85
+ export const INVITATION_TTL_SECONDS = 7 * 24 * 60 * 60
86
+
87
+ /** The path of IAM's page that accepts an invitation; the one-time token rides in the fragment. */
88
+ export const INVITATION_ACCEPT_PATH = '/auth/invitations/accept'
89
+
90
+ const DAY_SECONDS = 24 * 60 * 60
91
+
92
+ type CallerEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'FABRIKA_IAM_PROVISIONING_KEY' | 'ENVIRONMENT'>
93
+
94
+ const NOT_ALLOWED: MembershipFailure = { ok: false, reason: 'not_allowed' }
95
+ const NOT_FOUND: MembershipFailure = { ok: false, reason: 'not_found' }
96
+ const INVALID_DELEGATION: MembershipFailure = { ok: false, reason: 'invalid_delegation' }
97
+
98
+ function invalid(message: string): MembershipFailure {
99
+ return { ok: false, reason: 'invalid_request', message }
100
+ }
101
+
102
+ /** The caller of a membership operation, with its permissions at the verified app as IAM holds them now. */
103
+ interface MemberCaller {
104
+ readonly principal: PrincipalRow
105
+ readonly permissions: PermissionEntry[]
106
+ /** What the principal holds live and until when: what a grant it gives may not outlive (S8). */
107
+ readonly supports: readonly HeldEntry[]
108
+ readonly app: string
109
+ }
110
+
111
+ type CallerOutcome = { ok: true; caller: MemberCaller } | MembershipFailure
112
+
113
+ /**
114
+ * Resolve the caller and its LIVE permissions, never more than its credential carries. A token's `perms`
115
+ * are a snapshot up to five minutes old, so only the entries the principal still holds count; a `px_` key
116
+ * is already resolved live, downscoped by its own grants. An
117
+ * anonymous credential, a share link included, is never a member caller. `userOnly` refuses a service
118
+ * principal: a workload creates no scope and manages no member, so a form plus a job cannot sign anyone up.
119
+ */
120
+ async function resolveMemberCaller(services: Services, env: CallerEnv, input: MembershipCaller, userOnly: boolean): Promise<CallerOutcome> {
121
+ return memberCallerOf(services, input, await resolveCaller(services, env, input), userOnly)
122
+ }
123
+
124
+ async function memberCallerOf(services: Services, input: MembershipCaller, resolution: CallerResolution, userOnly: boolean): Promise<CallerOutcome> {
125
+ if (!resolution.ok) {
126
+ return { ok: false, reason: resolution.reason }
127
+ }
128
+ const { caller, verifiedApp } = resolution
129
+ if (caller.type === undefined || (userOnly && caller.type !== 'user')) {
130
+ return NOT_ALLOWED
131
+ }
132
+ const principal = await services.repositories.principals.getPrincipalById(caller.id)
133
+ if (principal === null) {
134
+ return { ok: false, reason: 'unknown_principal' }
135
+ }
136
+ if (principalStatus(principal) === 'disabled') {
137
+ return { ok: false, reason: 'disabled' }
138
+ }
139
+ const live = await resolveAuthorityAt(services, principal, verifiedApp)
140
+ if (input.credential?.startsWith(API_KEY_PREFIX) === true) {
141
+ return { ok: true, caller: { principal, permissions: caller.permissions, supports: live.supports, app: verifiedApp } }
142
+ }
143
+ // A token is a ceiling too: one minted from a downscoped key carries only that key's grants. A person's token from a
144
+ // terminal is held to what that terminal brings now: the ceiling-narrowed person and the terminal's own grants.
145
+ const held = caller.terminal === undefined ? live : await authorityOnTerminal(services, principal, caller.terminal, verifiedApp)
146
+ if (held === null) {
147
+ return { ok: false, reason: 'invalid_token' }
148
+ }
149
+ const permissions = caller.permissions.filter((entry) => permits(held.permissions, entry.action, entry.scope ?? undefined))
150
+ return { ok: true, caller: { principal, permissions, supports: held.supports, app: verifiedApp } }
151
+ }
152
+
153
+ /**
154
+ * The caller of a link operation. A job is admitted only while the app's schema declares that it issues a link mount
155
+ * (`app_workloads.issues`, reconciled from the approved artifact): `job` names it and that mount, null for a member
156
+ * caller. A job's permissions are its declared actions, app-wide, never more than its token carries.
157
+ */
158
+ interface IssuingJob {
159
+ readonly name: string
160
+ readonly issues: string
161
+ /** The job's declared actions as IAM read them: the issuance is written only while they are still declared. */
162
+ readonly actions: readonly string[]
163
+ }
164
+
165
+ type LinkCallerOutcome = { ok: true; caller: MemberCaller; job: IssuingJob | null } | MembershipFailure
166
+
167
+ async function resolveLinkOperationCaller(services: Services, env: CallerEnv, input: MembershipCaller): Promise<LinkCallerOutcome> {
168
+ const resolution = await resolveLinkCaller(services, env, input)
169
+ if (!resolution.ok) {
170
+ return { ok: false, reason: resolution.reason }
171
+ }
172
+ const { verifiedApp } = resolution
173
+ const { type, ...caller } = resolution.caller
174
+ if (type !== 'job') {
175
+ const member = await memberCallerOf(
176
+ services,
177
+ input,
178
+ { ok: true, caller: { ...caller, ...(type === undefined ? {} : { type }) }, verifiedApp },
179
+ false,
180
+ )
181
+ return member.ok ? { ...member, job: null } : member
182
+ }
183
+ const principal = await services.repositories.principals.getPrincipalById(caller.id)
184
+ if (principal === null) {
185
+ return { ok: false, reason: 'unknown_principal' }
186
+ }
187
+ if (principalStatus(principal) === 'disabled') {
188
+ return { ok: false, reason: 'disabled' }
189
+ }
190
+ const workload = await services.repositories.workloads.getByPrincipal(principal.id)
191
+ if (workload === null || workload.kind !== 'job' || workload.app !== verifiedApp) {
192
+ return NOT_ALLOWED
193
+ }
194
+ const declaration = await services.repositories.workloads.declaration(workload.app, 'job', workload.name)
195
+ if (declaration === null || declaration.issues === null) {
196
+ return NOT_ALLOWED
197
+ }
198
+ const permissions = caller.permissions.filter((entry) => entry.scope === null && declaration.actions.includes(entry.action))
199
+ return {
200
+ ok: true,
201
+ caller: { principal, permissions, supports: permissions.map((entry) => ({ action: entry.action, scope: null, until: null })), app: verifiedApp },
202
+ job: { name: workload.name, issues: declaration.issues, actions: declaration.actions },
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Spend the request's delegation grant. It is consumed BEFORE its binding is compared, as a handoff code
208
+ * is, so every attempt is single-use, a mismatched one included. The endpoint is read from the schema
209
+ * again: a grant for an endpoint the app no longer declares, or for another purpose or dimension, buys nothing.
210
+ */
211
+ async function spendDelegation(
212
+ services: Services,
213
+ caller: MemberCaller,
214
+ input: { delegation: string; requestId: string },
215
+ purpose: DelegatedEndpointRow['purpose'],
216
+ dimension: string,
217
+ ): Promise<{ ok: true; endpoint: DelegatedEndpointRow } | MembershipFailure> {
218
+ const grant = await services.repositories.membership.consumeDelegationGrant(await hashToken(input.delegation), unixNow())
219
+ if (grant === null || grant.app !== caller.app || grant.principal_id !== caller.principal.id || grant.request_id !== input.requestId) {
220
+ return INVALID_DELEGATION
221
+ }
222
+ const endpoint = await services.repositories.appSchema.getDelegatedEndpoint(caller.app, grant.endpoint)
223
+ if (endpoint === null || endpoint.purpose !== purpose || endpoint.dimension !== dimension) {
224
+ return INVALID_DELEGATION
225
+ }
226
+ return { ok: true, endpoint }
227
+ }
228
+
229
+ /** The dimension of `scope`, when it declares members, and the caller holds its `members.manage` there. */
230
+ async function manageAuthority(
231
+ services: Services,
232
+ actor: { app: string; permissions: PermissionEntry[] },
233
+ scope: Scope,
234
+ ): Promise<{ ok: true; dimension: AppScopeRow; manage: string } | MembershipFailure> {
235
+ const dimension = await services.repositories.appSchema.getScope(actor.app, scope.type)
236
+ if (dimension === null || dimension.members_manage === null) {
237
+ return invalid(`scope '${scope.type}' declares no members`)
238
+ }
239
+ if (!permits(actor.permissions, dimension.members_manage, scope)) {
240
+ return NOT_ALLOWED
241
+ }
242
+ return { ok: true, dimension, manage: dimension.members_manage }
243
+ }
244
+
245
+ /**
246
+ * Could `actor` give `role` in `scope`? The role is a membership role of the scope's dimension, the actor
247
+ * holds a role that `assignableBy` names — there, or an application-wide role globally — and the role grants
248
+ * nothing the actor lacks there, its `via` actions included. The same question decides an assignment, a revocation and, again at
249
+ * acceptance, an invitation.
250
+ */
251
+ async function roleAuthorityProblem(
252
+ services: Services,
253
+ actor: { app: string; principalId: string; permissions: PermissionEntry[] },
254
+ scope: Scope,
255
+ role: RoleRow,
256
+ ): Promise<MembershipFailure | null> {
257
+ if (role.member_scope !== scope.type || Object.hasOwn(BUILTIN_ROLES, role.role_key)) {
258
+ return invalid(`role '${role.role_key}' is not a membership role of scope '${scope.type}'`)
259
+ }
260
+ const assigners = role.assignable_by === null ? [] : parseJsonStringArray(role.assignable_by)
261
+ const held = (await services.repositories.membership.listAssigningGrants(actor.app, actor.principalId, scope)).map((grant) => grant.role_key)
262
+ if (!assigners.some((assigner) => held.includes(assigner))) {
263
+ return NOT_ALLOWED
264
+ }
265
+ // Its via actions too: a grant of the role there carries them inside the value, so whoever gives it holds them there.
266
+ if (!delegatedActions(role).every((action) => permits(actor.permissions, action, scope))) {
267
+ return NOT_ALLOWED
268
+ }
269
+ const contract = await contractGrantProblem(services.repositories.appSchema, actor.app, {
270
+ roleKey: role.role_key,
271
+ permissions: null,
272
+ scopeType: scope.type,
273
+ })
274
+ return contract === null ? null : invalid(contract)
275
+ }
276
+
277
+ /**
278
+ * The latest expiry a grant of `role` in `scope` given by `actor` may carry (S8): no later than the earliest expiry
279
+ * among the grants that authorize it — the assigning role held there or globally, the dimension's `manage` action and
280
+ * every action of the role there, its `via` actions included. `null` is no expiry. Asked only after `roleAuthorityProblem` admitted the actor.
281
+ */
282
+ async function delegationDeadline(
283
+ services: Services,
284
+ actor: { app: string; principalId: string; supports: readonly HeldEntry[] },
285
+ scope: Scope,
286
+ role: RoleRow,
287
+ manage: string,
288
+ ): Promise<number | null> {
289
+ const assigners = role.assignable_by === null ? [] : parseJsonStringArray(role.assignable_by)
290
+ const assigning = (await services.repositories.membership.listAssigningGrants(actor.app, actor.principalId, scope))
291
+ .filter((grant) => grant.role_key !== null && assigners.includes(grant.role_key))
292
+ const now = unixNow()
293
+ const assignerUntil = assigning.some((grant) => grant.expires_at === null)
294
+ ? null
295
+ : Math.max(now, ...assigning.map((grant) => grant.expires_at ?? now))
296
+ const carried = [manage, ...delegatedActions(role)].map((action): PermissionEntry => ({ action, scope, source: 'grant' }))
297
+ return earliest(assignerUntil, authorityDeadline(actor, carried, now))
298
+ }
299
+
300
+ /** The earlier of two deadlines, where `null` is none. */
301
+ function earliest(a: number | null, b: number | null): number | null {
302
+ return a === null ? b : b === null ? a : Math.min(a, b)
303
+ }
304
+
305
+ /** The record of a change the caller made. The repository writes it in the change's own transaction. */
306
+ function memberEvent(
307
+ caller: MemberCaller,
308
+ requestId: string,
309
+ event: { action: string; resourceType: string; resourceId: string; metadata?: unknown },
310
+ ): AuditEventInput {
311
+ return { requestId, principalId: caller.principal.id, principalLabel: auditLabelOf(caller.principal), app: caller.app, ...event }
312
+ }
313
+
314
+ function scopeId(scope: Scope): string {
315
+ return `${scope.type}:${scope.value}`
316
+ }
317
+
318
+ // ── Delegation grants ─────────────────────────────────────────────────────────
319
+
320
+ export async function requestDelegation(
321
+ services: Services,
322
+ env: CallerEnv,
323
+ ctx: RequestContext,
324
+ input: RequestDelegationInput,
325
+ ): Promise<RequestDelegationResult> {
326
+ const resolved = await resolveMemberCaller(services, env, input, true)
327
+ if (!resolved.ok) return resolved
328
+ const { caller } = resolved
329
+ const endpoint = await services.repositories.appSchema.getDelegatedEndpoint(caller.app, input.endpoint)
330
+ if (endpoint === null) {
331
+ return invalid(`endpoint '${input.endpoint}' declares no membership operation`)
332
+ }
333
+ if (!caller.permissions.some((entry) => matchAction(entry.action, endpoint.action))) {
334
+ return NOT_ALLOWED
335
+ }
336
+ const grant = generateToken()
337
+ const expiresAt = unixNow() + DELEGATION_GRANT_TTL_SECONDS
338
+ await services.repositories.membership.issueDelegationGrant({
339
+ grantHash: await hashToken(grant),
340
+ app: caller.app,
341
+ principalId: caller.principal.id,
342
+ endpoint: endpoint.endpoint,
343
+ requestId: input.requestId,
344
+ expiresAt,
345
+ })
346
+ return { ok: true, grant, expiresAt }
347
+ }
348
+
349
+ // ── Scope creation ────────────────────────────────────────────────────────────
350
+
351
+ /**
352
+ * A value of a top-level dimension. The caller holds the creating endpoint's action globally: a value it
353
+ * does not yet belong to cannot be the scope of its authority. A contained dimension's values are rows of
354
+ * the application, not values IAM creates.
355
+ */
356
+ export async function createScope(services: Services, env: CallerEnv, ctx: RequestContext, input: CreateScopeInput): Promise<CreateScopeResult> {
357
+ const resolved = await resolveMemberCaller(services, env, input, true)
358
+ if (!resolved.ok) return resolved
359
+ const { caller } = resolved
360
+ const spent = await spendDelegation(services, caller, input, 'creates', input.dimension)
361
+ if (!spent.ok) return spent
362
+ const dimension = await services.repositories.appSchema.getScope(caller.app, input.dimension)
363
+ if (dimension === null || dimension.creator_role === null || dimension.parent_scope !== null) {
364
+ return invalid(`scope '${input.dimension}' is not created by IAM: it needs a creator role and no containing scope`)
365
+ }
366
+ if (!permits(caller.permissions, spent.endpoint.action)) {
367
+ return NOT_ALLOWED
368
+ }
369
+ const role = await services.repositories.appSchema.getRole(caller.app, dimension.creator_role)
370
+ if (role === null || role.member_scope !== input.dimension || Object.hasOwn(BUILTIN_ROLES, role.role_key)) {
371
+ return invalid(`the creator role '${dimension.creator_role}' is not a membership role of scope '${input.dimension}'`)
372
+ }
373
+ const contract = await contractGrantProblem(services.repositories.appSchema, caller.app, {
374
+ roleKey: role.role_key,
375
+ permissions: null,
376
+ scopeType: input.dimension,
377
+ })
378
+ if (contract !== null) return invalid(contract)
379
+ const external = await externalGrantProblem(services.repositories.appSchema, caller.principal, caller.app, { roleKey: role.role_key })
380
+ if (external !== null) return invalid(external)
381
+ const scope: Scope = { type: input.dimension, value: uuidv7() }
382
+ // The creator gives itself the role on the strength of the creating action, so the grant ends when that action does.
383
+ const expiresAt = authorityDeadline(caller, [{ action: spent.endpoint.action, scope: null, source: 'grant' }], unixNow())
384
+ const created = await services.repositories.membership.createScope(
385
+ { app: caller.app, scope, createdBy: caller.principal.id, roleKey: role.role_key, expiresAt },
386
+ memberEvent(caller, input.requestId, {
387
+ action: 'iam.scope.create',
388
+ resourceType: 'scope',
389
+ resourceId: scopeId(scope),
390
+ metadata: { role: role.role_key, endpoint: spent.endpoint.endpoint },
391
+ }),
392
+ )
393
+ if (!created) {
394
+ // A reconcile narrowed the creator role after the check above; the write carries the condition itself.
395
+ return invalid(`the creator role '${role.role_key}' is not declared external, and the caller is an external principal`)
396
+ }
397
+ return { ok: true, scope, role: role.role_key }
398
+ }
399
+
400
+ // ── Membership ────────────────────────────────────────────────────────────────
401
+
402
+ /**
403
+ * Assign a role, or invite an address to it. An address always becomes an invitation, also when a
404
+ * principal already holds it: only the mailbox's owner, proving it with the emailed link, may accept.
405
+ */
406
+ export async function assignMember(services: Services, env: CallerEnv, ctx: RequestContext, input: AssignMemberInput): Promise<AssignMemberResult> {
407
+ const resolved = await resolveMemberCaller(services, env, input, true)
408
+ if (!resolved.ok) return resolved
409
+ const { caller } = resolved
410
+ const spent = await spendDelegation(services, caller, input, 'members', input.scope.type)
411
+ if (!spent.ok) return spent
412
+ const problem = membershipScopeProblem(input.scope)
413
+ if (problem !== null) return invalid(problem)
414
+ const manage = await manageAuthority(services, caller, input.scope)
415
+ if (!manage.ok) return manage
416
+ const role = await services.repositories.appSchema.getRole(caller.app, input.role)
417
+ if (role === null) {
418
+ return invalid(`unknown role '${input.role}'`)
419
+ }
420
+ const authority = await roleAuthorityProblem(services, { ...caller, principalId: caller.principal.id }, input.scope, role)
421
+ if (authority !== null) return authority
422
+
423
+ if ('principalId' in input.member) {
424
+ if (input.invitation !== undefined) {
425
+ return invalid('a label, a message, a locale and a resend go with an invitation by address')
426
+ }
427
+ const target = await services.repositories.principals.getPrincipalById(input.member.principalId)
428
+ if (target === null || target.type !== 'user') {
429
+ return NOT_FOUND
430
+ }
431
+ const external = await externalGrantProblem(services.repositories.appSchema, target, caller.app, { roleKey: role.role_key })
432
+ if (external !== null) return invalid(external)
433
+ // The same rule whoever the target is, the caller itself included: the grant ends with the authority behind it.
434
+ const expiresAt = await delegationDeadline(services, { ...caller, principalId: caller.principal.id }, input.scope, role, manage.manage)
435
+ const granted = await services.repositories.membership.grantMembershipRole(
436
+ { app: caller.app, principalId: target.id, roleKey: role.role_key, scope: input.scope, grantedBy: caller.principal.id, expiresAt },
437
+ memberEvent(caller, input.requestId, {
438
+ action: 'iam.member.assign',
439
+ resourceType: 'scope',
440
+ resourceId: scopeId(input.scope),
441
+ metadata: { principalId: target.id, role: role.role_key },
442
+ }),
443
+ )
444
+ const eligible = { principalId: target.id, app: caller.app, roleKey: role.role_key }
445
+ if (granted === null && !(await services.repositories.grants.isEligibleGrant(eligible))) {
446
+ // Not held but refused: a reconcile narrowed the role after the check above.
447
+ return invalid(`role '${role.role_key}' is not declared external, and the member is an external principal`)
448
+ }
449
+ return { ok: true, assigned: { principalId: target.id, role: role.role_key } }
450
+ }
451
+
452
+ return invite(services, caller, input, role, input.member.email, input.invitation ?? {})
453
+ }
454
+
455
+ /**
456
+ * Open an invitation and mail its link, or answer the open one. Repeating it sends nothing; `resend` gives the open
457
+ * invitation a new link and a new lifetime and sends that, so the earlier link stops working. A role declared external
458
+ * creates its principal at acceptance for a mailbox no principal holds, so IAM refuses one the organization names
459
+ * (`organizationMailbox`) before anything is written: it never becomes an external principal.
460
+ */
461
+ async function invite(
462
+ services: Services,
463
+ caller: MemberCaller,
464
+ input: AssignMemberInput,
465
+ role: RoleRow,
466
+ address: string,
467
+ options: InvitationOptions,
468
+ ): Promise<AssignMemberResult> {
469
+ if (services.email === null) {
470
+ return { ok: false, reason: 'invitations_disabled' }
471
+ }
472
+ const email = invitedAddress(address)
473
+ if (email === null) {
474
+ return invalid('the member email is not an address')
475
+ }
476
+ const wording = invitationOptionsProblem(options)
477
+ if (wording !== null) {
478
+ return invalid(wording)
479
+ }
480
+ if (role.external === 1 && organizationMailbox(email, services.config)) {
481
+ return { ok: false, reason: 'internal_mailbox' }
482
+ }
483
+ const companyLabel = nonEmpty(options.label)
484
+ const message = nonEmpty(options.message)
485
+ const locale = options.locale ?? null
486
+ const token = randomToken(32)
487
+ const tokenHash = await hashToken(token)
488
+ const expiresAt = unixNow() + INVITATION_TTL_SECONDS
489
+ const event = (action: string, invitationId: string) =>
490
+ memberEvent(caller, input.requestId, {
491
+ action,
492
+ resourceType: 'scope',
493
+ resourceId: scopeId(input.scope),
494
+ metadata: { invitationId, role: role.role_key },
495
+ })
496
+ const opened = await services.repositories.membership.openInvitation({
497
+ tokenHash,
498
+ app: caller.app,
499
+ scope: input.scope,
500
+ roleKey: role.role_key,
501
+ email,
502
+ invitedBy: caller.principal.id,
503
+ expiresAt,
504
+ companyLabel,
505
+ message,
506
+ locale,
507
+ }, (invitationId) => event('iam.member.invite', invitationId))
508
+ let invitation = opened.invitation
509
+ if (!opened.created) {
510
+ if (options.resend !== true) {
511
+ return invitedResult(invitation)
512
+ }
513
+ const rotated = await services.repositories.membership.rotateInvitation(
514
+ { id: invitation.id, tokenHash, expiresAt, companyLabel, message, locale },
515
+ event('iam.member.reinvite', invitation.id),
516
+ )
517
+ if (rotated === null) {
518
+ // Accepted or cancelled since it was read: nothing open is left to send again.
519
+ return NOT_FOUND
520
+ }
521
+ invitation = rotated
522
+ }
523
+ const withdrawCreated = async (): Promise<void> => {
524
+ if (!opened.created) return
525
+ await services.repositories.membership.deleteInvitation(
526
+ invitation.id,
527
+ memberEvent(caller, input.requestId, {
528
+ action: 'iam.member.uninvite',
529
+ resourceType: 'scope',
530
+ resourceId: scopeId(input.scope),
531
+ metadata: { invitationId: invitation.id, role: role.role_key, reason: 'delivery_failed' },
532
+ }),
533
+ )
534
+ }
535
+ // A resend is a new message with a new link: the sender must not take it for a retry of the first.
536
+ const idempotencyKey = opened.created ? `iam-invitation-${invitation.id}` : `iam-invitation-${invitation.id}-${uuidv7()}`
537
+ let invitationMessage: EmailMessage
538
+ try {
539
+ invitationMessage = await invitationEmail(services, caller, invitation, role, token, idempotencyKey)
540
+ } catch (err) {
541
+ await withdrawCreated()
542
+ throw err
543
+ }
544
+ try {
545
+ await services.email.send(invitationMessage, AbortSignal.timeout(EMAIL_SEND_DEADLINE_MS))
546
+ } catch (err) {
547
+ logError(`invitation email failed for request '${input.requestId}'`, err)
548
+ // The link may have arrived, so the invitation it names stays open.
549
+ const mayHaveArrived = err instanceof EmailDeliveryError && err.outcome === 'unknown'
550
+ if (!mayHaveArrived) await withdrawCreated()
551
+ // A resent invitation stays open under a link that may not have arrived; resending again sends a new one.
552
+ return { ok: false, reason: 'delivery_failed' }
553
+ }
554
+ return invitedResult(invitation)
555
+ }
556
+
557
+ function invitedResult(invitation: InvitationRow): AssignMemberResult {
558
+ return { ok: true, invited: { invitationId: invitation.id, role: invitation.role_key, expiresAt: invitation.expires_at } }
559
+ }
560
+
561
+ function nonEmpty(value: string | undefined): string | null {
562
+ return value === undefined || value === '' ? null : value
563
+ }
564
+
565
+ /**
566
+ * The invitation's e-mail, with the link to `token`, in its application's wording: in the language the invitation names,
567
+ * else the language the mailbox's principal keeps, else the application's.
568
+ */
569
+ async function invitationEmail(
570
+ services: Services,
571
+ caller: MemberCaller,
572
+ invitation: InvitationRow,
573
+ role: RoleRow,
574
+ token: string,
575
+ idempotencyKey: string,
576
+ ): Promise<EmailMessage> {
577
+ // An e-mail shows no logo, so the brand is not read.
578
+ const holder = invitation.locale === null ? await services.repositories.principals.getUserByEmail(invitation.email) : null
579
+ const presentation = await presentationFor(services, invitation.app, { brand: null, locale: invitation.locale ?? holder?.locale ?? null })
580
+ // The query names the application for the page's language; the fragment never reaches an access log, and the
581
+ // page copies it into its POST form in the browser.
582
+ const url = new URL(`${INVITATION_ACCEPT_PATH}${appQuery(presentation)}`, services.config.issuer)
583
+ url.hash = new URLSearchParams({ token }).toString()
584
+ return renderEmail(services, {
585
+ to: invitation.email,
586
+ presentation,
587
+ kind: 'invitation',
588
+ values: {
589
+ appName: presentation.displayName ?? invitation.app,
590
+ role: role.name,
591
+ scope: invitation.scope_type,
592
+ recipient: invitation.email,
593
+ inviterLabel: caller.principal.label,
594
+ companyLabel: invitation.company_label ?? '',
595
+ message: invitation.message ?? '',
596
+ actionUrl: url.toString(),
597
+ expiresAt: invitation.expires_at,
598
+ acceptance: await invitationAcceptance(services, invitation),
599
+ },
600
+ idempotencyKey,
601
+ })
602
+ }
603
+
604
+ /**
605
+ * Remove membership roles, or cancel an invitation. Every role removed must be one the caller could
606
+ * assign, checked before anything is removed. The creator role goes first and only while another
607
+ * principal still holds it, so a value never loses its last creator.
608
+ */
609
+ export async function revokeMember(services: Services, env: CallerEnv, ctx: RequestContext, input: RevokeMemberInput): Promise<RevokeMemberResult> {
610
+ const resolved = await resolveMemberCaller(services, env, input, true)
611
+ if (!resolved.ok) return resolved
612
+ const { caller } = resolved
613
+ const spent = await spendDelegation(services, caller, input, 'members', input.scope.type)
614
+ if (!spent.ok) return spent
615
+ const problem = membershipScopeProblem(input.scope)
616
+ if (problem !== null) return invalid(problem)
617
+ const manage = await manageAuthority(services, caller, input.scope)
618
+ if (!manage.ok) return manage
619
+ const actor = { ...caller, principalId: caller.principal.id }
620
+
621
+ if ('invitationId' in input.member) {
622
+ const invitation = await services.repositories.membership.getInvitationById(input.member.invitationId)
623
+ if (invitation === null || invitation.app !== caller.app || !sameScope(invitation, input.scope)) {
624
+ return NOT_FOUND
625
+ }
626
+ const role = await services.repositories.appSchema.getRole(caller.app, invitation.role_key)
627
+ const authority = role === null ? null : await roleAuthorityProblem(services, actor, input.scope, role)
628
+ if (authority !== null) return authority
629
+ await services.repositories.membership.revokeInvitation(
630
+ invitation.id,
631
+ memberEvent(caller, input.requestId, {
632
+ action: 'iam.member.uninvite',
633
+ resourceType: 'scope',
634
+ resourceId: scopeId(input.scope),
635
+ metadata: { invitationId: invitation.id, role: invitation.role_key },
636
+ }),
637
+ )
638
+ return { ok: true }
639
+ }
640
+
641
+ const target = input.member.principalId
642
+ const only = input.member.role ?? null
643
+ const roles: RoleRow[] = []
644
+ if (only !== null) {
645
+ const role = await services.repositories.appSchema.getRole(caller.app, only)
646
+ if (role === null || role.member_scope !== input.scope.type) {
647
+ return invalid(`role '${only}' is not a membership role of scope '${input.scope.type}'`)
648
+ }
649
+ }
650
+ for (const grant of await services.repositories.membership.listRoleGrantsAt(caller.app, target, input.scope)) {
651
+ if (grant.role_key === null || (only !== null && grant.role_key !== only)) continue
652
+ const role = await services.repositories.appSchema.getRole(caller.app, grant.role_key)
653
+ if (role !== null && role.member_scope === input.scope.type) roles.push(role)
654
+ }
655
+ for (const role of roles) {
656
+ const authority = await roleAuthorityProblem(services, actor, input.scope, role)
657
+ if (authority !== null) return authority
658
+ }
659
+
660
+ if (roles.length === 0) {
661
+ return { ok: true }
662
+ }
663
+ const creator = manage.dimension.creator_role
664
+ const removed = await services.repositories.membership.revokeMemberRoles(
665
+ { app: caller.app, principalId: target, scope: input.scope, roles: roles.map((role) => role.role_key), creatorRole: creator },
666
+ (roleKey) =>
667
+ memberEvent(caller, input.requestId, {
668
+ action: 'iam.member.revoke',
669
+ resourceType: 'scope',
670
+ resourceId: scopeId(input.scope),
671
+ metadata: { principalId: target, role: roleKey },
672
+ }),
673
+ )
674
+ if (creator !== null && roles.some((role) => role.role_key === creator) && !removed.includes(creator)) {
675
+ const stillHeld = (await services.repositories.membership.listRoleGrantsAt(caller.app, target, input.scope))
676
+ .some((grant) => grant.role_key === creator)
677
+ if (stillHeld) return { ok: false, reason: 'last_creator' }
678
+ }
679
+ return { ok: true }
680
+ }
681
+
682
+ function sameScope(invitation: InvitationRow, scope: Scope): boolean {
683
+ return invitation.scope_type === scope.type && invitation.scope_value === scope.value
684
+ }
685
+
686
+ export async function listMembers(services: Services, env: CallerEnv, ctx: RequestContext, input: ListMembersInput): Promise<ListMembersResult> {
687
+ const resolved = await resolveMemberCaller(services, env, input, false)
688
+ if (!resolved.ok) return resolved
689
+ const { caller } = resolved
690
+ const problem = membershipScopeProblem(input.scope)
691
+ if (problem !== null) return invalid(problem)
692
+ const dimension = await services.repositories.appSchema.getScope(caller.app, input.scope.type)
693
+ if (dimension === null || dimension.members_list === null) {
694
+ return invalid(`scope '${input.scope.type}' declares no members`)
695
+ }
696
+ if (!permits(caller.permissions, dimension.members_list, input.scope)) {
697
+ return NOT_ALLOWED
698
+ }
699
+ const manager = dimension.members_manage !== null && permits(caller.permissions, dimension.members_manage, input.scope)
700
+ const members = new Map<string, MemberItem>()
701
+ for (const row of await services.repositories.membership.listMemberGrants(caller.app, input.scope)) {
702
+ const member = members.get(row.principal_id)
703
+ if (member === undefined) {
704
+ members.set(row.principal_id, {
705
+ principalId: row.principal_id,
706
+ label: manager || dimension.members_directory === 'labels' ? row.label : null,
707
+ email: manager ? row.email : null,
708
+ lastSignInAt: manager ? row.signed_in_at : null,
709
+ roles: [row.role_key],
710
+ disabled: row.disabled_at !== null,
711
+ affiliation: row.affiliation,
712
+ })
713
+ } else {
714
+ member.roles.push(row.role_key)
715
+ }
716
+ }
717
+ const invitations = manager
718
+ ? (await services.repositories.membership.listOpenInvitations(caller.app, input.scope)).map((row) => ({
719
+ id: row.id,
720
+ email: row.email,
721
+ role: row.role_key,
722
+ expiresAt: row.expires_at,
723
+ }))
724
+ : []
725
+ return { ok: true, members: [...members.values()], invitations }
726
+ }
727
+
728
+ /**
729
+ * One principal among the members of `scope`, for an endpoint on, in or below its dimension. IAM establishes the
730
+ * authority itself, from nothing the application asserts: `action` must be one of the dimension's `lookups` (the
731
+ * actions of the approved endpoints that read this directory, from the reconciled schema), and the caller must hold it
732
+ * on `scope` itself (global included). IAM holds no containment below a value, so a grant on a contained object does
733
+ * not count. The caller learns only whether the principal it named is a member, and its label where the directory
734
+ * shows labels; an unknown id answers the same `null` as a non-member.
735
+ */
736
+ /**
737
+ * One page of the application's own people: every principal holding a role of it (`listAppMemberIds`). Needs the
738
+ * application's `members.list` held globally; labels where it declares `directory: 'labels'` or to its `members.manage`
739
+ * held globally, which alone sees addresses and last sign-ins.
740
+ */
741
+ export async function listAppMembers(
742
+ services: Services,
743
+ env: CallerEnv,
744
+ _ctx: RequestContext,
745
+ input: ListAppMembersInput,
746
+ ): Promise<ListAppMembersResult> {
747
+ const resolved = await resolveMemberCaller(services, env, input, false)
748
+ if (!resolved.ok) return resolved
749
+ const { caller } = resolved
750
+ const people = await services.repositories.appSchema.getAppMembers(caller.app)
751
+ if (people === null) {
752
+ return invalid('the application declares no members')
753
+ }
754
+ if (!permits(caller.permissions, people.list)) {
755
+ return NOT_ALLOWED
756
+ }
757
+ const limit = input.limit ?? MAX_APP_MEMBERS_PAGE
758
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_APP_MEMBERS_PAGE) {
759
+ return invalid(`a page holds 1 to ${MAX_APP_MEMBERS_PAGE} members`)
760
+ }
761
+ if (input.after !== undefined && (input.after === '' || input.after.length > MAX_MEMBERSHIP_SCOPE_PART_LENGTH)) {
762
+ return invalid('after is the next of a previous page')
763
+ }
764
+ const page = await appMemberPage(services, caller.app, people, permits(caller.permissions, people.manage), input.after ?? null, limit)
765
+ return { ok: true, ...page }
766
+ }
767
+
768
+ /**
769
+ * One page of the people of `app`, as a holder of its `members.list` sees them; `manager` adds labels, addresses and last
770
+ * sign-ins. `next` is the page's last id while another principal follows it, null on the last page.
771
+ */
772
+ export async function appMemberPage(
773
+ services: Services,
774
+ app: string,
775
+ people: AppMembersRow,
776
+ manager: boolean,
777
+ after: string | null,
778
+ limit: number,
779
+ ): Promise<{ members: AppMemberItem[]; next: string | null }> {
780
+ const read = await services.repositories.membership.listAppMemberIds(app, after, limit + 1)
781
+ const ids = read.slice(0, limit)
782
+ const members = new Map<string, AppMemberItem>()
783
+ for (const row of await services.repositories.membership.listAppMemberGrants(app, ids)) {
784
+ const scope = row.scope_type === null || row.scope_value === null ? null : { type: row.scope_type, value: row.scope_value }
785
+ const member = members.get(row.principal_id)
786
+ if (member === undefined) {
787
+ members.set(row.principal_id, {
788
+ principalId: row.principal_id,
789
+ label: manager || people.directory === 'labels' ? row.label : null,
790
+ email: manager ? row.email : null,
791
+ lastSignInAt: manager ? row.signed_in_at : null,
792
+ roles: [{ role: row.role_key, scope }],
793
+ disabled: row.disabled_at !== null,
794
+ affiliation: row.affiliation,
795
+ })
796
+ } else {
797
+ member.roles.push({ role: row.role_key, scope })
798
+ }
799
+ }
800
+ for (const member of members.values()) {
801
+ member.roles.sort((a, b) => byCodeUnit(a.role, b.role) || byCodeUnit(scopeKey(a.scope), scopeKey(b.scope)))
802
+ }
803
+ const listed = ids.flatMap((id) => {
804
+ const member = members.get(id)
805
+ return member === undefined ? [] : [member]
806
+ })
807
+ return { members: listed, next: read.length > limit ? (ids.at(-1) ?? null) : null }
808
+ }
809
+
810
+ /** A global grant first, then values by type and value. */
811
+ function scopeKey(scope: Scope | null): string {
812
+ return scope === null ? '' : `${scope.type}\u0000${scope.value}`
813
+ }
814
+
815
+ function byCodeUnit(a: string, b: string): number {
816
+ return a < b ? -1 : a > b ? 1 : 0
817
+ }
818
+
819
+ export async function findMember(services: Services, env: CallerEnv, ctx: RequestContext, input: FindMemberInput): Promise<FindMemberResult> {
820
+ const resolved = await resolveMemberCaller(services, env, input, false)
821
+ if (!resolved.ok) return resolved
822
+ const { caller } = resolved
823
+ const problem = membershipScopeProblem(input.scope)
824
+ if (problem !== null) return invalid(problem)
825
+ const dimension = await services.repositories.appSchema.getScope(caller.app, input.scope.type)
826
+ if (dimension === null || dimension.members_list === null) {
827
+ return invalid(`scope '${input.scope.type}' declares no members`)
828
+ }
829
+ const lookups = dimension.members_lookup === null ? [] : parseStoredPermissions(dimension.members_lookup)
830
+ if (!lookups.includes(input.action) || !permits(caller.permissions, input.action, input.scope)) {
831
+ return NOT_ALLOWED
832
+ }
833
+ if (input.principalId === '' || input.principalId.length > MAX_MEMBERSHIP_SCOPE_PART_LENGTH) {
834
+ return { ok: true, member: null }
835
+ }
836
+ const [grant] = await services.repositories.membership.listMemberGrantsOf(caller.app, input.scope, input.principalId)
837
+ if (grant === undefined) {
838
+ return { ok: true, member: null }
839
+ }
840
+ const manager = dimension.members_manage !== null && permits(caller.permissions, dimension.members_manage, input.scope)
841
+ return {
842
+ ok: true,
843
+ member: {
844
+ principalId: grant.principal_id,
845
+ label: manager || dimension.members_directory === 'labels' ? grant.label : null,
846
+ disabled: grant.disabled_at !== null,
847
+ affiliation: grant.affiliation,
848
+ },
849
+ }
850
+ }
851
+
852
+ // ── Invitation acceptance (IAM's own page) ────────────────────────────────────
853
+
854
+ export type AcceptInvitationOutcome =
855
+ | { ok: true; invitation: InvitationRow }
856
+ /** Unknown, used, cancelled or expired: one answer, so a page reveals nothing about a token. */
857
+ | { ok: false; reason: 'invalid' }
858
+ /** The signed-in principal does not own the invited mailbox. */
859
+ | { ok: false; reason: 'wrong_principal' }
860
+ /** The inviter could no longer give the role. */
861
+ | { ok: false; reason: 'not_allowed' }
862
+ /** The signed-in principal is external and the role is not declared external (ADR-0051). */
863
+ | { ok: false; reason: 'not_eligible' }
864
+
865
+ /**
866
+ * Accept an invitation for a signed-in principal. The emailed one-time token proves control of the
867
+ * mailbox, and the principal must own that mailbox. The inviter's authority is checked again here,
868
+ * against its permissions now, and its assigning role once more inside the write that consumes the
869
+ * invitation, so an invitation outlives no revocation of the person who sent it.
870
+ */
871
+ export async function acceptInvitation(
872
+ services: Services,
873
+ principal: PrincipalRow,
874
+ token: string,
875
+ requestId: string,
876
+ ): Promise<AcceptInvitationOutcome> {
877
+ const invitation = await openInvitationOf(services, token)
878
+ if (invitation === null) {
879
+ return { ok: false, reason: 'invalid' }
880
+ }
881
+ if (principal.type !== 'user' || principal.email === null || principal.email !== invitation.email) {
882
+ return { ok: false, reason: 'wrong_principal' }
883
+ }
884
+ if ((await externalGrantProblem(services.repositories.appSchema, principal, invitation.app, { roleKey: invitation.role_key })) !== null) {
885
+ return { ok: false, reason: 'not_eligible' }
886
+ }
887
+ const inviter = await inviterAssigners(services, invitation)
888
+ if (inviter === null) {
889
+ return { ok: false, reason: 'not_allowed' }
890
+ }
891
+ const accepted = await services.repositories.membership.acceptInvitation(
892
+ invitation,
893
+ principal.id,
894
+ inviter,
895
+ acceptanceEvent(invitation, principal.id, requestId),
896
+ )
897
+ if (accepted === 'not_eligible') {
898
+ return { ok: false, reason: 'not_eligible' }
899
+ }
900
+ if (accepted !== 'accepted') {
901
+ return { ok: false, reason: accepted === 'not_allowed' ? 'not_allowed' : 'invalid' }
902
+ }
903
+ // The language the inviting application named becomes the person's: IAM's later mail and pages speak it. The
904
+ // acceptance has committed, and a language picks words only, so a failed write is logged, not answered.
905
+ const locale = parseLocale(invitation.locale)
906
+ if (locale !== null && locale !== principal.locale) {
907
+ try {
908
+ await services.repositories.principals.setLocale(principal.id, locale)
909
+ } catch (err) {
910
+ logError(`the language of accepted invitation '${invitation.id}' could not be kept`, err)
911
+ }
912
+ }
913
+ return { ok: true, invitation }
914
+ }
915
+
916
+ /** The open invitation of a link's one-time token, or null for an unknown, used, cancelled, rotated or expired one. */
917
+ async function openInvitationOf(services: Services, token: string): Promise<InvitationRow | null> {
918
+ const invitation = await services.repositories.membership.getInvitationByHash(await hashToken(token))
919
+ if (invitation === null || invitation.accepted_at !== null || invitation.revoked_at !== null || invitation.expires_at <= unixNow()) {
920
+ return null
921
+ }
922
+ return invitation
923
+ }
924
+
925
+ /**
926
+ * The authority that lets the inviter give the invitation's role there against its permissions now: the roles that make
927
+ * it an assigner, the schema revision read before anything else and the inviter's grant revision read before its
928
+ * permissions, so the acceptance's write requires the declarations and the grants this check read (`InviterCheck`).
929
+ * Null when it could not give the role.
930
+ */
931
+ async function inviterAssigners(services: Services, invitation: InvitationRow): Promise<InviterCheck | null> {
932
+ const revision = await services.repositories.appSchema.getSchemaRevision(invitation.app)
933
+ const inviter = await services.repositories.principals.getPrincipalById(invitation.invited_by)
934
+ const role = await services.repositories.appSchema.getRole(invitation.app, invitation.role_key)
935
+ if (inviter === null || principalStatus(inviter) === 'disabled' || role === null) {
936
+ return null
937
+ }
938
+ const scope: Scope = { type: invitation.scope_type, value: invitation.scope_value }
939
+ const live = await resolveAuthorityAt(services, inviter, invitation.app)
940
+ const actor = { app: invitation.app, principalId: inviter.id, permissions: live.permissions, supports: live.supports }
941
+ const manage = await manageAuthority(services, actor, scope)
942
+ if (!manage.ok || (await roleAuthorityProblem(services, actor, scope, role)) !== null) {
943
+ return null
944
+ }
945
+ return {
946
+ assigners: role.assignable_by === null ? [] : parseJsonStringArray(role.assignable_by),
947
+ revision,
948
+ grantRevision: inviter.grant_revision,
949
+ expiresAt: await delegationDeadline(services, actor, scope, role, manage.manage),
950
+ }
951
+ }
952
+
953
+ /** The record of an acceptance, by the principal that accepted. A user's audit label is its id. */
954
+ function acceptanceEvent(invitation: InvitationRow, principalId: string, requestId: string): AuditEventInput {
955
+ return {
956
+ requestId,
957
+ principalId,
958
+ principalLabel: principalId,
959
+ app: invitation.app,
960
+ action: 'iam.member.accept',
961
+ resourceType: 'scope',
962
+ resourceId: scopeId({ type: invitation.scope_type, value: invitation.scope_value }),
963
+ metadata: { invitationId: invitation.id, role: invitation.role_key },
964
+ }
965
+ }
966
+
967
+ /**
968
+ * What an invitation link offers the browser that submits it. `create`: the role is declared external, the
969
+ * installation enables password authentication and e-mail, no principal holds the invited mailbox, the organization
970
+ * does not name it (`organizationMailbox`), and the inviter could still give the role — so accepting creates the
971
+ * external principal with a password the person chooses (ADR-0020). `no_account`: no principal holds the mailbox and
972
+ * nothing here would create one, so its owner cannot accept until someone gives it an account. `sign_in`: every other
973
+ * open invitation, accepted by the mailbox's principal signed in here. Reading the offer changes nothing.
974
+ */
975
+ export type InvitationOffer =
976
+ | { readonly kind: 'invalid' }
977
+ | { readonly kind: 'not_allowed' }
978
+ | { readonly kind: 'sign_in'; readonly invitation: InvitationRow }
979
+ | { readonly kind: 'no_account'; readonly invitation: InvitationRow }
980
+ | { readonly kind: 'create'; readonly invitation: InvitationRow }
981
+
982
+ export async function invitationOffer(services: Services, token: string): Promise<InvitationOffer> {
983
+ const invitation = await openInvitationOf(services, token)
984
+ if (invitation === null) {
985
+ return { kind: 'invalid' }
986
+ }
987
+ const acceptance = await invitationAcceptance(services, invitation)
988
+ if (acceptance === 'sign_in') {
989
+ return { kind: 'sign_in', invitation }
990
+ }
991
+ if (acceptance === 'no_account') {
992
+ return { kind: 'no_account', invitation }
993
+ }
994
+ return (await inviterAssigners(services, invitation)) === null ? { kind: 'not_allowed' } : { kind: 'create', invitation }
995
+ }
996
+
997
+ /**
998
+ * How the owner of an open invitation's mailbox accepts it now (`InvitationAcceptance`): the e-mail and the accept
999
+ * page say what this answers, and promise a password only when accepting creates the account. A mailbox no principal
1000
+ * holds that single sign-on admits (`admitted`) may still get its principal there, so it is `sign_in`.
1001
+ */
1002
+ export async function invitationAcceptance(services: Services, invitation: InvitationRow): Promise<InvitationAcceptance> {
1003
+ if (await createsPrincipal(services, invitation)) {
1004
+ return 'create'
1005
+ }
1006
+ if ((await services.repositories.principals.getUserByEmail(invitation.email)) !== null) {
1007
+ return 'sign_in'
1008
+ }
1009
+ return services.config.authentication.oidc.enabled && admitted(invitation.email, services.config) ? 'sign_in' : 'no_account'
1010
+ }
1011
+
1012
+ async function createsPrincipal(services: Services, invitation: InvitationRow): Promise<boolean> {
1013
+ if (!services.config.authentication.password.enabled || services.email === null || organizationMailbox(invitation.email, services.config)) {
1014
+ return false
1015
+ }
1016
+ const role = await services.repositories.appSchema.getRole(invitation.app, invitation.role_key)
1017
+ return role?.external === 1 && (await services.repositories.principals.getUserByEmail(invitation.email)) === null
1018
+ }
1019
+
1020
+ export type AcceptCreatingOutcome =
1021
+ | { ok: true; invitation: InvitationRow; principal: PrincipalRow }
1022
+ | { ok: false; reason: 'invalid' | 'not_allowed' | 'not_eligible' }
1023
+ /**
1024
+ * The invitation creates no principal now: another acceptance or sign-in gave the mailbox one first, or the
1025
+ * installation or the organization's addresses changed. Whoever holds the mailbox signs in and accepts.
1026
+ */
1027
+ | { ok: false; reason: 'sign_in' }
1028
+
1029
+ /**
1030
+ * Accept an `InvitationOffer` of kind `create` with the password the person chose (already checked by the password
1031
+ * policy and hashed): the external principal, its password, the grant, the consumed invitation and their records in
1032
+ * one transaction (`MembershipRepository.acceptAsNewPrincipal`). Everything the offer checked is checked again.
1033
+ */
1034
+ export async function acceptCreatingPrincipal(
1035
+ services: Services,
1036
+ invitation: InvitationRow,
1037
+ password: StoredPasswordHash,
1038
+ requestId: string,
1039
+ ): Promise<AcceptCreatingOutcome> {
1040
+ if (!(await createsPrincipal(services, invitation))) {
1041
+ return { ok: false, reason: 'sign_in' }
1042
+ }
1043
+ const inviter = await inviterAssigners(services, invitation)
1044
+ if (inviter === null) {
1045
+ return { ok: false, reason: 'not_allowed' }
1046
+ }
1047
+ const accepted = await services.repositories.membership.acceptAsNewPrincipal({ invitation, inviter, password }, (principalId) => ({
1048
+ principal: {
1049
+ requestId,
1050
+ principalId,
1051
+ principalLabel: principalId,
1052
+ app: 'propustka',
1053
+ action: 'iam.principal.create',
1054
+ resourceType: 'principal',
1055
+ resourceId: principalId,
1056
+ metadata: { affiliation: 'external', invitationId: invitation.id },
1057
+ },
1058
+ acceptance: acceptanceEvent(invitation, principalId, requestId),
1059
+ password: {
1060
+ requestId,
1061
+ principalId,
1062
+ principalLabel: principalId,
1063
+ app: 'propustka',
1064
+ action: 'iam.password.enrollment.complete',
1065
+ resourceType: 'principal',
1066
+ resourceId: principalId,
1067
+ metadata: { invitationId: invitation.id },
1068
+ },
1069
+ }))
1070
+ switch (accepted.outcome) {
1071
+ case 'accepted':
1072
+ return { ok: true, invitation, principal: accepted.principal }
1073
+ case 'account_exists':
1074
+ return { ok: false, reason: 'sign_in' }
1075
+ case 'not_eligible':
1076
+ return { ok: false, reason: 'not_eligible' }
1077
+ case 'not_allowed':
1078
+ return { ok: false, reason: 'not_allowed' }
1079
+ case 'not_open':
1080
+ return { ok: false, reason: 'invalid' }
1081
+ }
1082
+ }
1083
+
1084
+ // ── Share links ───────────────────────────────────────────────────────────────
1085
+
1086
+ /** Why `chain` is not a containment chain of `dimension` in the app's schema, or null. */
1087
+ async function chainProblem(services: Services, app: string, dimension: string, chain: Scope[]): Promise<string | null> {
1088
+ if (chain.length === 0 || chain.length > MAX_LINK_CHAIN_LENGTH) {
1089
+ return `a link chain names 1 to ${MAX_LINK_CHAIN_LENGTH} values`
1090
+ }
1091
+ let expected: string | null = dimension
1092
+ for (const scope of chain) {
1093
+ const problem = membershipScopeProblem(scope)
1094
+ if (problem !== null) return problem
1095
+ if (scope.type !== expected) {
1096
+ return `the link chain names '${scope.type}' where the schema contains '${expected ?? 'nothing'}'`
1097
+ }
1098
+ const row = await services.repositories.appSchema.getScope(app, scope.type)
1099
+ if (row === null) return `unknown scope '${scope.type}'`
1100
+ expected = row.parent_scope
1101
+ }
1102
+ return expected === null ? null : `the link chain stops before '${expected}'`
1103
+ }
1104
+
1105
+ /**
1106
+ * Issue a share link: an anonymous `px_` key bound to the app, the mount and the whole chain, with the
1107
+ * mount's grants frozen on the object. The caller holds the mount's `issuedBy` and every grant on some
1108
+ * link of the chain — the delegation rule of every key IAM issues. A job issues only for the mount its
1109
+ * declaration names, and holds those actions app-wide: it issues for any object of the mount's dimension.
1110
+ */
1111
+ export async function issueLink(services: Services, env: CallerEnv, ctx: RequestContext, input: IssueLinkInput): Promise<IssueLinkResult> {
1112
+ const resolved = await resolveLinkOperationCaller(services, env, input)
1113
+ if (!resolved.ok) return resolved
1114
+ const { caller, job } = resolved
1115
+ if (job !== null && job.issues !== input.mount) {
1116
+ return NOT_ALLOWED
1117
+ }
1118
+ const mount = await services.repositories.appSchema.getLinkMount(caller.app, input.mount)
1119
+ if (mount === null) {
1120
+ return invalid(`unknown link mount '${input.mount}'`)
1121
+ }
1122
+ const problem = await chainProblem(services, caller.app, mount.dimension, input.chain)
1123
+ if (problem !== null) return invalid(problem)
1124
+ if (!Number.isSafeInteger(input.days) || input.days < 1 || input.days > mount.max_days) {
1125
+ return invalid(`a link of '${mount.mount}' lives 1 to ${mount.max_days} days`)
1126
+ }
1127
+ const grants = parseStoredPermissions(mount.grants)
1128
+ const heldOnChain = (action: string): boolean => input.chain.some((scope) => permits(caller.permissions, action, scope))
1129
+ if (!heldOnChain(mount.issued_by) || !grants.every(heldOnChain)) {
1130
+ return NOT_ALLOWED
1131
+ }
1132
+ const [object] = input.chain
1133
+ if (object === undefined) return invalid('a link chain names its object first')
1134
+ // S8: the link ends no later than the issuer's grants behind it, so a lapse cannot revive with a later grant.
1135
+ const backing = await issuerAuthority(
1136
+ services,
1137
+ caller.principal.id,
1138
+ caller.app,
1139
+ mount.mount,
1140
+ [mount.issued_by, ...grants].map((action) => ({ action, on: input.chain })),
1141
+ )
1142
+ if (!backing.ok) return NOT_ALLOWED
1143
+ const requested = unixNow() + input.days * DAY_SECONDS
1144
+ const expiresAt = backing.expiresAt === null ? requested : Math.min(requested, backing.expiresAt)
1145
+ if (expiresAt <= unixNow()) return NOT_ALLOWED
1146
+ const key = `${API_KEY_PREFIX}${generateToken()}`
1147
+ const id = await services.repositories.credentials.createLinkCredential({
1148
+ tokenHash: await hashToken(key),
1149
+ label: `link:${mount.mount}`,
1150
+ app: caller.app,
1151
+ issuedBy: caller.principal.id,
1152
+ expiresAt,
1153
+ grants: grants.map((action) => ({ action, scopeType: object.type, scopeValue: object.value })),
1154
+ link: { mount: mount.mount, chain: input.chain.map((scope) => ({ type: scope.type, value: scope.value })) },
1155
+ checked: {
1156
+ grants,
1157
+ issuedBy: mount.issued_by,
1158
+ maxDays: mount.max_days,
1159
+ ...(job === null ? {} : { job: { name: job.name, actions: job.actions } }),
1160
+ },
1161
+ }, (credentialId) =>
1162
+ memberEvent(caller, input.requestId, {
1163
+ action: 'iam.link.issue',
1164
+ resourceType: 'credential',
1165
+ resourceId: credentialId,
1166
+ metadata: { mount: mount.mount, chain: input.chain, days: input.days },
1167
+ }))
1168
+ if (id === null) {
1169
+ // A reconcile changed what was checked above (the mount, the containment or the job) before the write.
1170
+ return NOT_ALLOWED
1171
+ }
1172
+ return { ok: true, key, id, expiresAt }
1173
+ }
1174
+
1175
+ /**
1176
+ * Revoke a link: by its issuer, or by a holder of `members.manage` on a value of its chain. A job revokes only a link
1177
+ * it issued, of the mount its declaration still names.
1178
+ */
1179
+ export async function revokeLink(services: Services, env: CallerEnv, ctx: RequestContext, input: RevokeLinkInput): Promise<RevokeLinkResult> {
1180
+ const resolved = await resolveLinkOperationCaller(services, env, input)
1181
+ if (!resolved.ok) return resolved
1182
+ const { caller, job } = resolved
1183
+ const credential = await services.repositories.credentials.getCredentialById(input.id)
1184
+ if (credential === null || credential.app !== caller.app || credential.link_mount === null || credential.link_chain === null) {
1185
+ return NOT_FOUND
1186
+ }
1187
+ if (job !== null) {
1188
+ if (credential.issued_by !== caller.principal.id || credential.link_mount !== job.issues) return NOT_ALLOWED
1189
+ } else if (credential.issued_by !== caller.principal.id) {
1190
+ let manager = false
1191
+ for (const scope of parseStoredChain(credential.link_chain) ?? []) {
1192
+ const dimension = await services.repositories.appSchema.getScope(caller.app, scope.type)
1193
+ if (dimension?.members_manage != null && permits(caller.permissions, dimension.members_manage, scope)) {
1194
+ manager = true
1195
+ break
1196
+ }
1197
+ }
1198
+ if (!manager) return NOT_ALLOWED
1199
+ }
1200
+ await services.repositories.credentials.revokeCredential(
1201
+ credential.id,
1202
+ memberEvent(caller, input.requestId, {
1203
+ action: 'iam.link.revoke',
1204
+ resourceType: 'credential',
1205
+ resourceId: credential.id,
1206
+ metadata: { mount: credential.link_mount },
1207
+ }),
1208
+ )
1209
+ return { ok: true }
1210
+ }