@pithy-sh/audit 0.6.0 → 0.7.0

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
package/README.md CHANGED
@@ -12,6 +12,99 @@ pithy add audit
12
12
 
13
13
  _Everything else is on the site. `pithy.sh/docs` is canonical — new prose goes there, not here._
14
14
 
15
+ ## Tamper evidence
16
+
17
+ **Every event is chained to the one before it.** Each tenant has its own chain, and the events with no tenant have one too. An event written after the upgrade carries its position, the hash of the event before it, and its own SHA-256 over a canonical serialization of every column. The IP, user-agent and metadata are committed by a salted hash rather than included, so an export that leaves them out still verifies. Appends are one compare-and-set statement, so concurrent writes never fork a chain, and an append that loses the race re-reads the head and tries again, so a burst of them to one tenant lands every event. The canonical form lives in `@pithy-sh/core/src/audit/chain`, the one definition the recorder, the Worker and the CLI all read.
18
+
19
+ **Checkpoints sit outside the database.** Hourly, the prebuilt checkpoint Worker writes each chain's head and count to the `AUDIT_CHECKPOINTS` R2 bucket, one object per checkpoint, never replaced. `pithy deploy` ships it, `pithy provision` creates the bucket, and `pithy audit lock --env <name>` puts an indefinite object lock on it. `pithy doctor` says whether the lock is in force. A chain rewritten end to end, hashes and all, disagrees with a checkpoint it cannot reach, and a truncated one ends before a checkpoint says it did.
20
+
21
+ **Verify it in the Worker, or without it.** Both reads need `audit:events:export`:
22
+
23
+ - `GET /audit/control-plane/verify?tenant=…&since=…&until=…` walks the range and answers intact, or the first break with its event id, its position and why: edited, missing, inserted, unlinked, against a checkpoint, or truncated before one.
24
+ - `GET /audit/control-plane/export?tenant=…` hands over the range in canonical form, each event with its hash, the link before it, every checkpoint covering it, and every tombstone of the chain. IP, user-agent and metadata values come out only when the connection also holds `audit:events:read_detail`; otherwise their commitments do.
25
+
26
+ `pithy audit verify <file>` recomputes an export's chain offline and checks it against its checkpoints, so an auditor trusts neither the Worker nor us. Nothing is signed, so nothing needs a key.
27
+
28
+ **Events from before the upgrade are marked, not chained.** Their chain columns stay null, the listing shows `chainSeq: null`, and verify counts them as `beforeChain`. Nothing back-fills them: a chain asserted over rows nobody checked would be a claim, not evidence. A row with no chain written *after* the chain began is counted as `outsideChain`, beside `beforeChain`, and is not a break: Workers redeploy one at a time, old and new versions serve side by side while one rolls out, and a rollback or an older CLI writes the same way, so an older recorder writing into a chained trail is a normal upgrade, not tampering. `intact` speaks for the chain itself. A row inserted with a chain position is the walk's, and is a break.
29
+
30
+ This proves the trail is whole. It adds no way to change it. The one way an event leaves is the retention prune, below, and it leaves a tombstone the verify reads across.
31
+
32
+ **The erasure attestation cites it.** `@pithy-sh/audit` declares `auditCitations`, the seam through which `GET /control-plane/erasure/:subjectType/:subjectId` points at the events a purge recorded: each by event id, tenant, chain position and hash, never its IP, user-agent or metadata. Hand an auditor the attestation and an export of that chain, and `pithy audit verify` checks the events it cites. Without this capability composed, the attestation says its trail is `absent`. [`docs/CONTROL-PLANE.md` §12](../../docs/CONTROL-PLANE.md#erasure) has the shape.
33
+
34
+ ## Retention
35
+
36
+ **The trail is kept forever unless the Worker says otherwise.** The `retention` block in its `pithy.config.ts` sets how long events are kept, by action prefix, with a default, and the kit holds `controlplane/*` and every lifecycle action at a year at least. The block, its floor and legal holds are [`docs/CONTROL-PLANE.md` §12](../../docs/CONTROL-PLANE.md#retention-and-legal-holds).
37
+
38
+ **The prune runs in your own Worker**, because it reads the block only that Worker resolves. Export the class beside `createEntrypoint`:
39
+
40
+ ```ts
41
+ // apps/api/src/index.ts
42
+ import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from "cloudflare:workers";
43
+ import { NonRetryableError } from "cloudflare:workflows";
44
+ import { runAuditPrune } from "@pithy-sh/audit/src/workflows/prune";
45
+
46
+ export class AuditPruneWorkflow extends WorkflowEntrypoint<Record<string, unknown>> {
47
+ override run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
48
+ return runAuditPrune(this.env, event, step, NonRetryableError);
49
+ }
50
+ }
51
+ ```
52
+
53
+ Then bind it as `AUDIT_PRUNE` in that Worker's `workflows`, beside the `0 2 * * *` cron auth's and organization's purge passes already use. The binding is optional: until it is bound, nothing is pruned.
54
+
55
+ **A pruned run leaves a tombstone, so the chain still verifies.** Before deleting a row, the prune writes one object per run to the `AUDIT_CHECKPOINTS` bucket, under the chain's checkpoint prefix, where the object lock covers it: the run's positions, the link before it, and the hashes at either end. `GET /audit/control-plane/verify` and `pithy audit verify` bridge the gap with it and answer intact. The Worker's verify also counts the events it crossed, as `pruned`; the CLI's report does not. Without the bucket bound in that Worker, nothing chained is pruned.
56
+
57
+ - **A run that does not verify stays.** The prune never removes the evidence of a break.
58
+ - **The head is never pruned.** The next append links to it.
59
+ - **An event kept longer stays where it is.** Windows differ by action, so each run of consecutive events past their windows is pruned on its own.
60
+ - **Rows from before the chain** are removed on their own window, with nothing to tombstone.
61
+ - **A legal hold on a tenant's trail stops it** at the next page, and the chain stays whole until the hold is released.
62
+
63
+ ## Shipping the trail
64
+
65
+ **Declare a sink and every event is sent to it as it is written.** Splunk HEC, Datadog Logs, or a generic JSON webhook for Elastic, Sumo Logic and anything else that takes HTTPS:
66
+
67
+ ```ts
68
+ audit({
69
+ sinks: {
70
+ siem: {
71
+ profile: "splunk-hec", // or "datadog-logs", or "webhook"
72
+ url: "https://splunk.example.com:8088/services/collector/event",
73
+ secret: "splunk-hec-token", // the @pithy-sh/secrets name the token is read through
74
+ actions: ["auth/", "controlplane/"], // optional: ship only these action prefixes
75
+ detail: false, // the default: ship hashes, never IP, user-agent or metadata values
76
+ },
77
+ },
78
+ });
79
+ ```
80
+
81
+ Set the token with `pithy secrets create splunk-hec-token --env prod`, then run `pithy upgrade` to write the queue bindings and `pithy provision` to create the queues. An unknown profile, a URL that is not HTTPS, a misspelled key, or a sink with no secret name is refused at config load. Shipping needs the `secrets` capability and Cloudflare Queues, which is on the Workers Paid plan; a project with no sink binds no queue.
82
+
83
+ **Declared, not toggled.** A sink is reviewed and deployed like code. No control-plane route adds, changes or removes one, so no management credential can point the trail somewhere new.
84
+
85
+ **Delivered at least once, and never in the way.** Each event a Worker writes goes on the `AUDIT_SHIP` queue once per sink that takes it, naming the event and the sink and nothing else; the Worker's own consumer reads the row back and posts each sink's share of a batch in one request. Enqueueing happens after the write and never fails it. A redirect is never followed, so the token and the batch go only to the URL you declared; a sink answering 3xx counts as a refusal. A sink that refuses or cannot be reached retries after 30 seconds, doubling to an hour, and fails alone: the other sinks still deliver. After ten retries a message goes to `AUDIT_SHIP_DLQ` and waits there for a person. Audit's manifest entry reports `auditShipBacklog`, `auditShipDeadLettered` and `auditShipDelivery` (`delivering`, `failing`, `idle`), behind `audit:events:read`, and `pithy doctor` lists every sink and whether each environment holds its token.
86
+
87
+ **Redacted by default.** Without `detail: true`, no IP, user-agent or metadata value leaves the Worker. The sink receives their salted commitments instead — the same ones the chain hashes — which verify and disclose nothing. With `detail: true` the values and their salt travel, so the receiver can check the commitments too.
88
+
89
+ **Verifiable at the receiver.** Every shipped event is the chain's canonical form, format `pithy-audit-ship/1`: its `eventId`, its tenant's `seq`, the `prev` hash and its own `hash`. A receiver de-duplicates a redelivery on `eventId`, which a redelivery carries unchanged. A tenant's `seq` that skips, or a `prev` naming a hash it never received, is where to look, and not every skip is a loss:
90
+
91
+ - **The CLI's events are in the chain and are not shipped.** `pithy deploy`, `pithy migrate`, `pithy secrets` and the rest record over the D1 REST API, outside any Worker, so they take a position in the chain and nothing enqueues them. Their `worker` is null.
92
+ - **A sink with an `actions` filter** skips every position it does not take, by design.
93
+
94
+ So reconcile a skip against the trail: export that range with `GET /audit/control-plane/export` and check it with `pithy audit verify`. A missing event that is neither a CLI action nor filtered out is a loss. An event from before the chain ships with `seq` and `hash` null.
95
+
96
+ | Profile | Request |
97
+ |---|---|
98
+ | `splunk-hec` | `Authorization: Splunk <token>`. One HEC event object per event, newline-joined: `time` in epoch seconds, `source: "pithy"`, `sourcetype: "pithy:audit"`, `host` the Worker, the event under `event`. |
99
+ | `datadog-logs` | `DD-API-KEY: <token>`. A JSON array of logs: `ddsource: "pithy"`, `service` the project, `hostname` the Worker, `ddtags` with `env`, `action` and `outcome`, a one-line `message`, the event under `audit`. |
100
+ | `webhook` | `Authorization: Bearer <token>`. One JSON document, `{ "format": "pithy-audit-ship/1", "events": [...] }`. |
101
+
102
+ This delivers the trail. It changes nothing in it.
103
+
104
+ ## A person's data
105
+
106
+ **Retained.** When an account is purged, audit erases nothing: *Kept as the record of who did what, which a security review or a dispute is read against.* The purge records the step as retained with that basis, and an export hands back every event where the person is the actor. See [`@pithy-sh/auth`'s account lifecycle](../auth/docs/account-lifecycle.md#what-each-capability-does-with-a-persons-rows).
107
+
15
108
  ## License
16
109
 
17
110
  `FSL-1.1-MIT` (Functional Source License). Use it freely for any purpose except a competing product; it converts to MIT two years after each release. The audit trail feeds the premium dashboard, so it starts more restrictive than the MIT core capabilities (CLAUDE.md §Packaging). See `LICENSE`.
@@ -0,0 +1,315 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { z } from "zod";
4
+ import type { AuditDatabase } from "./data/tables";
5
+ /**
6
+ * Who could do what, over time — `#831`.
7
+ *
8
+ * Every change to who can reach an environment's data is already in the trail: a membership joining, changing role,
9
+ * leaving or being removed, and a control-plane connection being registered, updated or removed, or a key on it
10
+ * registered, expired or revoked. What each changed — the role before and after, the scopes before and after — is in
11
+ * the row's `metadata`, which only the forensic one-event read returns, beside the IP and the user-agent. This reads
12
+ * the same rows in SQL and answers the changes.
13
+ *
14
+ * **One statement per page, never a walk.** The events are filtered, their known metadata keys lifted out, and each
15
+ * classified and given its before and after, all in D1. The handler pages the *answer*, oldest first; it never pages
16
+ * events to compute it.
17
+ *
18
+ * **Nothing personal, and nothing else, leaves this function.** It reads {@link ACCESS_HISTORY_METADATA_KEYS} out of
19
+ * `metadata` and no other key, and never the IP or the user-agent columns. The principal is the one personal field,
20
+ * and it is what the question is: who sanctioned a connection is half of who could reach the data through it.
21
+ *
22
+ * **A change recorded before its emitter carried the detail reads as `not_recorded`**, never as a guess. A role
23
+ * change from before `previousRole` was written has no before, and an update that moved no scope, from before the
24
+ * grant was written on every update, has neither — so their values are null and `recorded` says why.
25
+ */
26
+ /**
27
+ * The code an accepted invitation writes. It carries `joined: false` when the person was already a member: acceptance
28
+ * then changed nothing, and its `role` is the role the invitation offered, not the one the membership holds.
29
+ */
30
+ export declare const INVITATION_ACCEPTED_ACTION = "organization/member_joined";
31
+ /**
32
+ * The membership codes `@pithy-sh/organization` writes, as literals.
33
+ *
34
+ * Literals rather than an import: audit depends on core alone, and a capability never reaches into another's
35
+ * internals (principle 4). A code is stable forever once a row holds one, and `packages/cli/src/audit/accessHistoryCodes.test.ts`
36
+ * holds every literal here to the register that declares it, so a rename there fails the build here.
37
+ */
38
+ export declare const MEMBER_ACCESS_ACTIONS: {
39
+ /** A membership was created with nothing before it — save {@link INVITATION_ACCEPTED_ACTION} with `joined: false`. */
40
+ readonly joins: readonly ["organization/created", "organization/member_joined", "organization/admin_member_added"];
41
+ /** A membership's role changed, recorded with `previousRole` from #831 on. */
42
+ readonly changes: readonly ["organization/member_role_changed", "organization/admin_member_role_changed"];
43
+ /** Ownership reached a membership: its role became the conferred one. */
44
+ readonly ownership: readonly ["organization/ownership_accepted", "organization/admin_ownership_forced"];
45
+ /** A membership ended, recorded with the role it held. */
46
+ readonly ends: readonly ["organization/member_removed", "organization/member_left", "organization/admin_member_removed"];
47
+ };
48
+ /** Every code an access change is read from. */
49
+ export declare const ACCESS_ACTIONS: readonly string[];
50
+ /**
51
+ * Every `metadata` key this read lifts, and the only ones. `accessHistory.workers.test.ts` holds the compiled
52
+ * statement to this list, so a key added to the SQL and not here fails.
53
+ */
54
+ export declare const ACCESS_HISTORY_METADATA_KEYS: readonly ["role", "previousRole", "confers", "subjectUserId", "membershipId", "scopes", "scopesBefore", "scopesAfter", "actorKind", "purpose", "authorizedBy", "registeredKeyId", "expiredKeyId", "revokedKeyId", "joined", "replacedConnectionId"];
55
+ /** What to read: an inclusive window, and where to resume. */
56
+ export interface AccessHistoryFilter {
57
+ /** Inclusive lower bound on `occurredAt`. */
58
+ since: Date;
59
+ /** Inclusive upper bound on `occurredAt`. */
60
+ until: Date;
61
+ /** Where to resume, from the previous page's `nextCursor`. Opaque; a malformed one is a first page. */
62
+ cursor?: string;
63
+ /** How many changes to return, clamped into `[1, MAX_PAGE_SIZE]`. */
64
+ limit?: number;
65
+ }
66
+ /**
67
+ * One access change, decoded from the statement's row. Flat, because SQL is: `subject` says which fields mean
68
+ * something, and `http/views.ts` projects it into the wire union `AccessChangeView`.
69
+ */
70
+ export declare const AccessHistoryRow: z.ZodObject<{
71
+ id: z.ZodNumber;
72
+ eventId: z.ZodString;
73
+ occurredAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
74
+ action: z.ZodString;
75
+ actorType: z.ZodEnum<{
76
+ anonymous: "anonymous";
77
+ "control-plane": "control-plane";
78
+ service: "service";
79
+ system: "system";
80
+ user: "user";
81
+ }>;
82
+ actorId: z.ZodNullable<z.ZodString>;
83
+ actorKind: z.ZodNullable<z.ZodEnum<{
84
+ agent: "agent";
85
+ dashboard: "dashboard";
86
+ script: "script";
87
+ }>>;
88
+ subject: z.ZodEnum<{
89
+ connection: "connection";
90
+ key: "key";
91
+ member: "member";
92
+ }>;
93
+ recorded: z.ZodCodec<z.ZodUnion<readonly [z.ZodLiteral<0>, z.ZodLiteral<1>, z.ZodBoolean, z.ZodString]>, z.ZodBoolean>;
94
+ organizationId: z.ZodNullable<z.ZodString>;
95
+ membershipId: z.ZodNullable<z.ZodString>;
96
+ userId: z.ZodNullable<z.ZodString>;
97
+ roleBefore: z.ZodNullable<z.ZodString>;
98
+ roleAfter: z.ZodNullable<z.ZodString>;
99
+ connectionId: z.ZodNullable<z.ZodString>;
100
+ connectionKind: z.ZodNullable<z.ZodEnum<{
101
+ agent: "agent";
102
+ dashboard: "dashboard";
103
+ script: "script";
104
+ }>>;
105
+ purpose: z.ZodNullable<z.ZodString>;
106
+ principal: z.ZodNullable<z.ZodString>;
107
+ scopesBefore: z.ZodNullable<import("@pithy-sh/core/src/data/codecs").SqliteJson<z.ZodArray<z.ZodString>>>;
108
+ scopesAfter: z.ZodNullable<import("@pithy-sh/core/src/data/codecs").SqliteJson<z.ZodArray<z.ZodString>>>;
109
+ replacedConnectionId: z.ZodNullable<z.ZodString>;
110
+ keyId: z.ZodNullable<z.ZodString>;
111
+ keyChange: z.ZodNullable<z.ZodEnum<{
112
+ expired: "expired";
113
+ registered: "registered";
114
+ revoked: "revoked";
115
+ }>>;
116
+ }, z.core.$strip>;
117
+ export type AccessHistoryRow = z.output<typeof AccessHistoryRow>;
118
+ /** One page of access changes, oldest first, and where the next starts. */
119
+ export interface AccessHistoryPage {
120
+ /** The page, oldest first. */
121
+ changes: AccessHistoryRow[];
122
+ /** Where the next page starts, or null at the end of the window. */
123
+ nextCursor: string | null;
124
+ }
125
+ /**
126
+ * The page, as one Kysely statement — exported so a test can read what it compiles to.
127
+ *
128
+ * Three steps, in one statement:
129
+ *
130
+ * 1. **`extracted`** — the window's successful access events, after the cursor, with each named metadata key lifted
131
+ * out. `scopes` is an array on a registration and a removal and `{ from, to }` on an update that moved it, so the
132
+ * two are read apart. Kind, purpose and principal are the update's `to` where it moved them. An invitation redeemed
133
+ * by someone already a member (`joined` false) is left out here: it changed nothing.
134
+ * 2. **`classified`** — what changed. A member code is a member change; a key code is a key change, and so is a CLI
135
+ * update that registered or revoked a key, because that is what it did; the rest of the connection codes are
136
+ * connection changes.
137
+ * 3. **The answer** — each change's before and after by its code, and whether the event recorded them.
138
+ */
139
+ export declare function accessHistoryStatement(db: AuditDatabase, filter: AccessHistoryFilter, page: {
140
+ position?: {
141
+ sort: number;
142
+ id: number;
143
+ };
144
+ limit: number;
145
+ }): import("kysely").SelectQueryBuilder<import("@pithy-sh/core/src/data/db").DatabaseSchema<{
146
+ pithyAuditEvents: z.ZodObject<{
147
+ id: z.ZodNumber;
148
+ eventId: z.ZodString;
149
+ occurredAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
150
+ action: z.ZodString;
151
+ outcome: z.ZodEnum<{
152
+ denied: "denied";
153
+ failure: "failure";
154
+ success: "success";
155
+ }>;
156
+ severity: z.ZodEnum<{
157
+ critical: "critical";
158
+ info: "info";
159
+ warning: "warning";
160
+ }>;
161
+ actorType: z.ZodEnum<{
162
+ anonymous: "anonymous";
163
+ "control-plane": "control-plane";
164
+ service: "service";
165
+ system: "system";
166
+ user: "user";
167
+ }>;
168
+ actorId: z.ZodNullable<z.ZodString>;
169
+ actorKind: z.ZodDefault<z.ZodNullable<z.ZodEnum<{
170
+ agent: "agent";
171
+ dashboard: "dashboard";
172
+ script: "script";
173
+ }>>>;
174
+ sessionId: z.ZodNullable<z.ZodString>;
175
+ resourceType: z.ZodNullable<z.ZodString>;
176
+ resourceId: z.ZodNullable<z.ZodString>;
177
+ ip: z.ZodNullable<z.ZodString>;
178
+ userAgent: z.ZodNullable<z.ZodString>;
179
+ requestId: z.ZodNullable<z.ZodString>;
180
+ metadata: z.ZodNullable<import("@pithy-sh/core/src/data/codecs").SqliteJson<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
181
+ project: z.ZodNullable<z.ZodString>;
182
+ environment: z.ZodNullable<z.ZodString>;
183
+ worker: z.ZodNullable<z.ZodString>;
184
+ version: z.ZodNullable<z.ZodString>;
185
+ tenant: z.ZodNullable<z.ZodString>;
186
+ chainSeq: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
187
+ chainPrev: z.ZodDefault<z.ZodNullable<z.ZodString>>;
188
+ chainHash: z.ZodDefault<z.ZodNullable<z.ZodString>>;
189
+ chainSalt: z.ZodDefault<z.ZodNullable<z.ZodString>>;
190
+ }, z.core.$strip>;
191
+ pithyAuditSinks: z.ZodObject<{
192
+ sink: z.ZodString;
193
+ lastDeliveredAt: z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>;
194
+ lastFailedAt: z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>;
195
+ retrying: z.ZodNumber;
196
+ deadLettered: z.ZodNumber;
197
+ }, z.core.$strip>;
198
+ }> & {
199
+ extracted: {
200
+ action: string;
201
+ actorId: string | null;
202
+ actorKind: "agent" | "dashboard" | "script" | null | undefined;
203
+ actorType: "anonymous" | "control-plane" | "service" | "system" | "user";
204
+ confers: unknown;
205
+ connectionKind: unknown;
206
+ eventId: string;
207
+ expiredKeyId: unknown;
208
+ id: number;
209
+ occurredAt: string | number | Date;
210
+ previousRole: unknown;
211
+ principal: unknown;
212
+ purpose: unknown;
213
+ recordedMembershipId: unknown;
214
+ registeredKeyId: unknown;
215
+ replacedConnectionId: unknown;
216
+ resourceId: string | null;
217
+ revokedKeyId: unknown;
218
+ role: unknown;
219
+ scopes: unknown;
220
+ scopesAfterKey: unknown;
221
+ scopesBeforeKey: unknown;
222
+ scopesFrom: unknown;
223
+ scopesTo: unknown;
224
+ subjectUserId: unknown;
225
+ tenant: string | null;
226
+ };
227
+ } & {
228
+ classified: {
229
+ action: string;
230
+ actorId: string | null;
231
+ actorKind: "agent" | "dashboard" | "script" | null | undefined;
232
+ actorType: "anonymous" | "control-plane" | "service" | "system" | "user";
233
+ confers: unknown;
234
+ connectionKind: unknown;
235
+ eventId: string;
236
+ expiredKeyId: unknown;
237
+ id: number;
238
+ occurredAt: string | number | Date;
239
+ previousRole: unknown;
240
+ principal: unknown;
241
+ purpose: unknown;
242
+ recordedMembershipId: unknown;
243
+ registeredKeyId: unknown;
244
+ replacedConnectionId: unknown;
245
+ resourceId: string | null;
246
+ revokedKeyId: unknown;
247
+ role: unknown;
248
+ scopes: unknown;
249
+ scopesAfterKey: unknown;
250
+ scopesBeforeKey: unknown;
251
+ scopesFrom: unknown;
252
+ scopesTo: unknown;
253
+ subject: string;
254
+ subjectUserId: unknown;
255
+ tenant: string | null;
256
+ };
257
+ } & {
258
+ answered: {
259
+ action: string;
260
+ actorId: string | null;
261
+ actorKind: "agent" | "dashboard" | "script" | null | undefined;
262
+ actorType: "anonymous" | "control-plane" | "service" | "system" | "user";
263
+ connectionId: unknown;
264
+ connectionKind: unknown;
265
+ eventId: string;
266
+ id: number;
267
+ keyChange: unknown;
268
+ keyId: unknown;
269
+ membershipId: unknown;
270
+ occurredAt: string | number | Date;
271
+ organizationId: unknown;
272
+ principal: unknown;
273
+ purpose: unknown;
274
+ replacedConnectionId: unknown;
275
+ roleAfter: unknown;
276
+ roleBefore: unknown;
277
+ scopesAfter: unknown;
278
+ scopesBefore: unknown;
279
+ subject: string;
280
+ userId: unknown;
281
+ };
282
+ }, "answered", {
283
+ action: string;
284
+ actorId: string | null;
285
+ actorKind: "agent" | "dashboard" | "script" | null | undefined;
286
+ actorType: "anonymous" | "control-plane" | "service" | "system" | "user";
287
+ connectionId: unknown;
288
+ connectionKind: unknown;
289
+ eventId: string;
290
+ id: number;
291
+ keyChange: unknown;
292
+ keyId: unknown;
293
+ membershipId: unknown;
294
+ occurredAt: string | number | Date;
295
+ organizationId: unknown;
296
+ principal: unknown;
297
+ purpose: unknown;
298
+ replacedConnectionId: unknown;
299
+ roleAfter: unknown;
300
+ roleBefore: unknown;
301
+ scopesAfter: unknown;
302
+ scopesBefore: unknown;
303
+ subject: string;
304
+ userId: unknown;
305
+ } & {
306
+ recorded: number;
307
+ }>;
308
+ /**
309
+ * Read one page of access changes in a window, oldest first.
310
+ *
311
+ * **Keyset, never offset**, ascending: the trail is appended to while it is read, and a change recorded mid-read
312
+ * lands after the window's last page rather than pushing a row from one page onto the next.
313
+ */
314
+ export declare function accessHistory(db: AuditDatabase, filter: AccessHistoryFilter): Promise<AccessHistoryPage>;
315
+ //# sourceMappingURL=accessHistory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accessHistory.d.ts","sourceRoot":"","sources":["../src/accessHistory.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAEnD;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;GAGG;AACH,eAAO,MAAM,0BAA0B,+BAA+B,CAAC;AAEvE;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB;IAChC,sHAAsH;aACtH,KAAK,YAAG,sBAAsB,gCAA8B,iCAAiC;IAC7F,8EAA8E;aAC9E,OAAO,YAAG,kCAAkC,EAAE,wCAAwC;IACtF,yEAAyE;aACzE,SAAS,YAAG,iCAAiC,EAAE,qCAAqC;IACpF,0DAA0D;aAC1D,IAAI,YAAG,6BAA6B,EAAE,0BAA0B,EAAE,mCAAmC;CAC7F,CAAC;AAoBX,gDAAgD;AAChD,eAAO,MAAM,cAAc,EAAE,SAAS,MAAM,EAO3C,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,4BAA4B,YACvC,MAAM,EACN,cAAc,EACd,SAAS,EACT,eAAe,EACf,cAAc,EACd,QAAQ,EACR,cAAc,EACd,aAAa,EACb,WAAW,EACX,SAAS,EACT,cAAc,EACd,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,QAAQ,EACR,sBAAsB,CACd,CAAC;AAEX,8DAA8D;AAC9D,MAAM,WAAW,mBAAmB;IAClC,6CAA6C;IAC7C,KAAK,EAAE,IAAI,CAAC;IACZ,6CAA6C;IAC7C,KAAK,EAAE,IAAI,CAAC;IACZ,uGAAuG;IACvG,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,qEAAqE;IACrE,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAKD;;;GAGG;AACH,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6BgD,CAAC;AAC9E,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAEjE,2EAA2E;AAC3E,MAAM,WAAW,iBAAiB;IAChC,8BAA8B;IAC9B,OAAO,EAAE,gBAAgB,EAAE,CAAC;IAC5B,oEAAoE;IACpE,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B;AA4BD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,sBAAsB,CACpC,EAAE,EAAE,aAAa,EACjB,MAAM,EAAE,mBAAmB,EAC3B,IAAI,EAAE;IAAE,QAAQ,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqIjE;AAED;;;;;GAKG;AACH,wBAAsB,aAAa,CAAC,EAAE,EAAE,aAAa,EAAE,MAAM,EAAE,mBAAmB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAO9G"}