@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
@@ -0,0 +1,220 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { chainedEventOf, readChainHead, readChainLink, readChainRows, whereChain } from "./rows.js";
4
+ import { listCheckpoints, readCheckpoints } from "./checkpoint.js";
5
+ import { readTombstones, tombstoneEndingAt } from "./tombstone.js";
6
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
7
+ import { AUDIT_CHAIN_FORMAT, AUDIT_EXPORT_FORMAT, chainVerifier } from "@pithy-sh/core/src/audit/chain";
8
+ //#region src/chain/verify.ts
9
+ /**
10
+ * **The verify and export reads over one tenant's chain (#822).**
11
+ *
12
+ * A range is asked for in time and walked in chain order. `since` resolves to the first position whose event
13
+ * occurred at or after it, `until` to the last at or before it, and everything between is walked — including an
14
+ * event whose `occurredAt` an emitter set outside the window, because a chain is contiguous in position and a
15
+ * walk that skipped one would report the gap as a break.
16
+ */
17
+ /** How many rows one read of the walk takes. */
18
+ const WALK_PAGE = 500;
19
+ async function resolveRange(db, query) {
20
+ const head = await readChainHead(db, query.tenant);
21
+ let fromSeq = 1;
22
+ if (query.since) {
23
+ const first = await whereChain(db.selectFrom("pithyAuditEvents").select((eb) => eb.fn.min("chainSeq").as("seq")).where("chainSeq", "is not", null).where("occurredAt", ">=", SQLiteDate.encode(query.since)), query.tenant).executeTakeFirst();
24
+ fromSeq = typeof first?.seq === "number" ? first.seq : (head?.seq ?? 0) + 1;
25
+ }
26
+ let throughSeq = head?.seq ?? 0;
27
+ if (query.until) {
28
+ const last = await whereChain(db.selectFrom("pithyAuditEvents").select((eb) => eb.fn.max("chainSeq").as("seq")).where("chainSeq", "is not", null).where("occurredAt", "<=", SQLiteDate.encode(query.until)), query.tenant).executeTakeFirst();
29
+ throughSeq = typeof last?.seq === "number" ? last.seq : 0;
30
+ }
31
+ return {
32
+ fromSeq,
33
+ throughSeq,
34
+ toHead: query.until === void 0
35
+ };
36
+ }
37
+ /** The id of the chain's first row, or null when the tenant has no chained event yet. */
38
+ async function chainStartId(db, tenant) {
39
+ const start = await whereChain(db.selectFrom("pithyAuditEvents").select((eb) => eb.fn.min("id").as("id")).where("chainSeq", "is not", null), tenant).executeTakeFirst();
40
+ return typeof start?.id === "number" ? start.id : null;
41
+ }
42
+ /** The id of the first row holding a position, or null when none does. */
43
+ async function idAt(db, tenant, seq) {
44
+ const row = await whereChain(db.selectFrom("pithyAuditEvents").select((eb) => eb.fn.min("id").as("id")).where("chainSeq", "=", seq), tenant).executeTakeFirst();
45
+ return typeof row?.id === "number" ? row.id : null;
46
+ }
47
+ /** How many of the tenant's events in the window were written before the chain began. */
48
+ async function countBeforeChain(db, query, startId) {
49
+ let builder = whereChain(db.selectFrom("pithyAuditEvents").select((eb) => eb.fn.countAll().as("n")).where("chainSeq", "is", null), query.tenant);
50
+ if (startId !== null) builder = builder.where("id", "<", startId);
51
+ if (query.since) builder = builder.where("occurredAt", ">=", SQLiteDate.encode(query.since));
52
+ if (query.until) builder = builder.where("occurredAt", "<=", SQLiteDate.encode(query.until));
53
+ return Number((await builder.executeTakeFirst())?.n ?? 0);
54
+ }
55
+ /**
56
+ * How many rows carrying no chain were written after the chain began, among the range's positions. A recorder from
57
+ * before the chain writes them — a Worker not yet redeployed, an isolate still serving the old version while a new
58
+ * one rolls out, a rollback, an older CLI emitting into the same database — and Cloudflare deploys no two of those
59
+ * together, so such a row is no evidence of tampering and no break. It carries no evidence of anything: counted here,
60
+ * and marked `chainSeq: null` in the listing, so an auditor sees it. An insert dressed as a chained row is the walk's.
61
+ *
62
+ * A row sits at one past the last chained event recorded before it, so the range's rows lie between the row at the
63
+ * position before `fromSeq` and the row at `throughSeq`, by id — or past it, for a range that runs to the head.
64
+ */
65
+ async function countOutsideChain(db, tenant, range, startId) {
66
+ if (startId === null) return 0;
67
+ if (!range.toHead && range.throughSeq < range.fromSeq) return 0;
68
+ const lowerId = await idAt(db, tenant, Math.max(range.fromSeq - 1, 1)) ?? startId;
69
+ let builder = whereChain(db.selectFrom("pithyAuditEvents").select((eb) => eb.fn.countAll().as("n")).where("chainSeq", "is", null).where("id", ">", lowerId), tenant);
70
+ if (!range.toHead) {
71
+ const upperId = await idAt(db, tenant, range.throughSeq);
72
+ if (upperId !== null) builder = builder.where("id", "<", upperId);
73
+ }
74
+ return Number((await builder.executeTakeFirst())?.n ?? 0);
75
+ }
76
+ /**
77
+ * The link before position `seq`: the stored event there, or, where the retention prune removed it, the last hash its
78
+ * tombstone recorded. Null when neither holds it.
79
+ */
80
+ async function linkBefore(db, tenant, seq, tombstones) {
81
+ const stored = await readChainLink(db, tenant, seq);
82
+ if (stored) return stored;
83
+ const run = tombstoneEndingAt(tombstones, seq);
84
+ return run ? {
85
+ seq: run.throughSeq,
86
+ hash: run.last
87
+ } : null;
88
+ }
89
+ /**
90
+ * Walk a range: every link, every hash, and the checkpoints covering it. `pageSize` is how many rows one read
91
+ * takes, and is a test's to set, so a page boundary can be put where a test needs it.
92
+ */
93
+ async function verifyChainRange(db, bucket, query, options = {}) {
94
+ const first = await walkRange(db, bucket, query, options);
95
+ if (bucket && first.break?.reason === "missing") return walkRange(db, bucket, query, options);
96
+ return first;
97
+ }
98
+ async function walkRange(db, bucket, query, options) {
99
+ const pageSize = options.pageSize ?? WALK_PAGE;
100
+ const listing = bucket ? await listCheckpoints(bucket, query.tenant) : null;
101
+ const tombstones = bucket ? await readTombstones(bucket, query.tenant) : [];
102
+ const range = await resolveRange(db, query);
103
+ const startId = await chainStartId(db, query.tenant);
104
+ const beforeChain = await countBeforeChain(db, query, startId);
105
+ const outsideChain = await countOutsideChain(db, query.tenant, range, startId);
106
+ const prior = range.fromSeq > 1 ? await linkBefore(db, query.tenant, range.fromSeq - 1, tombstones) : null;
107
+ const checkpoints = bucket && listing ? await readCheckpoints(bucket, query.tenant, {
108
+ fromCount: range.fromSeq,
109
+ ...range.toHead ? {} : { throughCount: range.throughSeq }
110
+ }, listing) : [];
111
+ const result = (found, checked, head, held, pruned = 0) => ({
112
+ intact: found === null,
113
+ checked,
114
+ checkpoints: held,
115
+ pruned,
116
+ beforeChain,
117
+ outsideChain,
118
+ break: found,
119
+ head
120
+ });
121
+ if (range.fromSeq > 1 && !prior) return result({
122
+ eventId: null,
123
+ position: range.fromSeq - 1,
124
+ reason: "missing",
125
+ detail: `The event at position ${range.fromSeq - 1}, before the range, is missing.`
126
+ }, 0, null, 0);
127
+ const verifier = chainVerifier({
128
+ tenant: query.tenant,
129
+ prior,
130
+ checkpoints,
131
+ tombstones
132
+ });
133
+ let found = null;
134
+ let after = { seq: range.fromSeq - 1 };
135
+ walk: while (range.throughSeq >= range.fromSeq) {
136
+ const rows = await readChainRows(db, {
137
+ tenant: query.tenant,
138
+ afterSeq: after.seq,
139
+ ...after.id !== void 0 ? { afterId: after.id } : {},
140
+ limit: pageSize,
141
+ throughSeq: range.throughSeq
142
+ });
143
+ for (const row of rows) {
144
+ found = await verifier.push(await chainedEventOf(row, { detail: false }));
145
+ if (found) break walk;
146
+ }
147
+ const last = rows.at(-1);
148
+ if (rows.length < pageSize || !last) break;
149
+ after = {
150
+ seq: last.chainSeq ?? range.throughSeq,
151
+ id: last.id
152
+ };
153
+ }
154
+ found ??= verifier.finish(range.toHead);
155
+ return result(found, verifier.checked, verifier.head, verifier.checkpoints, verifier.pruned);
156
+ }
157
+ /**
158
+ * One page of a range as an export document: its events in canonical form with their hashes, the link before
159
+ * the page, and the checkpoints covering it. Each page verifies on its own from its `prior`, so an auditor can
160
+ * check a page without the ones before it.
161
+ */
162
+ async function exportChainRange(db, bucket, query, options) {
163
+ const listing = bucket ? await listCheckpoints(bucket, query.tenant) : null;
164
+ const tombstones = bucket ? await readTombstones(bucket, query.tenant) : [];
165
+ const range = await resolveRange(db, query);
166
+ const startId = await chainStartId(db, query.tenant);
167
+ const resumed = parseExportCursor(options.cursor);
168
+ const after = resumed && resumed.seq >= range.fromSeq - 1 ? resumed : { seq: range.fromSeq - 1 };
169
+ const afterSeq = after.seq;
170
+ const read = range.throughSeq >= range.fromSeq ? await readChainRows(db, {
171
+ tenant: query.tenant,
172
+ afterSeq,
173
+ ...after.id !== void 0 ? { afterId: after.id } : {},
174
+ limit: options.limit + 1,
175
+ throughSeq: range.throughSeq
176
+ }) : [];
177
+ const more = read.length > options.limit;
178
+ const rows = read.slice(0, options.limit);
179
+ const events = await Promise.all(rows.map((row) => chainedEventOf(row, { detail: options.detail })));
180
+ const lastSeq = events.at(-1)?.seq ?? afterSeq;
181
+ const lastRow = rows.at(-1);
182
+ const prior = afterSeq > 0 ? await linkBefore(db, query.tenant, afterSeq, tombstones) : null;
183
+ const complete = range.toHead && !more;
184
+ const checkpoints = bucket && listing ? await readCheckpoints(bucket, query.tenant, {
185
+ fromCount: afterSeq + 1,
186
+ throughCount: lastSeq
187
+ }, listing) : [];
188
+ return {
189
+ format: AUDIT_EXPORT_FORMAT,
190
+ chain: AUDIT_CHAIN_FORMAT,
191
+ tenant: query.tenant,
192
+ since: query.since?.toISOString() ?? null,
193
+ until: query.until?.toISOString() ?? null,
194
+ exportedAt: options.now.toISOString(),
195
+ detail: options.detail,
196
+ prior,
197
+ events,
198
+ checkpoints,
199
+ ...tombstones.length > 0 ? { tombstones } : {},
200
+ complete,
201
+ beforeChain: await countBeforeChain(db, query, startId),
202
+ outsideChain: await countOutsideChain(db, query.tenant, range, startId),
203
+ nextCursor: more && lastRow ? exportCursor(lastSeq, lastRow.id) : null
204
+ };
205
+ }
206
+ /** An export page's `nextCursor`: the last row's position and id, so the next page resumes after that one row. */
207
+ function exportCursor(seq, id) {
208
+ return `${seq}:${id}`;
209
+ }
210
+ /** A `nextCursor` read back, or null when it is not one — a malformed cursor is a first page. */
211
+ function parseExportCursor(cursor) {
212
+ const match = cursor === void 0 ? null : /^(\d{1,15}):(\d{1,15})$/.exec(cursor);
213
+ if (!match) return null;
214
+ return {
215
+ seq: Number(match[1]),
216
+ id: Number(match[2])
217
+ };
218
+ }
219
+ //#endregion
220
+ export { exportChainRange, parseExportCursor, verifyChainRange };
@@ -0,0 +1,17 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import type { AuditCitationReader } from "@pithy-sh/core/src/audit/citations";
4
+ import { type AuditDatabase } from "./data/tables";
5
+ /**
6
+ * **Citing the trail (#823)** — the reader core's `composedAuditCitations` finds, so the control plane's erasure
7
+ * attestation can point at the events a purge wrote by id and chain position, and import nothing from here.
8
+ *
9
+ * It hands back where an event is, never what it holds: no IP, no user-agent, and of the metadata only a `step`
10
+ * name, which is how a purge step's event says which step it records. A row written before the chain began has no
11
+ * position, and says so with `null` rather than a guess.
12
+ */
13
+ /** The reader over one audit database. */
14
+ export declare function auditCitationReader(db: AuditDatabase): AuditCitationReader;
15
+ /** The reader over the binding the config names, built per call from the env, like the Workflow recorder. */
16
+ export declare function auditCitationsFor(database: string): (env: Record<string, unknown>) => AuditCitationReader;
17
+ //# sourceMappingURL=citations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"citations.d.ts","sourceRoot":"","sources":["../src/citations.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAiB,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAG7F,OAAO,EAAE,KAAK,aAAa,EAAiB,MAAM,eAAe,CAAC;AAElE;;;;;;;GAOG;AAEH,0CAA0C;AAC1C,wBAAgB,mBAAmB,CAAC,EAAE,EAAE,aAAa,GAAG,mBAAmB,CA2B1E;AAED,6GAA6G;AAC7G,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,mBAAmB,CAYzG"}
@@ -0,0 +1,48 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { AuditEventRow } from "./data/auditEvent.js";
4
+ import { auditDatabase } from "./data/tables.js";
5
+ import { InternalError } from "@pithy-sh/core/src/error/pithyError";
6
+ //#region src/citations.ts
7
+ /**
8
+ * **Citing the trail (#823)** — the reader core's `composedAuditCitations` finds, so the control plane's erasure
9
+ * attestation can point at the events a purge wrote by id and chain position, and import nothing from here.
10
+ *
11
+ * It hands back where an event is, never what it holds: no IP, no user-agent, and of the metadata only a `step`
12
+ * name, which is how a purge step's event says which step it records. A row written before the chain began has no
13
+ * position, and says so with `null` rather than a guess.
14
+ */
15
+ /** The reader over one audit database. */
16
+ function auditCitationReader(db) {
17
+ return async (query) => {
18
+ if (query.resourceIds.length === 0 || query.actions.length === 0) return [];
19
+ return (await db.selectFrom("pithyAuditEvents").selectAll().where("resourceType", "=", query.resourceType).where("resourceId", "in", [...query.resourceIds]).where("action", "in", [...query.actions]).orderBy("occurredAt", "asc").orderBy("id", "asc").execute()).map((raw) => {
20
+ const row = AuditEventRow.parse(raw);
21
+ const step = row.metadata?.step;
22
+ return {
23
+ eventId: row.eventId,
24
+ action: row.action,
25
+ resourceId: row.resourceId ?? "",
26
+ occurredAt: row.occurredAt,
27
+ tenant: row.tenant ?? null,
28
+ seq: row.chainSeq ?? null,
29
+ hash: row.chainHash ?? null,
30
+ step: typeof step === "string" ? step : null
31
+ };
32
+ });
33
+ };
34
+ }
35
+ /** The reader over the binding the config names, built per call from the env, like the Workflow recorder. */
36
+ function auditCitationsFor(database) {
37
+ return (env) => {
38
+ const binding = env[database];
39
+ if (typeof binding !== "object" || binding === null) throw new InternalError({
40
+ message: "The audit database is not bound.",
41
+ action: `Bind the ${database} D1 database to this Worker.`,
42
+ detail: `the audit citation reader found no ${database} binding on the env`
43
+ });
44
+ return auditCitationReader(auditDatabase(binding));
45
+ };
46
+ }
47
+ //#endregion
48
+ export { auditCitationReader, auditCitationsFor };
@@ -32,6 +32,11 @@ export type CliAuditEvent = Omit<AuditEventInput, "actorType" | "actorId"> & {
32
32
  *
33
33
  * Like the in-Worker recorder, this is **non-fatal**: a write failure is logged, never thrown, so an
34
34
  * audit write never breaks the command it records.
35
+ *
36
+ * **It is never shipped (#824).** The event takes its position in the tenant's chain like any other, and nothing
37
+ * enqueues it: the CLI binds no queue, and pushing over the Queues REST API would need a credential and a queue
38
+ * name per environment that a command recording one event should not resolve. So a sink sees a `seq` skip at
39
+ * every CLI action, and the audit README says so, and says how a receiver reconciles one against an export.
35
40
  */
36
41
  export declare function emitFromCLI(d1: D1Database, event: CliAuditEvent, actor: ResolvedActor, options?: AuditRecorderOptions): Promise<void>;
37
42
  //# sourceMappingURL=emitFromCLI.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"emitFromCLI.d.ts","sourceRoot":"","sources":["../../src/cli/emitFromCLI.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AAE3E,OAAO,EAAE,KAAK,oBAAoB,EAAoB,MAAM,aAAa,CAAC;AAC1E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEpD;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,aAAa,GAAG,IAAI,CAAC,eAAe,EAAE,WAAW,GAAG,SAAS,CAAC,GAAG;IAC3E;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAsB,WAAW,CAC/B,EAAE,EAAE,UAAU,EACd,KAAK,EAAE,aAAa,EACpB,KAAK,EAAE,aAAa,EACpB,OAAO,CAAC,EAAE,oBAAoB,GAC7B,OAAO,CAAC,IAAI,CAAC,CAqBf"}
1
+ {"version":3,"file":"emitFromCLI.d.ts","sourceRoot":"","sources":["../../src/cli/emitFromCLI.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AAE3E,OAAO,EAAE,KAAK,oBAAoB,EAAoB,MAAM,aAAa,CAAC;AAC1E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEpD;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,aAAa,GAAG,IAAI,CAAC,eAAe,EAAE,WAAW,GAAG,SAAS,CAAC,GAAG;IAC3E;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,WAAW,CAC/B,EAAE,EAAE,UAAU,EACd,KAAK,EAAE,aAAa,EACpB,KAAK,EAAE,aAAa,EACpB,OAAO,CAAC,EAAE,oBAAoB,GAC7B,OAAO,CAAC,IAAI,CAAC,CAqBf"}
@@ -12,6 +12,11 @@ import { recordAuditEvent } from "../recorder.js";
12
12
  *
13
13
  * Like the in-Worker recorder, this is **non-fatal**: a write failure is logged, never thrown, so an
14
14
  * audit write never breaks the command it records.
15
+ *
16
+ * **It is never shipped (#824).** The event takes its position in the tenant's chain like any other, and nothing
17
+ * enqueues it: the CLI binds no queue, and pushing over the Queues REST API would need a credential and a queue
18
+ * name per environment that a command recording one event should not resolve. So a sink sees a `seq` skip at
19
+ * every CLI action, and the audit README says so, and says how a receiver reconciles one against an export.
15
20
  */
16
21
  async function emitFromCLI(d1, event, actor, options) {
17
22
  const { environment, ...rest } = event;
@@ -59,6 +59,10 @@ export declare const AuditEventRow: z.ZodObject<{
59
59
  worker: z.ZodNullable<z.ZodString>;
60
60
  version: z.ZodNullable<z.ZodString>;
61
61
  tenant: z.ZodNullable<z.ZodString>;
62
+ chainSeq: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
63
+ chainPrev: z.ZodDefault<z.ZodNullable<z.ZodString>>;
64
+ chainHash: z.ZodDefault<z.ZodNullable<z.ZodString>>;
65
+ chainSalt: z.ZodDefault<z.ZodNullable<z.ZodString>>;
62
66
  }, z.core.$strip>;
63
67
  export type AuditEventRow = z.output<typeof AuditEventRow>;
64
68
  //# sourceMappingURL=auditEvent.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"auditEvent.d.ts","sourceRoot":"","sources":["../../src/data/auditEvent.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;;;;GAWG;AACH;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,6FAA4B,CAAC;AAE7D,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAuF2F,CAAC;AACtH,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,aAAa,CAAC,CAAC"}
1
+ {"version":3,"file":"auditEvent.d.ts","sourceRoot":"","sources":["../../src/data/auditEvent.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;;;;GAWG;AACH;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,6FAA4B,CAAC;AAE7D,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAqH2F,CAAC;AACtH,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,aAAa,CAAC,CAAC"}
@@ -1,9 +1,9 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: FSL-1.1-MIT
3
3
  import { AuditAction, 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";
6
5
  import { SQLiteDate, sqliteJson } from "@pithy-sh/core/src/data/codecs";
6
+ import { z } from "zod";
7
7
  //#region src/data/auditEvent.ts
8
8
  /**
9
9
  * The `pithy_audit_events` table — one row per recorded security-relevant action. One Zod object is
@@ -32,7 +32,7 @@ const AuditEventRow = z.object({
32
32
  severity: AuditSeverity.describe("How serious the event is, orthogonal to outcome; drives dashboard filtering and alerting."),
33
33
  actorType: AuditActorType.describe("The kind of principal that acted."),
34
34
  actorId: z.string().nullable().describe("The acting principal's stable id (user id, service/token name); null for `system`/`anonymous`. Indexed."),
35
- actorKind: ControlPlaneActorKind.nullable().default(null).describe("For a `control-plane` actor, what kind of management client acted: `agent`, `dashboard` or `script`, from the connection it called through (#721). Null for every other actor, for a connection registered before the kind was recorded, and on rows written before this column existed (`audit_0002_actor_kind`)."),
35
+ actorKind: ControlPlaneActorKind.nullable().default(null).describe("What kind of client acted: `agent`, `dashboard` or `script`. For a `control-plane` actor, the connection it called through; for a `user` actor, `agent` when an MCP client acted as them. Null for every other row, for a connection registered before the kind was recorded, and on rows written before this column existed (`audit_0002_actor_kind`)."),
36
36
  sessionId: z.string().nullable().describe("The session this action belongs to, tying a chain of actions together; null when none."),
37
37
  resourceType: z.string().nullable().describe("The type of resource the action targeted (e.g. `user`, `secret`); null when not resource-scoped."),
38
38
  resourceId: z.string().nullable().describe("The id of the resource the action targeted; null when not resource-scoped."),
@@ -44,7 +44,11 @@ const AuditEventRow = z.object({
44
44
  environment: z.string().nullable().describe("The environment the recording Worker serves (`dev` | `staging` | `prod`), stamped by the recorder from the `ENVIRONMENT` var. Null on rows written before this column existed. Recorded on the row rather than inferred from the database, because an exported or aggregated trail no longer knows which database it came from."),
45
45
  worker: z.string().nullable().describe("The `apps/<name>` directory name of the Worker that recorded the event, stamped from the `WORKER` var; null for a CLI-originated action, which came from no Worker. Two Workers in one project share a database when they declare the same binding, so this is the only column that separates their events."),
46
46
  version: z.string().nullable().describe("The Cloudflare version id of the build that recorded the event, stamped by the recorder from the `CF_VERSION_METADATA` binding. Null for a CLI-originated action, for a Worker that does not declare the binding, and on rows written before this column existed. It is what turns \"this was revoked\" into \"this was revoked, by this subject, against this exact build\"."),
47
- tenant: z.string().nullable().describe("Whose action it was — the id of the tenant it was taken *for*, indexed with `occurredAt` for the (tenant, time) read this column exists to serve. **Supplied by the emitter, not stamped by the recorder** — the opposite of the four columns above it, and deliberately: `project`, `environment` and `worker` are properties of the writer, constant across every row a multi-tenant Worker writes, and no Worker var can know which customer an action belonged to. So this one is exactly as trustworthy as the call site that sets it, and it cannot be defaulted or verified here. Null means *not tenant-scoped* — a single-tenant app, a CLI-originated action, a fleet-wide operator action — and on rows written before this column existed. Never derived from a membership table afterwards: the tenant of an action is a fact at the time of the action, membership is a fact now.")
47
+ tenant: z.string().nullable().describe("Whose action it was — the id of the tenant it was taken *for*, indexed with `occurredAt` for the (tenant, time) read this column exists to serve. **Supplied by the emitter, not stamped by the recorder** — the opposite of the four columns above it, and deliberately: `project`, `environment` and `worker` are properties of the writer, constant across every row a multi-tenant Worker writes, and no Worker var can know which customer an action belonged to. So this one is exactly as trustworthy as the call site that sets it, and it cannot be defaulted or verified here. Null means *not tenant-scoped* — a single-tenant app, a CLI-originated action, a fleet-wide operator action — and on rows written before this column existed. Never derived from a membership table afterwards: the tenant of an action is a fact at the time of the action, membership is a fact now."),
48
+ chainSeq: z.number().int().nullable().default(null).describe("The event's 1-based position in its tenant's chain — one chain per tenant, and one for the events with no tenant. Null on a row written before the chain began, which is what marks it as before the chain; such a row is never back-filled."),
49
+ chainPrev: z.string().nullable().default(null).describe("The hash of the event before it in its chain, null for the first event and for a row before the chain."),
50
+ chainHash: z.string().nullable().default(null).describe("This event's SHA-256 over its canonical serialization (`@pithy-sh/core/src/audit/chain`), which covers its link and every column, with the IP, user-agent and metadata committed by salted hash. Null on a row before the chain."),
51
+ chainSalt: z.string().nullable().default(null).describe("The per-event salt the IP, user-agent and metadata are committed under. Travels only with those values, so a commitment in an export without them cannot be reversed by guessing. Null on a row before the chain.")
48
52
  }).describe("One audit event in `pithy_audit_events` — the durable, queryable record of a security-relevant action.");
49
53
  //#endregion
50
54
  export { AuditEventRow, AuditMetadataColumn };
@@ -0,0 +1,23 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * The `pithy_audit_sinks` table (#824) — one row per declared sink, written by the shipping consumer and read by
6
+ * the manifest's health keys. It holds what the queue cannot be asked: when the sink last took a delivery, when it
7
+ * last refused one, how many events are waiting on a retry, and how many were given up on.
8
+ *
9
+ * A row per **sink**, keyed by the name it is declared under, so a health read is a primary-key lookup per declared
10
+ * sink — bounded by the config, never by the trail. A sink renamed or removed leaves its row behind, read by
11
+ * nothing, and a sink declared again under the same name picks its counts back up.
12
+ *
13
+ * It records delivery, never the trail: no event, no value, no response body from the receiver.
14
+ */
15
+ export declare const AuditSinkStateRow: z.ZodObject<{
16
+ sink: z.ZodString;
17
+ lastDeliveredAt: z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>;
18
+ lastFailedAt: z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>;
19
+ retrying: z.ZodNumber;
20
+ deadLettered: z.ZodNumber;
21
+ }, z.core.$strip>;
22
+ export type AuditSinkStateRow = z.output<typeof AuditSinkStateRow>;
23
+ //# sourceMappingURL=sinkState.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sinkState.d.ts","sourceRoot":"","sources":["../../src/data/sinkState.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;;;GAUG;AACH,eAAO,MAAM,iBAAiB;;;;;;iBAsBqF,CAAC;AACpH,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,iBAAiB,CAAC,CAAC"}
@@ -0,0 +1,25 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
4
+ import { z } from "zod";
5
+ //#region src/data/sinkState.ts
6
+ /**
7
+ * The `pithy_audit_sinks` table (#824) — one row per declared sink, written by the shipping consumer and read by
8
+ * the manifest's health keys. It holds what the queue cannot be asked: when the sink last took a delivery, when it
9
+ * last refused one, how many events are waiting on a retry, and how many were given up on.
10
+ *
11
+ * A row per **sink**, keyed by the name it is declared under, so a health read is a primary-key lookup per declared
12
+ * sink — bounded by the config, never by the trail. A sink renamed or removed leaves its row behind, read by
13
+ * nothing, and a sink declared again under the same name picks its counts back up.
14
+ *
15
+ * It records delivery, never the trail: no event, no value, no response body from the receiver.
16
+ */
17
+ const AuditSinkStateRow = z.object({
18
+ sink: z.string().describe("The sink's name, as `audit({ sinks })` declares it. Primary key."),
19
+ lastDeliveredAt: SQLiteDate.nullable().describe("When the sink last accepted a delivery. Ms-epoch in SQLite, a `Date` in app code; null until the first."),
20
+ lastFailedAt: SQLiteDate.nullable().describe("When the sink last refused a delivery or could not be reached; null until the first failure."),
21
+ retrying: z.number().int().min(0).describe("How many events are waiting on a retry to this sink: its backlog of failed deliveries."),
22
+ deadLettered: z.number().int().min(0).describe("How many events exhausted their retries and went to the dead-letter queue, since the sink was first declared.")
23
+ }).describe("One sink's delivery state: its last delivery, its last failure, its backlog, and what it gave up on.");
24
+ //#endregion
25
+ export { AuditSinkStateRow };
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: FSL-1.1-MIT
3
3
  import type { D1Database } from "@cloudflare/workers-types";
4
4
  import { type DatabaseSchema } from "@pithy-sh/core/src/data/db";
5
- import type { Kysely } from "kysely";
5
+ import type { Insertable, Kysely } from "kysely";
6
6
  /**
7
7
  * The audit capability's table map: camelCase keys (CamelCasePlugin emits the snake_case
8
8
  * `pithy_audit_` SQL). One source of truth, shared by the capability wiring (`capability.ts`), the
@@ -49,11 +49,24 @@ export declare const auditTables: {
49
49
  worker: import("zod").ZodNullable<import("zod").ZodString>;
50
50
  version: import("zod").ZodNullable<import("zod").ZodString>;
51
51
  tenant: import("zod").ZodNullable<import("zod").ZodString>;
52
+ chainSeq: import("zod").ZodDefault<import("zod").ZodNullable<import("zod").ZodNumber>>;
53
+ chainPrev: import("zod").ZodDefault<import("zod").ZodNullable<import("zod").ZodString>>;
54
+ chainHash: import("zod").ZodDefault<import("zod").ZodNullable<import("zod").ZodString>>;
55
+ chainSalt: import("zod").ZodDefault<import("zod").ZodNullable<import("zod").ZodString>>;
56
+ }, import("zod/v4/core").$strip>;
57
+ pithyAuditSinks: import("zod").ZodObject<{
58
+ sink: import("zod").ZodString;
59
+ lastDeliveredAt: import("zod").ZodNullable<import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodNumber, import("zod").ZodString, import("zod").ZodDate]>, import("zod").ZodDate>>;
60
+ lastFailedAt: import("zod").ZodNullable<import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodNumber, import("zod").ZodString, import("zod").ZodDate]>, import("zod").ZodDate>>;
61
+ retrying: import("zod").ZodNumber;
62
+ deadLettered: import("zod").ZodNumber;
52
63
  }, import("zod/v4/core").$strip>;
53
64
  };
54
65
  export type AuditTables = typeof auditTables;
55
66
  /** The typed Kysely view over the audit table — what the recorder and query helper run against. */
56
67
  export type AuditDatabase = Kysely<DatabaseSchema<AuditTables>>;
68
+ /** One row as the recorder inserts it — the `z.input` side, every column it may name. */
69
+ export type AuditEventInsert = Insertable<DatabaseSchema<AuditTables>["pithyAuditEvents"]>;
57
70
  /** Build the audit Kysely over a D1 binding (or a REST `D1Database` from `@pithy-sh/cloudflare`). */
58
71
  export declare function auditDatabase(d1: D1Database): AuditDatabase;
59
72
  //# sourceMappingURL=tables.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tables.d.ts","sourceRoot":"","sources":["../../src/data/tables.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAkB,KAAK,cAAc,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGrC;;;;GAIG;AACH,eAAO,MAAM,WAAW;IACtB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CACjB,CAAC;AACF,MAAM,MAAM,WAAW,GAAG,OAAO,WAAW,CAAC;AAE7C,mGAAmG;AACnG,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC,CAAC;AAEhE,qGAAqG;AACrG,wBAAgB,aAAa,CAAC,EAAE,EAAE,UAAU,GAAG,aAAa,CAE3D"}
1
+ {"version":3,"file":"tables.d.ts","sourceRoot":"","sources":["../../src/data/tables.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAkB,KAAK,cAAc,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAIjD;;;;GAIG;AACH,eAAO,MAAM,WAAW;IACtB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAEhB,eAAe;;;;;;;CAChB,CAAC;AACF,MAAM,MAAM,WAAW,GAAG,OAAO,WAAW,CAAC;AAE7C,mGAAmG;AACnG,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC,CAAC;AAEhE,yFAAyF;AACzF,MAAM,MAAM,gBAAgB,GAAG,UAAU,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC;AAE3F,qGAAqG;AACrG,wBAAgB,aAAa,CAAC,EAAE,EAAE,UAAU,GAAG,aAAa,CAE3D"}
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: FSL-1.1-MIT
3
3
  import { AuditEventRow } from "./auditEvent.js";
4
+ import { AuditSinkStateRow } from "./sinkState.js";
4
5
  import { createDatabase } from "@pithy-sh/core/src/data/db";
5
6
  //#region src/data/tables.ts
6
7
  /**
@@ -8,7 +9,10 @@ import { createDatabase } from "@pithy-sh/core/src/data/db";
8
9
  * `pithy_audit_` SQL). One source of truth, shared by the capability wiring (`capability.ts`), the
9
10
  * recorder, and the query helper so all three type against the same schema.
10
11
  */
11
- const auditTables = { pithyAuditEvents: AuditEventRow };
12
+ const auditTables = {
13
+ pithyAuditEvents: AuditEventRow,
14
+ pithyAuditSinks: AuditSinkStateRow
15
+ };
12
16
  /** Build the audit Kysely over a D1 binding (or a REST `D1Database` from `@pithy-sh/cloudflare`). */
13
17
  function auditDatabase(d1) {
14
18
  return createDatabase(d1, auditTables);
@@ -1,6 +1,6 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: FSL-1.1-MIT
3
- import type { AdminRoute } from "@pithy-sh/core/src/controlPlane/discovery/adminRoute";
3
+ import type { AdminRouteDeclaration } from "@pithy-sh/core/src/controlPlane/discovery/adminRoute";
4
4
  import type { ControlPlaneScope } from "@pithy-sh/core/src/controlPlane/scope/scope";
5
5
  /**
6
6
  * Audit's control-plane scopes, and the admin surface a manifest advertises.
@@ -31,10 +31,33 @@ import type { ControlPlaneScope } from "@pithy-sh/core/src/controlPlane/scope/sc
31
31
  * `metadata` bag — which routinely holds the email address, the resource name, or the reason a
32
32
  * capability recorded alongside its event. Bulk-harvesting those over a whole trail is a privacy
33
33
  * incident, and requiring a second scope is what makes it a decision the adopter makes rather than
34
- * one a listing credential comes with. Since the two are separate routes, a credential holding only
35
- * the detail scope cannot enumerate the trail to find ids to read, and a credential holding only the
36
- * list scope cannot resolve one. `scopeCovers` matches exactly — no prefix, no wildcard — so holding
37
- * one confers nothing about the other.
34
+ * one a listing credential comes with. Since the listing and detail routes are separate, a credential holding
35
+ * only the detail scope cannot enumerate the trail to find ids to read, and a credential holding only the list scope
36
+ * cannot resolve one. `scopeCovers` matches exactly — no prefix, no wildcard — so holding one confers nothing about
37
+ * the other.
38
+ *
39
+ * **Usage rides the listing scope.** `GET {base}/control-plane/usage` counts one connection's calls by scope
40
+ * and key. Its answer is the scope, the key id, and the method and path of the last allowed call — the management
41
+ * client's own footprint, which the listing already discloses in shape through `action`, `actorId` and `resourceId`
42
+ * — and never an IP, a user-agent, or any other metadata key. So it needs no detail scope, and an access review does
43
+ * not have to hold the most dangerous grant audit defines to ask which grants are used.
44
+ *
45
+ * **The access history rides the listing scope.** `GET {base}/control-plane/access-history` answers every
46
+ * membership, connection and key change in a window with its before and after — roles, scopes, the connection's
47
+ * kind, purpose and principal, a key id. It lifts those named metadata keys and no other, and never an IP or a
48
+ * user-agent, so replaying who could reach the data does not need the grant that discloses where everyone was.
49
+ *
50
+ * **Reach rides the listing scope.** `GET {base}/control-plane/reach` answers what one credential touched:
51
+ * per tenant, route and outcome, counts and two instants, and on request one route's called paths and the subject
52
+ * ids they name. Those ids are segments of paths the credential itself sent, naming the subjects the listing
53
+ * already names in `resourceId`, and the tenant is what it shows as `tenant`; the answer never carries an IP, a user-agent, or a metadata key beyond the key id, scope, method and
54
+ * path. So a breach review does not need the detail scope to draw a breach scope.
55
+ *
56
+ * **The chain has a scope of its own.** `GET {base}/control-plane/verify` walks one tenant's chain, and
57
+ * `GET {base}/control-plane/export` takes it out in canonical form with its checkpoints. An export is the trail in
58
+ * bulk, meant to leave the building, so neither read rides the listing scope: both need `audit:events:export`. The
59
+ * export carries IP, user-agent and metadata values only when the connection also holds the detail scope, and their
60
+ * salted hashes otherwise, which verify and disclose nothing.
38
61
  *
39
62
  * The names are constants rather than config: a configurable scope name is a way to misconfigure a
40
63
  * default-denied gate into a differently-named one, and they are the join key with what
@@ -50,6 +73,16 @@ export declare const AUDIT_TRAIL_READ_SCOPE: ControlPlaneScope;
50
73
  * The forensic read, and the more dangerous of the two: this is where the trail's personal data is.
51
74
  */
52
75
  export declare const AUDIT_EVENT_DETAIL_READ_SCOPE: ControlPlaneScope;
76
+ /**
77
+ * Verify and export the hash chain: walk one tenant's chain against its checkpoints, and take it out in
78
+ * canonical form for an auditor to check offline.
79
+ *
80
+ * Its own scope, because an export is the trail in bulk — every event of a tenant, in a form meant to leave the
81
+ * building. The IP, user-agent and metadata ride along only when the connection also holds
82
+ * {@link AUDIT_EVENT_DETAIL_READ_SCOPE}; without it the export carries their salted hashes, which verify and
83
+ * disclose nothing.
84
+ */
85
+ export declare const AUDIT_CHAIN_EXPORT_SCOPE: ControlPlaneScope;
53
86
  /**
54
87
  * Every control-plane scope audit defines — what `pithy dashboard connect` offers for this capability,
55
88
  * and the list a manifest or a doc quotes rather than re-typing.
@@ -66,5 +99,5 @@ export declare const AUDIT_CONTROL_PLANE_SCOPES: readonly ControlPlaneScope[];
66
99
  * The summaries say what the operation is *for*. A client renders these beside a pane somebody is
67
100
  * about to open over other people's activity.
68
101
  */
69
- export declare function auditAdminRoutes(basePath: string): AdminRoute[];
102
+ export declare function auditAdminRoutes(basePath: string): AdminRouteDeclaration[];
70
103
  //# sourceMappingURL=guards.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"guards.d.ts","sourceRoot":"","sources":["../../src/http/guards.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sDAAsD,CAAC;AACvF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAErF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH;;;GAGG;AACH,eAAO,MAAM,sBAAsB,EAAE,iBAAuC,CAAC;AAE7E;;;GAGG;AACH,eAAO,MAAM,6BAA6B,EAAE,iBAA8C,CAAC;AAE3F;;;GAGG;AACH,eAAO,MAAM,0BAA0B,EAAE,SAAS,iBAAiB,EAGlE,CAAC;AAEF;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,UAAU,EAAE,CAgB/D"}
1
+ {"version":3,"file":"guards.d.ts","sourceRoot":"","sources":["../../src/http/guards.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,sDAAsD,CAAC;AAClG,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAErF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4DG;AAEH;;;GAGG;AACH,eAAO,MAAM,sBAAsB,EAAE,iBAAuC,CAAC;AAE7E;;;GAGG;AACH,eAAO,MAAM,6BAA6B,EAAE,iBAA8C,CAAC;AAE3F;;;;;;;;GAQG;AACH,eAAO,MAAM,wBAAwB,EAAE,iBAAyC,CAAC;AAEjF;;;GAGG;AACH,eAAO,MAAM,0BAA0B,EAAE,SAAS,iBAAiB,EAIlE,CAAC;AAEF;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,qBAAqB,EAAE,CAiE1E"}