@pithy-sh/audit 0.6.0 → 0.7.1

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 (183) hide show
  1. package/README.md +93 -0
  2. package/dist/accessHistory.d.ts +315 -0
  3. package/dist/accessHistory.d.ts.map +1 -0
  4. package/dist/accessHistory.js +299 -0
  5. package/dist/actions.d.ts +15 -1
  6. package/dist/actions.d.ts.map +1 -1
  7. package/dist/actions.js +16 -2
  8. package/dist/capability.d.ts +14 -0
  9. package/dist/capability.d.ts.map +1 -1
  10. package/dist/capability.js +106 -12
  11. package/dist/chain/append.d.ts +43 -0
  12. package/dist/chain/append.d.ts.map +1 -0
  13. package/dist/chain/append.js +110 -0
  14. package/dist/chain/checkpoint.d.ts +70 -0
  15. package/dist/chain/checkpoint.d.ts.map +1 -0
  16. package/dist/chain/checkpoint.js +133 -0
  17. package/dist/chain/lockCheck.d.ts +15 -0
  18. package/dist/chain/lockCheck.d.ts.map +1 -0
  19. package/dist/chain/lockCheck.js +75 -0
  20. package/dist/chain/prune.d.ts +84 -0
  21. package/dist/chain/prune.d.ts.map +1 -0
  22. package/dist/chain/prune.js +231 -0
  23. package/dist/chain/rows.d.ts +74 -0
  24. package/dist/chain/rows.d.ts.map +1 -0
  25. package/dist/chain/rows.js +133 -0
  26. package/dist/chain/tombstone.d.ts +21 -0
  27. package/dist/chain/tombstone.d.ts.map +1 -0
  28. package/dist/chain/tombstone.js +98 -0
  29. package/dist/chain/verify.d.ts +63 -0
  30. package/dist/chain/verify.d.ts.map +1 -0
  31. package/dist/chain/verify.js +220 -0
  32. package/dist/citations.d.ts +17 -0
  33. package/dist/citations.d.ts.map +1 -0
  34. package/dist/citations.js +48 -0
  35. package/dist/cli/emitFromCLI.d.ts +5 -0
  36. package/dist/cli/emitFromCLI.d.ts.map +1 -1
  37. package/dist/cli/emitFromCLI.js +5 -0
  38. package/dist/data/auditEvent.d.ts +4 -0
  39. package/dist/data/auditEvent.d.ts.map +1 -1
  40. package/dist/data/auditEvent.js +7 -3
  41. package/dist/data/sinkState.d.ts +23 -0
  42. package/dist/data/sinkState.d.ts.map +1 -0
  43. package/dist/data/sinkState.js +25 -0
  44. package/dist/data/tables.d.ts +14 -1
  45. package/dist/data/tables.d.ts.map +1 -1
  46. package/dist/data/tables.js +5 -1
  47. package/dist/http/guards.d.ts +39 -6
  48. package/dist/http/guards.d.ts.map +1 -1
  49. package/dist/http/guards.js +101 -17
  50. package/dist/http/responses.d.ts +503 -0
  51. package/dist/http/responses.d.ts.map +1 -1
  52. package/dist/http/responses.js +157 -5
  53. package/dist/http/routes.d.ts +25 -3
  54. package/dist/http/routes.d.ts.map +1 -1
  55. package/dist/http/routes.js +321 -15
  56. package/dist/http/schemas.d.ts +67 -0
  57. package/dist/http/schemas.d.ts.map +1 -1
  58. package/dist/http/schemas.js +88 -4
  59. package/dist/http/views.d.ts +25 -1
  60. package/dist/http/views.d.ts.map +1 -1
  61. package/dist/http/views.js +107 -2
  62. package/dist/migrations/0003_call_index.d.ts +21 -0
  63. package/dist/migrations/0003_call_index.d.ts.map +1 -0
  64. package/dist/migrations/0003_call_index.js +33 -0
  65. package/dist/migrations/0004_request_index.d.ts +16 -0
  66. package/dist/migrations/0004_request_index.d.ts.map +1 -0
  67. package/dist/migrations/0004_request_index.js +24 -0
  68. package/dist/migrations/0005_chain.d.ts +24 -0
  69. package/dist/migrations/0005_chain.d.ts.map +1 -0
  70. package/dist/migrations/0005_chain.js +43 -0
  71. package/dist/migrations/0006_sinks.d.ts +11 -0
  72. package/dist/migrations/0006_sinks.d.ts.map +1 -0
  73. package/dist/migrations/0006_sinks.js +20 -0
  74. package/dist/provision/resolveAuditConfig.d.ts +31 -0
  75. package/dist/provision/resolveAuditConfig.d.ts.map +1 -0
  76. package/dist/provision/resolveAuditConfig.js +43 -0
  77. package/dist/purge/contribution.d.ts +21 -0
  78. package/dist/purge/contribution.d.ts.map +1 -0
  79. package/dist/purge/contribution.js +41 -0
  80. package/dist/reach.d.ts +250 -0
  81. package/dist/reach.d.ts.map +1 -0
  82. package/dist/reach.js +244 -0
  83. package/dist/recorder.d.ts +11 -0
  84. package/dist/recorder.d.ts.map +1 -1
  85. package/dist/recorder.js +23 -5
  86. package/dist/routePattern.d.ts +60 -0
  87. package/dist/routePattern.d.ts.map +1 -0
  88. package/dist/routePattern.js +130 -0
  89. package/dist/seeds/example.d.ts.map +1 -1
  90. package/dist/seeds/example.js +23 -6
  91. package/dist/ship/consumer.d.ts +45 -0
  92. package/dist/ship/consumer.d.ts.map +1 -0
  93. package/dist/ship/consumer.js +141 -0
  94. package/dist/ship/event.d.ts +59 -0
  95. package/dist/ship/event.d.ts.map +1 -0
  96. package/dist/ship/event.js +77 -0
  97. package/dist/ship/health.d.ts +33 -0
  98. package/dist/ship/health.d.ts.map +1 -0
  99. package/dist/ship/health.js +80 -0
  100. package/dist/ship/profiles.d.ts +34 -0
  101. package/dist/ship/profiles.d.ts.map +1 -0
  102. package/dist/ship/profiles.js +62 -0
  103. package/dist/ship/queue.d.ts +57 -0
  104. package/dist/ship/queue.d.ts.map +1 -0
  105. package/dist/ship/queue.js +70 -0
  106. package/dist/ship/secrets.d.ts +7 -0
  107. package/dist/ship/secrets.d.ts.map +1 -0
  108. package/dist/ship/secrets.js +40 -0
  109. package/dist/ship/shipper.d.ts +15 -0
  110. package/dist/ship/shipper.d.ts.map +1 -0
  111. package/dist/ship/shipper.js +27 -0
  112. package/dist/ship/sinks.d.ts +54 -0
  113. package/dist/ship/sinks.d.ts.map +1 -0
  114. package/dist/ship/sinks.js +45 -0
  115. package/dist/ship/state.d.ts +27 -0
  116. package/dist/ship/state.d.ts.map +1 -0
  117. package/dist/ship/state.js +29 -0
  118. package/dist/usage.d.ts +159 -0
  119. package/dist/usage.d.ts.map +1 -0
  120. package/dist/usage.js +87 -0
  121. package/dist/version.generated.d.ts +1 -1
  122. package/dist/version.generated.js +1 -1
  123. package/dist/workflows/prune.d.ts +73 -0
  124. package/dist/workflows/prune.d.ts.map +1 -0
  125. package/dist/workflows/prune.js +128 -0
  126. package/dist/workflows/retryPolicy.d.ts +10 -0
  127. package/dist/workflows/retryPolicy.d.ts.map +1 -0
  128. package/dist/workflows/retryPolicy.js +14 -0
  129. package/dist/workflows/specs.d.ts +70 -0
  130. package/dist/workflows/specs.d.ts.map +1 -0
  131. package/dist/workflows/specs.js +70 -0
  132. package/dist/workflows/worker.d.ts +32 -0
  133. package/dist/workflows/worker.d.ts.map +1 -0
  134. package/dist/workflows/worker.js +41 -0
  135. package/package.json +5 -2
  136. package/pithy.manifest.json +36 -4
  137. package/src/accessHistory.ts +360 -0
  138. package/src/actions.ts +15 -1
  139. package/src/capability.ts +134 -12
  140. package/src/chain/append.ts +161 -0
  141. package/src/chain/checkpoint.ts +172 -0
  142. package/src/chain/lockCheck.ts +72 -0
  143. package/src/chain/prune.ts +340 -0
  144. package/src/chain/rows.ts +211 -0
  145. package/src/chain/tombstone.ts +104 -0
  146. package/src/chain/verify.ts +366 -0
  147. package/src/citations.ts +62 -0
  148. package/src/cli/emitFromCLI.ts +5 -0
  149. package/src/cloudflare-test.d.ts +1 -0
  150. package/src/data/auditEvent.ts +31 -1
  151. package/src/data/sinkState.ts +41 -0
  152. package/src/data/tables.ts +7 -1
  153. package/src/http/guards.ts +90 -6
  154. package/src/http/responses.ts +318 -3
  155. package/src/http/routes.ts +379 -7
  156. package/src/http/schemas.ts +158 -2
  157. package/src/http/views.ts +123 -1
  158. package/src/migrations/0003_call_index.ts +35 -0
  159. package/src/migrations/0004_request_index.ts +26 -0
  160. package/src/migrations/0005_chain.ts +56 -0
  161. package/src/migrations/0006_sinks.ts +28 -0
  162. package/src/provision/resolveAuditConfig.ts +60 -0
  163. package/src/purge/contribution.ts +39 -0
  164. package/src/reach.ts +454 -0
  165. package/src/recorder.ts +64 -42
  166. package/src/routePattern.ts +141 -0
  167. package/src/seeds/example.ts +13 -0
  168. package/src/ship/consumer.ts +169 -0
  169. package/src/ship/event.ts +86 -0
  170. package/src/ship/health.ts +92 -0
  171. package/src/ship/profiles.ts +99 -0
  172. package/src/ship/queue.ts +108 -0
  173. package/src/ship/secrets.ts +42 -0
  174. package/src/ship/shipper.ts +32 -0
  175. package/src/ship/sinks.ts +82 -0
  176. package/src/ship/state.ts +61 -0
  177. package/src/usage.ts +176 -0
  178. package/src/version.generated.ts +1 -1
  179. package/src/workflows/prune.ts +196 -0
  180. package/src/workflows/retryPolicy.ts +14 -0
  181. package/src/workflows/specs.ts +92 -0
  182. package/src/workflows/worker.ts +65 -0
  183. package/src/workflows/wrangler.jsonc +40 -0
@@ -0,0 +1,32 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from "cloudflare:workers";
4
+ import type { D1Database, R2Bucket } from "@cloudflare/workers-types";
5
+ import { AuditCheckpointParams } from "./specs";
6
+ /**
7
+ * **The prebuilt checkpoint host (#822).** It hosts the one checkpoint Workflow and fires it from its cron. The app
8
+ * Worker records the events; this one writes each chain's head and count to the checkpoint bucket, where nothing in
9
+ * the app's request path can reach to rewrite it.
10
+ */
11
+ /** What the host is bound to. */
12
+ export interface AuditWorkerEnv {
13
+ /** The audit database — the app's, by default, or whichever the adopter's `audit({ database })` names. */
14
+ DB: D1Database;
15
+ /** The checkpoint bucket. Under an object-lock rule, nothing here can replace or delete what it writes. */
16
+ AUDIT_CHECKPOINTS: R2Bucket;
17
+ /** The environment served, stamped at deploy. */
18
+ ENVIRONMENT?: string;
19
+ }
20
+ export declare class AuditCheckpointWorkflow extends WorkflowEntrypoint<AuditWorkerEnv, AuditCheckpointParams> {
21
+ run(event: WorkflowEvent<AuditCheckpointParams>, step: WorkflowStep): Promise<void>;
22
+ }
23
+ declare const _default: {
24
+ fetch(): Promise<Response>;
25
+ /**
26
+ * Cron entry: start one checkpoint run per fire, through the same dispatcher an on-demand run uses, so a host
27
+ * deployed with its binding absent logs a skip rather than throwing inside a cron nobody is watching.
28
+ */
29
+ scheduled(_controller: unknown, env: AuditWorkerEnv): Promise<void>;
30
+ };
31
+ export default _default;
32
+ //# sourceMappingURL=worker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.d.ts","sourceRoot":"","sources":["../../src/workflows/worker.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,kBAAkB,EAAE,KAAK,aAAa,EAAE,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAE/F,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAStE,OAAO,EAAoB,qBAAqB,EAAyB,MAAM,SAAS,CAAC;AAEzF;;;;GAIG;AAEH,iCAAiC;AACjC,MAAM,WAAW,cAAc;IAC7B,0GAA0G;IAC1G,EAAE,EAAE,UAAU,CAAC;IACf,2GAA2G;IAC3G,iBAAiB,EAAE,QAAQ,CAAC;IAC5B,iDAAiD;IACjD,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,qBAAa,uBAAwB,SAAQ,kBAAkB,CAAC,cAAc,EAAE,qBAAqB,CAAC;IACrF,GAAG,CAAC,KAAK,EAAE,aAAa,CAAC,qBAAqB,CAAC,EAAE,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAajG;CACF;;;IAIC;;;OAGG;2BAC0B,OAAO,OAAO,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC"}
@@ -0,0 +1,41 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { writeCheckpoints } from "../chain/checkpoint.js";
4
+ import { AUDIT_CAPABILITY, AuditCheckpointParams, auditWorkflowRegistry } from "./specs.js";
5
+ import { auditDatabase } from "../data/tables.js";
6
+ import { auditWorkflowRetry } from "./retryPolicy.js";
7
+ import { bindWorkflowContext, createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
8
+ import { workflowKey } from "@pithy-sh/core/src/workflow/naming";
9
+ import { classifiedSteps } from "@pithy-sh/core/src/workflow/faults";
10
+ import { WorkflowEntrypoint } from "cloudflare:workers";
11
+ import { NonRetryableError } from "cloudflare:workflows";
12
+ import { triggerWorkflow } from "@pithy-sh/core/src/workflow/dispatch";
13
+ import { workflowHostEntry } from "@pithy-sh/core/src/workflow/hostEntry";
14
+ //#region src/workflows/worker.ts
15
+ var AuditCheckpointWorkflow = class extends WorkflowEntrypoint {
16
+ async run(event, step) {
17
+ AuditCheckpointParams.parse(event.payload ?? {});
18
+ const log = bindWorkflowContext(createWorkerLogger({ name: AUDIT_CAPABILITY }), {
19
+ workflow: event.workflowName,
20
+ instance: event.instanceId,
21
+ env: this.env.ENVIRONMENT ?? "unknown"
22
+ });
23
+ const run = await classifiedSteps(step, auditWorkflowRetry, NonRetryableError).do("checkpoint", async () => writeCheckpoints(auditDatabase(this.env.DB), this.env.AUDIT_CHECKPOINTS, /* @__PURE__ */ new Date()));
24
+ log.info("audit checkpoint written", {
25
+ written: run.written,
26
+ unchanged: run.unchanged
27
+ });
28
+ }
29
+ };
30
+ var worker_default = {
31
+ ...workflowHostEntry(AUDIT_CAPABILITY),
32
+ /**
33
+ * Cron entry: start one checkpoint run per fire, through the same dispatcher an on-demand run uses, so a host
34
+ * deployed with its binding absent logs a skip rather than throwing inside a cron nobody is watching.
35
+ */
36
+ async scheduled(_controller, env) {
37
+ await triggerWorkflow(env, auditWorkflowRegistry, workflowKey(AUDIT_CAPABILITY, "checkpoint"), {}, createWorkerLogger({ name: AUDIT_CAPABILITY }));
38
+ }
39
+ };
40
+ //#endregion
41
+ export { AuditCheckpointWorkflow, worker_default as default };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithy-sh/audit",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "license": "FSL-1.1-MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -38,7 +38,8 @@
38
38
  "@hono/zod-validator": "^0.9.0"
39
39
  },
40
40
  "peerDependencies": {
41
- "@pithy-sh/core": "^0.13.0",
41
+ "@pithy-sh/core": "^0.15.0",
42
+ "@pithy-sh/secrets": "^0.6.3",
42
43
  "hono": "^4.13.2",
43
44
  "kysely": "^0.29.0",
44
45
  "zod": "^4.4.0"
@@ -46,9 +47,11 @@
46
47
  "devDependencies": {
47
48
  "@cloudflare/vitest-plugin": "^1.4.2",
48
49
  "@pithy-sh/core": "workspace:*",
50
+ "@pithy-sh/secrets": "workspace:*",
49
51
  "@pithy-sh/tsconfig": "workspace:*",
50
52
  "@types/node": "^22.15.0",
51
53
  "@vitest/coverage-v8": "^4.1.0",
54
+ "comment-json": "^5.0.0",
52
55
  "hono": "^4.13.2",
53
56
  "kysely": "^0.29.0",
54
57
  "kysely-d1": "^0.4.0",
@@ -1,19 +1,51 @@
1
1
  {
2
2
  "name": "audit",
3
3
  "package": "@pithy-sh/audit",
4
- "requiredBindings": [{ "type": "d1", "name": "DB" }],
4
+ "requiredBindings": [
5
+ {
6
+ "type": "d1",
7
+ "name": "DB"
8
+ },
9
+ {
10
+ "type": "r2",
11
+ "name": "AUDIT_CHECKPOINTS",
12
+ "optional": true
13
+ },
14
+ {
15
+ "type": "workflow",
16
+ "name": "AUDIT_CHECKPOINT",
17
+ "job": "checkpoint",
18
+ "className": "AuditCheckpointWorkflow",
19
+ "optional": true
20
+ },
21
+ {
22
+ "type": "queue",
23
+ "name": "AUDIT_SHIP",
24
+ "optional": true,
25
+ "consumer": {
26
+ "deadLetter": "AUDIT_SHIP_DLQ",
27
+ "maxRetries": 10,
28
+ "maxBatchSize": 50
29
+ }
30
+ },
31
+ {
32
+ "type": "queue",
33
+ "name": "AUDIT_SHIP_DLQ",
34
+ "optional": true
35
+ }
36
+ ],
5
37
  "migrationNamespace": "audit",
6
- "whenToEnable": "A queryable, tamper-resistant audit trail of security-relevant actions — logins, token refreshes, entitlement grants, admin config changes. Records who did what, when, and whether it succeeded, attributed to the right actor. Other capabilities emit through the core seam; auth needs it the moment it lands.",
38
+ "whenToEnable": "A queryable, tamper-evident audit trail of security-relevant actions \u2014 logins, token refreshes, entitlement grants, admin config changes. Records who did what, when, and whether it succeeded, attributed to the right actor. Other capabilities emit through the core seam; auth needs it the moment it lands.",
7
39
  "configOptions": [
8
40
  {
9
41
  "key": "database",
10
42
  "default": "DB",
11
- "describe": "The D1 binding the audit table and its migrations target. Defaults to `DB`, the shared app database. KV is not an option — an audit log is a query workload, not a key lookup."
43
+ "describe": "The D1 binding the audit table and its migrations target. Defaults to `DB`, the shared app database. KV is not an option \u2014 an audit log is a query workload, not a key lookup."
12
44
  },
13
45
  {
14
46
  "key": "basePath",
15
47
  "default": "/audit",
16
- "describe": "Where the control-plane routes that read the trail mount. Reads only — the trail is append-only and this surface never writes."
48
+ "describe": "Where the control-plane routes that read the trail mount. Reads only \u2014 the trail is append-only and this surface never writes."
17
49
  }
18
50
  ]
19
51
  }
@@ -0,0 +1,360 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+
4
+ import { AuditActorType } from "@pithy-sh/core/src/audit/auditEvent";
5
+ import { ControlPlaneAuditActions } from "@pithy-sh/core/src/controlPlane/audit/actions";
6
+ import { ControlPlaneActorKind } from "@pithy-sh/core/src/controlPlane/data/connection";
7
+ import { SQLiteBoolean, SQLiteDate, sqliteJson } from "@pithy-sh/core/src/data/codecs";
8
+ import { decodeCursor, type PageCursor, pageLimit, toPage } from "@pithy-sh/core/src/data/cursor";
9
+ import { type RawBuilder, sql } from "kysely";
10
+ import { z } from "zod";
11
+ import type { AuditDatabase } from "./data/tables";
12
+
13
+ /**
14
+ * Who could do what, over time — `#831`.
15
+ *
16
+ * Every change to who can reach an environment's data is already in the trail: a membership joining, changing role,
17
+ * leaving or being removed, and a control-plane connection being registered, updated or removed, or a key on it
18
+ * registered, expired or revoked. What each changed — the role before and after, the scopes before and after — is in
19
+ * the row's `metadata`, which only the forensic one-event read returns, beside the IP and the user-agent. This reads
20
+ * the same rows in SQL and answers the changes.
21
+ *
22
+ * **One statement per page, never a walk.** The events are filtered, their known metadata keys lifted out, and each
23
+ * classified and given its before and after, all in D1. The handler pages the *answer*, oldest first; it never pages
24
+ * events to compute it.
25
+ *
26
+ * **Nothing personal, and nothing else, leaves this function.** It reads {@link ACCESS_HISTORY_METADATA_KEYS} out of
27
+ * `metadata` and no other key, and never the IP or the user-agent columns. The principal is the one personal field,
28
+ * and it is what the question is: who sanctioned a connection is half of who could reach the data through it.
29
+ *
30
+ * **A change recorded before its emitter carried the detail reads as `not_recorded`**, never as a guess. A role
31
+ * change from before `previousRole` was written has no before, and an update that moved no scope, from before the
32
+ * grant was written on every update, has neither — so their values are null and `recorded` says why.
33
+ */
34
+
35
+ /**
36
+ * The code an accepted invitation writes. It carries `joined: false` when the person was already a member: acceptance
37
+ * then changed nothing, and its `role` is the role the invitation offered, not the one the membership holds.
38
+ */
39
+ export const INVITATION_ACCEPTED_ACTION = "organization/member_joined";
40
+
41
+ /**
42
+ * The membership codes `@pithy-sh/organization` writes, as literals.
43
+ *
44
+ * Literals rather than an import: audit depends on core alone, and a capability never reaches into another's
45
+ * internals (principle 4). A code is stable forever once a row holds one, and `packages/cli/src/audit/accessHistoryCodes.test.ts`
46
+ * holds every literal here to the register that declares it, so a rename there fails the build here.
47
+ */
48
+ export const MEMBER_ACCESS_ACTIONS = {
49
+ /** A membership was created with nothing before it — save {@link INVITATION_ACCEPTED_ACTION} with `joined: false`. */
50
+ joins: ["organization/created", INVITATION_ACCEPTED_ACTION, "organization/admin_member_added"],
51
+ /** A membership's role changed, recorded with `previousRole` from #831 on. */
52
+ changes: ["organization/member_role_changed", "organization/admin_member_role_changed"],
53
+ /** Ownership reached a membership: its role became the conferred one. */
54
+ ownership: ["organization/ownership_accepted", "organization/admin_ownership_forced"],
55
+ /** A membership ended, recorded with the role it held. */
56
+ ends: ["organization/member_removed", "organization/member_left", "organization/admin_member_removed"],
57
+ } as const;
58
+
59
+ /** The member codes whose actor is the member, so an older row without `subjectUserId` still names them. */
60
+ const SELF_ACTIONS = [
61
+ "organization/created",
62
+ "organization/member_joined",
63
+ "organization/member_left",
64
+ "organization/ownership_accepted",
65
+ ];
66
+
67
+ /** The connection-lifecycle codes, written by the CLI's `connectionRegistry`. */
68
+ const CONNECTION_ACTIONS = [
69
+ ControlPlaneAuditActions.connectionRegistered,
70
+ ControlPlaneAuditActions.connectionUpdated,
71
+ ControlPlaneAuditActions.connectionRemoved,
72
+ ];
73
+
74
+ /** The key codes the seam's own routes write. */
75
+ const KEY_ACTIONS = [ControlPlaneAuditActions.keyRegistered, ControlPlaneAuditActions.keyExpired];
76
+
77
+ /** Every code an access change is read from. */
78
+ export const ACCESS_ACTIONS: readonly string[] = [
79
+ ...MEMBER_ACCESS_ACTIONS.joins,
80
+ ...MEMBER_ACCESS_ACTIONS.changes,
81
+ ...MEMBER_ACCESS_ACTIONS.ownership,
82
+ ...MEMBER_ACCESS_ACTIONS.ends,
83
+ ...CONNECTION_ACTIONS,
84
+ ...KEY_ACTIONS,
85
+ ];
86
+
87
+ /**
88
+ * Every `metadata` key this read lifts, and the only ones. `accessHistory.workers.test.ts` holds the compiled
89
+ * statement to this list, so a key added to the SQL and not here fails.
90
+ */
91
+ export const ACCESS_HISTORY_METADATA_KEYS = [
92
+ "role",
93
+ "previousRole",
94
+ "confers",
95
+ "subjectUserId",
96
+ "membershipId",
97
+ "scopes",
98
+ "scopesBefore",
99
+ "scopesAfter",
100
+ "actorKind",
101
+ "purpose",
102
+ "authorizedBy",
103
+ "registeredKeyId",
104
+ "expiredKeyId",
105
+ "revokedKeyId",
106
+ "joined",
107
+ "replacedConnectionId",
108
+ ] as const;
109
+
110
+ /** What to read: an inclusive window, and where to resume. */
111
+ export interface AccessHistoryFilter {
112
+ /** Inclusive lower bound on `occurredAt`. */
113
+ since: Date;
114
+ /** Inclusive upper bound on `occurredAt`. */
115
+ until: Date;
116
+ /** Where to resume, from the previous page's `nextCursor`. Opaque; a malformed one is a first page. */
117
+ cursor?: string;
118
+ /** How many changes to return, clamped into `[1, MAX_PAGE_SIZE]`. */
119
+ limit?: number;
120
+ }
121
+
122
+ /** A list of scopes, as `json_extract` hands an array back: JSON text, decoded through the codec. */
123
+ const ScopeList = sqliteJson(z.array(z.string()).describe("A connection's granted scopes."));
124
+
125
+ /**
126
+ * One access change, decoded from the statement's row. Flat, because SQL is: `subject` says which fields mean
127
+ * something, and `http/views.ts` projects it into the wire union `AccessChangeView`.
128
+ */
129
+ export const AccessHistoryRow = z
130
+ .object({
131
+ id: z.number().int().describe("The event's surrogate id. The keyset tiebreak; never on the wire."),
132
+ eventId: z.string().describe("The event's public UUID."),
133
+ occurredAt: SQLiteDate.describe("When the change happened."),
134
+ action: z.string().describe("The `domain/reason` code the change was read from."),
135
+ actorType: AuditActorType.describe("The kind of principal that made the change."),
136
+ actorId: z.string().nullable().describe("The principal that made the change, or null."),
137
+ actorKind: ControlPlaneActorKind.nullable().describe("For a `control-plane` actor, which kind of client, or null."),
138
+ subject: z.enum(["member", "connection", "key"]).describe("What changed: a membership, a connection, or a key."),
139
+ recorded: SQLiteBoolean.describe("Whether the event carried its before and after. False reads as not recorded."),
140
+ organizationId: z.string().nullable().describe("A member change's organization — the event's tenant."),
141
+ membershipId: z.string().nullable().describe("A member change's membership."),
142
+ userId: z.string().nullable().describe("A member change's member."),
143
+ roleBefore: z.string().nullable().describe("A member change's role before, or null for none or not recorded."),
144
+ roleAfter: z.string().nullable().describe("A member change's role after, or null for none or not recorded."),
145
+ connectionId: z.string().nullable().describe("A connection or key change's connection."),
146
+ connectionKind: ControlPlaneActorKind.nullable().describe("The connection's kind of client, or null."),
147
+ purpose: z.string().nullable().describe("The connection's purpose, or null."),
148
+ principal: z.string().nullable().describe("Who sanctioned the connection, or null."),
149
+ scopesBefore: ScopeList.nullable().describe("The connection's scopes before, or null for none or not recorded."),
150
+ scopesAfter: ScopeList.nullable().describe("The connection's scopes after, or null for none or not recorded."),
151
+ replacedConnectionId: z
152
+ .string()
153
+ .nullable()
154
+ .describe("For a registration that started over, the connection it replaced, whose grant ended with it."),
155
+ keyId: z.string().nullable().describe("A key change's key id."),
156
+ keyChange: z.enum(["registered", "expired", "revoked"]).nullable().describe("What happened to the key."),
157
+ })
158
+ .describe("One access change, as the access-history statement answers it.");
159
+ export type AccessHistoryRow = z.output<typeof AccessHistoryRow>;
160
+
161
+ /** One page of access changes, oldest first, and where the next starts. */
162
+ export interface AccessHistoryPage {
163
+ /** The page, oldest first. */
164
+ changes: AccessHistoryRow[];
165
+ /** Where the next page starts, or null at the end of the window. */
166
+ nextCursor: string | null;
167
+ }
168
+
169
+ /** `json_extract(metadata, '<path>')`, the path a literal of ours and never a caller's. */
170
+ function meta(path: string): RawBuilder<unknown> {
171
+ return sql`json_extract(${sql.ref("metadata")}, ${sql.lit(path)})`;
172
+ }
173
+
174
+ /**
175
+ * A key an update may write as the value it holds now, or as `{ from, to }` when the update moved it: the `to`, or
176
+ * the plain value. `json_type` is null for an absent key, which reads as the plain value — also null.
177
+ */
178
+ function currentValue(key: string): RawBuilder<unknown> {
179
+ return sql`case json_type(${sql.ref("metadata")}, ${sql.lit(`$.${key}`)})
180
+ when 'object' then ${meta(`$.${key}.to`)} else ${meta(`$.${key}`)} end`;
181
+ }
182
+
183
+ /** `<column> in (<codes>)`, the codes bound as parameters. */
184
+ function oneOf(column: string, codes: readonly string[]): RawBuilder<boolean> {
185
+ return sql<boolean>`${sql.ref(column)} in (${sql.join(codes)})`;
186
+ }
187
+
188
+ /** A decoded cursor, narrowed to the `(occurredAt, id)` pair this ordering can use. Anything else is a first page. */
189
+ function keysetPosition(cursor: PageCursor | undefined): { sort: number; id: number } | undefined {
190
+ if (!cursor) return undefined;
191
+ if (typeof cursor.sort !== "number" || typeof cursor.id !== "number") return undefined;
192
+ return { sort: cursor.sort, id: cursor.id };
193
+ }
194
+
195
+ /**
196
+ * The page, as one Kysely statement — exported so a test can read what it compiles to.
197
+ *
198
+ * Three steps, in one statement:
199
+ *
200
+ * 1. **`extracted`** — the window's successful access events, after the cursor, with each named metadata key lifted
201
+ * out. `scopes` is an array on a registration and a removal and `{ from, to }` on an update that moved it, so the
202
+ * two are read apart. Kind, purpose and principal are the update's `to` where it moved them. An invitation redeemed
203
+ * by someone already a member (`joined` false) is left out here: it changed nothing.
204
+ * 2. **`classified`** — what changed. A member code is a member change; a key code is a key change, and so is a CLI
205
+ * update that registered or revoked a key, because that is what it did; the rest of the connection codes are
206
+ * connection changes.
207
+ * 3. **The answer** — each change's before and after by its code, and whether the event recorded them.
208
+ */
209
+ export function accessHistoryStatement(
210
+ db: AuditDatabase,
211
+ filter: AccessHistoryFilter,
212
+ page: { position?: { sort: number; id: number }; limit: number },
213
+ ) {
214
+ const { joins, changes, ownership, ends } = MEMBER_ACCESS_ACTIONS;
215
+ const memberActions = [...joins, ...changes, ...ownership, ...ends];
216
+ const position = page.position;
217
+ return db
218
+ .with("extracted", (q) =>
219
+ q
220
+ .selectFrom("pithyAuditEvents")
221
+ .select([
222
+ "id",
223
+ "eventId",
224
+ "occurredAt",
225
+ "action",
226
+ "actorType",
227
+ "actorId",
228
+ "actorKind",
229
+ "tenant",
230
+ "resourceId",
231
+ meta("$.role").as("role"),
232
+ meta("$.previousRole").as("previousRole"),
233
+ meta("$.confers").as("confers"),
234
+ meta("$.subjectUserId").as("subjectUserId"),
235
+ meta("$.membershipId").as("recordedMembershipId"),
236
+ sql`case json_type(${sql.ref("metadata")}, '$.scopes') when 'array' then ${meta("$.scopes")} end`.as(
237
+ "scopes",
238
+ ),
239
+ meta("$.scopes.from").as("scopesFrom"),
240
+ meta("$.scopes.to").as("scopesTo"),
241
+ meta("$.scopesBefore").as("scopesBeforeKey"),
242
+ meta("$.scopesAfter").as("scopesAfterKey"),
243
+ currentValue("actorKind").as("connectionKind"),
244
+ currentValue("purpose").as("purpose"),
245
+ currentValue("authorizedBy").as("principal"),
246
+ meta("$.registeredKeyId").as("registeredKeyId"),
247
+ meta("$.expiredKeyId").as("expiredKeyId"),
248
+ meta("$.revokedKeyId").as("revokedKeyId"),
249
+ meta("$.replacedConnectionId").as("replacedConnectionId"),
250
+ ])
251
+ .where("action", "in", ACCESS_ACTIONS)
252
+ // An invitation redeemed by someone already a member changed nothing. `json_extract` reads a JSON `false` as
253
+ // 0 and an absent key as null, so a row written before `joined` was recorded still reads as the join it was.
254
+ .where(
255
+ sql<boolean>`not (${sql.ref("action")} = ${INVITATION_ACCEPTED_ACTION} and coalesce(${meta("$.joined")}, 1) = 0)`,
256
+ )
257
+ .where("outcome", "=", "success")
258
+ .where("occurredAt", ">=", SQLiteDate.encode(filter.since))
259
+ .where("occurredAt", "<=", SQLiteDate.encode(filter.until))
260
+ .$if(position !== undefined, (query) =>
261
+ query.where((eb) =>
262
+ eb.or([
263
+ eb("occurredAt", ">", position?.sort ?? 0),
264
+ eb.and([eb("occurredAt", "=", position?.sort ?? 0), eb("id", ">", position?.id ?? 0)]),
265
+ ]),
266
+ ),
267
+ ),
268
+ )
269
+ .with("classified", (q) =>
270
+ q
271
+ .selectFrom("extracted")
272
+ .selectAll()
273
+ .select(
274
+ sql<string>`case
275
+ when ${oneOf("action", memberActions)} then 'member'
276
+ when ${oneOf("action", KEY_ACTIONS)} then 'key'
277
+ when ${sql.ref("registeredKeyId")} is not null or ${sql.ref("revokedKeyId")} is not null then 'key'
278
+ else 'connection' end`.as("subject"),
279
+ ),
280
+ )
281
+ .with("answered", (q) =>
282
+ q.selectFrom("classified").select([
283
+ "id",
284
+ "eventId",
285
+ "occurredAt",
286
+ "action",
287
+ "actorType",
288
+ "actorId",
289
+ "actorKind",
290
+ "subject",
291
+ sql`case when ${sql.ref("subject")} = 'member' then ${sql.ref("tenant")} end`.as("organizationId"),
292
+ sql`case when ${sql.ref("subject")} = 'member' then
293
+ case when ${sql.ref("action")} = 'organization/created' then ${sql.ref("recordedMembershipId")}
294
+ else ${sql.ref("resourceId")} end end`.as("membershipId"),
295
+ sql`case when ${sql.ref("subject")} = 'member' then coalesce(${sql.ref("subjectUserId")},
296
+ case when ${oneOf("action", SELF_ACTIONS)} then ${sql.ref("actorId")} end) end`.as("userId"),
297
+ sql`case
298
+ when ${oneOf("action", changes)} or ${oneOf("action", ownership)} then ${sql.ref("previousRole")}
299
+ when ${oneOf("action", ends)} then ${sql.ref("role")} end`.as("roleBefore"),
300
+ sql`case
301
+ when ${oneOf("action", joins)} or ${oneOf("action", changes)} then ${sql.ref("role")}
302
+ when ${oneOf("action", ownership)} then coalesce(${sql.ref("role")}, ${sql.ref("confers")}) end`.as(
303
+ "roleAfter",
304
+ ),
305
+ sql`case when ${sql.ref("subject")} != 'member' then ${sql.ref("resourceId")} end`.as("connectionId"),
306
+ sql`case when ${sql.ref("subject")} = 'connection' then ${sql.ref("connectionKind")} end`.as("connectionKind"),
307
+ sql`case when ${sql.ref("subject")} = 'connection' then ${sql.ref("purpose")} end`.as("purpose"),
308
+ sql`case when ${sql.ref("subject")} = 'connection' then ${sql.ref("principal")} end`.as("principal"),
309
+ sql`case when ${sql.ref("subject")} = 'connection' then case ${sql.ref("action")}
310
+ when ${ControlPlaneAuditActions.connectionUpdated} then coalesce(${sql.ref("scopesBeforeKey")}, ${sql.ref("scopesFrom")})
311
+ when ${ControlPlaneAuditActions.connectionRemoved} then ${sql.ref("scopes")} end end`.as("scopesBefore"),
312
+ sql`case when ${sql.ref("subject")} = 'connection' then case ${sql.ref("action")}
313
+ when ${ControlPlaneAuditActions.connectionRegistered} then ${sql.ref("scopes")}
314
+ when ${ControlPlaneAuditActions.connectionUpdated} then coalesce(${sql.ref("scopesAfterKey")}, ${sql.ref("scopesTo")})
315
+ end end`.as("scopesAfter"),
316
+ sql`case when ${sql.ref("subject")} = 'connection' and ${sql.ref("action")} = ${ControlPlaneAuditActions.connectionRegistered}
317
+ then ${sql.ref("replacedConnectionId")} end`.as("replacedConnectionId"),
318
+ sql`case when ${sql.ref("subject")} = 'key' then
319
+ coalesce(${sql.ref("registeredKeyId")}, ${sql.ref("expiredKeyId")}, ${sql.ref("revokedKeyId")}) end`.as(
320
+ "keyId",
321
+ ),
322
+ sql`case when ${sql.ref("subject")} = 'key' then case
323
+ when ${sql.ref("action")} = ${ControlPlaneAuditActions.keyExpired} then 'expired'
324
+ when ${sql.ref("action")} = ${ControlPlaneAuditActions.keyRegistered} or ${sql.ref("registeredKeyId")} is not null then 'registered'
325
+ else 'revoked' end end`.as("keyChange"),
326
+ ]),
327
+ )
328
+ .selectFrom("answered")
329
+ .selectAll()
330
+ .select(
331
+ sql<number>`case ${sql.ref("subject")}
332
+ when 'member' then case
333
+ when ${oneOf("action", joins)} then ${sql.ref("roleAfter")} is not null
334
+ when ${oneOf("action", ends)} then ${sql.ref("roleBefore")} is not null
335
+ else ${sql.ref("roleBefore")} is not null and ${sql.ref("roleAfter")} is not null end
336
+ when 'connection' then case ${sql.ref("action")}
337
+ when ${ControlPlaneAuditActions.connectionRegistered} then ${sql.ref("scopesAfter")} is not null
338
+ when ${ControlPlaneAuditActions.connectionRemoved} then ${sql.ref("scopesBefore")} is not null
339
+ else ${sql.ref("scopesBefore")} is not null and ${sql.ref("scopesAfter")} is not null end
340
+ else ${sql.ref("keyId")} is not null end`.as("recorded"),
341
+ )
342
+ .orderBy("occurredAt", "asc")
343
+ .orderBy("id", "asc")
344
+ .limit(page.limit + 1);
345
+ }
346
+
347
+ /**
348
+ * Read one page of access changes in a window, oldest first.
349
+ *
350
+ * **Keyset, never offset**, ascending: the trail is appended to while it is read, and a change recorded mid-read
351
+ * lands after the window's last page rather than pushing a row from one page onto the next.
352
+ */
353
+ export async function accessHistory(db: AuditDatabase, filter: AccessHistoryFilter): Promise<AccessHistoryPage> {
354
+ const limit = pageLimit(filter.limit);
355
+ const position = keysetPosition(decodeCursor(filter.cursor));
356
+ const rows = await accessHistoryStatement(db, filter, { position, limit }).execute();
357
+ const decoded = rows.map((row) => AccessHistoryRow.parse(row));
358
+ const page = toPage(decoded, limit, (row) => ({ sort: row.occurredAt.getTime(), id: row.id }));
359
+ return { changes: page.items, nextCursor: page.nextCursor };
360
+ }
package/src/actions.ts CHANGED
@@ -42,10 +42,14 @@ export function defineAuditActions<const T extends Record<string, string>>(actio
42
42
  * every other capability, so a management client paging through it is doing something that has to be
43
43
  * answerable later; a trail that records every write and no read cannot answer "who looked".
44
44
  *
45
- * They are separate codes rather than one, because the two reads disclose different things and a
45
+ * They are separate codes rather than one, because the reads disclose different things and a
46
46
  * reviewer filtering the trail should not have to inspect metadata to tell them apart:
47
47
  * `audit/trail_read` is a filtered page of structural fields, while `audit/event_read` is the full
48
48
  * record of one event — the IP, the user-agent, and the capability metadata included.
49
+ * `audit/access_history_read` is the access changes in a window: who held what, and when it changed.
50
+ * `audit/reach_read` is one credential's reach: counts by tenant and route, and on request one route's subjects.
51
+ * `audit/usage_read` is counts: which scopes one connection exercised and was refused, by key, over a window.
52
+ * `audit/chain_verified` is a walk of one tenant's chain, and `audit/chain_exported` a page of it in canonical form (#822).
49
53
  *
50
54
  * Yes, this appends to the table it just read. That is a loop by design, not by accident: the row it
51
55
  * writes is one row, it is the only durable evidence the read happened, and the alternative is a
@@ -56,4 +60,14 @@ export const AuditTrailActions = defineAuditActions({
56
60
  trailRead: "audit/trail_read",
57
61
  /** One event was read in full, network identifiers and metadata included. */
58
62
  eventRead: "audit/event_read",
63
+ /** The access changes in a window were read — before and after, never an event in full (#831). */
64
+ accessHistoryRead: "audit/access_history_read",
65
+ /** One control-plane credential's reach was read — tenants, routes and subjects, never an event in full (#828). */
66
+ reachRead: "audit/reach_read",
67
+ /** One control-plane connection's usage was counted — scopes and keys, never an event in full (#812). */
68
+ usageRead: "audit/usage_read",
69
+ /** One tenant's chain was walked and checked against its checkpoints (#822). */
70
+ chainVerified: "audit/chain_verified",
71
+ /** A page of one tenant's chain was exported in canonical form, its personal values only with the detail scope (#822). */
72
+ chainExported: "audit/chain_exported",
59
73
  });