@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,405 @@
1
+ import { type SqlDatabase, type SqlQueryResult, type SqlStatement, uuidv7 } from '@fabrika/platform'
2
+
3
+ import { unixNow } from './sql'
4
+
5
+ export interface AuditEventRow {
6
+ id: string
7
+ request_id: string
8
+ principal_id: string | null
9
+ principal_label: string
10
+ credential_id: string | null
11
+ app: string
12
+ action: string
13
+ resource_type: string
14
+ resource_id: string | null
15
+ diff: string | null
16
+ metadata: string | null
17
+ created_at: number
18
+ }
19
+
20
+ export interface AuthLogRow {
21
+ /**
22
+ * THE ONE COLUMN IN THIS SCHEMA WHOSE JS TYPE DEPENDS ON THE BACKEND. `auth_log.id` is engine-
23
+ * assigned and has no SQLite ∩ Postgres spelling (see the block comment on `auth_log` in
24
+ * `migrations/0001` and `migrations-postgres/0001`): SQLite's `INTEGER PRIMARY KEY` rowid alias
25
+ * hands back a `number`; Postgres needs `BIGINT GENERATED BY DEFAULT AS IDENTITY`, and Bun decodes
26
+ * `int8` as a STRING by column type OID — `'42'`, never `42`, even for small values.
27
+ *
28
+ * Narrowing this to `number` would be a lie on Postgres, and widening the column to `INTEGER` to
29
+ * make it true would cap the highest-volume table in the schema at 2147483647 rows. So the union
30
+ * stands and the SINGLE reader (`toAuthLogDto`, admin/audit.ts) normalises it. Anything new
31
+ * that reads this column must do the same — do not assume arithmetic works on it.
32
+ */
33
+ id: number | string
34
+ request_id: string
35
+ app: string
36
+ kind: AuthLogKind
37
+ principal_id: string | null
38
+ credential_id: string | null
39
+ decision: 'allow' | 'deny'
40
+ reason: string | null
41
+ created_at: number
42
+ /** 1 when the session's principal held the installation-admin action at login; 0 otherwise. */
43
+ privileged: number
44
+ /** The terminal of the session this row is about (ADR-0067), copied from the session row. */
45
+ terminal_id: string | null
46
+ /** The application that asserted that session's person on `terminal_id`. */
47
+ asserted_by: string | null
48
+ }
49
+
50
+ /** A login attempt (`authenticate`) or the end of a session (`logout`). */
51
+ export type AuthLogKind = 'authenticate' | 'logout'
52
+
53
+ // Inputs that audit/auth-log writes accept (the Worker stamps ids/timestamps).
54
+ export interface AuditEventInput {
55
+ requestId: string
56
+ principalId: string | null
57
+ principalLabel: string
58
+ credentialId?: string | null
59
+ app: string
60
+ action: string
61
+ resourceType: string
62
+ resourceId?: string | null
63
+ diff?: unknown
64
+ metadata?: unknown
65
+ }
66
+
67
+ export interface AuthLogInput {
68
+ requestId: string
69
+ app: string
70
+ kind: AuthLogKind
71
+ principalId: string | null
72
+ credentialId?: string | null
73
+ decision: 'allow' | 'deny'
74
+ reason?: string | null
75
+ /** The principal held the installation-admin action when this session was opened. */
76
+ privileged?: boolean
77
+ /** The session's `terminal_id` and `asserted_by`, read from its row, never from what an application sent. */
78
+ terminal?: { terminalId: string; assertedBy: string } | null
79
+ }
80
+
81
+ /**
82
+ * The `principal_label` an audit row stores for a principal: a user's is its id, because a user's label spells its
83
+ * mailbox and an audit row holds no email; a service's is its key name. A caller of unknown kind is treated as a user.
84
+ */
85
+ export function auditLabelOf(
86
+ principal: { readonly id: string; readonly type: 'user' | 'service' | undefined; readonly label: string | null },
87
+ ): string {
88
+ return principal.type === 'service' ? principal.label ?? principal.id : principal.id
89
+ }
90
+
91
+ /** A write that ends in `RETURNING`, as SQL text and its bound values, so an `AuditWriter` can wrap it. */
92
+ export interface SqlChange {
93
+ readonly sql: string
94
+ readonly binds: readonly unknown[]
95
+ }
96
+
97
+ /** The SQL dialect a composition root runs on: D1/SQLite or Postgres. */
98
+ export type SqlDialect = 'sqlite' | 'postgres'
99
+
100
+ const AUDIT_COLUMNS =
101
+ '(id, request_id, principal_id, principal_label, credential_id, app, action, resource_type, resource_id, diff, metadata, created_at)'
102
+
103
+ /** The bound values of one audit row, in `AUDIT_COLUMNS` order; `id` is the row's own. */
104
+ function auditValues(id: string, event: AuditEventInput): unknown[] {
105
+ return [
106
+ id,
107
+ event.requestId,
108
+ event.principalId,
109
+ event.principalLabel,
110
+ event.credentialId ?? null,
111
+ event.app,
112
+ event.action,
113
+ event.resourceType,
114
+ event.resourceId ?? null,
115
+ event.diff === undefined ? null : JSON.stringify(event.diff),
116
+ event.metadata === undefined ? null : JSON.stringify(event.metadata),
117
+ unixNow(),
118
+ ]
119
+ }
120
+
121
+ const AUDIT_PLACEHOLDERS = '?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?'
122
+
123
+ /**
124
+ * The INSERT of one audit row, for the batch of an unconditional change it records: the row and the change commit
125
+ * together, and a failed insert rolls the change back. Diff and metadata are stored JSON-encoded.
126
+ */
127
+ export function auditEventStatement(db: SqlDatabase, event: AuditEventInput): SqlStatement {
128
+ return db.prepare(`INSERT INTO audit_events ${AUDIT_COLUMNS} VALUES (${AUDIT_PLACEHOLDERS})`).bind(...auditValues(uuidv7(), event))
129
+ }
130
+
131
+ /**
132
+ * `auditEventStatement` whose `resource_id` is read in the batch by `resourceId`, a one-row SELECT of one column: for
133
+ * a resource whose id the batch itself settles, such as a principal another writer may have created first.
134
+ */
135
+ export function auditEventAboutStatement(db: SqlDatabase, event: AuditEventInput, resourceId: SqlChange): SqlStatement {
136
+ const values = auditValues(uuidv7(), event)
137
+ const before = values.slice(0, 8)
138
+ const after = values.slice(9)
139
+ return db
140
+ .prepare(`INSERT INTO audit_events ${AUDIT_COLUMNS} SELECT ?, ?, ?, ?, ?, ?, ?, ?, (${resourceId.sql}), ?, ?, ?`)
141
+ .bind(...before, ...resourceId.binds, ...after)
142
+ }
143
+
144
+ /** A change and its record, as batch statements, and where the change's `RETURNING` rows land in the batch results. */
145
+ export interface AuditedChange {
146
+ readonly statements: SqlStatement[]
147
+ /** The rows the LAST change returned, read from the results of a batch whose statements start at `offset`. */
148
+ rows<T>(results: SqlQueryResult<T>[], offset?: number): T[]
149
+ }
150
+
151
+ /**
152
+ * Writes the record of a guarded change exactly when the change changed a row, decided by the change itself and never
153
+ * by an earlier existence check another writer can invalidate.
154
+ *
155
+ * - **Postgres** runs the changes and the record as ONE statement: `WITH c0 AS (<change> RETURNING …), … INSERT INTO
156
+ * audit_events … WHERE EXISTS (SELECT 1 FROM c0) …`. The record sees exactly the rows this statement changed.
157
+ * Data-modifying CTEs share one snapshot, so the changes of one group must not depend on each other.
158
+ * - **SQLite/D1** has no data-modifying CTE, but it serializes writers, so `changes()` right after each change is
159
+ * exact: the record is inserted after the first change that changed a row, and its fixed id keeps it to one.
160
+ */
161
+ export class AuditWriter {
162
+ constructor(
163
+ private readonly db: SqlDatabase,
164
+ readonly dialect: SqlDialect,
165
+ ) {}
166
+
167
+ /** The changes and, when `event` is given, their record; without one, the changes alone (a seed, a test). */
168
+ changed(changes: readonly SqlChange[], event: AuditEventInput | undefined): AuditedChange {
169
+ if (changes.length === 0) {
170
+ throw new Error('an audited change needs at least one write')
171
+ }
172
+ if (event === undefined) {
173
+ const last = changes.length - 1
174
+ return {
175
+ statements: changes.map((change) => this.db.prepare(change.sql).bind(...change.binds)),
176
+ rows: (results, offset = 0) => results[offset + last]?.results ?? [],
177
+ }
178
+ }
179
+ const id = uuidv7()
180
+ const values = auditValues(id, event)
181
+ if (this.dialect === 'postgres') {
182
+ const ctes = changes.map((change, index) => `c${index} AS (${change.sql})`)
183
+ const changed = changes.map((_, index) => `EXISTS (SELECT 1 FROM c${index})`).join(' OR ')
184
+ const statement = this.db
185
+ .prepare(`WITH ${ctes.join(', ')}, recorded AS (
186
+ INSERT INTO audit_events ${AUDIT_COLUMNS} SELECT ${AUDIT_PLACEHOLDERS} WHERE ${changed} RETURNING id
187
+ ) SELECT * FROM c${changes.length - 1}`)
188
+ .bind(...changes.flatMap((change) => change.binds), ...values)
189
+ return { statements: [statement], rows: (results, offset = 0) => results[offset]?.results ?? [] }
190
+ }
191
+ const statements = changes.flatMap((change) => [
192
+ this.db.prepare(change.sql).bind(...change.binds),
193
+ this.db
194
+ .prepare(`INSERT INTO audit_events ${AUDIT_COLUMNS} SELECT ${AUDIT_PLACEHOLDERS}
195
+ WHERE changes() > 0 AND NOT EXISTS (SELECT 1 FROM audit_events WHERE id = ?)`)
196
+ .bind(...values, id),
197
+ ])
198
+ const last = (changes.length - 1) * 2
199
+ return { statements, rows: (results, offset = 0) => results[offset + last]?.results ?? [] }
200
+ }
201
+
202
+ /** Run one audited group as its own batch and answer the rows its last change returned. */
203
+ async run<T>(changes: readonly SqlChange[], event: AuditEventInput | undefined): Promise<T[]> {
204
+ const change = this.changed(changes, event)
205
+ const [only, ...more] = change.statements
206
+ // One statement is atomic alone, and a Postgres transaction would hold a pooled connection for nothing.
207
+ if (only !== undefined && more.length === 0) {
208
+ return change.rows([await only.all<T>()])
209
+ }
210
+ return change.rows(await this.db.batch<T>(change.statements))
211
+ }
212
+ }
213
+
214
+ /**
215
+ * A one-row SELECT that statements after a guarded change in one batch require: they write only when it finds a row,
216
+ * so they follow the change exactly when it changed something.
217
+ */
218
+ export interface SqlGuard {
219
+ readonly sql: string
220
+ readonly binds: readonly unknown[]
221
+ }
222
+
223
+ /** `INSERT INTO <target> SELECT <placeholders>`, guarded by `guard` when there is one. */
224
+ export function guardedInsert(target: string, placeholders: string, values: readonly unknown[], guard?: SqlGuard): { sql: string; binds: unknown[] } {
225
+ if (guard === undefined) {
226
+ return { sql: `INSERT INTO ${target} VALUES (${placeholders})`, binds: [...values] }
227
+ }
228
+ return { sql: `INSERT INTO ${target} SELECT ${placeholders} WHERE EXISTS (${guard.sql})`, binds: [...values, ...guard.binds] }
229
+ }
230
+
231
+ /**
232
+ * The INSERT of one `auth_log` row. `id` is deliberately omitted — the column is auto-assigned (SQLite rowid alias /
233
+ * Postgres identity; see the note on `auth_log` in migration 0001). Everything else, `created_at` included, is bound.
234
+ * With `guard`, the row is written only when the guard finds its row.
235
+ */
236
+ export function authLogStatement(db: SqlDatabase, input: AuthLogInput, guard?: SqlGuard): SqlStatement {
237
+ const insert = guardedInsert(
238
+ 'auth_log (request_id, app, kind, principal_id, credential_id, decision, reason, privileged, created_at, terminal_id, asserted_by)',
239
+ '?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?',
240
+ [
241
+ input.requestId,
242
+ input.app,
243
+ input.kind,
244
+ input.principalId,
245
+ input.credentialId ?? null,
246
+ input.decision,
247
+ input.reason ?? null,
248
+ input.privileged === true ? 1 : 0,
249
+ unixNow(),
250
+ input.terminal?.terminalId ?? null,
251
+ input.terminal?.assertedBy ?? null,
252
+ ],
253
+ guard,
254
+ )
255
+ return db.prepare(insert.sql).bind(...insert.binds)
256
+ }
257
+
258
+ export class AuditRepository {
259
+ constructor(
260
+ protected readonly db: SqlDatabase,
261
+ readonly writer: AuditWriter = new AuditWriter(db, 'sqlite'),
262
+ ) {}
263
+
264
+ /** Write an audit row that records no change of IAM's own, such as an application's event or an admin's access. */
265
+ async writeAuditEvent(input: AuditEventInput): Promise<void> {
266
+ await auditEventStatement(this.db, input).run()
267
+ }
268
+
269
+ async writeAuthLog(input: AuthLogInput): Promise<void> {
270
+ await authLogStatement(this.db, input).run()
271
+ }
272
+
273
+ /**
274
+ * Run a change of several repositories and its audit rows as ONE batch, in order. Every statement must come from
275
+ * the database this repository holds; a composition root builds all repositories over one.
276
+ */
277
+ commit<T = Record<string, unknown>>(statements: SqlStatement[]): Promise<SqlQueryResult<T>[]> {
278
+ return this.db.batch<T>(statements)
279
+ }
280
+
281
+ /** The statement form of `writeAuthLog`, for a use case that composes a `commit`. */
282
+ authLogStatement(input: AuthLogInput): SqlStatement {
283
+ return authLogStatement(this.db, input)
284
+ }
285
+
286
+ /** The statement form of `auditEventStatement`, for a use case that composes a `commit`. */
287
+ eventStatement(event: AuditEventInput): SqlStatement {
288
+ return auditEventStatement(this.db, event)
289
+ }
290
+
291
+ // ── Audit reads (admin) ───────────────────────────────────────────────────
292
+
293
+ async listAuditEvents(filter: {
294
+ resourceType?: string
295
+ resourceId?: string
296
+ principalId?: string
297
+ subjectPrincipalId?: string
298
+ action?: string
299
+ /** Actions to leave out, before the page is cut, so `limit` counts only the rows that remain. */
300
+ excludeActions?: readonly string[]
301
+ requestId?: string
302
+ before?: string
303
+ limit: number
304
+ }): Promise<AuditEventRow[]> {
305
+ const where: string[] = []
306
+ const binds: (string | number)[] = []
307
+ if (filter.subjectPrincipalId) {
308
+ // Old events already identify the affected person in metadata. Guard malformed legacy JSON on both engines.
309
+ const subject = this.writer.dialect === 'postgres'
310
+ ? "CASE WHEN metadata IS JSON THEN CAST(metadata AS jsonb) ->> 'principalId' END"
311
+ : "CASE WHEN json_valid(metadata) THEN json_extract(metadata, '$.principalId') END"
312
+ where.push(`((resource_type = 'principal' AND resource_id = ?) OR ${subject} = ?
313
+ OR (action = 'iam.member.accept' AND principal_id = ?)
314
+ OR (resource_type = 'oauth_grant' AND resource_id IN (SELECT id FROM oauth_grants WHERE principal_id = ?)))`)
315
+ binds.push(filter.subjectPrincipalId, filter.subjectPrincipalId, filter.subjectPrincipalId, filter.subjectPrincipalId)
316
+ }
317
+ if (filter.resourceType) {
318
+ where.push('resource_type = ?')
319
+ binds.push(filter.resourceType)
320
+ }
321
+ if (filter.resourceId) {
322
+ where.push('resource_id = ?')
323
+ binds.push(filter.resourceId)
324
+ }
325
+ if (filter.principalId) {
326
+ where.push('principal_id = ?')
327
+ binds.push(filter.principalId)
328
+ }
329
+ if (filter.action) {
330
+ where.push('action = ?')
331
+ binds.push(filter.action)
332
+ }
333
+ if (filter.excludeActions !== undefined && filter.excludeActions.length > 0) {
334
+ where.push(`action NOT IN (${filter.excludeActions.map(() => '?').join(', ')})`)
335
+ binds.push(...filter.excludeActions)
336
+ }
337
+ if (filter.requestId) {
338
+ where.push('request_id = ?')
339
+ binds.push(filter.requestId)
340
+ }
341
+ if (filter.before) {
342
+ // Cursor by UUIDv7 id — keyset pagination, descending. The generator is monotonic (RFC 9562
343
+ // §6.2 counter), so two events from one millisecond cannot tie and the cursor can neither
344
+ // skip nor repeat a row.
345
+ where.push('id < ?')
346
+ binds.push(filter.before)
347
+ }
348
+ const sql = `SELECT * FROM audit_events${where.length ? ` WHERE ${where.join(' AND ')}` : ''} ORDER BY id DESC LIMIT ?`
349
+ binds.push(filter.limit)
350
+ const { results } = await this.db.prepare(sql).bind(...binds).all<AuditEventRow>()
351
+ return results
352
+ }
353
+
354
+ async listAuthLog(filter: {
355
+ principalId?: string
356
+ requestId?: string
357
+ decision?: 'allow' | 'deny'
358
+ before?: number
359
+ limit: number
360
+ }): Promise<AuthLogRow[]> {
361
+ const where: string[] = []
362
+ const binds: (string | number)[] = []
363
+ if (filter.principalId) {
364
+ where.push('principal_id = ?')
365
+ binds.push(filter.principalId)
366
+ }
367
+ if (filter.requestId) {
368
+ where.push('request_id = ?')
369
+ binds.push(filter.requestId)
370
+ }
371
+ if (filter.decision) {
372
+ where.push('decision = ?')
373
+ binds.push(filter.decision)
374
+ }
375
+ if (filter.before !== undefined) {
376
+ // Cursor by rowid (time-correlated, monotonic) — keyset pagination.
377
+ where.push('id < ?')
378
+ binds.push(filter.before)
379
+ }
380
+ const sql = `SELECT * FROM auth_log${where.length ? ` WHERE ${where.join(' AND ')}` : ''} ORDER BY id DESC LIMIT ?`
381
+ binds.push(filter.limit)
382
+ const { results } = await this.db.prepare(sql).bind(...binds).all<AuthLogRow>()
383
+ return results
384
+ }
385
+
386
+ // ── Retention (cron) ──────────────────────────────────────────────────────
387
+
388
+ /**
389
+ * Prune `auth_log` rows older than `olderThanSeconds` (unix seconds). The rowid
390
+ * is time-correlated, so pruning by `created_at` needs no extra index.
391
+ */
392
+ async pruneAuthLog(olderThanSeconds: number): Promise<number> {
393
+ const result = await this.db
394
+ .prepare('DELETE FROM auth_log WHERE created_at < ?')
395
+ .bind(olderThanSeconds)
396
+ .run()
397
+ return result.meta.changes ?? 0
398
+ }
399
+
400
+ /** Prune `audit_events` older than `olderThanSeconds` — only where the operator set an audit retention. */
401
+ async pruneAuditEvents(olderThanSeconds: number): Promise<number> {
402
+ const result = await this.db.prepare('DELETE FROM audit_events WHERE created_at < ?').bind(olderThanSeconds).run()
403
+ return result.meta.changes ?? 0
404
+ }
405
+ }
@@ -0,0 +1,66 @@
1
+ import { type SqlDatabase } from '@fabrika/platform'
2
+ import { type AuditEventInput, AuditWriter } from './audit'
3
+ import { unixNow } from './sql'
4
+
5
+ /** The one row of `installation_brand` (migration 0021). A row without a light image is no brand. */
6
+ export interface InstallationBrandRow {
7
+ id: number
8
+ light_type: string | null
9
+ light_base64: string | null
10
+ dark_type: string | null
11
+ dark_base64: string | null
12
+ /** When the brand was last set or cleared, in epoch seconds. */
13
+ updated_at: number
14
+ }
15
+
16
+ /** The images a write stores: the light one always, the dark one when the brand has it. */
17
+ export interface InstallationBrandImages {
18
+ readonly light: { readonly type: string; readonly base64: string }
19
+ readonly dark: { readonly type: string; readonly base64: string } | null
20
+ }
21
+
22
+ const COLUMNS = 'id, light_type, light_base64, dark_type, dark_base64, updated_at'
23
+
24
+ /**
25
+ * The installation's client logo (ADR-0066). The row is the installation's, so its key is the constant 1. The caller
26
+ * has checked the images; this stores them as given, and the reader checks them again.
27
+ */
28
+ export class InstallationBrandRepository {
29
+ constructor(
30
+ protected readonly db: SqlDatabase,
31
+ private readonly writer: AuditWriter = new AuditWriter(db, 'sqlite'),
32
+ ) {}
33
+
34
+ /** The stored row, or null when no brand was ever set. */
35
+ async get(): Promise<InstallationBrandRow | null> {
36
+ return this.db.prepare(`SELECT ${COLUMNS} FROM installation_brand WHERE id = 1`).first<InstallationBrandRow>()
37
+ }
38
+
39
+ /** Store the brand in place of any earlier one, with its record in the same statement group. Always a change. */
40
+ async set(images: InstallationBrandImages, audit: AuditEventInput): Promise<InstallationBrandRow> {
41
+ const [row] = await this.writer.run<InstallationBrandRow>([{
42
+ sql: `INSERT INTO installation_brand (${COLUMNS}) VALUES (1, ?, ?, ?, ?, ?)
43
+ ON CONFLICT (id) DO UPDATE SET light_type = excluded.light_type, light_base64 = excluded.light_base64,
44
+ dark_type = excluded.dark_type, dark_base64 = excluded.dark_base64, updated_at = excluded.updated_at
45
+ RETURNING ${COLUMNS}`,
46
+ binds: [images.light.type, images.light.base64, images.dark?.type ?? null, images.dark?.base64 ?? null, unixNow()],
47
+ }], audit)
48
+ if (row === undefined) {
49
+ throw new Error('expected a row from a RETURNING statement, got none')
50
+ }
51
+ return row
52
+ }
53
+
54
+ /**
55
+ * Remove the images and keep the row, so `updated_at` says when the brand was cleared. Only a row that still has an
56
+ * image changes, so clearing an absent brand writes neither the row nor its record; null then.
57
+ */
58
+ async clear(audit: AuditEventInput): Promise<InstallationBrandRow | null> {
59
+ const [row] = await this.writer.run<InstallationBrandRow>([{
60
+ sql: `UPDATE installation_brand SET light_type = NULL, light_base64 = NULL, dark_type = NULL, dark_base64 = NULL, updated_at = ?
61
+ WHERE id = 1 AND light_type IS NOT NULL RETURNING ${COLUMNS}`,
62
+ binds: [unixNow()],
63
+ }], audit)
64
+ return row ?? null
65
+ }
66
+ }