@voltro/plugin-audit 0.18.0 → 0.20.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.
- package/CHANGELOG.md +245 -3
- package/dist/index.d.ts +76 -0
- package/dist/index.js +81 -34
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -39,6 +39,246 @@ _Changes staged for the next release accumulate here (rolled up from
|
|
|
39
39
|
|
|
40
40
|
---
|
|
41
41
|
|
|
42
|
+
## [0.20.0] — 2026-07-29
|
|
43
|
+
|
|
44
|
+
### ⚠ BREAKING
|
|
45
|
+
|
|
46
|
+
- **@voltro/plugin-versioning, @voltro/database, @voltro/voltro, @voltro/sql-postgres, @voltro/sql-mysql, @voltro/sql-sqlite, @voltro/sql-mssql** — `versioningPlugin({ timing: 'in-transaction' })` produced a WRONG trail, not merely a slow one. Reported and reproduced against MariaDB 11 by a team that wired both plugins and measured before migrating a single call site.
|
|
47
|
+
|
|
48
|
+
**It recorded every change twice.** The two timings are alternatives, but the post-commit change tap stayed wired when the in-transaction recorder was registered, so both ran. One `bookmarks.create` → two history rows.
|
|
49
|
+
|
|
50
|
+
**And the trail was mis-ordered, which is worse.** Each path numbered independently: one insert plus one update produced versions `0, 0, 1, 2` across four rows. `selectAsOf`, `sortHistory` and `diffVersionRows` all read `version`, so `rowAsOf` returned the wrong snapshot and `diffVersions` found nothing. A duplicate can be deduped; a wrong order cannot be detected from the data.
|
|
51
|
+
|
|
52
|
+
The recorder wrote a constant `version: 0` on purpose, with a design note arguing that ordering could come from `changedAt` and that a read per covered write was too expensive. Both halves were wrong: `changedAt` is millisecond-resolution, so two writes to one row inside one transaction tie routinely, and the number is what every reader consults.
|
|
53
|
+
|
|
54
|
+
**BREAKING —** a `WriteRecorder` now receives a PORT (`{ append, maxOf }`) rather than a bare `append`. `maxOf` is one aggregate with an equality filter on the connection the write already holds; it is what lets an append-only trail number its own entries. A recorder still cannot UPDATE, DELETE or open a nested transaction, and a throw from either operation still rolls the caller's write back. Apps that merely ENABLE the timing need no change — only a hand-written recorder does, and `tsc` names every site.
|
|
55
|
+
|
|
56
|
+
**Cost, stated rather than avoided:** `'in-transaction'` now takes TWO round-trips per recorded write, roughly doubling this timing's published per-write overhead. Both timings number from 1, so switching `timing` no longer shifts version numbers.
|
|
57
|
+
|
|
58
|
+
### Fixed
|
|
59
|
+
|
|
60
|
+
- **@voltro/database, @voltro/sql-postgres, @voltro/sql-mysql, @voltro/sql-sqlite, @voltro/sql-mssql** — The correlation bridge did not survive a transaction, and did not survive CDC. Both are fixed, and both were found by measuring against live databases after a consumer isolated the symptom in a scratch app.
|
|
61
|
+
|
|
62
|
+
**Every write a framework mutation makes was unattributed.** `transactional()` is entered from the request's async-local scope, but its callback runs from inside the Effect the store builds — and measured against live postgres AND live mariadb, the scope is active at the call site and EMPTY inside the callback. Framework mutations are auto-transactional, so this was every handler write. Same class as the `bindMutation` defect fixed alongside it: a scope covering the construction of an Effect and not its execution. The caller's attribution is now captured at `transactional()` entry and re-established around the callback, in all four dialect stores.
|
|
63
|
+
|
|
64
|
+
**And the CDC transports could not carry it at all.** Under `changeStrategy: 'cdc'` — the DEFAULT — the event a subscriber receives is rebuilt from a postgres NOTIFY payload or a mysql binlog row image, neither of which can hold a request context. `registerPendingAttribution` / `claimPendingAttribution` (`@voltro/database`) let the write path hand its identity to the echo, keyed by `(table, op, id)` and claimed once. A write made on ANOTHER replica has nothing pending and stays unattributed, which is the correct answer rather than a gap.
|
|
65
|
+
|
|
66
|
+
**Plus one nobody had reported, found on the way:** on postgres under CDC the write path skipped `routeEvent` entirely, and `runWriteRecorders` lives inside it — so `versioningPlugin({ timing: 'in-transaction' })` with the default `CDC=1` recorded NOTHING. The mode whose entire promise is "if the change committed, the entry is there" wrote an empty trail, silently. `routeEvent` now runs in both modes; only the DELIVERY decision is strategy-dependent.
|
|
67
|
+
|
|
68
|
+
New live-dialect suites (`cdcAttribution.integration.test.ts` in `sql-postgres` and `sql-mysql`) pin all of it, and were verified red against the previous code.
|
|
69
|
+
- **@voltro/plugin-versioning, @voltro/runtime, @voltro/cli** — `_voltro_row_history.traceId` and `.subjectId` were NULL on every write. Three independent causes, all found from one consumer report whose evidence pinned the diagnosis before we looked: `subjectId` was NULL while `changedBy` on the SAME row carried the acting user — so the identity was known and was not travelling.
|
|
70
|
+
|
|
71
|
+
- **The adapter dropped them.** `dataStoreHistoryStore.append` hand-wrote its insert object and listed `changedBy` but not `traceId` / `subjectId`. This is the second time that shape has bitten in this file — the READ side (`rowToVersion`) had drifted identically. A row built by hand in one place and read by hand in another disagree exactly when a field is ADDED, because nothing fails. Both now spread the row. - **An Effect-returning handler was unattributed.** `bindMutation` established the scope around the CALL, which covers an async executor for its whole run — but an Effect-returning one is only CONSTRUCTED there and runs later. It is now forked inside the scope, with interruption and typed failures preserved (both pinned by tests). Verified by measurement, not assumption: an Effect forked inside an ALS scope keeps seeing it across `sleep`, `yieldNow` and a `setTimeout` promise, while the same effect merely constructed inside sees nothing. - **The devtools `/invoke` path never entered the scope at all.** It bypasses the rpc stack by design, and that also bypassed everything `bindMutation` sets up. The audit plugin recorded a traceId (it reads `requestContext.traceId`, which this path does build) while every write underneath carried none — three consumers of one call disagreeing about its trace. It also synthesised `inspect-<8 random chars>`, which no trace consumer can parse; the reporter's framing is the rule worth keeping — *a synthesised id produces a column that looks joinable and is not; NULL at least fails honestly.* It is a real 32-hex id now, and it reaches all three sinks.
|
|
72
|
+
|
|
73
|
+
`actingUserId` is imported at the new call site rather than re-derived — one answer to "who is writing", shared with what `audit()` stamps.
|
|
74
|
+
- **@voltro/cli** — Three ways a check reported nothing while checking nothing, all found by a consumer verifying the silence instead of trusting it.
|
|
75
|
+
|
|
76
|
+
- **`unexercised-row-filter` never fired on a typed registration.** The match was `/\bsetRowFilter\s*\(/`, which demands the paren directly after the name, so `setRowFilter<Ctx>({…})` — the spelling our own generic signature invites — broke it. The rule was blind for exactly the teams that had wired `load`/`predicate` carefully. It counts CALLS now. - **…and its test-side condition was satisfiable by a COMMENT.** It matched `rowFilter:` in raw text. Comments and string literals are stripped, and the suite must both call `makeTestContext` and bind `rowFilter` in real code. - **The same paren-adjacent shape sat in two shipped codemod gates.** `0.7.0/01` (row filter) and `0.7.0/02` (`invoke`) both gate on a generic export, so a typed call made `voltro update` print nothing at all: the upgrade reads as clean and the behaviour change lands unread. Both now use the shared `callPattern`, which allows type arguments including nested ones.
|
|
77
|
+
|
|
78
|
+
Two false-positive fixes in the hand-roll detector, from the same report:
|
|
79
|
+
|
|
80
|
+
- **A file that WIRES a plugin is no longer told to adopt it.** The `presence` rule reported `app.config.ts` (which calls `presencePlugin()`) to an app that had just deleted its hand-rolled table. Rules that recommend a package now declare it, and a file referencing that package is skipped. - **Generated files and `.d.ts` are out of the scan.** A recommendation aimed at a file the next boot overwrites is never actionable.
|
|
81
|
+
|
|
82
|
+
And one more of the first kind, found while checking why a withdrawn report's probe had stayed silent: `raw-fetch` counted only a BARE `fetch(…)` callee, so `globalThis.fetch(url)` / `self.fetch(url)` in a server file read as clean.
|
|
83
|
+
- **@voltro/cli** — `voltro doctor`'s `serverOnly: NOT CHECKED` line now names the failure, and the field exists in `--json`.
|
|
84
|
+
|
|
85
|
+
The refusal to claim a pass was right. What shipped with it was nothing to act on: the `catch` discarded the error entirely, so there was no reason, no failing module, and — because the field was absent from `--json` — no way for CI to assert "still unchecked" rather than reading silence as a pass.
|
|
86
|
+
|
|
87
|
+
A consumer's verdict, which is the useful part: *"The message is honest and that is the problem."* They had already verified that every descriptor, `app.config.ts` and the generated rpc group imported cleanly under `tsx` on their own, so the difference had to be in what `loadDiscovered` does BEYOND importing — and none of that was visible from outside. It matters more than its size because `.serverOnly()` is what guards their `sessions.tokenHash` and `apiKeys.keyHash`, markers they added after finding a query whose output schema shipped a hash over the wire.
|
|
88
|
+
|
|
89
|
+
`--json` now carries `serverOnly: { checked, reason?, leaks? }`. Gate CI on `checked === false`.
|
|
90
|
+
- **@voltro/plugin-versioning** — A version snapshot no longer copies `.serverOnly()` columns into `_voltro_row_history`. `.encrypted()` columns are KEPT, and that distinction is the whole finding.
|
|
91
|
+
|
|
92
|
+
Reported by a team choosing which tables to version: `sessions` holds `.encrypted()` PATs and a `tokenHash`, `apiKeys` holds a `keyHash`, and they could not determine from outside what the snapshot would contain. They excluded both tables — then went and measured it, which corrected their own report:
|
|
93
|
+
|
|
94
|
+
```
|
|
95
|
+
probeItems.secret enc:v1:a56iziEV9THLhzmJ:Vk0ux+0bECleTLBJkCa0Rg==:3AtMwP…
|
|
96
|
+
_voltro_row_history {"secret":"enc:v1:a56iziEV9THLhzmJ:Vk0ux+0bECleTLBJkCa0Rg==:…"}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
**`.encrypted()` lands as ciphertext, byte-identical to the source column**, so versioning such a table widens nothing — the history is exactly as readable as the row it came from. Withholding it would have cost real audit data to prevent an exposure that does not exist.
|
|
100
|
+
|
|
101
|
+
**`.serverOnly()` is withheld**, and the reason is not "a second copy under different retention" — that argument is weak on its own, since the hash already sits in the source table. The decisive one: `crud.*` STRIPS `.serverOnly()` columns from every row it returns, and a snapshot would smuggle the same value back past that stripping inside a `json()` blob, where no column-level rule applies.
|
|
102
|
+
|
|
103
|
+
Withheld names are listed under `data._omitted`, so a reader can tell "this column was withheld" from "this column did not exist then". Both timings apply the same policy. `.sensitive()` is not involved: it is an export-masking marker for values that are legitimately readable in the app.
|
|
104
|
+
- **@voltro/cli** — A page that RE-EXPORTS its component (`export { default, renderMode } from '../page'`) no longer fails the codegen gate with "exports no default". The check required the literal words `as default`, so the one spelling that lets two routes share a screen without copying it was the one spelling it refused — and it refused in `voltro build`, while dev and tests stayed green because nothing prerenders there. `export { default as Screen }` is still correctly rejected: it renames the default away.
|
|
105
|
+
|
|
106
|
+
Two follow-ons from the same shape:
|
|
107
|
+
|
|
108
|
+
- The refusal message said the file "ends in `.page.tsx`" and offered "drop the `.page` suffix" as a fix. That is the 0.15.0 convention, replaced by directory routing in 0.17.0 — it named a convention that no longer exists and a fix that could not work. It now names `page.tsx` and both real fixes. - `scanRenderProfile` read a forwarded `renderMode` as absent and fell back to `'static'`, so `staticSafe` and the deploy-target classification could call an app CDN-deployable with an `ssr` route in it. The forward is now followed (relative specifiers, depth-capped); an unresolvable one still falls back rather than failing the scan.
|
|
109
|
+
- **@voltro/database** — `VOLTRO_SOFT_DROP=1` could never converge. The applier renames the object to `<name>__dropped_<ts>` instead of dropping it, which leaves it undeclared — and the differ read that as one more forgotten table, planning the drop again. The re-plan inside `applyPlan` then found an operation still outstanding and aborted with "the DDL for these operations is a no-op — this is a framework bug", which was a wrong diagnosis of a real defect: the DDL had worked. No fingerprint was recorded, so the migration counted as unapplied and every later `db apply` / boot hit the same wall. The only exit was a hard drop of the snapshot — exactly the recoverability the flag is chosen for.
|
|
110
|
+
|
|
111
|
+
The planner now treats `<name>__dropped_<YYYYMMDDHHMMSS>` as framework-managed, alongside `_voltro_*` / `cluster_*`. Deliberately not retention-aware: a planner whose output depends on the clock would produce different plans before and after midnight, and `db gc-snapshots` already owns expiry.
|
|
112
|
+
|
|
113
|
+
Reported against tables; the same defect existed one level down for soft-dropped COLUMNS, where it was worse — a re-planned `drop-column` carries no `dropped()` marker and so refuses to plan at all. Both are fixed.
|
|
114
|
+
|
|
115
|
+
The convergence message itself no longer asserts a cause it cannot know. It said "the DDL for these operations is a no-op", which was flatly wrong here and sent the reporter looking for dead DDL. It now names both causes — no-op DDL, and a planner that cannot see what the DDL did — and says which one an operation naming a just-renamed object usually is.
|
|
116
|
+
|
|
117
|
+
### Internal (no consumer-facing effect)
|
|
118
|
+
|
|
119
|
+
- **The `0.20.0/01_write-recorder-port` codemod gains the gate test its two predecessors have.**
|
|
120
|
+
|
|
121
|
+
`codemodRegistry.test.ts` asserts that every `*.codemod.ts` on disk is registered and that ids are unique — registration, not behaviour. What it cannot see is the one way a `manual` codemod fails in practice: an `appliesTo` that is too broad, so the note prints for projects that have nothing to do. That is not a cosmetic problem. A note which fires on every app is how readers learn to skip notes, and the next one carries a boot refusal.
|
|
122
|
+
|
|
123
|
+
This codemod is the case where the silent direction matters most. The break is a TYPE error, so `tsc` already names every affected site; the note exists only to explain `maxOf`, which the compiler cannot. Apps that merely ENABLE `timing: 'in-transaction'` need to do nothing — `plugin-versioning` ships the recorder and it is already updated — and they are the large majority.
|
|
124
|
+
|
|
125
|
+
Four cases, covering both directions: a project registering its own recorder (note prints, and names `{ append }`, `maxOf`, and the `null`-is-not-zero distinction that a hand-written sequence gets wrong), an app that only enables the timing (silent), the identifier in a comment or a string (silent), and the generic call form `registerWriteRecorder<Row>(…)`, which `callPattern` admits and a naive match would miss.
|
|
126
|
+
|
|
127
|
+
---
|
|
128
|
+
|
|
129
|
+
## [0.19.0] — 2026-07-29
|
|
130
|
+
|
|
131
|
+
### ⚠ BREAKING
|
|
132
|
+
|
|
133
|
+
- **@voltro/plugin-audit** — **The durable audit sink stops writing credentials to a log table by default.** `redactInput` defaults to `'all'` — the payload becomes `{ __redacted: 'all' }`, which still proves a payload existed. `redactInput: 'none'` restores the previous behaviour, and a function gives field-level control.
|
|
134
|
+
|
|
135
|
+
`AuditEvent.input` is the raw mutation input, so an unredacted trail is where a password change, an API key at issuance and a PAT land — the one place nobody thinks to look for a credential. Losing payload detail is visible the first time you read a row; leaking a credential is not visible at all, which is why the default moved rather than staying opt-in.
|
|
136
|
+
|
|
137
|
+
**It is deliberately NOT driven by `.serverOnly()` / `.sensitive()`,** which is the design a consumer proposed and the one that cannot work: those markers live on TABLE COLUMNS and this is a mutation's INPUT. `changePassword({ oldPassword, newPassword })` has no column to consult, so a marker-driven default would cover exactly 0% of the motivating case while reading, to whoever configured it, like protection. (`.sensitive()` is also the export axis, not "unsafe to log" — the category error the three-marker table exists to prevent.)
|
|
138
|
+
|
|
139
|
+
Also:
|
|
140
|
+
|
|
141
|
+
- **`record: 'all' | 'errors' | predicate`** — filters by OUTCOME, where `include`/`exclude` filter by tag. `'errors'` is the forensic core and pairs with `plugin-versioning` for the successful writes. **`'all'` stays the default** on purpose: defaulting to errors would silently stop recording successes on upgrade, and "what did this compromised account touch" is answered by successes. - **`errorTag`** — the typed error's `_tag`, flattened out of the `outcome` json and indexable. `null` for an untagged failure rather than a guess: "this had no tag" and "the tag is 'Error'" are different, and a column that invents the second makes every filter on it quietly wrong. - **Two indices for the questions asked under pressure** — `(subjectId, status, at)` and `(tenantId, status, at)`. "Every denied call by subject X in the last 30 days" and "every failure against tenant Y" were both unindexed; the existing `byAuditTag` / `byAuditTrace` cannot serve either. - **Retention registers itself** — 365 days, `VOLTRO_AUDIT_LOG_TTL_HOURS`, drained by the boot sweep. "Pair it with the governance sweep" was a docs sentence rather than a default, so nobody did. - **Erasure is deliberately NOT auto-registered.** Erasing a subject must not delete the record that they were refused four hundred times — that record *is* the evidence. Anonymise instead; the docs carry the `subjectScopes` entry to paste, and it stays a decision the app makes explicitly.
|
|
142
|
+
|
|
143
|
+
**Migration** — `voltro update` prints it (`0.19.0/02_audit-redact-input-default`, `manual`, and it fires only for apps that mount the plugin). Nothing stops compiling and existing rows are untouched; what changes is what the NEXT row records. Keep the new default unless you know your mutation inputs carry no secrets; pass a function for field-level control; or opt back in explicitly with `redactInput: 'none'`. The codemod deliberately does NOT write `'none'` into your config — a transform could do it perfectly, which is exactly why it must not: it would pin every adopter to the behaviour the default moved away from and report the migration as complete.
|
|
144
|
+
|
|
145
|
+
*Why this is `BREAKING` and not `Changed`: it is a silent behaviour change on upgrade. Nothing fails, which is the problem — an operator who never reads this section keeps a trail that has quietly lost its payload detail. `BREAKING` is what routes it into `voltro update`.*
|
|
146
|
+
- **@voltro/cli, @voltro/database** — **`.serverOnly()` now gates where it said it did.** A wire-reachable query that declares a `.serverOnly()` column of its source table in its `output` fails the boot under `voltro serve`, and makes `voltro doctor` exit non-zero. `voltro dev` still warns.
|
|
147
|
+
|
|
148
|
+
It shipped as one `log.warn` and nothing else — in every command — while `ColumnBuilder.serverOnly()`'s own doc comment and the seeded `AGENTS.md` marker table both said "**the boot audit — it FAILS the boot**, it does not warn". A team read the strong sentence, adopted the marker on four credential columns, injected a deliberate leak to check, and watched the server come up serving the leaking query. That is the register this repo keeps meeting from a new angle: *a check that prints instead of gating still reads as coverage* — here on the one marker whose entire job is the enforcement.
|
|
149
|
+
|
|
150
|
+
Two smaller things went with it, both of which had misled the reporter:
|
|
151
|
+
|
|
152
|
+
- **The message names the command.** It was emitted through a module-level logger scoped `voltro:dev`, so a warning from `voltro serve` announced itself as dev — which is why they concluded, and reported, that the audit does not run in production at all. It did; it just misattributed itself and stopped nothing. - **The audit is computed once, in `loadDiscovered`**, the discovery dev / serve / doctor / check all share — the same reasoning `validateRegisteredRelations()` lives there for. Dev and serve may disagree about what a leak COSTS; they must not disagree about what a leak IS.
|
|
153
|
+
|
|
154
|
+
`VOLTRO_SERVER_ONLY` moves the line both ways: `strict` fails `voltro dev` too, `warn` downgrades serve, `off` silences it. The downgrades are documented rather than hidden, because the alternative to a stated escape hatch is deleting the marker, and a check whose only way out is to disable it gets disabled.
|
|
155
|
+
|
|
156
|
+
`voltro check` deliberately does NOT run it: it has a live-api mode with no access to your table definitions, and a rule that fires in one of its two modes is worse than one that fires in neither.
|
|
157
|
+
|
|
158
|
+
**Migration** — `voltro update` prints it (`0.19.0/01_server-only-gates-the-boot`, `manual`, and it fires only for apps that actually use the marker). Run `voltro doctor` BEFORE you deploy: it reports exactly what `voltro serve` will now refuse, with no deploy involved. Each finding has two honest fixes and only its author can choose — the column is not wire-safe (drop it from the query's `output`, keep the marker), or the marker is wrong (drop the `.serverOnly()`). Do not substitute `.encrypted()`: that is the at-rest axis, the runtime decrypts for the handler, and reading it as "safe to expose" is the category error the three-marker table exists to prevent. To ship while triaging, `VOLTRO_SERVER_ONLY=warn` downgrades serve back to a warning — a bridge, not a setting to keep.
|
|
159
|
+
|
|
160
|
+
*Why this is `BREAKING` and not `Changed`: no signature moves and nothing that compiled stops compiling, so the literal type-level test does not catch it. It can still turn a booting production app into one that refuses — which is the point, the boot it refuses is the one shipping the column — and that failure lands at DEPLOY time. Filing it as `Changed` would have kept it out of the one section the stability contract names as the migration path, and out of `voltro update` entirely, because codemods hang off `BREAKING`. Both doc claims were corrected in the same change, so the `.d.ts`, the agent template and the docs site now describe the same behaviour.*
|
|
161
|
+
|
|
162
|
+
### Added
|
|
163
|
+
|
|
164
|
+
- **@voltro/plugin-audit** — **`auditByTrace` / `auditBySubject` — the read side of the correlation join.**
|
|
165
|
+
|
|
166
|
+
`byAuditTrace` and `byAuditSubjectStatus` shipped in the same release with **no caller**. That is the identical defect the versioning side had and that its own entry points were added to fix, repeated on the other half of the join one file away: an index nobody can enter is a query the app still hand-writes, and the docs then demonstrate a raw select over a framework-internal table.
|
|
167
|
+
|
|
168
|
+
It surfaced by checking an adopting team's design document against the code rather than from memory. Their §6 asks for *"a read-side composition joining `_voltro_row_history` × the audit sink (on `traceId`) × `actors`"* — which needs BOTH halves to have an entry point, or neither is usable.
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
const calls = await auditByTrace(ctx.store, traceId) // who called, and was it refused
|
|
172
|
+
const changed = await historyByTrace(ctx.store, traceId, tenantId) // what it changed
|
|
173
|
+
const denied = await auditBySubject(ctx.store, actorId, { status: 'error' })
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
`auditBySubject` takes `status` as a real argument rather than leaving the caller to filter in JS — the index is `(subjectId, status, at)`, so a filter applied after fetching would not use it. `limit` defaults to 100, because an actor's history is unbounded and an entry point that returns all of it is one you call once in production.
|
|
177
|
+
|
|
178
|
+
*They were also not exported from the package index when first written — built, tested, and unreachable. Caught before shipping; worth recording because "it has a test" and "a consumer can call it" are different claims.*
|
|
179
|
+
- **@voltro/database, @voltro/runtime, @voltro/protocol, @voltro/cli, @voltro/plugin-versioning, @voltro/plugin-audit, @voltro/voltro** — **`ChangeEvent` carries the calling `traceId` and `subjectId`** — the join key that lets `plugin-versioning` (what changed) and `auditPlugin` (who called, and whether they were refused) be read as one trail.
|
|
180
|
+
|
|
181
|
+
Both halves shipped and neither could be joined to the other. A consumer put it exactly right: *"we are not asking you to build our audit feature. We are asking for the join key that lets anyone build one on the three pieces you have already shipped."*
|
|
182
|
+
|
|
183
|
+
**The mechanism, and the part that was an empirical question rather than a design one.** Identity is known one layer up (`subject` in the middleware, `traceId` at the rpc boundary) and the event is created several layers down, inside each dialect store's private emit. Threading a context argument through every `DataStore` method to reach it would change the port every driver implements, for metadata that is ambient by nature — so it rides an `AsyncLocalStorage` (`@voltro/database`'s `writeAttribution.ts`), the same shape as the existing trace and replica-routing contexts.
|
|
184
|
+
|
|
185
|
+
Whether that survives a SQL store was *not* obvious: the write goes through `ManagedRuntime.runPromise`, so the read happens inside an Effect fiber, and a scheduler draining fibers from a shared loop would run them under the async context of whoever created the drain. If that were true the attribution would be silently ABSENT — a join key that is simply never there, on a trail nobody checks until an incident. Verified against a real sqlite store, including the transactional path (which queues events and flushes them post-commit, *outside* the scope — which is why the stamp goes at event CREATION, not delivery).
|
|
186
|
+
|
|
187
|
+
- **One call site, not one per method.** The scope is established at the rpc executor boundary, so it covers every write the handler makes — `ctx.store`, `EffectStore`, the crud helpers, a plugin interceptor's own writes. Wrapping the store middleware instead would have meant wrapping each mutating method and hoping the next one added remembers. - **`subjectId` is the same identity `audit()` stamps** (`actingUserId`, now exported so there is one source). Two answers to "who wrote this row" on one write would be worse than one; which API *key* was used is recoverable from the audit row sharing the `traceId`. - **Absent is a fact, not a gap** — no request behind the write (seed, startup hook, schedule, workflow step), or an event from another replica, where stamping the local ambient trace would attribute a remote write to a local call. The keys are omitted rather than set to `undefined`, so an unattributed event is byte-identical to one from before this existed. - **`dev.ts` and `serveCommand.ts` no longer hand-mirror the plugin fan-out.** They built that object literal separately in two files; a field added to one and not the other gives a plugin the data in dev and silence in production, and both files typecheck alone. Now `toPluginChangeEvent`.
|
|
188
|
+
|
|
189
|
+
`_voltro_row_history` gains `traceId` / `subjectId` plus `byTrace` and `bySubject` indices — "what did this call touch" and "what did this actor touch" were previously unanswerable at any speed, since `byRow` requires already knowing which row you are asking about. `changedBy` now prefers the caller over the row's `audit()` stamp, which fixes a reported case for free: the stamp is `null` for every write through the boot store, so a login route produced version rows with no actor at all.
|
|
190
|
+
|
|
191
|
+
*`apiSurface: compatible`: every golden line this touches is either a pure addition (the new fields and `actingUserId`) or api-extractor renumbering an import alias — `Subject_2` became `Subject` across `runtime` and the `voltro` re-export because a new import changed the ordering. No declaration changed shape and no call site is affected.*
|
|
192
|
+
- **@voltro/cli** — **`voltro doctor`'s hand-roll detector gains six rules and ranks its findings by file count.**
|
|
193
|
+
|
|
194
|
+
An adopting team audited four apps by hand against the framework's "reach for instead" table and produced twenty items, each with a count (`1631` files with a manual `rows[0]`, `500` queries with `input.offset`, `306` forms, `368` relations declared against `17` uses). **The detector already reported eleven of those twenty, with counts.** These are rules for what it missed — the findings that made a person do work a scan should have done:
|
|
195
|
+
|
|
196
|
+
- **`offset-pagination`** — `.offset(` / `input.offset` / `.skip(` on a list query. `hand-cursor` did not catch this: it wants `hasMore` AND `limit+1`, which is a hand-rolled *keyset* pager. Plain OFFSET is a different smell with a worse ending — O(n) in the page number, so it does not fail, it just stops loading once the table is big, on the tables (audit logs, time entries) that get big first. - **`oauth-token-table`** — an `accessToken`/`refreshToken` column on an app table → `defineConnection({ kind: 'oauth2' })`. The reporting team's version of this leaked: a `json()` column holding a Slack payload with the token inside, readable by every colleague in the tenant. - **`non-incremental-aggregate`** — a `count/sum/avg/min/max` aggregate with no `incremental:`, rescanned in full on every refresh. - **`external-state-library`** — jotai / zustand / mobx / redux → `defineStore`. A second runtime beside the reactive engine, and one that does not participate in the subscription graph. - **`hand-route-module`** — importing a hand-maintained `routes` / `urls` module instead of `.framework/routes.generated`, where a renamed page is a compile error rather than a 404 someone finds in production. - **`hand-permission-check`** — a component reading a permission bag by hand instead of `useCan` / `useResourceCan`.
|
|
197
|
+
|
|
198
|
+
**And the findings are now ordered by file count rather than by the order the rules happen to be declared in.** A reader facing twenty findings acts on the top of the list, so an arbitrary order silently decides what gets fixed. The reporting team ranked their own work by exactly that number and had to count it by hand, because this printed the same facts unranked. Effort we cannot know; magnitude we can.
|
|
199
|
+
|
|
200
|
+
*Two of these rules were caught being wrong by their own tests before shipping: `offset-pagination`'s first version checked only `input.offset` and did not match its own fixture (a narrow rule reports nothing and reads like a clean codebase), and the ranking test passed with the sort deleted until the fixture was rebuilt so declaration order and count order disagree.*
|
|
201
|
+
- **@voltro/plugin-versioning** — **`historyByTrace` / `historyBySubject` — the entry points the new indices existed for.** Plus their Effect twins.
|
|
202
|
+
|
|
203
|
+
The correlation bridge added `byTrace` and `bySubject` to `_voltro_row_history` in the same release, and shipped them with no caller: `rowHistory` requires a `rowId` you already have, which is the wrong way round during an incident, when what you have is a trace or an actor. The docs demonstrated a raw `ctx.store.select('_voltro_row_history')`, which is the shape an index is supposed to save you from writing.
|
|
204
|
+
|
|
205
|
+
Both are tenant-scoped exactly like `rowHistory` (own-tenant rows plus null-tenant rows from untenanted source tables; `undefined` skips the filter, for system paths only). `historyBySubject` takes a `limit`, default 100, because an actor's history is unbounded and an entry point that returns all of it is one you call once in production and never again.
|
|
206
|
+
|
|
207
|
+
**And a bug this surfaced.** The stored-row → `VersionRow` decoder was written inline inside `versionsOf`, before the bridge existed, and silently dropped `traceId` / `subjectId` — so `rowHistory()` returned rows missing the very field the feature exists to carry. Extracted to one `rowToVersion` now shared by all three readers, which is why the drift was possible in the first place.
|
|
208
|
+
- **@voltro/cli, @voltro/database** — **`setRowFilter` is now named in the always-loaded agent core**, with the distinction that makes it findable.
|
|
209
|
+
|
|
210
|
+
A team migrating eleven hand-written row filters reported missing it **twice** — once in a full framework audit, and once while telling a colleague in writing that the framework has no row-filter primitive. The depth doc covers it well; a depth doc is opened by someone who already suspects the topic. The core's SERVER rubric asked *"a permission check?"* and answered with two BOOLEAN questions, so a reader holding a row-VISIBILITY question took the nearest-fitting answer and wrote the filter by hand. Eleven times.
|
|
211
|
+
|
|
212
|
+
The rubric now asks it directly, and the pairing is the point:
|
|
213
|
+
|
|
214
|
+
> `guards:` → *may I call this procedure?* → a typed `ScopeError`. > `setRowFilter` → *which rows may I see?* → the rows are simply absent.
|
|
215
|
+
|
|
216
|
+
Plus the failure it deletes — a `WHERE ownerId = me` in the list handler covers the query and **not** the subscription — and the trap they lost time to: `load` must read through an UNFILTERED store, because applying the filter to its own loader recurses until the stack blows.
|
|
217
|
+
|
|
218
|
+
Also:
|
|
219
|
+
|
|
220
|
+
- **`voltro doctor` gains `unexercised-row-filter`.** Their 7466 tests stayed green when the filter landed because not one passed `rowFilter:` to `makeTestContext`; they only noticed because they sabotage their own predicates before believing a pass, and four sabotages ran green. `makeTestContext({ rowFilter })` being opt-in is right — a process-global in a parallel suite would be worse — but the consequence is a visibility rule nothing verifies. Same class as a suite reporting `passed` with no database. - **`MATCHES_NO_ROWS` is exported from `@voltro/database`.** They wrote `eq('id', '')` for "this caller sees nothing", because the natural spelling `inSet(col, [])` is the one that is dangerous in most query builders: an empty `IN ()` gets dropped, and a dropped predicate does not narrow, it WIDENS to the whole tenant. Here it is safe — the SQL compiler emits `FALSE`, the memory evaluator returns false — but that held by accident, with no test enforcing it. Now pinned in both evaluators, including the mirror case: an empty `notIn` matches EVERYTHING.
|
|
221
|
+
|
|
222
|
+
*The doctor rule was itself wrong when first written: it read the normal source set, which excludes test files, so it could never observe the passing case and would have fired unconditionally on every app. Caught by writing the negative test.*
|
|
223
|
+
- **@voltro/database, @voltro/plugin-versioning, @voltro/sql-postgres, @voltro/sql-mysql, @voltro/sql-mssql, @voltro/sql-sqlite** — **`versioningPlugin({ timing: 'in-transaction' })` — the history row commits or rolls back WITH the change it records.** Default stays `'post-commit'`.
|
|
224
|
+
|
|
225
|
+
Post-commit recording is lossy by construction: between COMMIT and the forked history write there is a window, and a process that dies inside it leaves the change permanent and the trail silent. The size of the window is not the point — the direction is. A missing entry cannot be told apart from "nothing happened", so a trail that can lose entries proves nothing. Retry does not close it either; the process that would retry is the one that died.
|
|
226
|
+
|
|
227
|
+
This was the sole reason an adopting team could not replace their hand-rolled audit writer — called from **315 of 358 mutation handlers**, with the 43 misses being what happens to any rule that depends on someone remembering.
|
|
228
|
+
|
|
229
|
+
**What a recorder receives is an `append`, not a store.** Bound to the caller's transaction, insert-only. It cannot open a nested transaction (which throws by design), cannot read-modify-write its way into a deadlock, and "append-only" stops being a docs claim and becomes the shape of the only thing it is handed.
|
|
230
|
+
|
|
231
|
+
**The rejection is the guarantee, not a defect.** When the history insert fails, a transaction offers exactly two outcomes: the mutation fails with it, or the error is swallowed and the change commits without its entry — which is post-commit's hole with the cost already paid. There is no third option, so recorders do not swallow.
|
|
232
|
+
|
|
233
|
+
**Why the default did not move.** In-transaction makes the history table a hard dependency of every covered write path: its availability becomes your write path's availability, and every covered write holds locks longer. Post-commit loses at worst one entry; in-transaction can at worst stop writes to the covered tables. Right trade for a compliance trail, wrong one for the undo / time-travel use this plugin also serves.
|
|
234
|
+
|
|
235
|
+
**It refuses the in-memory store at boot** rather than silently no-op'ing. `memory` is the default dev store; an option that appears to work where it is cheapest to try and stops where it matters is worse than one that says so. Two limits hold in both timings and are documented: `store.raw()` produces no change event and is absent from the trail, and a write made outside a transaction is recorded immediately after rather than atomically.
|
|
236
|
+
|
|
237
|
+
*Two design claims in the plan for this were wrong and are corrected there. "Twelve write sites across three layers, no funnel" was true of `storeMiddleware` and irrelevant — each dialect store funnels every write through one private `routeEvent`, which is where this hooks. "Bulk writes have no per-row post-image" was simply false: `updateMany` already issues `RETURNING *` and emits one event per affected row, so bulk needed no special case at all. Both were found by looking in the middleware instead of the store — twice.*
|
|
238
|
+
|
|
239
|
+
### Fixed
|
|
240
|
+
|
|
241
|
+
- **@voltro/cli** — **A `voltro serve` that refuses to boot says why, instead of blaming the serve bundle.** A deliberate refusal — a missing `VOLTRO_SESSION_SECRET`, a `.serverOnly()` leak — came out of the launcher as:
|
|
242
|
+
|
|
243
|
+
```
|
|
244
|
+
[voltro] serve bundle failed to load: VOLTRO_SESSION_SECRET is not set — refusing to serve. …
|
|
245
|
+
[voltro] FATAL: production `voltro serve` requires a precompiled serve bundle at …
|
|
246
|
+
but it is missing or failed to load. Run `voltro build` before serving …
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
The real reason is on the first line, under a wrong headline, followed by a louder and more confident wrong instruction. An operator whose first deploy forgot the session secret is told to rebuild an artefact that is fine — and rebuilding it produces the identical output, so the loop has no exit.
|
|
250
|
+
|
|
251
|
+
The cause is a catch that has to exist: `bin/voltro.mjs` imports the precompiled serve bundle inside a `try`, because an unusable bundle must degrade to the tsx path rather than kill the boot. It could not tell "this artefact is broken" from "this app decided not to start". Refusals now carry a marker (`bootRefusal.ts`) and the launcher prints them and exits 1.
|
|
252
|
+
|
|
253
|
+
The marker is the error's `name`, a plain string, rather than a class: the serve bundle INLINES the framework, so the thrown Error crosses an instance boundary where `instanceof` does not survive — the same reason the core-table registry is keyed by `Symbol.for`.
|
|
254
|
+
|
|
255
|
+
Found by running the new `.serverOnly()` gate against a real fixture rather than by reading it, which is also how the misleading pair came into view: the session-secret case had been shipping that way for a while.
|
|
256
|
+
- **@voltro/sql-postgres, @voltro/sql-mysql** — **`insertIgnore` explains a second-unique conflict instead of reporting an internal invariant.** The message was `row conflicted but lookup found nothing`, which tells a caller nothing they can act on.
|
|
257
|
+
|
|
258
|
+
It is reachable by ordinary means, and on mariadb it is the *common* path: `INSERT IGNORE` swallows ANY unique violation, so a row with a fresh `id` and a duplicate `slug` is skipped, and the lookup by the named `conflictColumns` then finds nothing. A team with `tenants (id PK, slug UNIQUE)` hits it on the first duplicate slug.
|
|
259
|
+
|
|
260
|
+
The message now names the columns that were checked, the table, and the actual cause — a different unique constraint fired, and `insertIgnore` models one conflict target. This is step 1 of `plans/framework-insertignore-any-unique.md` and is deliberately independent of the feature: whether or not `conflictColumns: 'any'` ever ships, this error should have been readable.
|
|
261
|
+
- **@voltro/cli** — **`ui/unlinked` and `ui/orphaned` resolve through barrel re-exports.** A `*.component.ui.tsx` reached only via `export { X } from './x'` was reported as unrendered, however many pages actually rendered it.
|
|
262
|
+
|
|
263
|
+
On the app that reported it, `PageContent` is imported by 42 pages — every one of them through `@/components/shared` — and doctor said `imported only by: index.ts, its own test`. It was the last false positive standing after the alias fix took that app from 16 findings to 2.
|
|
264
|
+
|
|
265
|
+
The rules ask "does anything RENDER this". A barrel is a real importer and renders nothing, so stopping at the first importer answers a different question than the one asked — but only in an app that has an `index.ts`, which is why it survived.
|
|
266
|
+
|
|
267
|
+
The walk is narrowed by NAME rather than opened up wholesale: a downstream file counts only if it imports one of the names the barrel republishes from that file (aliases followed, `export *` expanded to the file's own exports, type-only re-exports ignored — they publish nothing at runtime). Without that narrowing, `export *` on a 40-entry barrel would credit its entire readership to every entry and `ui/orphaned` would quietly stop finding anything — trading a visible false positive for a silent false negative. There is a test for exactly that direction: a barrel with a used entry and a dead one must still report the dead one.
|
|
268
|
+
|
|
269
|
+
### Internal (no consumer-facing effect)
|
|
270
|
+
|
|
271
|
+
- **@voltro/protocol** — **`PluginHttpRouteRequest.store` names all four absences instead of one.** The docstring said "It is not tenant-scoped" and left soft-delete filtering, audit stamping and row-level security to be inferred from "everything that does not need a Subject".
|
|
272
|
+
|
|
273
|
+
A team planning to port 19 raw-SQL sites onto that seam inferred the opposite: they wrote down "a store read adds `deletedAt IS NULL`" as the trap with teeth on their list — a soft-deleted user logging back in would go from "found and revived" to "not found → insert → unique violation on email" — and deferred the whole port partly over it. The store does no such thing; it is the raw store plus the storage codec. Naming exactly one of four absences reads as an exhaustive list.
|
|
274
|
+
|
|
275
|
+
The docstring now carries the same table the `AuthStrategyInput.store` docs do, with the soft-delete row called out for anyone porting: a read here returns tombstones the way their SQL did, so a lookup that must see one needs no opt-out. (`.withDeleted()` is the opt-out on `ctx.store`, which *does* apply the filter.) Doc-only; the behaviour is unchanged and was already correct.
|
|
276
|
+
- **`ci.yml` gains a `workflow_dispatch` trigger.** The full matrix — 11 database services plus the SQL Server AG init containers — is not reachable from a push to `main`: `paths-ignore` plus the job-level `if: github.event_name != 'push'` mean a main push runs static checks only.
|
|
277
|
+
|
|
278
|
+
So the only ways to exercise it were a pull request and the release gate, which meant a change to the workflow itself could sit unrun until it fired for the first time INSIDE a release — where a failure costs a ~40-minute round-trip and blocks the publish. That is precisely the position this repo was in.
|
|
279
|
+
|
|
280
|
+
---
|
|
281
|
+
|
|
42
282
|
## [0.18.0] — 2026-07-28
|
|
43
283
|
|
|
44
284
|
### ⚠ BREAKING
|
|
@@ -116,6 +356,8 @@ _Changes staged for the next release accumulate here (rolled up from
|
|
|
116
356
|
The consequence was a silent wrong answer rather than an error. An auth strategy reading an `.encrypted()` column got the literal string `enc:v1:…` back — which compares, concatenates, renders and logs perfectly well, and simply never matches the token it is compared to. The failure surfaces as "wrong credential". On the write side it was worse and unrecoverable: an insert through that store wrote PLAINTEXT into a column the schema declares encrypted.
|
|
117
357
|
|
|
118
358
|
The line is now **everything that does not need a Subject**, not "less than `ctx.store`". Wired in `voltro dev` and `voltro serve` in the same change (`wrapStoreWithBootCodec`); `raw()` is deliberately left as a pass-through, since it is the documented escape hatch for hand-written SQL and re-encoding rows a caller asked for verbatim would be its own surprise.
|
|
359
|
+
|
|
360
|
+
**Upgrading: a reader that compensated for the missing codec by hand now gets the decoded value.** Two shapes, and they land differently. A hand-rolled `decryptField` on the way out is HARMLESS — it passes a non-`enc:v1:` value through unchanged, so the call simply stops doing anything. A hand-rolled `JSON.parse(row.someJsonColumn)` on a column the codec now deserialises is NOT: it is handed an object and throws. If you read an `.encrypted()` or array column through `AuthStrategyInput.store` / `PluginHttpRouteRequest.store` and unpacked it yourself, grep those call sites — the ones typed as a `string | ReadonlyArray<string>` union already survive, a bare `JSON.parse` does not. (Reported by an adopter whose two such reads happened to be written defensively, which is why their upgrade was silent.)
|
|
119
361
|
- **@voltro/cli** — **The remaining file-moving codemods narrow their projects too**, and the shared project is no longer a stale snapshot.
|
|
120
362
|
|
|
121
363
|
`0.14.0/03_pages-suffix` is gated on `/src/pages/` throughout — plus each app's `app.config.ts`, which is how it tells a real web app's pages from a library that merely keeps components under `src/pages/`. `0.15.0/01_undo-mistaken-taxonomy-renames` only ever renames `*.component[.ui].ts(x)` and an export-less `*.types.ts(x)`. Both now declare that scope and take the importer closure instead of the workspace.
|
|
@@ -169,15 +411,15 @@ _Changes staged for the next release accumulate here (rolled up from
|
|
|
169
411
|
The catalogue said a `*.component.tsx` promises "exactly one component **(+ types)**", which reads as "types are the only exception". It never was — the rule counts components, and a `const COLUMNS = […]` beside the table that renders it was always allowed. The docs now say so in both languages.
|
|
170
412
|
- **@voltro/cli** — **The seeded `AGENTS.md` / `CLAUDE.md` never mentioned `.serverOnly()` — the one marker that decides leak vs no leak.**
|
|
171
413
|
|
|
172
|
-
Reported from a strict-mode pass over five apps: the template documents `.encrypted()`, `audit()`, `tenant()`, `softDelete()`, `.check()`, `validate()` — and not the marker
|
|
414
|
+
Reported from a strict-mode pass over five apps: the template documents `.encrypted()`, `audit()`, `tenant()`, `softDelete()`, `.check()`, `validate()` — and not the marker that decides leak vs no leak. *(Corrected after publication: this entry said the boot audit "hard-fails" on it. It did not — it was a single `log.warn`, in every command. The next release makes the claim true; see that entry.)* Depth existed (`database/sensitivity`, `data/crud`, both languages); the always-loaded core simply never pointed at it, so an agent or a human following the template never learned the marker exists.
|
|
173
415
|
|
|
174
416
|
The core now carries a short section on the three markers as ORTHOGONAL questions, because the substitution is the real hazard:
|
|
175
417
|
|
|
176
|
-
| Marker | Answers | Enforced by | |---|---|---| | `.serverOnly()` | may this leave the server at all? |
|
|
418
|
+
| Marker | Answers | Enforced by | |---|---|---| | `.serverOnly()` | may this leave the server at all? | an audit — see the correction above | | `.sensitive()` / `.safe()` | may it appear in an export? | the masking profile, fail-closed | | `.encrypted()` | is it encrypted at rest? | the store's codec |
|
|
177
419
|
|
|
178
420
|
Reading `.encrypted()` as "safe to expose" is a category error and a plausible one — the runtime decrypts for the handler, so an encrypted column reaches a client like any other unless it is ALSO `.serverOnly()`.
|
|
179
421
|
|
|
180
|
-
**The doc-drift guard is why this survived, so it grew the missing half.** It asserted the core carries the EXPORT axis (`.sensitive(`, fail-closed, the export endpoint) and said nothing about the wire axis. There is now a matching assertion for `.serverOnly()`, the
|
|
422
|
+
**The doc-drift guard is why this survived, so it grew the missing half.** It asserted the core carries the EXPORT axis (`.sensitive(`, fail-closed, the export endpoint) and said nothing about the wire axis. There is now a matching assertion for `.serverOnly()`, the enforcement, and the orthogonality — verified by deleting the section and watching it go red. *(It asked only for the words "boot audit", which the template supplied while promising a failure nothing performed. The next release makes it name the commands that gate.)*
|
|
181
423
|
- **@voltro/cli** — **`voltro dev` could not start at all in a strict-pnpm install: the supervisor respawned with a bare `--import tsx`.**
|
|
182
424
|
|
|
183
425
|
Node resolves a bare specifier against the CHILD's working directory. `@voltro/cli` declares tsx; the user's app does not — so under a non-hoisting layout tsx lives inside `node_modules/.pnpm/@voltro+cli@…/node_modules/tsx` and is invisible from the app root. The first respawn died with `Cannot find package 'tsx'`, naming a package the reader never asked for and cannot usefully install.
|
package/dist/index.d.ts
CHANGED
|
@@ -15,6 +15,31 @@ export declare const audit: () => MixinDefinition<{
|
|
|
15
15
|
|
|
16
16
|
export declare const AUDIT_LOG_TABLE = "_voltro_audit_log";
|
|
17
17
|
|
|
18
|
+
/**
|
|
19
|
+
* One actor's audit rows, newest first — the `byAuditSubjectStatus` index's
|
|
20
|
+
* caller. `status: 'error'` is the question asked under pressure ("every
|
|
21
|
+
* refusal by X"), which is why it is a first-class argument rather than
|
|
22
|
+
* something you filter in JS after fetching everything.
|
|
23
|
+
*
|
|
24
|
+
* `limit` defaults to 100: an actor's history is unbounded, and an entry point
|
|
25
|
+
* that returns all of it by default is one you call once in production.
|
|
26
|
+
*/
|
|
27
|
+
export declare const auditBySubject: (store: AuditQueryStore, subjectId: string, options?: {
|
|
28
|
+
readonly status?: "ok" | "error";
|
|
29
|
+
readonly limit?: number;
|
|
30
|
+
}) => Promise<ReadonlyArray<Record<string, unknown>>>;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Every audit row for ONE call — the other half of the correlation join.
|
|
34
|
+
*
|
|
35
|
+
* `byAuditTrace` existed with no caller, which is the same defect the versioning
|
|
36
|
+
* side had: an index nobody can enter is a query you still have to hand-write.
|
|
37
|
+
* Pair it with `historyByTrace` from `@voltro/plugin-versioning` on the same
|
|
38
|
+
* `traceId` and you have "who called, whether they were refused, and what they
|
|
39
|
+
* changed" in two reads.
|
|
40
|
+
*/
|
|
41
|
+
export declare const auditByTrace: (store: AuditQueryStore, traceId: string) => Promise<ReadonlyArray<Record<string, unknown>>>;
|
|
42
|
+
|
|
18
43
|
/** Narrow slice of the framework DataStore the durable sink needs. */
|
|
19
44
|
export declare interface AuditDataStore {
|
|
20
45
|
insert: (table: string, row: Record<string, unknown>) => Promise<unknown>;
|
|
@@ -111,6 +136,57 @@ export declare interface AuditPluginOptions {
|
|
|
111
136
|
* Typically `/^debug\./` or similar. Default: skip nothing.
|
|
112
137
|
*/
|
|
113
138
|
readonly exclude?: RegExp;
|
|
139
|
+
/**
|
|
140
|
+
* Which OUTCOMES are recorded. `include`/`exclude` filter by tag, before the
|
|
141
|
+
* call runs; this filters by what happened, after.
|
|
142
|
+
*
|
|
143
|
+
* - `'all'` (default) — every invocation.
|
|
144
|
+
* - `'errors'` — refusals only. The forensic core: a denied guard, a revoked
|
|
145
|
+
* key, a validation rejection. Pairs with `plugin-versioning`, which
|
|
146
|
+
* records the SUCCESSFUL writes, so the two together still cover
|
|
147
|
+
* everything while this table stays small enough for retention to be a
|
|
148
|
+
* footnote.
|
|
149
|
+
* - a predicate — anything else (`(e) => e.outcome.kind === 'error' ||
|
|
150
|
+
* e.tag.startsWith('auth.')`).
|
|
151
|
+
*
|
|
152
|
+
* **`'all'` is the default deliberately, though `'errors'` is often the right
|
|
153
|
+
* choice.** Defaulting to errors would silently stop recording successes for
|
|
154
|
+
* every app that upgrades, and "what did this compromised account touch" is
|
|
155
|
+
* answered by successes. Shrinking the trail is a decision an app makes with
|
|
156
|
+
* its eyes open, not one an upgrade makes for it.
|
|
157
|
+
*/
|
|
158
|
+
readonly record?: 'all' | 'errors' | ((event: AuditEvent) => boolean);
|
|
159
|
+
/**
|
|
160
|
+
* What happens to `AuditEvent.input` before it is handed to the sink.
|
|
161
|
+
*
|
|
162
|
+
* - `'all'` (DEFAULT) — the payload is replaced by `{ __redacted: 'all' }`.
|
|
163
|
+
* The row still proves a payload existed; it just does not carry it.
|
|
164
|
+
* - `'none'` — the raw input, verbatim. What every sink did before this
|
|
165
|
+
* option existed.
|
|
166
|
+
* - a function — `(event) => unknown`, for field-level control.
|
|
167
|
+
*
|
|
168
|
+
* **Why the default is `'all'`, and why it is NOT marker-driven.** The obvious
|
|
169
|
+
* design — redact using `.serverOnly()` / `.sensitive()` — cannot work: those
|
|
170
|
+
* markers live on TABLE COLUMNS, and this is a mutation's INPUT. A
|
|
171
|
+
* `changePassword({ oldPassword, newPassword })` has no column to consult, so
|
|
172
|
+
* a marker-driven default would cover exactly 0% of the case it exists for
|
|
173
|
+
* while reading, to anyone configuring it, like protection. (`.sensitive()` is
|
|
174
|
+
* also the EXPORT axis, not "unsafe to log" — treating one as the other is the
|
|
175
|
+
* category error the three-marker table warns about.)
|
|
176
|
+
*
|
|
177
|
+
* So the choice is between recording credentials by default and recording no
|
|
178
|
+
* payload by default. A password change, an API key at issuance and a PAT all
|
|
179
|
+
* land in `input`, and an audit table is the one place nobody thinks to look
|
|
180
|
+
* for a credential. Losing payload detail is visible the first time you read a
|
|
181
|
+
* row; leaking a credential is not visible at all. Opt in per app with a
|
|
182
|
+
* function once you know your own inputs.
|
|
183
|
+
*/
|
|
184
|
+
readonly redactInput?: 'all' | 'none' | ((event: AuditEvent) => unknown);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The narrow read surface the entry points need. */
|
|
188
|
+
export declare interface AuditQueryStore {
|
|
189
|
+
query: (descriptor: unknown) => Promise<ReadonlyArray<Record<string, unknown>>>;
|
|
114
190
|
}
|
|
115
191
|
|
|
116
192
|
export declare type AuditSink = (event: AuditEvent) => void | Promise<void> | Effect.Effect<void>;
|
package/dist/index.js
CHANGED
|
@@ -2,21 +2,30 @@ import { audit as e } from "./mixin.js";
|
|
|
2
2
|
import { Effect as t } from "effect";
|
|
3
3
|
import { definePlugin as n } from "@voltro/protocol";
|
|
4
4
|
import { createLogger as r } from "@voltro/logger";
|
|
5
|
-
import {
|
|
5
|
+
import { and as i, eq as a, id as o, json as s, registerRetention as c, retentionTtlMsFromEnv as l, table as u, text as d, timestamp as f } from "@voltro/database";
|
|
6
6
|
//#region src/store.ts
|
|
7
|
-
var
|
|
8
|
-
id:
|
|
9
|
-
tag:
|
|
10
|
-
at:
|
|
11
|
-
subjectId:
|
|
12
|
-
tenantId:
|
|
13
|
-
traceId:
|
|
14
|
-
status:
|
|
15
|
-
durationMs:
|
|
16
|
-
subject:
|
|
17
|
-
input:
|
|
18
|
-
outcome:
|
|
19
|
-
|
|
7
|
+
var p = "_voltro_audit_log", m = u(p, {
|
|
8
|
+
id: o({ prefix: "audit" }),
|
|
9
|
+
tag: d(),
|
|
10
|
+
at: f(),
|
|
11
|
+
subjectId: d().nullable(),
|
|
12
|
+
tenantId: d().nullable(),
|
|
13
|
+
traceId: d(),
|
|
14
|
+
status: d(),
|
|
15
|
+
durationMs: d(),
|
|
16
|
+
subject: s(),
|
|
17
|
+
input: s(),
|
|
18
|
+
outcome: s(),
|
|
19
|
+
errorTag: d().nullable()
|
|
20
|
+
}).index("byAuditTag", ["tag"]).index("byAuditTrace", ["traceId"]).index("byAuditSubjectStatus", [
|
|
21
|
+
"subjectId",
|
|
22
|
+
"status",
|
|
23
|
+
"at"
|
|
24
|
+
]).index("byAuditTenantStatus", [
|
|
25
|
+
"tenantId",
|
|
26
|
+
"status",
|
|
27
|
+
"at"
|
|
28
|
+
]), h = [m], g = (e) => ({
|
|
20
29
|
tag: e.tag,
|
|
21
30
|
at: new Date(e.ts),
|
|
22
31
|
subjectId: e.subject.id ?? null,
|
|
@@ -26,14 +35,37 @@ var l = "_voltro_audit_log", u = o(l, {
|
|
|
26
35
|
durationMs: String(e.outcome.durationMs),
|
|
27
36
|
subject: e.subject,
|
|
28
37
|
input: e.input,
|
|
29
|
-
outcome: e.outcome
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
38
|
+
outcome: e.outcome,
|
|
39
|
+
errorTag: e.outcome.kind === "error" ? _(e.outcome.error) : null
|
|
40
|
+
}), _ = (e) => {
|
|
41
|
+
if (typeof e != "object" || !e) return null;
|
|
42
|
+
let t = e._tag;
|
|
43
|
+
return typeof t == "string" && t !== "" ? t : null;
|
|
44
|
+
}, v = async (e, t) => e.query({
|
|
45
|
+
table: p,
|
|
46
|
+
predicate: a("traceId", t),
|
|
47
|
+
order: [{
|
|
48
|
+
column: "at",
|
|
49
|
+
direction: "asc"
|
|
50
|
+
}]
|
|
51
|
+
}), y = async (e, t, n = {}) => {
|
|
52
|
+
let r = a("subjectId", t);
|
|
53
|
+
return e.query({
|
|
54
|
+
table: p,
|
|
55
|
+
predicate: n.status === void 0 ? r : i(r, a("status", n.status)),
|
|
56
|
+
order: [{
|
|
57
|
+
column: "at",
|
|
58
|
+
direction: "desc"
|
|
59
|
+
}],
|
|
60
|
+
take: n.limit ?? 100
|
|
61
|
+
});
|
|
62
|
+
}, b = (e) => async (t) => {
|
|
63
|
+
await e.insert(p, g(t));
|
|
64
|
+
}, x = r({ scope: "@voltro/plugin-audit" }), S = 1e3, C = [], w = () => [...C], T = () => {
|
|
65
|
+
C.length = 0;
|
|
66
|
+
}, E = (e) => {
|
|
67
|
+
C.push(e), C.length > S && C.splice(0, C.length - S);
|
|
68
|
+
}, D = (e) => {
|
|
37
69
|
let t = e.subject.id ? `${e.subject.type}:${e.subject.id}` : e.subject.type, n = e.outcome.kind === "ok" ? "ok" : "error", r = {
|
|
38
70
|
subject: t,
|
|
39
71
|
tenant: e.subject.tenantId ?? null,
|
|
@@ -41,8 +73,8 @@ var l = "_voltro_audit_log", u = o(l, {
|
|
|
41
73
|
durationMs: e.outcome.durationMs,
|
|
42
74
|
traceId: e.traceId
|
|
43
75
|
};
|
|
44
|
-
n === "error" ?
|
|
45
|
-
},
|
|
76
|
+
n === "error" ? x.warn(e.tag, r) : x.info(e.tag, r);
|
|
77
|
+
}, O = (e, n) => typeof e == "function" ? (n) => t.suspend(() => {
|
|
46
78
|
let r = e(n);
|
|
47
79
|
return r === void 0 ? t.void : t.isEffect(r) ? r : t.tryPromise({
|
|
48
80
|
try: () => Promise.resolve(r),
|
|
@@ -54,7 +86,7 @@ var l = "_voltro_audit_log", u = o(l, {
|
|
|
54
86
|
try: () => r(e),
|
|
55
87
|
catch: (e) => e
|
|
56
88
|
}) : t.void;
|
|
57
|
-
}) : e === "memory" ? (e) => t.sync(() =>
|
|
89
|
+
}) : e === "memory" ? (e) => t.sync(() => E(e)) : (e) => t.sync(() => D(e)), k = (e) => {
|
|
58
90
|
let t = [], n = [], r = (e) => {
|
|
59
91
|
if (e._tag !== "Empty") {
|
|
60
92
|
if (e._tag === "Fail") {
|
|
@@ -78,10 +110,25 @@ var l = "_voltro_audit_log", u = o(l, {
|
|
|
78
110
|
}
|
|
79
111
|
};
|
|
80
112
|
return r(e), t[0] ?? n[0] ?? e;
|
|
81
|
-
},
|
|
82
|
-
let r = e.sink === "datastore"
|
|
113
|
+
}, A = (e = {}) => {
|
|
114
|
+
let r = e.sink === "datastore";
|
|
115
|
+
r && c({
|
|
116
|
+
table: p,
|
|
117
|
+
timeColumn: "at",
|
|
118
|
+
ttlMs: l(process.env.VOLTRO_AUDIT_LOG_TTL_HOURS, 24 * 365)
|
|
119
|
+
});
|
|
120
|
+
let i, a = O(e.sink, () => i), o = (t) => !(e.exclude?.test(t) || e.include && !e.include.test(t)), s = (t) => {
|
|
121
|
+
let n = e.record ?? "all";
|
|
122
|
+
return n === "all" ? !0 : n === "errors" ? t.outcome.kind === "error" : n(t);
|
|
123
|
+
}, u = { __redacted: "all" }, d = (t) => {
|
|
124
|
+
let n = e.redactInput ?? "all";
|
|
125
|
+
return n === "none" ? t : {
|
|
126
|
+
...t,
|
|
127
|
+
input: n === "all" ? u : n(t)
|
|
128
|
+
};
|
|
129
|
+
}, f = (e) => s(e) ? a(d(e)) : t.void, m = (e, n) => o(n.tag) ? t.suspend(() => {
|
|
83
130
|
let r = Date.now();
|
|
84
|
-
return e.pipe(t.tap((e) =>
|
|
131
|
+
return e.pipe(t.tap((e) => f({
|
|
85
132
|
ts: r,
|
|
86
133
|
tag: n.tag,
|
|
87
134
|
subject: n.subject,
|
|
@@ -92,7 +139,7 @@ var l = "_voltro_audit_log", u = o(l, {
|
|
|
92
139
|
value: e,
|
|
93
140
|
durationMs: Date.now() - r
|
|
94
141
|
}
|
|
95
|
-
}).pipe(t.catchAllCause(() => t.void))), t.tapErrorCause((e) =>
|
|
142
|
+
}).pipe(t.catchAllCause(() => t.void))), t.tapErrorCause((e) => f({
|
|
96
143
|
ts: r,
|
|
97
144
|
tag: n.tag,
|
|
98
145
|
subject: n.subject,
|
|
@@ -100,7 +147,7 @@ var l = "_voltro_audit_log", u = o(l, {
|
|
|
100
147
|
input: n.input,
|
|
101
148
|
outcome: {
|
|
102
149
|
kind: "error",
|
|
103
|
-
error:
|
|
150
|
+
error: k(e),
|
|
104
151
|
durationMs: Date.now() - r
|
|
105
152
|
}
|
|
106
153
|
}).pipe(t.catchAllCause(() => t.void))));
|
|
@@ -110,13 +157,13 @@ var l = "_voltro_audit_log", u = o(l, {
|
|
|
110
157
|
description: "Records every mutation invocation; ships an audit() schema mixin for row-level metadata.",
|
|
111
158
|
permissions: r ? ["rpc:intercept:mutation", "store:write"] : ["rpc:intercept:mutation"],
|
|
112
159
|
...r ? {
|
|
113
|
-
extendSchema: { tables:
|
|
160
|
+
extendSchema: { tables: h },
|
|
114
161
|
bindDataStore: (e) => {
|
|
115
|
-
i =
|
|
162
|
+
i = b(e);
|
|
116
163
|
}
|
|
117
164
|
} : {},
|
|
118
|
-
interceptMutation:
|
|
165
|
+
interceptMutation: m
|
|
119
166
|
});
|
|
120
167
|
};
|
|
121
168
|
//#endregion
|
|
122
|
-
export {
|
|
169
|
+
export { p as AUDIT_LOG_TABLE, e as audit, y as auditBySubject, v as auditByTrace, g as auditEventToRow, m as auditLogTable, h as auditLogTables, A as auditPlugin, T as clearAuditBuffer, b as dataStoreAuditSink, w as readAuditBuffer };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@voltro/plugin-audit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.20.0",
|
|
4
4
|
"description": "Audit plugin — ships the `audit()` schema mixin (createdAt/updatedAt/createdBy/updatedBy → Actor) plus an optional mutation interceptor that records every call to a configurable sink (console / memory / custom function).",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"voltro",
|
|
@@ -37,9 +37,9 @@
|
|
|
37
37
|
"node": ">=24.0.0"
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"@voltro/database": "0.
|
|
41
|
-
"@voltro/logger": "0.
|
|
42
|
-
"@voltro/protocol": "0.
|
|
40
|
+
"@voltro/database": "0.20.0",
|
|
41
|
+
"@voltro/logger": "0.20.0",
|
|
42
|
+
"@voltro/protocol": "0.20.0"
|
|
43
43
|
},
|
|
44
44
|
"peerDependencies": {
|
|
45
45
|
"effect": "^3.21.4"
|