@pithy-sh/audit 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/README.md +93 -0
  2. package/dist/accessHistory.d.ts +315 -0
  3. package/dist/accessHistory.d.ts.map +1 -0
  4. package/dist/accessHistory.js +299 -0
  5. package/dist/actions.d.ts +15 -1
  6. package/dist/actions.d.ts.map +1 -1
  7. package/dist/actions.js +16 -2
  8. package/dist/capability.d.ts +14 -0
  9. package/dist/capability.d.ts.map +1 -1
  10. package/dist/capability.js +106 -12
  11. package/dist/chain/append.d.ts +43 -0
  12. package/dist/chain/append.d.ts.map +1 -0
  13. package/dist/chain/append.js +110 -0
  14. package/dist/chain/checkpoint.d.ts +70 -0
  15. package/dist/chain/checkpoint.d.ts.map +1 -0
  16. package/dist/chain/checkpoint.js +133 -0
  17. package/dist/chain/lockCheck.d.ts +15 -0
  18. package/dist/chain/lockCheck.d.ts.map +1 -0
  19. package/dist/chain/lockCheck.js +75 -0
  20. package/dist/chain/prune.d.ts +84 -0
  21. package/dist/chain/prune.d.ts.map +1 -0
  22. package/dist/chain/prune.js +231 -0
  23. package/dist/chain/rows.d.ts +74 -0
  24. package/dist/chain/rows.d.ts.map +1 -0
  25. package/dist/chain/rows.js +133 -0
  26. package/dist/chain/tombstone.d.ts +21 -0
  27. package/dist/chain/tombstone.d.ts.map +1 -0
  28. package/dist/chain/tombstone.js +98 -0
  29. package/dist/chain/verify.d.ts +63 -0
  30. package/dist/chain/verify.d.ts.map +1 -0
  31. package/dist/chain/verify.js +220 -0
  32. package/dist/citations.d.ts +17 -0
  33. package/dist/citations.d.ts.map +1 -0
  34. package/dist/citations.js +48 -0
  35. package/dist/cli/emitFromCLI.d.ts +5 -0
  36. package/dist/cli/emitFromCLI.d.ts.map +1 -1
  37. package/dist/cli/emitFromCLI.js +5 -0
  38. package/dist/data/auditEvent.d.ts +4 -0
  39. package/dist/data/auditEvent.d.ts.map +1 -1
  40. package/dist/data/auditEvent.js +7 -3
  41. package/dist/data/sinkState.d.ts +23 -0
  42. package/dist/data/sinkState.d.ts.map +1 -0
  43. package/dist/data/sinkState.js +25 -0
  44. package/dist/data/tables.d.ts +14 -1
  45. package/dist/data/tables.d.ts.map +1 -1
  46. package/dist/data/tables.js +5 -1
  47. package/dist/http/guards.d.ts +39 -6
  48. package/dist/http/guards.d.ts.map +1 -1
  49. package/dist/http/guards.js +101 -17
  50. package/dist/http/responses.d.ts +503 -0
  51. package/dist/http/responses.d.ts.map +1 -1
  52. package/dist/http/responses.js +157 -5
  53. package/dist/http/routes.d.ts +25 -3
  54. package/dist/http/routes.d.ts.map +1 -1
  55. package/dist/http/routes.js +321 -15
  56. package/dist/http/schemas.d.ts +67 -0
  57. package/dist/http/schemas.d.ts.map +1 -1
  58. package/dist/http/schemas.js +88 -4
  59. package/dist/http/views.d.ts +25 -1
  60. package/dist/http/views.d.ts.map +1 -1
  61. package/dist/http/views.js +107 -2
  62. package/dist/migrations/0003_call_index.d.ts +21 -0
  63. package/dist/migrations/0003_call_index.d.ts.map +1 -0
  64. package/dist/migrations/0003_call_index.js +33 -0
  65. package/dist/migrations/0004_request_index.d.ts +16 -0
  66. package/dist/migrations/0004_request_index.d.ts.map +1 -0
  67. package/dist/migrations/0004_request_index.js +24 -0
  68. package/dist/migrations/0005_chain.d.ts +24 -0
  69. package/dist/migrations/0005_chain.d.ts.map +1 -0
  70. package/dist/migrations/0005_chain.js +43 -0
  71. package/dist/migrations/0006_sinks.d.ts +11 -0
  72. package/dist/migrations/0006_sinks.d.ts.map +1 -0
  73. package/dist/migrations/0006_sinks.js +20 -0
  74. package/dist/provision/resolveAuditConfig.d.ts +31 -0
  75. package/dist/provision/resolveAuditConfig.d.ts.map +1 -0
  76. package/dist/provision/resolveAuditConfig.js +43 -0
  77. package/dist/purge/contribution.d.ts +21 -0
  78. package/dist/purge/contribution.d.ts.map +1 -0
  79. package/dist/purge/contribution.js +41 -0
  80. package/dist/reach.d.ts +250 -0
  81. package/dist/reach.d.ts.map +1 -0
  82. package/dist/reach.js +244 -0
  83. package/dist/recorder.d.ts +11 -0
  84. package/dist/recorder.d.ts.map +1 -1
  85. package/dist/recorder.js +23 -5
  86. package/dist/routePattern.d.ts +60 -0
  87. package/dist/routePattern.d.ts.map +1 -0
  88. package/dist/routePattern.js +130 -0
  89. package/dist/seeds/example.d.ts.map +1 -1
  90. package/dist/seeds/example.js +23 -6
  91. package/dist/ship/consumer.d.ts +45 -0
  92. package/dist/ship/consumer.d.ts.map +1 -0
  93. package/dist/ship/consumer.js +141 -0
  94. package/dist/ship/event.d.ts +59 -0
  95. package/dist/ship/event.d.ts.map +1 -0
  96. package/dist/ship/event.js +77 -0
  97. package/dist/ship/health.d.ts +33 -0
  98. package/dist/ship/health.d.ts.map +1 -0
  99. package/dist/ship/health.js +80 -0
  100. package/dist/ship/profiles.d.ts +34 -0
  101. package/dist/ship/profiles.d.ts.map +1 -0
  102. package/dist/ship/profiles.js +62 -0
  103. package/dist/ship/queue.d.ts +57 -0
  104. package/dist/ship/queue.d.ts.map +1 -0
  105. package/dist/ship/queue.js +70 -0
  106. package/dist/ship/secrets.d.ts +7 -0
  107. package/dist/ship/secrets.d.ts.map +1 -0
  108. package/dist/ship/secrets.js +40 -0
  109. package/dist/ship/shipper.d.ts +15 -0
  110. package/dist/ship/shipper.d.ts.map +1 -0
  111. package/dist/ship/shipper.js +27 -0
  112. package/dist/ship/sinks.d.ts +54 -0
  113. package/dist/ship/sinks.d.ts.map +1 -0
  114. package/dist/ship/sinks.js +45 -0
  115. package/dist/ship/state.d.ts +27 -0
  116. package/dist/ship/state.d.ts.map +1 -0
  117. package/dist/ship/state.js +29 -0
  118. package/dist/usage.d.ts +159 -0
  119. package/dist/usage.d.ts.map +1 -0
  120. package/dist/usage.js +87 -0
  121. package/dist/version.generated.d.ts +1 -1
  122. package/dist/version.generated.js +1 -1
  123. package/dist/workflows/prune.d.ts +73 -0
  124. package/dist/workflows/prune.d.ts.map +1 -0
  125. package/dist/workflows/prune.js +128 -0
  126. package/dist/workflows/retryPolicy.d.ts +10 -0
  127. package/dist/workflows/retryPolicy.d.ts.map +1 -0
  128. package/dist/workflows/retryPolicy.js +14 -0
  129. package/dist/workflows/specs.d.ts +70 -0
  130. package/dist/workflows/specs.d.ts.map +1 -0
  131. package/dist/workflows/specs.js +70 -0
  132. package/dist/workflows/worker.d.ts +32 -0
  133. package/dist/workflows/worker.d.ts.map +1 -0
  134. package/dist/workflows/worker.js +41 -0
  135. package/package.json +5 -2
  136. package/pithy.manifest.json +36 -4
  137. package/src/accessHistory.ts +360 -0
  138. package/src/actions.ts +15 -1
  139. package/src/capability.ts +134 -12
  140. package/src/chain/append.ts +161 -0
  141. package/src/chain/checkpoint.ts +172 -0
  142. package/src/chain/lockCheck.ts +72 -0
  143. package/src/chain/prune.ts +340 -0
  144. package/src/chain/rows.ts +211 -0
  145. package/src/chain/tombstone.ts +104 -0
  146. package/src/chain/verify.ts +366 -0
  147. package/src/citations.ts +62 -0
  148. package/src/cli/emitFromCLI.ts +5 -0
  149. package/src/cloudflare-test.d.ts +1 -0
  150. package/src/data/auditEvent.ts +31 -1
  151. package/src/data/sinkState.ts +41 -0
  152. package/src/data/tables.ts +7 -1
  153. package/src/http/guards.ts +90 -6
  154. package/src/http/responses.ts +318 -3
  155. package/src/http/routes.ts +379 -7
  156. package/src/http/schemas.ts +158 -2
  157. package/src/http/views.ts +123 -1
  158. package/src/migrations/0003_call_index.ts +35 -0
  159. package/src/migrations/0004_request_index.ts +26 -0
  160. package/src/migrations/0005_chain.ts +56 -0
  161. package/src/migrations/0006_sinks.ts +28 -0
  162. package/src/provision/resolveAuditConfig.ts +60 -0
  163. package/src/purge/contribution.ts +39 -0
  164. package/src/reach.ts +454 -0
  165. package/src/recorder.ts +64 -42
  166. package/src/routePattern.ts +141 -0
  167. package/src/seeds/example.ts +13 -0
  168. package/src/ship/consumer.ts +169 -0
  169. package/src/ship/event.ts +86 -0
  170. package/src/ship/health.ts +92 -0
  171. package/src/ship/profiles.ts +99 -0
  172. package/src/ship/queue.ts +108 -0
  173. package/src/ship/secrets.ts +42 -0
  174. package/src/ship/shipper.ts +32 -0
  175. package/src/ship/sinks.ts +82 -0
  176. package/src/ship/state.ts +61 -0
  177. package/src/usage.ts +176 -0
  178. package/src/version.generated.ts +1 -1
  179. package/src/workflows/prune.ts +196 -0
  180. package/src/workflows/retryPolicy.ts +14 -0
  181. package/src/workflows/specs.ts +92 -0
  182. package/src/workflows/worker.ts +65 -0
  183. package/src/workflows/wrangler.jsonc +40 -0
package/dist/recorder.js CHANGED
@@ -2,10 +2,11 @@
2
2
  // SPDX-License-Identifier: FSL-1.1-MIT
3
3
  import { AuditInvalidEventError, AuditWriteFailedError } from "./error/errors.js";
4
4
  import { AuditMetadataColumn } from "./data/auditEvent.js";
5
+ import { appendChained, isUnmigratedChain } from "./chain/append.js";
5
6
  import { AuditEvent } from "@pithy-sh/core/src/audit/auditEvent";
6
- import { PithyError, messageOf } from "@pithy-sh/core/src/error/pithyError";
7
- import { z } from "zod";
8
7
  import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
8
+ import { z } from "zod";
9
+ import { PithyError, messageOf } from "@pithy-sh/core/src/error/pithyError";
9
10
  import { withD1Retry } from "@pithy-sh/core/src/data/withD1Retry";
10
11
  //#region src/recorder.ts
11
12
  /** No origin established — what an unstamped Worker and an un-migrated caller both record. */
@@ -29,11 +30,13 @@ function toAuditError(error) {
29
30
  async function recordAuditEvent(db, input, options) {
30
31
  const onError = options?.onError ?? (() => {});
31
32
  const origin = options?.origin ?? NO_ORIGIN;
33
+ const eventId = crypto.randomUUID();
34
+ let action;
32
35
  try {
33
36
  const event = AuditEvent.parse(input);
37
+ action = event.action;
34
38
  const occurredAt = event.occurredAt ?? /* @__PURE__ */ new Date();
35
- const eventId = crypto.randomUUID();
36
- await withD1Retry(() => db.insertInto("pithyAuditEvents").values({
39
+ const record = {
37
40
  eventId,
38
41
  occurredAt: SQLiteDate.encode(occurredAt),
39
42
  action: event.action,
@@ -54,9 +57,24 @@ async function recordAuditEvent(db, input, options) {
54
57
  environment: origin.environment,
55
58
  worker: origin.worker,
56
59
  version: origin.version
57
- }).execute(), options?.retry);
60
+ };
61
+ try {
62
+ await appendChained(db, record, options?.retry ? { retry: options.retry } : {});
63
+ } catch (error) {
64
+ if (!isUnmigratedChain(error)) throw error;
65
+ await withD1Retry(() => db.insertInto("pithyAuditEvents").values(record).execute(), options?.retry);
66
+ }
58
67
  } catch (error) {
59
68
  onError(toAuditError(error));
69
+ return;
70
+ }
71
+ if (options?.ship) try {
72
+ await options.ship({
73
+ eventId,
74
+ action
75
+ });
76
+ } catch (error) {
77
+ options.onShipError?.(error);
60
78
  }
61
79
  }
62
80
  /** Bind a recorder to one audit database — the `emit` seam `@pithy-sh/audit` installs on the request context. */
@@ -0,0 +1,60 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import type { AdminRoute } from "@pithy-sh/core/src/controlPlane/discovery/adminRoute";
4
+ import { z } from "zod";
5
+ /**
6
+ * A declared admin route, in the form the reach statement matches a called path against (#828).
7
+ *
8
+ * The gate records the path as called — `/admin/users/u_8f2`, not `/admin/users/:userId` — so grouping a credential's
9
+ * calls by what they did means matching each one back to the route that served it. That match runs in SQL, inside the
10
+ * one statement, so the routes go in as one JSON parameter of these objects and SQLite compares each call against
11
+ * them with `GLOB`.
12
+ *
13
+ * **A glob and a slash count, together.** A parameter becomes `*`, and `*` in a glob also matches `/`, so on its own
14
+ * `/admin/users/*` would claim `/admin/users/u_8f2/sessions`. Requiring the called path to have exactly as many
15
+ * slashes as the pattern closes that: the pattern's literal slashes already account for every one, so no `*` can
16
+ * swallow another. A route ending in Hono's `*` wildcard matches any depth, and carries no count.
17
+ */
18
+ export declare const ReachPattern: z.ZodObject<{
19
+ method: z.ZodString;
20
+ pattern: z.ZodString;
21
+ glob: z.ZodString;
22
+ slashes: z.ZodNullable<z.ZodNumber>;
23
+ params: z.ZodNumber;
24
+ rank: z.ZodNumber;
25
+ }, z.core.$strip>;
26
+ export type ReachPattern = z.infer<typeof ReachPattern>;
27
+ /**
28
+ * Every declared route as a {@link ReachPattern}, most specific first, one per method and path.
29
+ *
30
+ * Ranked the way a router prefers a static segment to a parameter, so a call to `/admin/users/search` is the search
31
+ * route and not a read of a user called `search`. Two routes of equal specificity cannot both match one path — they
32
+ * differ in a literal segment — so the order between them never decides anything.
33
+ */
34
+ export declare function reachPatterns(routes: readonly Pick<AdminRoute, "method" | "path">[]): ReachPattern[];
35
+ /**
36
+ * The value each of `pattern`'s parameters took in the called `path` — the subject ids a call touched.
37
+ *
38
+ * Read in the Worker rather than in SQL, and only for the rows a `subjects=true` read returns: the statement has
39
+ * already narrowed them to one route, and splitting a path on `/` is not something SQLite does without a recursive
40
+ * CTE per row. A path with a different number of segments names nothing.
41
+ */
42
+ export declare function routeParams(pattern: string, path: string): Record<string, string>;
43
+ /**
44
+ * The subject one call to `pattern` acted on, read from the called `path`.
45
+ *
46
+ * **The subject is the last parameter that names an id**, not the last parameter: on
47
+ * `/accounts/:userId/:currency/transactions` the user is whose data was read, and the currency only narrows what was
48
+ * read of them. A route none of whose parameters names an id falls back to its last one.
49
+ *
50
+ * **`key` tells subjects apart**: the values of the subject parameter and of every parameter before it. The same id
51
+ * under another subject type or another organization is another subject — `/entitlements/user/s_1` and
52
+ * `/entitlements/organization/s_1` are two holders — while the parameters after it are not part of who it is, so one
53
+ * user's ledger read in two currencies is one subject. Both are null when the route declares no parameter, or the path
54
+ * does not fit it.
55
+ */
56
+ export declare function routeSubject(pattern: string, path: string): {
57
+ subjectId: string | null;
58
+ key: string | null;
59
+ };
60
+ //# sourceMappingURL=routePattern.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routePattern.d.ts","sourceRoot":"","sources":["../src/routePattern.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sDAAsD,CAAC;AACvF,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,YAAY;;;;;;;iBAgB4E,CAAC;AACtG,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,YAAY,CAAC,CAAC;AAkBxD;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,SAAS,IAAI,CAAC,UAAU,EAAE,QAAQ,GAAG,MAAM,CAAC,EAAE,GAAG,YAAY,EAAE,CAyBpG;AAWD;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAUjF;AAKD;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG;IAAE,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAQ5G"}
@@ -0,0 +1,130 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { z } from "zod";
4
+ //#region src/routePattern.ts
5
+ /**
6
+ * A declared admin route, in the form the reach statement matches a called path against (#828).
7
+ *
8
+ * The gate records the path as called — `/admin/users/u_8f2`, not `/admin/users/:userId` — so grouping a credential's
9
+ * calls by what they did means matching each one back to the route that served it. That match runs in SQL, inside the
10
+ * one statement, so the routes go in as one JSON parameter of these objects and SQLite compares each call against
11
+ * them with `GLOB`.
12
+ *
13
+ * **A glob and a slash count, together.** A parameter becomes `*`, and `*` in a glob also matches `/`, so on its own
14
+ * `/admin/users/*` would claim `/admin/users/u_8f2/sessions`. Requiring the called path to have exactly as many
15
+ * slashes as the pattern closes that: the pattern's literal slashes already account for every one, so no `*` can
16
+ * swallow another. A route ending in Hono's `*` wildcard matches any depth, and carries no count.
17
+ */
18
+ const ReachPattern = z.object({
19
+ method: z.string().describe("The HTTP method the route answers on."),
20
+ pattern: z.string().describe("The route as declared, with the capability's `basePath` applied."),
21
+ glob: z.string().describe("The pattern as an SQLite `GLOB`: each parameter a `*`, each metacharacter escaped."),
22
+ slashes: z.number().int().nullable().describe("How many `/` a called path must hold to be this route, or null for a wildcard route of any depth."),
23
+ params: z.number().int().describe("How many named parameters the route declares — the subjects it can name."),
24
+ rank: z.number().int().describe("Which route wins when two match one path: the lower rank, so `/users/search` beats `/users/:id`.")
25
+ }).describe("One declared admin route, ready for the reach statement to match called paths against.");
26
+ /** A segment that names a parameter, with Hono's optional `{regex}` and `?` after the name. */
27
+ const PARAM_SEGMENT = /^:([A-Za-z0-9_]+)(\{.*\})?\??$/;
28
+ /** One literal segment, with every `GLOB` metacharacter wrapped in a one-character class so it matches itself. */
29
+ function escapeGlob(segment) {
30
+ return segment.replace(/[*?[]/g, (char) => `[${char}]`);
31
+ }
32
+ /** How specific a route is: literal segments first, then fewer parameters, and a wildcard last. */
33
+ function specificity(path) {
34
+ const segments = path.split("/").slice(1);
35
+ const params = segments.filter((segment) => PARAM_SEGMENT.test(segment)).length;
36
+ const wildcard = segments.includes("*") ? 1 : 0;
37
+ return [
38
+ segments.length - params - wildcard,
39
+ -params,
40
+ -wildcard
41
+ ];
42
+ }
43
+ /**
44
+ * Every declared route as a {@link ReachPattern}, most specific first, one per method and path.
45
+ *
46
+ * Ranked the way a router prefers a static segment to a parameter, so a call to `/admin/users/search` is the search
47
+ * route and not a read of a user called `search`. Two routes of equal specificity cannot both match one path — they
48
+ * differ in a literal segment — so the order between them never decides anything.
49
+ */
50
+ function reachPatterns(routes) {
51
+ const unique = /* @__PURE__ */ new Map();
52
+ for (const route of routes) unique.set(`${route.method} ${route.path}`, route);
53
+ return [...unique.values()].sort((a, b) => {
54
+ const [x, y] = [specificity(a.path), specificity(b.path)];
55
+ for (let i = 0; i < x.length; i++) {
56
+ const difference = y[i] - x[i];
57
+ if (difference !== 0) return difference;
58
+ }
59
+ return 0;
60
+ }).map((route, rank) => {
61
+ const segments = route.path.split("/");
62
+ const wildcard = segments.includes("*");
63
+ return {
64
+ method: route.method,
65
+ pattern: route.path,
66
+ glob: segments.map((segment) => segment === "*" || PARAM_SEGMENT.test(segment) ? "*" : escapeGlob(segment)).join("/"),
67
+ slashes: wildcard ? null : segments.length - 1,
68
+ params: segments.filter((segment) => PARAM_SEGMENT.test(segment)).length,
69
+ rank
70
+ };
71
+ });
72
+ }
73
+ /** One segment of a called path, decoded, or as called when it is not valid percent-encoding. */
74
+ function decodeSegment(segment) {
75
+ try {
76
+ return decodeURIComponent(segment);
77
+ } catch {
78
+ return segment;
79
+ }
80
+ }
81
+ /**
82
+ * The value each of `pattern`'s parameters took in the called `path` — the subject ids a call touched.
83
+ *
84
+ * Read in the Worker rather than in SQL, and only for the rows a `subjects=true` read returns: the statement has
85
+ * already narrowed them to one route, and splitting a path on `/` is not something SQLite does without a recursive
86
+ * CTE per row. A path with a different number of segments names nothing.
87
+ */
88
+ function routeParams(pattern, path) {
89
+ const declared = pattern.split("/");
90
+ const called = path.split("/");
91
+ if (declared.length !== called.length) return {};
92
+ const params = {};
93
+ declared.forEach((segment, index) => {
94
+ const name = PARAM_SEGMENT.exec(segment)?.[1];
95
+ if (name !== void 0) params[name] = decodeSegment(called[index]);
96
+ });
97
+ return params;
98
+ }
99
+ /** A parameter name that names an id: `id` itself, or anything ending in `Id`. */
100
+ const ID_PARAM = /^id$|Id$/;
101
+ /**
102
+ * The subject one call to `pattern` acted on, read from the called `path`.
103
+ *
104
+ * **The subject is the last parameter that names an id**, not the last parameter: on
105
+ * `/accounts/:userId/:currency/transactions` the user is whose data was read, and the currency only narrows what was
106
+ * read of them. A route none of whose parameters names an id falls back to its last one.
107
+ *
108
+ * **`key` tells subjects apart**: the values of the subject parameter and of every parameter before it. The same id
109
+ * under another subject type or another organization is another subject — `/entitlements/user/s_1` and
110
+ * `/entitlements/organization/s_1` are two holders — while the parameters after it are not part of who it is, so one
111
+ * user's ledger read in two currencies is one subject. Both are null when the route declares no parameter, or the path
112
+ * does not fit it.
113
+ */
114
+ function routeSubject(pattern, path) {
115
+ const params = routeParams(pattern, path);
116
+ const names = Object.keys(params);
117
+ if (names.length === 0) return {
118
+ subjectId: null,
119
+ key: null
120
+ };
121
+ const ids = names.filter((name) => ID_PARAM.test(name));
122
+ const subject = ids[ids.length - 1] ?? names[names.length - 1];
123
+ const qualifiers = names.slice(0, names.indexOf(subject) + 1);
124
+ return {
125
+ subjectId: params[subject] ?? null,
126
+ key: JSON.stringify(qualifiers.map((name) => params[name]))
127
+ };
128
+ }
129
+ //#endregion
130
+ export { ReachPattern, reachPatterns, routeParams, routeSubject };
@@ -1 +1 @@
1
- {"version":3,"file":"example.d.ts","sourceRoot":"","sources":["../../src/seeds/example.ts"],"names":[],"mappings":"AAIA,OAAO,EAA2B,KAAK,OAAO,EAAE,MAAM,8BAA8B,CAAC;AA0CrF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,gBAAgB,EAAE,OAuI7B,CAAC"}
1
+ {"version":3,"file":"example.d.ts","sourceRoot":"","sources":["../../src/seeds/example.ts"],"names":[],"mappings":"AAIA,OAAO,EAA2B,KAAK,OAAO,EAAE,MAAM,8BAA8B,CAAC;AAiDrF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,gBAAgB,EAAE,OA6I7B,CAAC"}
@@ -34,6 +34,17 @@ const EXAMPLE_ORIGIN = {
34
34
  version: null
35
35
  };
36
36
  /**
37
+ * Example rows are seeded straight into the table, outside the recorder, so they carry no chain (#822): they are
38
+ * marked as before the chain, exactly as a row written before the upgrade is. A seed is a dev fixture, never
39
+ * evidence, and inventing links for it would teach the verify read to trust rows nobody recorded.
40
+ */
41
+ const BEFORE_THE_CHAIN = {
42
+ chainSeq: null,
43
+ chainPrev: null,
44
+ chainHash: null,
45
+ chainSalt: null
46
+ };
47
+ /**
37
48
  * Two fictional tenants, so a dev database can show what the tenant filter is for.
38
49
  *
39
50
  * **Ada's events are split across both**, deliberately: one person administering two accounts is the
@@ -81,7 +92,8 @@ const auditExampleSeed = defineSeed({
81
92
  requestId: "example-req-0001",
82
93
  metadata: { method: "magic_link" },
83
94
  tenant: EXAMPLE_TENANT_ACME,
84
- ...EXAMPLE_ORIGIN
95
+ ...EXAMPLE_ORIGIN,
96
+ ...BEFORE_THE_CHAIN
85
97
  },
86
98
  {
87
99
  id: 2,
@@ -101,7 +113,8 @@ const auditExampleSeed = defineSeed({
101
113
  requestId: "example-req-0002",
102
114
  metadata: { reason: "expired_link" },
103
115
  tenant: EXAMPLE_TENANT_GLOBEX,
104
- ...EXAMPLE_ORIGIN
116
+ ...EXAMPLE_ORIGIN,
117
+ ...BEFORE_THE_CHAIN
105
118
  },
106
119
  {
107
120
  id: 3,
@@ -124,7 +137,8 @@ const auditExampleSeed = defineSeed({
124
137
  grantedBy: "system"
125
138
  },
126
139
  tenant: EXAMPLE_TENANT_ACME,
127
- ...EXAMPLE_ORIGIN
140
+ ...EXAMPLE_ORIGIN,
141
+ ...BEFORE_THE_CHAIN
128
142
  },
129
143
  {
130
144
  id: 4,
@@ -148,7 +162,8 @@ const auditExampleSeed = defineSeed({
148
162
  to: 10
149
163
  },
150
164
  tenant: EXAMPLE_TENANT_GLOBEX,
151
- ...EXAMPLE_ORIGIN
165
+ ...EXAMPLE_ORIGIN,
166
+ ...BEFORE_THE_CHAIN
152
167
  },
153
168
  {
154
169
  id: 5,
@@ -171,7 +186,8 @@ const auditExampleSeed = defineSeed({
171
186
  action: "family_revoked"
172
187
  },
173
188
  tenant: EXAMPLE_TENANT_GLOBEX,
174
- ...EXAMPLE_ORIGIN
189
+ ...EXAMPLE_ORIGIN,
190
+ ...BEFORE_THE_CHAIN
175
191
  },
176
192
  {
177
193
  id: 6,
@@ -194,7 +210,8 @@ const auditExampleSeed = defineSeed({
194
210
  currency: "coins"
195
211
  },
196
212
  tenant: null,
197
- ...EXAMPLE_ORIGIN
213
+ ...EXAMPLE_ORIGIN,
214
+ ...BEFORE_THE_CHAIN
198
215
  }
199
216
  ])]
200
217
  });
@@ -0,0 +1,45 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import type { Logger } from "@pithy-sh/core/src/logger/logger";
4
+ import type { CapabilityQueueHandler } from "@pithy-sh/core/src/queue/consumer";
5
+ import type { AuditDatabase } from "../data/tables";
6
+ import type { AuditSinks } from "./sinks";
7
+ /**
8
+ * **The shipping consumer (#824): one request per sink per batch, at least once.**
9
+ *
10
+ * Each sink's share of a batch is read back from the trail, built into the sink's own format, and posted once. A 2xx
11
+ * acknowledges every message in it; anything else — a refusal, a timeout, a token that will not resolve — retries
12
+ * every one of them after a delay that doubles from 30 seconds to an hour, so a failing sink backs off instead of
13
+ * being hammered. A message whose last retry fails goes to the dead-letter queue, and the sink's state counts it.
14
+ *
15
+ * A sink fails on its own. One sink down costs that sink's messages a retry and leaves every other sink's delivered:
16
+ * a message names one sink, so nothing a healthy sink took is ever sent to it again.
17
+ *
18
+ * **Two messages are acknowledged without a delivery**, because no retry could ever deliver them: one naming a sink
19
+ * the config no longer declares, and one naming an event with no row. Both are logged.
20
+ *
21
+ * **What the log never carries:** a token, a response body, or any value from the event. The sink's name, the
22
+ * status and the count are enough to act on, and the receiver's response is the receiver's.
23
+ */
24
+ /** How long one delivery may take before it counts as a failure, in ms. */
25
+ export declare const SHIP_TIMEOUT_MS = 10000;
26
+ /** What the consumer needs, every piece injectable so a test runs it against recorded requests. */
27
+ export interface ShipConsumerOptions {
28
+ /** The declared sinks. */
29
+ sinks: AuditSinks;
30
+ /** The audit database for this invocation's env. Throws when the binding is absent. */
31
+ database: (env: Record<string, unknown>) => AuditDatabase;
32
+ /** A sink's token, read through `@pithy-sh/secrets`. Throws when it is not set. */
33
+ token: (env: Record<string, unknown>, secret: string) => Promise<string>;
34
+ /** The network. Defaults to the global `fetch`. */
35
+ fetch?: (url: string, init: RequestInit) => Promise<Response>;
36
+ /** The clock. */
37
+ now?: () => Date;
38
+ /** The retries the queue's consumer entry declares. Defaults to {@link AUDIT_SHIP_MAX_RETRIES}. */
39
+ maxRetries?: number;
40
+ /** Where a skipped message or a failed delivery is said. */
41
+ log?: Pick<Logger, "warn">;
42
+ }
43
+ /** The capability's queue handler: every message of a batch that names audit, by sink. */
44
+ export declare function auditShipConsumer(options: ShipConsumerOptions): CapabilityQueueHandler;
45
+ //# sourceMappingURL=consumer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"consumer.d.ts","sourceRoot":"","sources":["../../src/ship/consumer.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kCAAkC,CAAC;AAC/D,OAAO,KAAK,EAAE,sBAAsB,EAAgB,MAAM,mCAAmC,CAAC;AAE9F,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAIpD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAG1C;;;;;;;;;;;;;;;;GAgBG;AAEH,2EAA2E;AAC3E,eAAO,MAAM,eAAe,QAAS,CAAC;AAEtC,mGAAmG;AACnG,MAAM,WAAW,mBAAmB;IAClC,0BAA0B;IAC1B,KAAK,EAAE,UAAU,CAAC;IAClB,uFAAuF;IACvF,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,aAAa,CAAC;IAC1D,mFAAmF;IACnF,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACzE,mDAAmD;IACnD,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC9D,iBAAiB;IACjB,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;IACjB,mGAAmG;IACnG,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,4DAA4D;IAC5D,GAAG,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC5B;AA0FD,0FAA0F;AAC1F,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,mBAAmB,GAAG,sBAAsB,CA2BtF"}
@@ -0,0 +1,141 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { readRowsByEventId } from "../chain/rows.js";
4
+ import { shippedEventOf } from "./event.js";
5
+ import { sinkDelivery } from "./profiles.js";
6
+ import { ShipMessage, isFinalAttempt, retryDelaySeconds } from "./queue.js";
7
+ import { recordSinkOutcome } from "./state.js";
8
+ //#region src/ship/consumer.ts
9
+ /**
10
+ * **The shipping consumer (#824): one request per sink per batch, at least once.**
11
+ *
12
+ * Each sink's share of a batch is read back from the trail, built into the sink's own format, and posted once. A 2xx
13
+ * acknowledges every message in it; anything else — a refusal, a timeout, a token that will not resolve — retries
14
+ * every one of them after a delay that doubles from 30 seconds to an hour, so a failing sink backs off instead of
15
+ * being hammered. A message whose last retry fails goes to the dead-letter queue, and the sink's state counts it.
16
+ *
17
+ * A sink fails on its own. One sink down costs that sink's messages a retry and leaves every other sink's delivered:
18
+ * a message names one sink, so nothing a healthy sink took is ever sent to it again.
19
+ *
20
+ * **Two messages are acknowledged without a delivery**, because no retry could ever deliver them: one naming a sink
21
+ * the config no longer declares, and one naming an event with no row. Both are logged.
22
+ *
23
+ * **What the log never carries:** a token, a response body, or any value from the event. The sink's name, the
24
+ * status and the count are enough to act on, and the receiver's response is the receiver's.
25
+ */
26
+ /** How long one delivery may take before it counts as a failure, in ms. */
27
+ const SHIP_TIMEOUT_MS = 1e4;
28
+ /** Why a delivery failed, as one line with nothing from the receiver's body in it. */
29
+ function failureOf(error) {
30
+ if (error instanceof Error) return error.name === "TimeoutError" ? "timed out" : error.message;
31
+ return String(error);
32
+ }
33
+ /** Deliver one sink's messages, and settle every one of them. */
34
+ async function deliver(options, env, db, sinkName, messages) {
35
+ const sink = options.sinks[sinkName];
36
+ const log = options.log;
37
+ if (sink === void 0) {
38
+ log?.warn("audit shipment dropped", {
39
+ reason: "sink no longer declared",
40
+ sink: sinkName,
41
+ count: messages.length
42
+ });
43
+ for (const { message } of messages) message.ack();
44
+ return;
45
+ }
46
+ const rows = new Map((await readRowsByEventId(db, [...new Set(messages.map((m) => m.eventId))])).map((r) => [r.eventId, r]));
47
+ const deliverable = [];
48
+ for (const entry of messages) if (rows.has(entry.eventId)) deliverable.push(entry);
49
+ else {
50
+ log?.warn("audit shipment dropped", {
51
+ reason: "event not in the trail",
52
+ sink: sinkName,
53
+ eventId: entry.eventId
54
+ });
55
+ entry.message.ack();
56
+ }
57
+ if (deliverable.length === 0) return;
58
+ const unique = [...new Set(deliverable.map((entry) => entry.eventId))];
59
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
60
+ const maxRetries = options.maxRetries ?? 10;
61
+ let failure = null;
62
+ try {
63
+ const events = await Promise.all(unique.map((eventId) => shippedEventOf(rows.get(eventId), sink)));
64
+ const token = await options.token(env, sink.secret);
65
+ const request = sinkDelivery(sink, token, events);
66
+ const response = await (options.fetch ?? fetch)(request.url, {
67
+ ...request.init,
68
+ redirect: "manual",
69
+ signal: AbortSignal.timeout(SHIP_TIMEOUT_MS)
70
+ });
71
+ await response.body?.cancel().catch(() => {});
72
+ if (!response.ok) failure = `answered ${response.status}`;
73
+ } catch (error) {
74
+ failure = failureOf(error);
75
+ }
76
+ if (failure === null) {
77
+ for (const { message } of deliverable) message.ack();
78
+ await recordSinkOutcome(db, sinkName, {
79
+ delivered: true,
80
+ at: now(),
81
+ retryingDelta: -deliverable.filter(({ message }) => message.attempts > 1).length,
82
+ deadLettered: 0
83
+ });
84
+ return;
85
+ }
86
+ let retryingDelta = 0;
87
+ let deadLettered = 0;
88
+ for (const { message } of deliverable) {
89
+ if (isFinalAttempt(message.attempts, maxRetries)) {
90
+ deadLettered += 1;
91
+ if (message.attempts > 1) retryingDelta -= 1;
92
+ } else if (message.attempts === 1) retryingDelta += 1;
93
+ message.retry({ delaySeconds: retryDelaySeconds(message.attempts) });
94
+ }
95
+ log?.warn("audit shipment failed", {
96
+ sink: sinkName,
97
+ failure,
98
+ count: deliverable.length,
99
+ deadLettered
100
+ });
101
+ await recordSinkOutcome(db, sinkName, {
102
+ delivered: false,
103
+ at: now(),
104
+ retryingDelta,
105
+ deadLettered
106
+ });
107
+ }
108
+ /** The capability's queue handler: every message of a batch that names audit, by sink. */
109
+ function auditShipConsumer(options) {
110
+ return async (messages, env) => {
111
+ const bySink = /* @__PURE__ */ new Map();
112
+ for (const message of messages) {
113
+ const parsed = ShipMessage.safeParse(message.body);
114
+ if (!parsed.success) {
115
+ options.log?.warn("audit shipment dropped", {
116
+ reason: "not a shipment",
117
+ messageId: message.id
118
+ });
119
+ message.ack();
120
+ continue;
121
+ }
122
+ const list = bySink.get(parsed.data.sink) ?? [];
123
+ list.push({
124
+ message,
125
+ eventId: parsed.data.eventId
126
+ });
127
+ bySink.set(parsed.data.sink, list);
128
+ }
129
+ if (bySink.size === 0) return;
130
+ const db = options.database(env);
131
+ const failures = [];
132
+ for (const [sink, list] of bySink) try {
133
+ await deliver(options, env, db, sink, list);
134
+ } catch (error) {
135
+ failures.push(error);
136
+ }
137
+ if (failures[0] !== void 0) throw failures[0];
138
+ };
139
+ }
140
+ //#endregion
141
+ export { SHIP_TIMEOUT_MS, auditShipConsumer };
@@ -0,0 +1,59 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { z } from "zod";
4
+ import { type ChainRow } from "../chain/rows";
5
+ /**
6
+ * **One event as a sink receives it (#824)** — the chain's own canonical form, so a receiver can check it.
7
+ *
8
+ * Every field the event's chain hash covers, its position, the hash before it and its own hash. A receiver
9
+ * de-duplicates a redelivery on `eventId`, which a redelivery carries unchanged, and spots a gap where a tenant's
10
+ * `seq` skips or a `prev` names no hash it holds. With the values and the salt — only for a sink declared
11
+ * `detail: true` — it can recompute the commitments too; without them it holds the commitments, which verify
12
+ * against the hash and disclose nothing. It is the same serialization `pithy audit verify` checks, so what a
13
+ * receiver holds checks against an export of the same range.
14
+ *
15
+ * **Not every skip is a loss.** An event the CLI records takes a position in the chain and is never shipped (see
16
+ * `emitFromCLI`), and a sink with an `actions` filter skips what it does not take.
17
+ *
18
+ * **A row from before the chain**, or written by an older recorder, carries no position and no hash, and its
19
+ * commitments are null: they were never made, and an unsalted hash of an IP address would be reversible.
20
+ */
21
+ /** The format string of a shipped event. A new shape is a new string. */
22
+ export declare const AUDIT_SHIP_FORMAT = "pithy-audit-ship/1";
23
+ export declare const ShippedAuditEvent: z.ZodObject<{
24
+ eventId: z.ZodString;
25
+ occurredAt: z.ZodNumber;
26
+ action: z.ZodString;
27
+ outcome: z.ZodString;
28
+ severity: z.ZodString;
29
+ actorType: z.ZodString;
30
+ actorId: z.ZodNullable<z.ZodString>;
31
+ actorKind: z.ZodNullable<z.ZodString>;
32
+ sessionId: z.ZodNullable<z.ZodString>;
33
+ resourceType: z.ZodNullable<z.ZodString>;
34
+ resourceId: z.ZodNullable<z.ZodString>;
35
+ requestId: z.ZodNullable<z.ZodString>;
36
+ tenant: z.ZodNullable<z.ZodString>;
37
+ project: z.ZodNullable<z.ZodString>;
38
+ environment: z.ZodNullable<z.ZodString>;
39
+ worker: z.ZodNullable<z.ZodString>;
40
+ version: z.ZodNullable<z.ZodString>;
41
+ ipCommitment: z.ZodNullable<z.ZodString>;
42
+ userAgentCommitment: z.ZodNullable<z.ZodString>;
43
+ metadataCommitment: z.ZodNullable<z.ZodString>;
44
+ format: z.ZodLiteral<"pithy-audit-ship/1">;
45
+ chain: z.ZodLiteral<"pithy-audit-chain/1">;
46
+ seq: z.ZodNullable<z.ZodNumber>;
47
+ prev: z.ZodNullable<z.ZodString>;
48
+ hash: z.ZodNullable<z.ZodString>;
49
+ salt: z.ZodOptional<z.ZodString>;
50
+ ip: z.ZodOptional<z.ZodNullable<z.ZodString>>;
51
+ userAgent: z.ZodOptional<z.ZodNullable<z.ZodString>>;
52
+ metadata: z.ZodOptional<z.ZodNullable<z.ZodString>>;
53
+ }, z.core.$strip>;
54
+ export type ShippedAuditEvent = z.infer<typeof ShippedAuditEvent>;
55
+ /** One stored row as a sink receives it. `detail` decides whether the personal values travel. */
56
+ export declare function shippedEventOf(row: ChainRow, options: {
57
+ detail: boolean;
58
+ }): Promise<ShippedAuditEvent>;
59
+ //# sourceMappingURL=event.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event.d.ts","sourceRoot":"","sources":["../../src/ship/event.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,KAAK,QAAQ,EAAiB,MAAM,eAAe,CAAC;AAE7D;;;;;;;;;;;;;;;GAeG;AAEH,yEAAyE;AACzE,eAAO,MAAM,iBAAiB,uBAAuB,CAAC;AAEtD,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsBqF,CAAC;AACpH,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAElE,iGAAiG;AACjG,wBAAsB,cAAc,CAAC,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE;IAAE,MAAM,EAAE,OAAO,CAAA;CAAE,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAoB5G"}
@@ -0,0 +1,77 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { chainFieldsOf } from "../chain/rows.js";
4
+ import { z } from "zod";
5
+ import { AUDIT_CHAIN_FORMAT, ChainedEventFields, Sha256Hex } from "@pithy-sh/core/src/audit/chain";
6
+ //#region src/ship/event.ts
7
+ /**
8
+ * **One event as a sink receives it (#824)** — the chain's own canonical form, so a receiver can check it.
9
+ *
10
+ * Every field the event's chain hash covers, its position, the hash before it and its own hash. A receiver
11
+ * de-duplicates a redelivery on `eventId`, which a redelivery carries unchanged, and spots a gap where a tenant's
12
+ * `seq` skips or a `prev` names no hash it holds. With the values and the salt — only for a sink declared
13
+ * `detail: true` — it can recompute the commitments too; without them it holds the commitments, which verify
14
+ * against the hash and disclose nothing. It is the same serialization `pithy audit verify` checks, so what a
15
+ * receiver holds checks against an export of the same range.
16
+ *
17
+ * **Not every skip is a loss.** An event the CLI records takes a position in the chain and is never shipped (see
18
+ * `emitFromCLI`), and a sink with an `actions` filter skips what it does not take.
19
+ *
20
+ * **A row from before the chain**, or written by an older recorder, carries no position and no hash, and its
21
+ * commitments are null: they were never made, and an unsalted hash of an IP address would be reversible.
22
+ */
23
+ /** The format string of a shipped event. A new shape is a new string. */
24
+ const AUDIT_SHIP_FORMAT = "pithy-audit-ship/1";
25
+ const ShippedAuditEvent = ChainedEventFields.extend({
26
+ format: z.literal(AUDIT_SHIP_FORMAT).describe("The shipped-event format."),
27
+ chain: z.literal(AUDIT_CHAIN_FORMAT).describe("The canonical form `hash` was computed over."),
28
+ seq: z.number().int().min(1).nullable().describe("The 1-based position in the tenant's chain, or null for an event outside the chain."),
29
+ prev: Sha256Hex.nullable().describe("The hash of the event before it, or null for a chain's first event."),
30
+ hash: Sha256Hex.nullable().describe("This event's chain hash, or null for an event outside the chain."),
31
+ salt: z.string().optional().describe("The per-event salt the commitments were made under. Only for a sink declared `detail: true`."),
32
+ ip: z.string().nullable().optional().describe("The client IP. Only for a sink declared `detail: true`."),
33
+ userAgent: z.string().nullable().optional().describe("The user-agent. Only for a sink declared `detail: true`."),
34
+ metadata: z.string().nullable().optional().describe("The metadata's stored JSON text, byte for byte. Only for a sink declared `detail: true`.")
35
+ }).describe("One audit event as a sink receives it: the chain's canonical form, personal values only with detail.");
36
+ /** One stored row as a sink receives it. `detail` decides whether the personal values travel. */
37
+ async function shippedEventOf(row, options) {
38
+ const link = chainLinkOf(row);
39
+ const fields = await chainFieldsOf(row, link?.salt ?? "");
40
+ return {
41
+ format: AUDIT_SHIP_FORMAT,
42
+ chain: AUDIT_CHAIN_FORMAT,
43
+ ...fields,
44
+ ...link ? {} : {
45
+ ipCommitment: null,
46
+ userAgentCommitment: null,
47
+ metadataCommitment: null
48
+ },
49
+ seq: link?.seq ?? null,
50
+ prev: link?.prev ?? null,
51
+ hash: link?.hash ?? null,
52
+ ...options.detail ? {
53
+ ...link ? { salt: link.salt } : {},
54
+ ip: row.ip,
55
+ userAgent: row.userAgent,
56
+ metadata: row.metadata
57
+ } : {}
58
+ };
59
+ }
60
+ /**
61
+ * A row's place in the chain, or null for a row outside it. The type checks are not decoration, the same as the
62
+ * reader's: SQLite reads an unknown double-quoted identifier as a string literal, so a database the app reached
63
+ * before `audit_0005_chain` ran hands back the text `chain_seq` for the position and `chain_salt` for the salt, and
64
+ * the recorder writes there unchained on purpose. A null check would ship those names as a position, a hash and a salt.
65
+ */
66
+ function chainLinkOf(row) {
67
+ const { chainSeq, chainPrev, chainHash, chainSalt } = row;
68
+ if (typeof chainSeq !== "number" || typeof chainHash !== "string" || typeof chainSalt !== "string") return null;
69
+ return {
70
+ seq: chainSeq,
71
+ prev: typeof chainPrev === "string" ? chainPrev : null,
72
+ hash: chainHash,
73
+ salt: chainSalt
74
+ };
75
+ }
76
+ //#endregion
77
+ export { AUDIT_SHIP_FORMAT, ShippedAuditEvent, shippedEventOf };