@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
@@ -1,8 +1,9 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: FSL-1.1-MIT
3
3
  import { AuditActorType, AuditMetadata, AuditOutcome, AuditSeverity } from "@pithy-sh/core/src/audit/auditEvent";
4
- import { z } from "zod";
5
4
  import { ControlPlaneActorKind } from "@pithy-sh/core/src/controlPlane/data/connection";
5
+ import { z } from "zod";
6
+ import { AuditChainExport, ChainBreak, ChainLink } from "@pithy-sh/core/src/audit/chain";
6
7
  //#region src/http/responses.ts
7
8
  /**
8
9
  * What the audit routes return, as Zod objects a management client can validate against.
@@ -24,7 +25,7 @@ import { ControlPlaneActorKind } from "@pithy-sh/core/src/controlPlane/data/conn
24
25
  * **A field added here later is `.optional()`, not merely `.nullable()`.** This module is read across a
25
26
  * version boundary — a management client validates a response with this schema against a customer's
26
27
  * Worker at whatever kit version it is on — so an additive required key fails `safeParse` for everyone
27
- * below that release and takes the whole pane with it (#450). Absent then means *this Worker cannot
28
+ * below that release and takes the whole pane with it. Absent then means *this Worker cannot
28
29
  * say*, which is a different fact from `null`.
29
30
  */
30
31
  /** Where a page resumes, or the end of the list. */
@@ -43,7 +44,7 @@ const AuditEventView = z.object({
43
44
  severity: AuditSeverity.describe("How serious it is, orthogonal to the outcome."),
44
45
  actorType: AuditActorType.describe("The kind of principal that acted."),
45
46
  actorId: z.string().nullable().describe("The acting principal's stable id, or null."),
46
- actorKind: ControlPlaneActorKind.nullable().optional().describe("For a `control-plane` actor, which kind of management client acted — `agent`, `dashboard` or `script` — or null. Absent from a Worker older than the field."),
47
+ actorKind: ControlPlaneActorKind.nullable().optional().describe("Which kind of client acted — `agent`, `dashboard` or `script` — or null. A `control-plane` actor's connection kind, or `agent` on a `user` row an MCP client wrote. Absent from a Worker older than the field."),
47
48
  sessionId: z.string().nullable().describe("The session the action belongs to — a row id, never a token — or null."),
48
49
  resourceType: z.string().nullable().describe("The kind of thing acted on, or null."),
49
50
  resourceId: z.string().nullable().describe("The thing acted on, or null."),
@@ -52,7 +53,8 @@ const AuditEventView = z.object({
52
53
  environment: z.string().nullable().describe("The environment the recording Worker served, or null."),
53
54
  worker: z.string().nullable().describe("The `apps/<name>` Worker that recorded it, or null for a CLI action."),
54
55
  version: z.string().nullable().describe("The Cloudflare build id that recorded it, or null."),
55
- tenant: z.string().nullable().describe("The tenant the action was taken for, or null when it was not tenant-scoped.")
56
+ tenant: z.string().nullable().describe("The tenant the action was taken for, or null when it was not tenant-scoped."),
57
+ chainSeq: z.number().int().nullable().optional().describe("The event's position in its tenant's hash chain, or null when it was written before the chain began and is marked so. Absent from a Worker older than the chain.")
56
58
  }).describe("One audit event as the listing shows it. No client IP, no user-agent, no metadata bag.");
57
59
  /**
58
60
  * One event in full — the listing view plus the three fields the detail scope exists to separate.
@@ -71,5 +73,155 @@ const AuditEventsResponse = z.object({
71
73
  }).describe("A filtered, resumable page of the audit trail.");
72
74
  /** `GET {base}/events/:eventId`. */
73
75
  const AuditEventResponse = z.object({ event: AuditEventDetailView.describe("The event, with the fields the detail scope gates.") }).describe("One audit event in full.");
76
+ /**
77
+ * Whether a change's event carried its before and after.
78
+ *
79
+ * `not_recorded` is an event written before its emitter recorded the detail — a role change from before
80
+ * `previousRole`, an update that moved no scope from before every update carried the grant. Its unknown values are
81
+ * null, and this says they are unknown rather than none: the reader is told, never handed a guess.
82
+ */
83
+ const ChangeDetail = z.enum(["recorded", "not_recorded"]).describe("Whether the event recorded this change's before and after. `not_recorded` means a null before or after is unknown, not none: the event predates the emitter recording it.");
84
+ /** What every access change carries: when, who, and from which code. */
85
+ const AccessChangeBase = z.object({
86
+ eventId: z.string().describe("The event the change was read from — the listing's `eventId`."),
87
+ occurredAt: z.iso.datetime().describe("When it changed, ISO-8601."),
88
+ action: z.string().describe("The `domain/reason` code it was recorded under."),
89
+ actorType: AuditActorType.describe("The kind of principal that made the change."),
90
+ actorId: z.string().nullable().describe("The principal that made the change, or null."),
91
+ actorKind: ControlPlaneActorKind.nullable().describe("Which kind of client made the change — a `control-plane` actor's connection kind, or `agent` for a user's MCP client — or null."),
92
+ detail: ChangeDetail
93
+ });
94
+ /** A membership joined, changed role, or ended. */
95
+ const MemberAccessChange = AccessChangeBase.extend({
96
+ subject: z.literal("member").describe("A membership changed."),
97
+ organizationId: z.string().nullable().describe("The organization the membership is in."),
98
+ membershipId: z.string().nullable().describe("The membership that changed."),
99
+ userId: z.string().nullable().describe("Whose membership it is, or null when the event did not say."),
100
+ roleBefore: z.string().nullable().describe("The role it held before. Null for a join, or when `detail` is `not_recorded`."),
101
+ roleAfter: z.string().nullable().describe("The role it holds after. Null for a leave or a removal, or when `detail` is `not_recorded`.")
102
+ }).describe("A membership joined, changed role, or ended.");
103
+ /** A control-plane connection was registered, updated, or removed. */
104
+ const ConnectionAccessChange = AccessChangeBase.extend({
105
+ subject: z.literal("connection").describe("A control-plane connection changed."),
106
+ connectionId: z.string().nullable().describe("The connection that changed."),
107
+ connectionKind: ControlPlaneActorKind.nullable().describe("What kind of client the connection is for, or null when it was not recorded."),
108
+ purpose: z.string().nullable().describe("What the connection is for, in its registrant's words, or null."),
109
+ principal: z.string().nullable().describe("Who sanctioned the connection — the registering session's email address — or null."),
110
+ scopesBefore: z.array(z.string().describe("A granted scope.")).nullable().describe("The scopes it held before. Null for a registration, or when `detail` is `not_recorded`."),
111
+ scopesAfter: z.array(z.string().describe("A granted scope.")).nullable().describe("The scopes it holds after. Null for a removal, or when `detail` is `not_recorded`."),
112
+ replacedConnectionId: z.string().nullable().describe("For a registration that started over, the connection it replaced: that connection's grant ended here. Null otherwise. A start-over recorded by a current CLI also has the old connection's own removal, just before.")
113
+ }).describe("A control-plane connection was registered, updated, or removed.");
114
+ /** A key on a connection was registered, expired, or revoked. */
115
+ const KeyAccessChange = AccessChangeBase.extend({
116
+ subject: z.literal("key").describe("A key on a control-plane connection changed."),
117
+ connectionId: z.string().nullable().describe("The connection the key belongs to."),
118
+ keyId: z.string().nullable().describe("The key's id. Never key material."),
119
+ change: z.enum([
120
+ "registered",
121
+ "expired",
122
+ "revoked"
123
+ ]).describe("What happened to it: registered, expired at the end of a rotation, or revoked.")
124
+ }).describe("A key on a control-plane connection was registered, expired, or revoked.");
125
+ /** One access change, discriminated on what changed. */
126
+ const AccessChangeView = z.discriminatedUnion("subject", [
127
+ MemberAccessChange,
128
+ ConnectionAccessChange,
129
+ KeyAccessChange
130
+ ]).describe("One change to who can reach this environment's data, with its before and after.");
131
+ /** `GET {base}/control-plane/access-history`. */
132
+ const AccessHistoryResponse = z.object({
133
+ since: z.iso.datetime().describe("The window's inclusive start, ISO-8601."),
134
+ until: z.iso.datetime().describe("The window's inclusive end, ISO-8601 — now, when the query named none."),
135
+ changes: z.array(AccessChangeView).describe("The page, oldest first."),
136
+ nextCursor: NextCursor
137
+ }).describe("Every membership, connection and key change in a window, oldest first, with its before and after.");
138
+ /**
139
+ * One tenant, action, method, route and outcome a control-plane credential reached.
140
+ *
141
+ * Counts, two instants, and the route. No IP, no user-agent, no metadata key beyond what the route and scope already
142
+ * say: this is the credential's own footprint, which is why it sits behind the listing scope.
143
+ */
144
+ const ControlPlaneReachView = z.object({
145
+ tenant: z.string().nullable().describe("The tenant the calls reached, as the handler behind them recorded it in the same request. Null when the handler named none."),
146
+ action: z.string().describe("`controlplane/call_allowed` for admitted calls, `controlplane/call_denied` for refusals."),
147
+ method: z.string().describe("The HTTP method called."),
148
+ route: z.string().describe("The declared admin route the calls matched, or the path as called when no declared route matched."),
149
+ matched: z.boolean().describe("Whether `route` is a declared pattern. False marks an unmatched path, which is its own row."),
150
+ outcome: z.string().describe("The calls' outcome: `success`, or `denied` for a call a handler refused past the gate, which is counted once, as denied."),
151
+ scope: z.string().nullable().describe("The scope the calls' credential carried. On a refusal it is the scope the refused credential held, not one it lacked, which the trail does not record."),
152
+ count: z.number().int().describe("How many calls."),
153
+ subjects: z.number().int().nullable().describe("How many distinct subjects the calls touched: distinct values of the route's subject parameter and the parameters before it, so one user read in two currencies is one subject. 0 for a route with no parameters, null for an unmatched path."),
154
+ firstAt: z.iso.datetime().describe("When the first call landed, ISO-8601."),
155
+ lastAt: z.iso.datetime().describe("When the last call landed, ISO-8601.")
156
+ }).describe("One tenant, action, method, route and outcome one control-plane credential reached in a window.");
157
+ /** One path a route was called with, and the subject ids it names. */
158
+ const ControlPlaneReachSubjectView = z.object({
159
+ tenant: z.string().nullable().describe("The tenant the calls reached, or null when their handler named none."),
160
+ action: z.string().describe("`controlplane/call_allowed` or `controlplane/call_denied`."),
161
+ method: z.string().describe("The HTTP method called."),
162
+ route: z.string().describe("The route expanded, as asked for."),
163
+ matched: z.boolean().describe("Whether the route is a declared pattern."),
164
+ path: z.string().describe("The path as called."),
165
+ outcome: z.string().describe("The calls' outcome: `success` or `denied`."),
166
+ scope: z.string().nullable().describe("The scope the calls' credential carried, refused or not. Never the scope a refusal lacked."),
167
+ subjectId: z.string().nullable().describe("Whose data the call acted on: the value of the route's last id parameter (`id`, or a name ending in `Id`), or of its last parameter when none names an id. On `/accounts/:userId/:currency/transactions` it is the user, not the currency. `params` has the rest. Null when the route declares none."),
168
+ params: z.record(z.string(), z.string()).describe("Every parameter the route declares, with the value it took in `path`, decoded."),
169
+ count: z.number().int().describe("How many calls to this path."),
170
+ firstAt: z.iso.datetime().describe("When the first call to this path landed, ISO-8601."),
171
+ lastAt: z.iso.datetime().describe("When the last call to this path landed, ISO-8601.")
172
+ }).describe("One path a route was called with by one control-plane credential, and the subject ids it names.");
173
+ /** `GET {base}/control-plane/reach`. */
174
+ const ControlPlaneReachResponse = z.object({
175
+ connectionId: z.string().describe("The connection read, as asked for."),
176
+ keyId: z.string().nullable().describe("The key the read was narrowed to, or null for every key."),
177
+ since: z.iso.datetime().describe("The window's inclusive start, ISO-8601."),
178
+ until: z.iso.datetime().describe("The window's inclusive end, ISO-8601 — now, when the query named none."),
179
+ reach: z.array(ControlPlaneReachView).describe("One row per tenant, route, action, method and outcome reached, ordered in that order."),
180
+ subjects: z.array(ControlPlaneReachSubjectView).optional().describe("The route's subjects, one row per tenant and path called. Present only when the query asked with `subjects=true`.")
181
+ }).describe("Everything one control-plane credential reached over a window, by tenant, route and outcome.");
182
+ /**
183
+ * One `(scope, keyId)` a control-plane connection exercised.
184
+ *
185
+ * Counts, two instants, and the method and path of the last allowed call. No IP, no user-agent, no other metadata key:
186
+ * this is the management client's own footprint, which is why it sits behind the listing scope.
187
+ */
188
+ const ControlPlaneUsageView = z.object({
189
+ scope: z.string().describe("The scope exercised — what an allowed call's token carried, or what a refused call required. A scope never exercised has no row."),
190
+ keyId: z.string().nullable().describe("The registered key that signed the calls, or null when none was recorded."),
191
+ allowed: z.number().int().describe("How many calls under this scope and key were admitted in the window."),
192
+ denied: z.number().int().describe("How many verified calls naming this scope were refused in the window. An under-grant shows here, beside an over-grant's zero. A refusal that failed verification proves no connection and is not counted."),
193
+ lastAllowedAt: z.iso.datetime().nullable().describe("When the last admitted call landed, ISO-8601, or null when none was admitted."),
194
+ lastAllowedMethod: z.string().nullable().describe("The HTTP method of the last admitted call, or null."),
195
+ lastAllowedPath: z.string().nullable().describe("The path of the last admitted call, or null."),
196
+ lastDeniedAt: z.iso.datetime().nullable().describe("When the last refusal landed, ISO-8601, or null when none was refused.")
197
+ }).describe("One scope and key a control-plane connection exercised in a window.");
198
+ /** `GET {base}/control-plane/usage`. */
199
+ const ControlPlaneUsageResponse = z.object({
200
+ connectionId: z.string().describe("The connection counted, as asked for."),
201
+ since: z.iso.datetime().describe("The window's inclusive start, ISO-8601."),
202
+ until: z.iso.datetime().describe("The window's inclusive end, ISO-8601 — now, when the query named none."),
203
+ usage: z.array(ControlPlaneUsageView).describe("One row per scope and key exercised, ordered by scope then key."),
204
+ oldestEventAt: z.iso.datetime().nullable().describe("The oldest event the trail holds, for any connection, or null on an empty trail. A window starting before it was not fully covered: retention removed what came before.")
205
+ }).describe("Which scopes one control-plane connection exercised and was refused, by key, over a window.");
206
+ /** `GET {base}/control-plane/verify`. */
207
+ const ChainVerifyResponse = z.object({
208
+ tenant: z.string().nullable().describe("The tenant whose chain was walked, or null for the untenanted chain."),
209
+ since: z.iso.datetime().nullable().describe("The window's inclusive start as asked, or null for the chain's start."),
210
+ until: z.iso.datetime().nullable().describe("The window's inclusive end as asked, or null for the chain's head."),
211
+ intact: z.boolean().describe("Whether the range is whole: every link, every hash, every checkpoint covering it."),
212
+ checked: z.number().int().nonnegative().describe("How many chained events were checked before the first break, or all of them."),
213
+ checkpoints: z.number().int().nonnegative().describe("How many checkpoints the walk was held to."),
214
+ pruned: z.number().int().nonnegative().optional().describe("How many events the walk crossed as pruned by the retention policy, each run bridged by the tombstone written before it was deleted. Absent from a Worker that cannot prune."),
215
+ checkpointStore: z.enum(["bound", "absent"]).describe("`absent` when this Worker binds no checkpoint bucket, so the walk checked links alone: a chain rewritten end to end would read as intact."),
216
+ beforeChain: z.number().int().nonnegative().describe("How many of the tenant's events in the window were written before the chain, and so are not in it."),
217
+ outsideChain: z.number().int().nonnegative().describe("How many rows in the window carry no chain though written after it began — an older recorder's during an upgrade or a rollback. Not in the chain, and not a break: `intact` is about the chain itself."),
218
+ break: ChainBreak.nullable().describe("The first break — its event, its position and why — or null."),
219
+ head: ChainLink.nullable().describe("The last position the walk reached intact, or null when it reached none.")
220
+ }).describe("Whether one tenant's audit chain is whole over a window, or where it first breaks.");
221
+ /**
222
+ * `GET {base}/control-plane/export`. Core's export document, which `pithy audit verify` reads offline —
223
+ * one schema, so what the Worker writes and what the verifier accepts cannot drift.
224
+ */
225
+ const ChainExportResponse = AuditChainExport.describe("One page of one tenant's audit chain: canonical events, their hashes, the link before them and the checkpoints covering them.");
74
226
  //#endregion
75
- export { AuditEventDetailView, AuditEventResponse, AuditEventView, AuditEventsResponse };
227
+ export { AccessChangeView, AccessHistoryResponse, AuditEventDetailView, AuditEventResponse, AuditEventView, AuditEventsResponse, ChainExportResponse, ChainVerifyResponse, ConnectionAccessChange, ControlPlaneReachResponse, ControlPlaneReachSubjectView, ControlPlaneReachView, ControlPlaneUsageResponse, ControlPlaneUsageView, KeyAccessChange, MemberAccessChange };
@@ -1,6 +1,8 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import type { R2Bucket } from "@cloudflare/workers-types";
3
4
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
5
+ import type { AdminRoute } from "@pithy-sh/core/src/controlPlane/discovery/adminRoute";
4
6
  import type { ControlPlaneScope } from "@pithy-sh/core/src/controlPlane/scope/scope";
5
7
  import type { VerificationStrategy } from "@pithy-sh/core/src/http/verification";
6
8
  import type { Context, Hono } from "hono";
@@ -10,18 +12,28 @@ import type { AuditDatabase } from "../data/tables";
10
12
  *
11
13
  * GET /audit/events → a page of the trail (control-plane: audit:events:read) query: ListAuditEventsQuery
12
14
  * GET /audit/events/:eventId → one event in full (control-plane: audit:events:read_detail) param: AuditEventIdParam
15
+ * GET /audit/control-plane/access-history → every access change in a window, before and after
16
+ * (control-plane: audit:events:read) query: AccessHistoryQuery
17
+ * GET /audit/control-plane/reach → what one credential reached, by tenant, route and outcome
18
+ * (control-plane: audit:events:read) query: ControlPlaneReachQuery
19
+ * GET /audit/control-plane/usage → one connection's calls, counted by scope and key
20
+ * (control-plane: audit:events:read) query: ControlPlaneUsageQuery
21
+ * GET /audit/control-plane/verify → whether one tenant's hash chain is whole, or where it breaks
22
+ * (control-plane: audit:events:export) query: ChainVerifyQuery
23
+ * GET /audit/control-plane/export → one tenant's chain in canonical form, with its checkpoints
24
+ * (control-plane: audit:events:export) query: ChainExportQuery
13
25
  *
14
- * **Both are reads, and there is nothing else.** The trail is append-only: no route here deletes,
26
+ * **All are reads, and there is nothing else.** The trail is append-only: no route here deletes,
15
27
  * edits, or prunes, because a management credential that could erase an audit row could erase the
16
28
  * evidence of its own use. Retention is a lifecycle concern for a Workflow, not a button on a
17
29
  * dashboard.
18
30
  *
19
- * **Neither has an end-user surface.** A user does not call the record of themselves being audited,
31
+ * **None has an end-user surface.** A user does not call the record of themselves being audited,
20
32
  * so `requireAuth()` appears nowhere in this file — and must not: the seam leaves `c.var.auth` null
21
33
  * for a control-plane caller by design, so an auth gate would deny every legitimate management call
22
34
  * permanently, with no credential able to fix it.
23
35
  *
24
- * **Validators sit after the gate on both lines.** A validator ahead of it turns a 403 into a 400 and
36
+ * **Validators sit after the gate on every line.** A validator ahead of it turns a 403 into a 400 and
25
37
  * tells an unverified caller which requests were well-formed — here that is a live oracle for which
26
38
  * projects, Workers, and action codes this deployment records.
27
39
  */
@@ -55,6 +67,16 @@ export interface AuditRoutesOptions {
55
67
  basePath: string;
56
68
  /** The audit database for this request — resolved by the capability, which owns the registry key. */
57
69
  database: (c: Context<PithyHonoEnv>) => AuditDatabase;
70
+ /**
71
+ * Every admin route the composed Worker declares — what the manifest reports, and what a credential's reach groups
72
+ * its called paths by. A function, because the capability learns them at `compose`, after these routes are built.
73
+ */
74
+ adminRoutes: () => readonly AdminRoute[];
75
+ /**
76
+ * The checkpoint bucket for this request, or null when the Worker binds none (#822). Absent, verify checks links
77
+ * alone and says so, and an export carries no checkpoints.
78
+ */
79
+ checkpoints?: (c: Context<PithyHonoEnv>) => R2Bucket | null;
58
80
  }
59
81
  /** Register the audit sub-router. Returned as the capability's `routes` hook. */
60
82
  export declare function registerAuditRoutes(options: AuditRoutesOptions): (app: Hono<PithyHonoEnv>) => void;
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAG7E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAIrF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE1C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAOpD;;;;;;;;;;;;;;;;;;;GAmBG;AAEH;;;;;;;;GAQG;AACH,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC;IACvB,sEAAsE;IACtE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,oBAAoB,CAAC;IACxC,iDAAiD;IACjD,QAAQ,CAAC,KAAK,EAAE,iBAAiB,CAAC;CACnC;AAED,wCAAwC;AACxC,eAAO,MAAM,YAAY,EAAE,SAAS,qBAAqB,EAGxD,CAAC;AAEF,yCAAyC;AACzC,MAAM,WAAW,kBAAkB;IACjC;;;;;OAKG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB,qGAAqG;IACrG,QAAQ,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,KAAK,aAAa,CAAC;CACvD;AA2CD,iFAAiF;AACjF,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,kBAAkB,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAiGlG"}
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAE7E,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sDAAsD,CAAC;AAEvF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAIrF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAI1C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAiCpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH;;;;;;;;GAQG;AACH,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC;IACvB,sEAAsE;IACtE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,oBAAoB,CAAC;IACxC,iDAAiD;IACjD,QAAQ,CAAC,KAAK,EAAE,iBAAiB,CAAC;CACnC;AAED,wCAAwC;AACxC,eAAO,MAAM,YAAY,EAAE,SAAS,qBAAqB,EAQxD,CAAC;AAEF,yCAAyC;AACzC,MAAM,WAAW,kBAAkB;IACjC;;;;;OAKG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB,qGAAqG;IACrG,QAAQ,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,KAAK,aAAa,CAAC;IACtD;;;OAGG;IACH,WAAW,EAAE,MAAM,SAAS,UAAU,EAAE,CAAC;IACzC;;;OAGG;IACH,WAAW,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,KAAK,QAAQ,GAAG,IAAI,CAAC;CAC7D;AA2CD,iFAAiF;AACjF,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,kBAAkB,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CA8ZlG"}
@@ -1,28 +1,66 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { accessHistory } from "../accessHistory.js";
3
4
  import { AuditTrailActions } from "../actions.js";
4
- import { AUDIT_EVENT_DETAIL_READ_SCOPE, AUDIT_TRAIL_READ_SCOPE } from "./guards.js";
5
+ import { AUDIT_CHAIN_EXPORT_SCOPE, AUDIT_EVENT_DETAIL_READ_SCOPE, AUDIT_TRAIL_READ_SCOPE } from "./guards.js";
6
+ import { exportChainRange, verifyChainRange } from "../chain/verify.js";
5
7
  import { pageAuditEvents, readAuditEvent } from "../query.js";
6
- import { AuditEventResponse, AuditEventsResponse } from "./responses.js";
7
- import { AuditEventIdParam, ListAuditEventsQuery } from "./schemas.js";
8
- import { auditEventDetailView, auditEventView } from "./views.js";
8
+ import { reachPatterns } from "../routePattern.js";
9
+ import { controlPlaneReach, controlPlaneReachSubjects } from "../reach.js";
10
+ import { controlPlaneUsage } from "../usage.js";
11
+ import { AccessHistoryResponse, AuditEventResponse, AuditEventsResponse, ChainExportResponse, ChainVerifyResponse, ControlPlaneReachResponse, ControlPlaneUsageResponse } from "./responses.js";
12
+ import { AccessHistoryQuery, AuditEventIdParam, ChainExportQuery, ChainVerifyQuery, ControlPlaneReachQuery, ControlPlaneUsageQuery, ListAuditEventsQuery } from "./schemas.js";
13
+ import { accessChangeView, auditEventDetailView, auditEventView, controlPlaneReachSubjectView, controlPlaneReachView, controlPlaneUsageView } from "./views.js";
9
14
  import { InternalError, NotFoundError } from "@pithy-sh/core/src/error/pithyError";
10
15
  import { requireControlPlane } from "@pithy-sh/core/src/controlPlane/http/guard";
11
16
  import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
12
17
  import { validate } from "@pithy-sh/core/src/http/validation";
13
18
  //#region src/http/routes.ts
14
19
  /** Every route, and how it is gated. */
15
- const AUDIT_ROUTES = [{
16
- method: "GET",
17
- path: "/events",
18
- strategy: "control-plane",
19
- scope: AUDIT_TRAIL_READ_SCOPE
20
- }, {
21
- method: "GET",
22
- path: "/events/:eventId",
23
- strategy: "control-plane",
24
- scope: AUDIT_EVENT_DETAIL_READ_SCOPE
25
- }];
20
+ const AUDIT_ROUTES = [
21
+ {
22
+ method: "GET",
23
+ path: "/events",
24
+ strategy: "control-plane",
25
+ scope: AUDIT_TRAIL_READ_SCOPE
26
+ },
27
+ {
28
+ method: "GET",
29
+ path: "/events/:eventId",
30
+ strategy: "control-plane",
31
+ scope: AUDIT_EVENT_DETAIL_READ_SCOPE
32
+ },
33
+ {
34
+ method: "GET",
35
+ path: "/control-plane/access-history",
36
+ strategy: "control-plane",
37
+ scope: AUDIT_TRAIL_READ_SCOPE
38
+ },
39
+ {
40
+ method: "GET",
41
+ path: "/control-plane/reach",
42
+ strategy: "control-plane",
43
+ scope: AUDIT_TRAIL_READ_SCOPE
44
+ },
45
+ {
46
+ method: "GET",
47
+ path: "/control-plane/usage",
48
+ strategy: "control-plane",
49
+ scope: AUDIT_TRAIL_READ_SCOPE
50
+ },
51
+ {
52
+ method: "GET",
53
+ path: "/control-plane/verify",
54
+ strategy: "control-plane",
55
+ scope: AUDIT_CHAIN_EXPORT_SCOPE
56
+ },
57
+ {
58
+ method: "GET",
59
+ path: "/control-plane/export",
60
+ strategy: "control-plane",
61
+ scope: AUDIT_CHAIN_EXPORT_SCOPE
62
+ }
63
+ ];
26
64
  /**
27
65
  * The verified management client behind a control-plane call.
28
66
  *
@@ -63,6 +101,8 @@ function askedFor(query) {
63
101
  function registerAuditRoutes(options) {
64
102
  const base = options.basePath;
65
103
  const database = options.database;
104
+ const adminRoutes = options.adminRoutes;
105
+ const checkpoints = options.checkpoints ?? (() => null);
66
106
  return (app) => {
67
107
  /**
68
108
  * CONTROL-PLANE READ. A filtered, resumable page of the trail — keyset, never offset, because the
@@ -132,6 +172,272 @@ function registerAuditRoutes(options) {
132
172
  });
133
173
  return c.json({ event: auditEventDetailView(row) }, 200);
134
174
  });
175
+ /**
176
+ * CONTROL-PLANE READ (#831). Who could do what, over time: every membership, connection and key change in a
177
+ * window, oldest first, with its before and after — one SQL statement per page, never a walk of events here.
178
+ * Behind the listing scope, not the detail one: it lifts named metadata keys and never an IP or a user-agent.
179
+ */
180
+ app.get(`${base}/control-plane/access-history`, describeRoute({
181
+ summary: "Replay every membership, connection and key change in a window, oldest first, with its before and after.",
182
+ verification: "control-plane",
183
+ scopes: [AUDIT_TRAIL_READ_SCOPE],
184
+ responses: { 200: AccessHistoryResponse }
185
+ }), requireControlPlane(AUDIT_TRAIL_READ_SCOPE), validate("query", AccessHistoryQuery), async (c) => {
186
+ const operator = caller(c);
187
+ const query = c.req.valid("query");
188
+ const window = {
189
+ since: query.since,
190
+ until: query.until ?? /* @__PURE__ */ new Date()
191
+ };
192
+ const page = await accessHistory(database(c), {
193
+ ...window,
194
+ cursor: query.cursor,
195
+ limit: query.limit
196
+ });
197
+ await c.var.emit({
198
+ action: AuditTrailActions.accessHistoryRead,
199
+ outcome: "success",
200
+ actorType: "control-plane",
201
+ actorId: operator.subject,
202
+ resourceType: "audit_trail",
203
+ requestId: c.req.header("cf-ray"),
204
+ ip: c.req.header("cf-connecting-ip"),
205
+ userAgent: c.req.header("user-agent"),
206
+ metadata: {
207
+ connectionId: operator.connectionId,
208
+ query: {
209
+ since: window.since.toISOString(),
210
+ until: window.until.toISOString(),
211
+ resumed: query.cursor !== void 0
212
+ },
213
+ returned: page.changes.length,
214
+ more: page.nextCursor !== null
215
+ }
216
+ });
217
+ return c.json({
218
+ since: window.since.toISOString(),
219
+ until: window.until.toISOString(),
220
+ changes: page.changes.map(accessChangeView),
221
+ nextCursor: page.nextCursor
222
+ }, 200);
223
+ });
224
+ /**
225
+ * CONTROL-PLANE READ (#828). What one credential reached — by tenant, action, method, route and outcome — over a
226
+ * window, in one SQL statement, never by paging events here. `subjects=true` expands one route into the subject
227
+ * ids its called paths name. Behind the listing scope, not the detail one: the answer is the tenant, the route,
228
+ * the scope and ids the listing already shows, and never an IP, a user-agent or any other metadata key.
229
+ */
230
+ app.get(`${base}/control-plane/reach`, describeRoute({
231
+ summary: "Read what one control-plane credential reached, by tenant, route and outcome, over a window.",
232
+ verification: "control-plane",
233
+ scopes: [AUDIT_TRAIL_READ_SCOPE],
234
+ responses: { 200: ControlPlaneReachResponse }
235
+ }), requireControlPlane(AUDIT_TRAIL_READ_SCOPE), validate("query", ControlPlaneReachQuery), async (c) => {
236
+ const operator = caller(c);
237
+ const query = c.req.valid("query");
238
+ const filter = {
239
+ connectionId: query.connectionId,
240
+ since: query.since,
241
+ until: query.until ?? /* @__PURE__ */ new Date(),
242
+ ...query.keyId !== void 0 ? { keyId: query.keyId } : {},
243
+ ...query.route !== void 0 ? { route: query.route } : {}
244
+ };
245
+ const patterns = reachPatterns(adminRoutes());
246
+ const expanded = query.subjects === "true" && filter.route !== void 0 ? await controlPlaneReachSubjects(database(c), {
247
+ ...filter,
248
+ route: filter.route
249
+ }, patterns) : {
250
+ reach: await controlPlaneReach(database(c), filter, patterns),
251
+ subjects: void 0
252
+ };
253
+ await c.var.emit({
254
+ action: AuditTrailActions.reachRead,
255
+ outcome: "success",
256
+ actorType: "control-plane",
257
+ actorId: operator.subject,
258
+ resourceType: "controlplane_connection",
259
+ resourceId: query.connectionId,
260
+ requestId: c.req.header("cf-ray"),
261
+ ip: c.req.header("cf-connecting-ip"),
262
+ userAgent: c.req.header("user-agent"),
263
+ metadata: {
264
+ connectionId: operator.connectionId,
265
+ query: {
266
+ connectionId: filter.connectionId,
267
+ keyId: filter.keyId ?? null,
268
+ since: filter.since.toISOString(),
269
+ until: filter.until.toISOString(),
270
+ route: filter.route ?? null,
271
+ subjects: expanded.subjects !== void 0
272
+ },
273
+ returned: expanded.reach.length,
274
+ ...expanded.subjects !== void 0 ? { subjects: expanded.subjects.length } : {}
275
+ }
276
+ });
277
+ return c.json({
278
+ connectionId: filter.connectionId,
279
+ keyId: filter.keyId ?? null,
280
+ since: filter.since.toISOString(),
281
+ until: filter.until.toISOString(),
282
+ reach: expanded.reach.map(controlPlaneReachView),
283
+ ...expanded.subjects !== void 0 ? { subjects: expanded.subjects.map(controlPlaneReachSubjectView) } : {}
284
+ }, 200);
285
+ });
286
+ /**
287
+ * CONTROL-PLANE READ (#812). Which scopes one connection exercised and was refused, by key, over a window —
288
+ * counted in one SQL statement, never by paging events here. Behind the listing scope, not the detail one: the
289
+ * answer is the scope, the key, and the last allowed call's method and path, and never an IP, a user-agent or any
290
+ * other metadata key.
291
+ */
292
+ app.get(`${base}/control-plane/usage`, describeRoute({
293
+ summary: "Count which scopes one control-plane connection exercised and was refused, by key, over a window.",
294
+ verification: "control-plane",
295
+ scopes: [AUDIT_TRAIL_READ_SCOPE],
296
+ responses: { 200: ControlPlaneUsageResponse }
297
+ }), requireControlPlane(AUDIT_TRAIL_READ_SCOPE), validate("query", ControlPlaneUsageQuery), async (c) => {
298
+ const operator = caller(c);
299
+ const query = c.req.valid("query");
300
+ const window = {
301
+ since: query.since,
302
+ until: query.until ?? /* @__PURE__ */ new Date()
303
+ };
304
+ const result = await controlPlaneUsage(database(c), {
305
+ connectionId: query.connectionId,
306
+ ...window
307
+ });
308
+ await c.var.emit({
309
+ action: AuditTrailActions.usageRead,
310
+ outcome: "success",
311
+ actorType: "control-plane",
312
+ actorId: operator.subject,
313
+ resourceType: "controlplane_connection",
314
+ resourceId: query.connectionId,
315
+ requestId: c.req.header("cf-ray"),
316
+ ip: c.req.header("cf-connecting-ip"),
317
+ userAgent: c.req.header("user-agent"),
318
+ metadata: {
319
+ connectionId: operator.connectionId,
320
+ query: {
321
+ connectionId: query.connectionId,
322
+ since: window.since.toISOString(),
323
+ until: window.until.toISOString()
324
+ },
325
+ returned: result.usage.length
326
+ }
327
+ });
328
+ return c.json({
329
+ connectionId: query.connectionId,
330
+ since: window.since.toISOString(),
331
+ until: window.until.toISOString(),
332
+ usage: result.usage.map(controlPlaneUsageView),
333
+ oldestEventAt: result.oldestEventAt?.toISOString() ?? null
334
+ }, 200);
335
+ });
336
+ /**
337
+ * CONTROL-PLANE READ (#822). Walk one tenant's hash chain over a window — every link, every hash, the
338
+ * checkpoints covering it — and answer intact or the first break. Reads only: it proves the trail whole and
339
+ * changes nothing.
340
+ */
341
+ app.get(`${base}/control-plane/verify`, describeRoute({
342
+ summary: "Walk one tenant's audit chain against its checkpoints, and say whether it is whole.",
343
+ verification: "control-plane",
344
+ scopes: [AUDIT_CHAIN_EXPORT_SCOPE],
345
+ responses: { 200: ChainVerifyResponse }
346
+ }), requireControlPlane(AUDIT_CHAIN_EXPORT_SCOPE), validate("query", ChainVerifyQuery), async (c) => {
347
+ const operator = caller(c);
348
+ const query = c.req.valid("query");
349
+ const bucket = checkpoints(c);
350
+ const range = {
351
+ tenant: query.tenant,
352
+ ...query.since ? { since: query.since } : {},
353
+ ...query.until ? { until: query.until } : {}
354
+ };
355
+ const found = await verifyChainRange(database(c), bucket, range);
356
+ await c.var.emit({
357
+ action: AuditTrailActions.chainVerified,
358
+ outcome: found.intact ? "success" : "failure",
359
+ severity: found.intact ? "info" : "critical",
360
+ actorType: "control-plane",
361
+ actorId: operator.subject,
362
+ resourceType: "audit_chain",
363
+ requestId: c.req.header("cf-ray"),
364
+ ip: c.req.header("cf-connecting-ip"),
365
+ userAgent: c.req.header("user-agent"),
366
+ metadata: {
367
+ connectionId: operator.connectionId,
368
+ query: {
369
+ tenant: query.tenant,
370
+ since: query.since?.toISOString() ?? null,
371
+ until: query.until?.toISOString() ?? null
372
+ },
373
+ checked: found.checked,
374
+ checkpoints: found.checkpoints,
375
+ ...found.break ? { break: found.break } : {}
376
+ }
377
+ });
378
+ return c.json({
379
+ tenant: query.tenant,
380
+ since: query.since?.toISOString() ?? null,
381
+ until: query.until?.toISOString() ?? null,
382
+ intact: found.intact,
383
+ checked: found.checked,
384
+ checkpoints: found.checkpoints,
385
+ pruned: found.pruned,
386
+ checkpointStore: bucket ? "bound" : "absent",
387
+ beforeChain: found.beforeChain,
388
+ outsideChain: found.outsideChain,
389
+ break: found.break,
390
+ head: found.head
391
+ }, 200);
392
+ });
393
+ /**
394
+ * CONTROL-PLANE READ (#822). One page of one tenant's chain in canonical form, each event with its hash, the
395
+ * link before the page and the checkpoints covering it — what `pithy audit verify` checks offline. The IP,
396
+ * user-agent and metadata values ride along only when the connection also holds the detail scope.
397
+ */
398
+ app.get(`${base}/control-plane/export`, describeRoute({
399
+ summary: "Export one tenant's audit chain in canonical form, with its checkpoints, to verify offline.",
400
+ verification: "control-plane",
401
+ scopes: [AUDIT_CHAIN_EXPORT_SCOPE],
402
+ responses: { 200: ChainExportResponse }
403
+ }), requireControlPlane(AUDIT_CHAIN_EXPORT_SCOPE), validate("query", ChainExportQuery), async (c) => {
404
+ const operator = caller(c);
405
+ const query = c.req.valid("query");
406
+ const detail = operator.grantedScopes.includes(AUDIT_EVENT_DETAIL_READ_SCOPE);
407
+ const page = await exportChainRange(database(c), checkpoints(c), {
408
+ tenant: query.tenant,
409
+ ...query.since ? { since: query.since } : {},
410
+ ...query.until ? { until: query.until } : {}
411
+ }, {
412
+ detail,
413
+ limit: query.limit ?? 500,
414
+ now: /* @__PURE__ */ new Date(),
415
+ ...query.cursor !== void 0 ? { cursor: query.cursor } : {}
416
+ });
417
+ await c.var.emit({
418
+ action: AuditTrailActions.chainExported,
419
+ outcome: "success",
420
+ actorType: "control-plane",
421
+ actorId: operator.subject,
422
+ resourceType: "audit_chain",
423
+ requestId: c.req.header("cf-ray"),
424
+ ip: c.req.header("cf-connecting-ip"),
425
+ userAgent: c.req.header("user-agent"),
426
+ metadata: {
427
+ connectionId: operator.connectionId,
428
+ query: {
429
+ tenant: query.tenant,
430
+ since: query.since?.toISOString() ?? null,
431
+ until: query.until?.toISOString() ?? null,
432
+ resumed: query.cursor !== void 0
433
+ },
434
+ detail,
435
+ returned: page.events.length,
436
+ more: page.nextCursor !== null
437
+ }
438
+ });
439
+ return c.json(page, 200);
440
+ });
135
441
  };
136
442
  }
137
443
  //#endregion