@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,36 @@
1
+ /**
2
+ * Whether a request proves it came through the platform proxy, which decides if IAM may read the request-id header the
3
+ * composition names (`src/request-id.ts`), and a client-address header where one is named (`src/client-address.ts`).
4
+ *
5
+ * On Zerops IAM is not publicly routed, but anything on the platform project's private network can reach its port and
6
+ * write the request id. So the proxy sends a per-installation secret in `PROXY_SECRET_HEADER` on IAM's route, and a
7
+ * request without it is attributed to nobody. This is attribution, not an enforcement decision (ADR-0022): a missing
8
+ * proof is never a refusal by itself, though the one bucket all such requests share refuses once exhausted.
9
+ */
10
+
11
+ import { PROXY_SECRET_HEADER } from '@fabrika/auth-core'
12
+ import { hashToken, timingSafeEqualHex } from './secret'
13
+
14
+ /**
15
+ * The client coordinate every request without the proof shares. One bucket for all of them: a caller that cannot prove
16
+ * the proxy sent it cannot pick a fresh bucket per attempt, and the proxy's own requests never land here.
17
+ */
18
+ export const UNPROVEN_CLIENT_ADDRESS = 'unproven-caller'
19
+
20
+ /** Resolves true when the request may be attributed by the composition's headers. */
21
+ export type ProxyProof = (request: Request) => Promise<boolean>
22
+
23
+ /**
24
+ * The proof check for a configured secret. An empty secret means the composition checks nothing, and every request is
25
+ * read as it arrives — the Worker root, and an installation before the deploy that writes the secret.
26
+ */
27
+ export function proxyProof(secret: string): ProxyProof {
28
+ if (secret === '') {
29
+ return () => Promise.resolve(true)
30
+ }
31
+ const expected = hashToken(secret)
32
+ return async (request) => {
33
+ const presented = request.headers.get(PROXY_SECRET_HEADER) ?? ''
34
+ return presented !== '' && timingSafeEqualHex(await hashToken(presented), await expected)
35
+ }
36
+ }
@@ -0,0 +1,64 @@
1
+ // IAM's mail through Control's relay, and the one case it falls back to its own provider: the relay answered that it did
2
+ // not take the message. Both compositions use it, so the Worker and the Bun process fall back alike.
3
+
4
+ import { EmailDeliveryError, type EmailSender } from '@fabrika/email'
5
+ import { logWarn } from './log'
6
+ import type { AuditEventInput } from './repositories/audit'
7
+
8
+ /**
9
+ * Whether the relay refused the message for good, so nothing was recorded and the provider cannot have it:
10
+ * - `provider_unauthorized`: Control knows no such key (a Control that holds an older secret, or none);
11
+ * - `mail_not_configured`: Control has no transport of its own;
12
+ * - a 404: Control runs no relay (an older release, or a Worker without its queue and bucket);
13
+ * - a 3xx: the URL is not where the relay answers (an `http:` origin that redirects to `https:`, say); the sender
14
+ * never follows it, so the relay never saw the message;
15
+ * - `invalid_configuration`: IAM's own relay settings cannot reach it.
16
+ * A timeout, a network failure or a provider outage may have reached the relay, so they never fall back.
17
+ */
18
+ export function relayRefused(error: unknown): error is EmailDeliveryError {
19
+ if (!(error instanceof EmailDeliveryError)) return false
20
+ return error.code === 'provider_unauthorized' || error.code === 'mail_not_configured' || error.code === 'invalid_configuration'
21
+ || error.httpStatus === 404 || isRedirectStatus(error.httpStatus)
22
+ }
23
+
24
+ function isRedirectStatus(status: number | undefined): boolean {
25
+ return status !== undefined && status >= 300 && status < 400
26
+ }
27
+
28
+ /**
29
+ * Sends through `relay`, and through `direct` (IAM's own provider) only when the relay refused the message for good
30
+ * (`relayRefused`). The relay's capabilities are the sender's: a message goes there first. Without that fallback, sign-in
31
+ * links would stop while IAM deploys ahead of Control, or between a rotated secret reaching IAM and reaching Control.
32
+ *
33
+ * A fallback that lasts past a rollout means the relay is misconfigured, and the gate and the console's Mail page no
34
+ * longer see IAM's mail, so each one is `recorded` where an operator looks (the audit log), not only in the Worker's log.
35
+ * A record that fails never stops the message.
36
+ */
37
+ export function relayWithFallback(relay: EmailSender, direct: EmailSender, recorded: (refusal: EmailDeliveryError) => Promise<void>): EmailSender {
38
+ return {
39
+ capabilities: relay.capabilities,
40
+ async send(message, signal) {
41
+ try {
42
+ return await relay.send(message, signal)
43
+ } catch (error) {
44
+ if (!relayRefused(error)) throw error
45
+ logWarn("iam mail: Control's relay refused the message, so IAM sends it with its own provider", error)
46
+ await recorded(error).catch((cause: unknown) => logWarn('iam mail: the relay fallback was not recorded', cause))
47
+ return direct.send(message, signal)
48
+ }
49
+ },
50
+ }
51
+ }
52
+
53
+ /** The audit record of one fallback: which refusal, never the message, its recipient or a key. */
54
+ export function relayFallbackEvent(requestId: string, refusal: EmailDeliveryError): AuditEventInput {
55
+ return {
56
+ requestId,
57
+ principalId: null,
58
+ principalLabel: 'mail-relay',
59
+ app: 'propustka',
60
+ action: 'iam.mail.relay_fallback',
61
+ resourceType: 'mail',
62
+ metadata: { code: refusal.code, ...(refusal.httpStatus === undefined ? {} : { httpStatus: refusal.httpStatus }) },
63
+ }
64
+ }
@@ -0,0 +1,550 @@
1
+ import { terminalIdentifyProblem, type WorkloadKind } from '@fabrika/auth-core'
2
+ import { type SqlDatabase, type SqlStatement } from '@fabrika/platform'
3
+
4
+ import { type AuditEventInput, auditEventStatement, AuditWriter } from './audit'
5
+ import { unixNow } from './sql'
6
+
7
+ /** A role/policy bundle row (the `roles` table). `permissions` is a JSON array string. */
8
+ export interface RoleRow {
9
+ app: string
10
+ role_key: string
11
+ name: string
12
+ description: string | null
13
+ /** JSON array of action patterns, e.g. '["project.read","report.*"]'. */
14
+ permissions: string
15
+ /** 'app' = reconciled from code, 'custom' = admin-composed. */
16
+ origin: 'app' | 'custom'
17
+ /** The scope dimension a membership role is granted in; NULL for every other role. */
18
+ member_scope: string | null
19
+ /** JSON array of the membership roles whose holders may assign this one; NULL = only an administrator. */
20
+ assignable_by: string | null
21
+ /** 1 when an external principal may hold this membership role (ADR-0051); 0 for every other role. */
22
+ external: 0 | 1
23
+ /** JSON object relation → exact actions a grant of the role carries as `~rel` (global) or `~relin` (at a node) entries; NULL = none. */
24
+ via: string | null
25
+ created_at: number
26
+ }
27
+
28
+ /** A scope-dimension row (the `app_scopes` table). */
29
+ export interface AppScopeRow {
30
+ app: string
31
+ scope_type: string
32
+ label: string | null
33
+ /** The dimension containing every value of this one. */
34
+ parent_scope: string | null
35
+ /** The membership role `createScope` grants in a new value. */
36
+ creator_role: string | null
37
+ members_manage: string | null
38
+ members_list: string | null
39
+ /** `labels`: `listMembers` shows labels to a `members.list` holder too. */
40
+ members_directory: 'labels' | null
41
+ /** A JSON array of the actions that look up one member (`findMember`), or null for none. */
42
+ members_lookup: string | null
43
+ }
44
+
45
+ /** A share-link mount (the `app_link_mounts` table). `grants` is a JSON array of exact actions. */
46
+ export interface LinkMountRow {
47
+ app: string
48
+ mount: string
49
+ dimension: string
50
+ grants: string
51
+ issued_by: string
52
+ max_days: number
53
+ }
54
+
55
+ /** An endpoint that may spend membership authority (the `app_delegated_endpoints` table). */
56
+ export interface DelegatedEndpointRow {
57
+ app: string
58
+ endpoint: string
59
+ action: string
60
+ dimension: string
61
+ purpose: 'members' | 'creates'
62
+ }
63
+
64
+ /**
65
+ * How IAM names an application (the `app_presentation` table). `locale` is stored as reconciled and parsed at read
66
+ * (`presentationFor`); NULL is "not declared".
67
+ */
68
+ export interface AppPresentationRow {
69
+ app: string
70
+ locale: string | null
71
+ display_name: string | null
72
+ }
73
+
74
+ /** An application's wording of one IAM e-mail in one language (the `app_mail_templates` table), parsed at render. */
75
+ export interface AppMailTemplateRow {
76
+ app: string
77
+ kind: string
78
+ locale: string
79
+ subject: string
80
+ body: string
81
+ /** The HTML body in the subset of `mailHtmlTokens`, or NULL for none: IAM builds the HTML part from the text. */
82
+ html: string | null
83
+ }
84
+
85
+ /** The application's own people (the `app_members` table): the actions that manage and list them. */
86
+ export interface AppMembersRow {
87
+ app: string
88
+ manage: string
89
+ list: string
90
+ directory: 'labels' | null
91
+ }
92
+
93
+ /** An action-catalog row (the `app_actions` table). */
94
+ export interface AppActionRow {
95
+ app: string
96
+ action: string
97
+ description: string | null
98
+ }
99
+
100
+ export class AppSchemaRepository {
101
+ constructor(
102
+ protected readonly db: SqlDatabase,
103
+ protected readonly writer: AuditWriter = new AuditWriter(db, 'sqlite'),
104
+ ) {}
105
+
106
+ /**
107
+ * The set of app ids IAM knows about — the distinct `app` across the schema tables
108
+ * (`app_actions ∪ app_scopes ∪ roles ∪ app_schema_revisions`). An app registers itself by reconciling its vocabulary
109
+ * via `PUT /admin/apps/:app/schema`, so this is the live registry (no static config list). Every reconcile writes a
110
+ * revision, so an app that declares nothing is known too, and its return origins can be registered.
111
+ */
112
+ async listKnownApps(): Promise<string[]> {
113
+ const { results } = await this.db
114
+ .prepare(`SELECT app FROM app_actions
115
+ UNION SELECT app FROM app_scopes
116
+ UNION SELECT app FROM roles
117
+ UNION SELECT app FROM app_schema_revisions
118
+ ORDER BY app`)
119
+ .all<{ app: string }>()
120
+ return results.map((r) => r.app)
121
+ }
122
+
123
+ /** The app's declared locale and display name, or null when it declares neither. */
124
+ async getPresentation(app: string): Promise<AppPresentationRow | null> {
125
+ return this.db.prepare('SELECT * FROM app_presentation WHERE app = ?').bind(app).first<AppPresentationRow>()
126
+ }
127
+
128
+ /**
129
+ * The path of the app's identification page at a terminal (ADR-0067), or null when the app declares none: an absolute
130
+ * path on its own origin, which a sign-in resolves against its return origin. The column's CHECK admits `//host`, a
131
+ * reference to another origin, so a stored path is parsed again here and one that is no identification page is none.
132
+ */
133
+ async getTerminalIdentifyPath(app: string): Promise<string | null> {
134
+ const row = await this.db.prepare('SELECT identify FROM app_terminals WHERE app = ?').bind(app).first<{ identify: string }>()
135
+ return row === null || terminalIdentifyProblem(row.identify) !== null ? null : row.identify
136
+ }
137
+
138
+ /** The app's template of one message in one language, or null when it declares none. */
139
+ async getMailTemplate(app: string, kind: string, locale: string): Promise<AppMailTemplateRow | null> {
140
+ return this.db
141
+ .prepare('SELECT * FROM app_mail_templates WHERE app = ? AND kind = ? AND locale = ?')
142
+ .bind(app, kind, locale)
143
+ .first<AppMailTemplateRow>()
144
+ }
145
+
146
+ /** The actions that manage and list the app's own people, or null when it declares none. */
147
+ async getAppMembers(app: string): Promise<AppMembersRow | null> {
148
+ return this.db.prepare('SELECT * FROM app_members WHERE app = ?').bind(app).first<AppMembersRow>()
149
+ }
150
+
151
+ /** Every app that declares its own people, for the apps an administrator of one may administer. */
152
+ async listAppMembers(): Promise<AppMembersRow[]> {
153
+ return (await this.db.prepare('SELECT * FROM app_members ORDER BY app').all<AppMembersRow>()).results
154
+ }
155
+
156
+ /** True when the app's schema was compiled from a contract (ADR-0022 rule 6). */
157
+ async isContractApp(app: string): Promise<boolean> {
158
+ return (await this.db.prepare('SELECT app FROM contract_apps WHERE app = ?').bind(app).first<{ app: string }>()) !== null
159
+ }
160
+
161
+ // ── App-declared vocabulary (roles, scopes, actions) ──────────────────────
162
+
163
+ /** Every role row for an app (origin='app' AND origin='custom') — for resolution + listing. */
164
+ async listRoles(app: string): Promise<RoleRow[]> {
165
+ const { results } = await this.db
166
+ .prepare('SELECT * FROM roles WHERE app = ? ORDER BY role_key')
167
+ .bind(app)
168
+ .all<RoleRow>()
169
+ return results
170
+ }
171
+
172
+ /** Role rows for an app filtered by origin — used to list just the app/custom set. */
173
+ async listRolesByOrigin(app: string, origin: 'app' | 'custom'): Promise<RoleRow[]> {
174
+ const { results } = await this.db
175
+ .prepare('SELECT * FROM roles WHERE app = ? AND origin = ? ORDER BY role_key')
176
+ .bind(app, origin)
177
+ .all<RoleRow>()
178
+ return results
179
+ }
180
+
181
+ async getRole(app: string, roleKey: string): Promise<RoleRow | null> {
182
+ return this.db.prepare('SELECT * FROM roles WHERE app = ? AND role_key = ?').bind(app, roleKey).first<RoleRow>()
183
+ }
184
+
185
+ /**
186
+ * Upsert a single role. `permissions` is JSON-encoded here. ON CONFLICT keeps the
187
+ * row's PK (app, role_key) and overwrites the mutable columns — origin included, so
188
+ * a reconcile can (re)assert origin='app' on an existing key. `created_at` is left
189
+ * untouched on update.
190
+ */
191
+ async upsertRole(input: {
192
+ app: string
193
+ roleKey: string
194
+ name: string
195
+ description?: string | null
196
+ permissions: string[]
197
+ origin: 'app' | 'custom'
198
+ }, audit?: AuditEventInput): Promise<RoleRow> {
199
+ const upsert = this.db
200
+ .prepare(`INSERT INTO roles (app, role_key, name, description, permissions, origin, created_at)
201
+ VALUES (?, ?, ?, ?, ?, ?, ?)
202
+ ON CONFLICT (app, role_key) DO UPDATE SET
203
+ name = excluded.name,
204
+ description = excluded.description,
205
+ permissions = excluded.permissions,
206
+ origin = excluded.origin
207
+ RETURNING *`)
208
+ .bind(
209
+ input.app,
210
+ input.roleKey,
211
+ input.name,
212
+ input.description ?? null,
213
+ JSON.stringify(input.permissions),
214
+ input.origin,
215
+ unixNow(),
216
+ )
217
+ const results = await this.db.batch<RoleRow>([
218
+ this.bumpRevisionStatement(input.app),
219
+ upsert,
220
+ ...(audit === undefined ? [] : [auditEventStatement(this.db, audit)]),
221
+ ])
222
+ const row = results[1]?.results[0]
223
+ if (row === undefined) throw new Error('expected a row from a RETURNING statement, got none')
224
+ return row
225
+ }
226
+
227
+ /** Delete a role. `audit` is written exactly when this call deleted it. */
228
+ async deleteRole(app: string, roleKey: string, audit?: AuditEventInput): Promise<boolean> {
229
+ const remove = this.writer.changed([{ sql: 'DELETE FROM roles WHERE app = ? AND role_key = ? RETURNING role_key', binds: [app, roleKey] }], audit)
230
+ const results = await this.db.batch([this.bumpRevisionStatement(app), ...remove.statements])
231
+ return remove.rows(results, 1).length > 0
232
+ }
233
+
234
+ /**
235
+ * The revision of the app's schema and policies (`app_schema_revisions`); 0 for an app IAM never reconciled. A check
236
+ * that authorizes a later write reads it FIRST, before the rows it checks, and the write requires it unchanged
237
+ * (`schemaRevisionSql`): a reconcile in between then makes the write change nothing.
238
+ */
239
+ async getSchemaRevision(app: string): Promise<number> {
240
+ const row = await this.db.prepare('SELECT revision FROM app_schema_revisions WHERE app = ?').bind(app).first<{ revision: number }>()
241
+ return row?.revision ?? 0
242
+ }
243
+
244
+ /** The first statement of every write of the app's schema or policies: it moves the revision on, and on Postgres locks it. */
245
+ private bumpRevisionStatement(app: string): SqlStatement {
246
+ return this.db
247
+ .prepare(`INSERT INTO app_schema_revisions (app, revision) VALUES (?, 1)
248
+ ON CONFLICT (app) DO UPDATE SET revision = app_schema_revisions.revision + 1`)
249
+ .bind(app)
250
+ }
251
+
252
+ /** The app's action catalog as plain strings — the validation source for patterns. */
253
+ async listActionCatalog(app: string): Promise<string[]> {
254
+ const { results } = await this.db
255
+ .prepare('SELECT action FROM app_actions WHERE app = ? ORDER BY action')
256
+ .bind(app)
257
+ .all<{ action: string }>()
258
+ return results.map((r) => r.action)
259
+ }
260
+
261
+ async getScope(app: string, scopeType: string): Promise<AppScopeRow | null> {
262
+ return this.db.prepare('SELECT * FROM app_scopes WHERE app = ? AND scope_type = ?').bind(app, scopeType).first<AppScopeRow>()
263
+ }
264
+
265
+ async getLinkMount(app: string, mount: string): Promise<LinkMountRow | null> {
266
+ return this.db.prepare('SELECT * FROM app_link_mounts WHERE app = ? AND mount = ?').bind(app, mount).first<LinkMountRow>()
267
+ }
268
+
269
+ async listLinkMounts(app: string): Promise<LinkMountRow[]> {
270
+ const { results } = await this.db.prepare('SELECT * FROM app_link_mounts WHERE app = ? ORDER BY mount').bind(app).all<LinkMountRow>()
271
+ return results
272
+ }
273
+
274
+ async getDelegatedEndpoint(app: string, endpoint: string): Promise<DelegatedEndpointRow | null> {
275
+ return this.db
276
+ .prepare('SELECT * FROM app_delegated_endpoints WHERE app = ? AND endpoint = ?')
277
+ .bind(app, endpoint)
278
+ .first<DelegatedEndpointRow>()
279
+ }
280
+
281
+ async listDelegatedEndpoints(app: string): Promise<DelegatedEndpointRow[]> {
282
+ const { results } = await this.db
283
+ .prepare('SELECT * FROM app_delegated_endpoints WHERE app = ? ORDER BY endpoint')
284
+ .bind(app)
285
+ .all<DelegatedEndpointRow>()
286
+ return results
287
+ }
288
+
289
+ async listAppScopes(app: string): Promise<AppScopeRow[]> {
290
+ const { results } = await this.db
291
+ .prepare('SELECT * FROM app_scopes WHERE app = ? ORDER BY scope_type')
292
+ .bind(app)
293
+ .all<AppScopeRow>()
294
+ return results
295
+ }
296
+
297
+ async listAppActions(app: string): Promise<AppActionRow[]> {
298
+ const { results } = await this.db
299
+ .prepare('SELECT * FROM app_actions WHERE app = ? ORDER BY action')
300
+ .bind(app)
301
+ .all<AppActionRow>()
302
+ return results
303
+ }
304
+
305
+ /**
306
+ * Idempotent reconcile of an app's declared vocabulary in one atomic batch. Validation (patterns
307
+ * vs. the new action catalog, and a collision with an admin's custom policy) is the caller's job —
308
+ * this layer just writes the reconciled state.
309
+ *
310
+ * **Clear, then write.** The previous shape upserted the incoming rows and then deleted whatever
311
+ * was `NOT IN` the incoming set, which put ONE BOUND PARAMETER PER KEPT VALUE in a single
312
+ * statement — D1 allows 100 bound parameters per query, so an app with a hundred actions could not
313
+ * reconcile at all (CORR-9). Deleting the app's rows first makes every statement's width constant
314
+ * and the reconcile independent of catalog size. The batch is one transaction, so there is no
315
+ * window in which the app has no vocabulary.
316
+ *
317
+ * `origin='custom'` roles are NEVER touched: the DELETE names `origin = 'app'`, and the upsert's
318
+ * `WHERE roles.origin = 'app'` makes a collision with a surviving custom row a no-op instead of
319
+ * silently flipping an admin's policy to `origin='app'` and making it unmanageable (SEC-3). The
320
+ * caller refuses that collision outright; this is the second lock on the same rule.
321
+ */
322
+ async reconcileAppSchema(input: {
323
+ app: string
324
+ scopes: {
325
+ scopeType: string
326
+ label?: string | null
327
+ parentScope?: string | null
328
+ creatorRole?: string | null
329
+ members?: { manage: string; list: string } | null
330
+ directory?: 'labels' | null
331
+ lookups?: string[] | null
332
+ }[]
333
+ actions: { action: string; description?: string | null }[]
334
+ roles: {
335
+ roleKey: string
336
+ name: string
337
+ description?: string | null
338
+ permissions: string[]
339
+ memberScope?: string | null
340
+ assignableBy?: string[] | null
341
+ external?: boolean
342
+ via?: Record<string, string[]> | null
343
+ }[]
344
+ /** The contract flag is part of the vocabulary: written in the same batch, so it never outlives the roles it constrains. */
345
+ contract?: boolean
346
+ links?: { mount: string; dimension: string; grants: string[]; issuedBy: string; maxDays: number }[]
347
+ delegations?: { endpoint: string; action: string; dimension: string; purpose: 'members' | 'creates' }[]
348
+ workloads?: { kind: WorkloadKind; name: string; actions: string[]; issues?: string }[]
349
+ /** How IAM names the app; a field left out is "not declared", and both left out remove the row. */
350
+ presentation?: { locale: string | null; displayName: string | null }
351
+ /** The app's e-mail templates; every row of the app is replaced, and none left out removes them all. */
352
+ mail?: { kind: string; locale: string; subject: string; text: string; html?: string }[]
353
+ /** The actions that manage and list the app's own people; absent or null removes the row. */
354
+ members?: { manage: string; list: string; directory: 'labels' | null } | null
355
+ /** The app's identification page at a terminal; absent or null removes the row. */
356
+ terminal?: { identify: string } | null
357
+ }, audit?: AuditEventInput): Promise<void> {
358
+ const { app } = input
359
+ const statements: SqlStatement[] = [
360
+ this.bumpRevisionStatement(app),
361
+ this.db.prepare('DELETE FROM app_scopes WHERE app = ?').bind(app),
362
+ this.db.prepare('DELETE FROM app_actions WHERE app = ?').bind(app),
363
+ this.db.prepare(`DELETE FROM roles WHERE app = ? AND origin = 'app'`).bind(app),
364
+ this.db.prepare('DELETE FROM contract_apps WHERE app = ?').bind(app),
365
+ this.db.prepare('DELETE FROM app_link_mounts WHERE app = ?').bind(app),
366
+ this.db.prepare('DELETE FROM app_delegated_endpoints WHERE app = ?').bind(app),
367
+ this.db.prepare('DELETE FROM app_workloads WHERE app = ?').bind(app),
368
+ this.db.prepare('DELETE FROM app_presentation WHERE app = ?').bind(app),
369
+ this.db.prepare('DELETE FROM app_mail_templates WHERE app = ?').bind(app),
370
+ this.db.prepare('DELETE FROM app_members WHERE app = ?').bind(app),
371
+ this.db.prepare('DELETE FROM app_terminals WHERE app = ?').bind(app),
372
+ ]
373
+ if (input.terminal != null) {
374
+ statements.push(this.db.prepare('INSERT INTO app_terminals (app, identify) VALUES (?, ?)').bind(app, input.terminal.identify))
375
+ }
376
+ if (input.members != null) {
377
+ statements.push(
378
+ this.db
379
+ .prepare('INSERT INTO app_members (app, manage, list, directory) VALUES (?, ?, ?, ?)')
380
+ .bind(app, input.members.manage, input.members.list, input.members.directory),
381
+ )
382
+ }
383
+ for (const template of input.mail ?? []) {
384
+ statements.push(
385
+ this.db
386
+ .prepare('INSERT INTO app_mail_templates (app, kind, locale, subject, body, html) VALUES (?, ?, ?, ?, ?, ?)')
387
+ .bind(app, template.kind, template.locale, template.subject, template.text, template.html ?? null),
388
+ )
389
+ }
390
+ const presentation = input.presentation
391
+ if (presentation !== undefined && (presentation.locale !== null || presentation.displayName !== null)) {
392
+ statements.push(
393
+ this.db
394
+ .prepare('INSERT INTO app_presentation (app, locale, display_name) VALUES (?, ?, ?)')
395
+ .bind(app, presentation.locale, presentation.displayName),
396
+ )
397
+ }
398
+ if (input.contract === true) {
399
+ statements.push(this.db.prepare('INSERT INTO contract_apps (app, created_at) VALUES (?, ?)').bind(app, unixNow()))
400
+ }
401
+ for (const role of input.roles) {
402
+ if (role.memberScope == null) continue
403
+ // The caller refuses an incompatible grant with a 409 first; this NOT NULL violation rolls the
404
+ // batch back if one was written in between, so the declaration never lands over it.
405
+ statements.push(
406
+ this.db
407
+ .prepare(`INSERT INTO contract_apps (app, created_at) SELECT ?, NULL WHERE EXISTS (
408
+ SELECT 1 FROM grants WHERE app = ? AND role_key = ? AND (scope_type IS NULL OR scope_type <> ?))`)
409
+ .bind(`${app}#incompatible-membership-grant`, app, role.roleKey, role.memberScope),
410
+ )
411
+ }
412
+
413
+ for (const scope of input.scopes) {
414
+ statements.push(
415
+ this.db
416
+ .prepare(
417
+ `INSERT INTO app_scopes (app, scope_type, label, parent_scope, creator_role, members_manage, members_list, members_directory, members_lookup)
418
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
419
+ ON CONFLICT (app, scope_type) DO UPDATE SET
420
+ label = excluded.label,
421
+ parent_scope = excluded.parent_scope,
422
+ creator_role = excluded.creator_role,
423
+ members_manage = excluded.members_manage,
424
+ members_list = excluded.members_list,
425
+ members_directory = excluded.members_directory,
426
+ members_lookup = excluded.members_lookup`,
427
+ )
428
+ .bind(
429
+ app,
430
+ scope.scopeType,
431
+ scope.label ?? null,
432
+ scope.parentScope ?? null,
433
+ scope.creatorRole ?? null,
434
+ scope.members?.manage ?? null,
435
+ scope.members?.list ?? null,
436
+ scope.directory ?? null,
437
+ scope.lookups == null || scope.lookups.length === 0 ? null : JSON.stringify(scope.lookups),
438
+ ),
439
+ )
440
+ }
441
+
442
+ for (const action of input.actions) {
443
+ statements.push(
444
+ this.db
445
+ .prepare(`INSERT INTO app_actions (app, action, description) VALUES (?, ?, ?)
446
+ ON CONFLICT (app, action) DO UPDATE SET description = excluded.description`)
447
+ .bind(app, action.action, action.description ?? null),
448
+ )
449
+ }
450
+
451
+ for (const role of input.roles) {
452
+ statements.push(
453
+ this.db
454
+ .prepare(`INSERT INTO roles (app, role_key, name, description, permissions, origin, member_scope, assignable_by, external, via, created_at)
455
+ VALUES (?, ?, ?, ?, ?, 'app', ?, ?, ?, ?, ?)
456
+ ON CONFLICT (app, role_key) DO UPDATE SET
457
+ name = excluded.name,
458
+ description = excluded.description,
459
+ permissions = excluded.permissions,
460
+ member_scope = excluded.member_scope,
461
+ assignable_by = excluded.assignable_by,
462
+ external = excluded.external,
463
+ via = excluded.via,
464
+ origin = 'app'
465
+ WHERE roles.origin = 'app'`)
466
+ .bind(
467
+ app,
468
+ role.roleKey,
469
+ role.name,
470
+ role.description ?? null,
471
+ JSON.stringify(role.permissions),
472
+ role.memberScope ?? null,
473
+ role.assignableBy == null ? null : JSON.stringify(role.assignableBy),
474
+ role.external === true ? 1 : 0,
475
+ role.via == null ? null : JSON.stringify(role.via),
476
+ unixNow(),
477
+ ),
478
+ )
479
+ }
480
+ // The caller refuses a role an external principal holds and the schema no longer declares external with a 409
481
+ // first; this NOT NULL violation rolls the batch back if such a grant was written in between (ADR-0051).
482
+ statements.push(
483
+ this.db
484
+ .prepare(`INSERT INTO contract_apps (app, created_at) SELECT ?, NULL WHERE EXISTS (
485
+ SELECT 1 FROM grants g
486
+ JOIN principals p ON p.id = g.principal_id
487
+ JOIN roles r ON r.app = g.app AND r.role_key = g.role_key
488
+ WHERE g.app = ? AND p.affiliation = 'external' AND r.external = 0)`)
489
+ .bind(`${app}#internal-role-of-external-principal`, app),
490
+ )
491
+
492
+ for (const link of input.links ?? []) {
493
+ statements.push(
494
+ this.db
495
+ .prepare('INSERT INTO app_link_mounts (app, mount, dimension, grants, issued_by, max_days) VALUES (?, ?, ?, ?, ?, ?)')
496
+ .bind(app, link.mount, link.dimension, JSON.stringify(link.grants), link.issuedBy, link.maxDays),
497
+ )
498
+ }
499
+ for (const delegation of input.delegations ?? []) {
500
+ statements.push(
501
+ this.db
502
+ .prepare('INSERT INTO app_delegated_endpoints (app, endpoint, action, dimension, purpose) VALUES (?, ?, ?, ?, ?)')
503
+ .bind(app, delegation.endpoint, delegation.action, delegation.dimension, delegation.purpose),
504
+ )
505
+ }
506
+ for (const workload of input.workloads ?? []) {
507
+ statements.push(
508
+ this.db
509
+ .prepare('INSERT INTO app_workloads (app, kind, name, actions, issues) VALUES (?, ?, ?, ?, ?)')
510
+ .bind(app, workload.kind, workload.name, JSON.stringify(workload.actions), workload.issues ?? null),
511
+ )
512
+ }
513
+ // A workload no longer declared keeps no key: its keys are revoked in the same transaction.
514
+ statements.push(
515
+ this.db
516
+ .prepare(`UPDATE credentials SET revoked_at = ?
517
+ WHERE revoked_at IS NULL AND principal_id IN (
518
+ SELECT w.principal_id FROM workload_principals w
519
+ WHERE w.app = ? AND NOT EXISTS (
520
+ SELECT 1 FROM app_workloads a WHERE a.app = w.app AND a.kind = w.kind AND a.name = w.name))`)
521
+ .bind(unixNow(), app),
522
+ )
523
+ // Removing a link mount, or moving it to another dimension, revokes its keys in the same transaction.
524
+ statements.push(
525
+ this.db
526
+ .prepare(`UPDATE credentials SET revoked_at = ?
527
+ WHERE app = ? AND link_mount IS NOT NULL AND revoked_at IS NULL AND NOT EXISTS (
528
+ SELECT 1 FROM app_link_mounts m
529
+ WHERE m.app = credentials.app AND m.mount = credentials.link_mount AND m.dimension = credentials.link_dimension)`)
530
+ .bind(unixNow(), app),
531
+ )
532
+ // An app left with no delegated endpoint, no link mount, no dimension that lists its members, no people of its own and
533
+ // no terminal calls no membership or identification operation, so it keeps no transport key.
534
+ statements.push(
535
+ this.db
536
+ .prepare(`DELETE FROM membership_transport_keys
537
+ WHERE app = ? AND NOT EXISTS (SELECT 1 FROM app_delegated_endpoints d WHERE d.app = ?)
538
+ AND NOT EXISTS (SELECT 1 FROM app_link_mounts m WHERE m.app = ?)
539
+ AND NOT EXISTS (SELECT 1 FROM app_scopes s WHERE s.app = ? AND s.members_list IS NOT NULL)
540
+ AND NOT EXISTS (SELECT 1 FROM app_members p WHERE p.app = ?)
541
+ AND NOT EXISTS (SELECT 1 FROM app_terminals t WHERE t.app = ?)`)
542
+ .bind(app, app, app, app, app, app),
543
+ )
544
+ if (audit !== undefined) {
545
+ statements.push(auditEventStatement(this.db, audit))
546
+ }
547
+
548
+ await this.db.batch(statements)
549
+ }
550
+ }