Skip to content

Commit 4f0a5f3

Browse files
fix(plugin-audit, cli): isolate audit sealer faults per chain; os serve hands its crypto provider to an app-supplied AuditPlugin (objectstack-ai#33503)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DXuamRUC67fx2TTYrFfyuSH)_ Part of objectstack-ai#31908 (slice P4b1; seat ruling 6884540128 items 2 and 3) Clause-②: yes (widening) Metadata-protocol: none ## Maintainer quick read - What changes: the audit sealer isolates faults per chain. When a canonical rule refuses one of a chain's rows, or one of a chain's checkpoints (its head included) is malformed, only that chain is skipped, and the other chains seal as usual. Each chain has its own cursor and resumes from its own oldest unsealed window. Past a window that holds a skipped chain, `sealed_through` stops advancing. A lock lapse or a signer, crypto or storage fault still aborts the object's whole pass. Also: when an app puts its own `AuditPlugin` in `plugins` without a `cryptoProvider`, `os serve` now hands it the host's crypto provider. It does this only for the real `AuditPlugin` class, and it never overrides an explicit provider. - Why: before, one bad row stopped sealing for every chain of the object. And an app's own `AuditPlugin` (one added to turn on `readAudit`, for example) replaced the CLI's instance, got no crypto provider, and sealed nothing. - Risk and rollback: verdicts and refusal reasons are unchanged, and every existing seal and verify pin passes as is. The PR adds one public method, `AuditPlugin.adoptHostCryptoProvider` (widening). The sealer pass is window-major, and `late` never sweeps a lagging chain. Both are pinned per seat ruling 6885452378, the precondition for the verifier's sealed-window rule, which lands in P4c. Rollback is a revert. - Read first: in `sealer.ts`, `run`, `cursorOf`, `skip`, `writeChains` and the catch in `readWindow`. In `serve.ts`, the `handHostCryptoToAppAuditPlugin` line inside the stack plugins loop. In `audit-plugin.ts`, `adoptHostCryptoProvider`. - Two-minute check: `pnpm --filter @objectstack/plugin-audit exec vitest run src/audit-seal/audit-seal-sealer.test.ts src/audit-plugin.test.ts`. Expect 2 files and 65 tests, all green. - Needed from you: nothing. The seat lands it. ## What changes 1. **S4, per-chain isolation (seat ruling 6884540128 item 2).** `sealer.ts`: - Only a chain-local fault skips a chain: a row a canonical rule refuses (`CanonicalFormError` while reading the row), or a malformed checkpoint of that chain (`SignedBodyError`/`CanonicalFormError` while reading it back: its head in `headOf`, a lister in the late re-count, a lister in `listedIn`, or its `window_start` while the cursors are read). The skipped chain stays out for the rest of the pass; every other chain is sealed. Lock lapse, signer, crypto-provider and storage faults (and the Q6 coordinate bound) still throw out of the object's pass, as before. - Each chain has its own cursor: the window after its last `window` checkpoint at or past the object's floor (the stored `sealed_through`, before which every chain is complete). A row is `late` only before its own chain's cursor; at or past it the window pass seals it as `window`. So a skipped chain (or one a stopped pass left) resumes from its own oldest unsealed window as `window` checkpoints. This replaces the object-wide `lastWindow` / `resumed` pair. - `sealed_through` on every `window` checkpoint is `min(window start, earliest window a skipped chain leaves unsealed)`, never below the stored floor. So it never passes a window that has a skipped chain. - The window walk starts at the floor. A window that only re-reads chains already sealed (or skipped) past it does not count toward `MAX_WINDOWS_PER_PASS`, so a stuck chain cannot stall the others behind the cap. - Each skipped chain is reported once at `error` per cause per hour, naming the object, the chain, the fault (code and reason, never a statement) and the window it is unsealed from. A chain sealed again is forgotten. 2. **App-supplied AuditPlugin (seat ruling 6884540128 item 3).** - `audit-plugin.ts`: new `adoptHostCryptoProvider(provider, { armSealer })`. It takes the provider only when the instance was composed with no `cryptoProvider`, so an explicit one is never overridden. `armSealer: false` (a one-shot boot) keeps the sealer off. `true` leaves the instance's own `armSealer` standing, so an app's `armSealer: false` is never turned on. Kept in private fields; the app's options object is not mutated. - `packages/cli/src/utils/app-audit-plugin-host-crypto.ts`: `handHostCryptoToAppAuditPlugin` hands over only to `instanceof` the real class, as this host loads it. A same-named lookalike is never touched. It never throws. - `serve.ts`: the class is loaded once, best-effort, ahead of the stack `plugins` loop. Each entry is handed `() => hostCrypto?.provider` and `!migrateAndExit` (the same provider function and one-shot posture as the 5d instance and the `requires: ['audit']` resolver) right before `kernel.use`. Boot is never refused. An instance left with no provider keeps D3's once-at-`error` report from its sealer. Out of scope, untouched: S7, the item-5 DB session lock, verify's bootStack crypto (item 4, P4c), any `lifecycle.seal` default, expiry amendments, objectql lifecycle, `docs/adr/**`, `.claude/**`, `skills/**`, `.github/workflows/**`. ## Tests Tests first. Each new pin was run red before its fix. - `audit-seal-sealer.test.ts`, new describe `per-chain isolation …`: - A refused row in org_b's 08:00 window. The deployment chain and org_a are sealed at 08:00, 09:00 and 10:00. org_b is not. Every `sealed_through` stays at 08:00. One `error` line names the object, `org:org_b`, `b1.payload` and "NOT being sealed". - Once the row is fixed, org_b resumes: `window` checkpoints at 08:00 (seq 0) and 09:00 (seq 1), not `late`. A third pass writes nothing. - A malformed head (org_b's checkpoint `root`). org_a is sealed at 09:00 and 10:00, both with `sealed_through` 09:00. org_b is skipped with one `error` line naming `root`. - A storage fault (`connection reset` on org_a's insert) still stops the whole object: nothing is stored, and one object-level `error` line. This one is green before and after; it preserves the abort. - Verify stays loud: `verifyAuditLedger` over the first scenario answers `ok: false`, with totals `unmodified: 2, late: 2, unsealed: 2`. This is the verdict `os audit verify` exits 1 on. - Window-major (seat ruling 6885452378): org_a writes every hour for 30 hours, which is more windows than one pass seals, and org_b writes only at hours 0, 11, 23 and 29. After pass 1, both chains' newest `window` checkpoint is at 23:00. After pass 2, both are at 29:00, and there is no `late` checkpoint. It was green at first run, so no code change was needed: the pass is one loop over windows that seals every due chain under one shared budget. Giving org_b its own budget turns it red (Verification). - No late sweep (seat ruling 6885452378): org_x is skipped at 08:00 while org_a seals 08:00 and 09:00. In pass 2, org_x recovers into `window` checkpoints at 08:00 (seq 0) and 09:00 (seq 1), and the only `late` checkpoint is org_a's own late row at 08:00. It was green at first run, so no code change was needed. Restoring the old every-chain late rule turns it red (Verification). - `audit-plugin.test.ts`, new describe: takes the host provider when none was composed, and the sealer seals under it. Never overrides an explicit one. A one-shot host keeps the sealer off, and an app's `armSealer: false` stands. A host with no provider composes none, so the sealer is built without crypto and reports at `error`. - `cli/src/utils/app-audit-plugin-host-crypto.test.ts`: the real class with no provider is fed. An explicit provider is not replaced. A same-named lookalike with an `adoptHostCryptoProvider` of its own is never called. The class missing or no plugin feeds nothing. A one-shot host disarms the sealer. - `serve-audit-registration.contract.test.ts`: every existing assertion is kept. New: the hand-over call (exact spelling, with `() => hostCrypto?.provider` and `!migrateAndExit`) sits inside the stack `plugins` loop before `await kernel.use(pluginToLoad);`, and the real class is loaded ahead of the loop. ## Acceptance notes - **Ruled: verify for a window where the skipped chain is the only chain.** The verifier today reads a window as sealed when a trusted `window` checkpoint names it, or when the window ends at or before the highest `sealed_through`. Ruling item 2 holds `sealed_through` at the skipped window. So if no other chain sealed that window, the skipped chain's rows there get no verdict. Seat ruling 6885452378 (option A) closes this in P4c: a window is also sealed when it starts at or before the highest `window_start` among trusted `window` checkpoints. The ADR-0154 D3 line is in objectstack-ai#33489. Its two preconditions, a window-major pass and `late` never sweeping a lagging chain, are pinned in this PR (Tests). - **A row whose `created_at` will not parse, when it is the oldest row of a span**, is met by the window walk's `firstRowAt` before any chain is read. That still stops the object's pass, as before. In `readWindow` the same fault skips only its chain. - **Cost while a chain is stuck.** Each pass walks from the floor, so it re-reads the windows other chains already sealed past it until the stuck chain is fixed. This is bounded by how long the chain stays stuck. The cursor read fetches the `window` checkpoints at or past the floor. review#3 S1: bounding this re-walk is carried to P4b2. - **A separately installed copy of `@objectstack/plugin-audit`** in the app is a different class from the one the host loads, so an instance of it is treated as a lookalike and is not fed. Its sealer reports the missing provider at `error`. - **`OS_MIGRATE_AND_EXIT=1` with an app AuditPlugin that composed its own provider** arms its sealer, as before. The ruling feeds only instances with no provider, so this PR does not touch them. - **Stacked on P4a (objectstack-ai#33476).** Base is `claude/area-A2-31908-p4a`; the area thread retargets it to `main` once objectstack-ai#33476 merges. ## Verification All readings were taken at head `4cbd2fca9` unless they name another commit; the follow-up block was taken at `22d4da3f6`. <details><summary>Red before the fixes</summary> ``` # 5ada48f (sealer pins only) × skips the chain of a row a canonical rule refuses, seals every other chain, and holds sealed_through at the skipped window × resumes a skipped chain from its own oldest unsealed window, as window checkpoints and not late ones × skips the chain whose head checkpoint is malformed, and seals the others past it × keeps verify loud: the skipped chain's rows read unsealed and the verdict is not ok Tests 4 failed | 30 passed (34) os-verify-lock: VERDICT command-exit 1 # 03a059d (plugin pins only) TypeError: plugin.adoptHostCryptoProvider is not a function Tests 4 failed | 25 passed (29) os-verify-lock: VERDICT command-exit 1 # cli pins before the helper and the serve wiring Error: Cannot find module './app-audit-plugin-host-crypto.js' × hands the host crypto provider to an app-supplied AuditPlugin in the stack `plugins` loop, before the kernel takes it (seat ruling 6884540128 item 3) Tests 1 failed | 7 passed (8) os-verify-lock: VERDICT command-exit 1 ``` </details> <details><summary>Green: the full plugin-audit suite, and the CLI tests that read serve.ts</summary> ``` # pnpm --filter @objectstack/plugin-audit exec vitest run --maxWorkers=2 Test Files 93 passed (93) Tests 1511 passed (1511) os-verify-lock: VERDICT command-exit 0 # pnpm --filter @objectstack/cli exec vitest run --project unit --maxWorkers=2 (every test file that reads serve.ts, plus the helper's) Test Files 40 passed (40) Tests 600 passed (600) os-verify-lock: VERDICT command-exit 0 ``` 48 files were named, and the `unit` project ran the 40 that are unit-tier. The rest are integration-tier, which CI's `Test Core` runs. </details> <details><summary>Follow-up pins (seat ruling 6885452378): green at first run, and each bites under ablation</summary> ``` # 22d4da3, sealer file: Tests 36 passed (36), VERDICT command-exit 0 # ablation: the sealLate accept against the chain's own cursor replaced by the every-chain rule (start before the pass end) # no-late-sweep pin red, expected 5 to be 3; Tests 3 failed | 33 passed (36); restored blob == HEAD (5e40b51) # ablation: a separate per-pass budget for org_b in the window pass # window-major pin red, expected 25 to be 27; Tests 1 failed | 35 passed (36); restored blob == HEAD (5e40b51) # full plugin-audit suite at 22d4da3: Test Files 93 passed (93), Tests 1513 passed (1513), VERDICT command-exit 0 ``` </details> <details><summary>Type-check, lint and gates</summary> ``` pnpm --filter '@objectstack/cli^...' build -> VERDICT command-exit 0 pnpm --filter @objectstack/plugin-audit typecheck -> VERDICT command-exit 0 (check:test-typecheck OK, 0 pinned) pnpm --filter @objectstack/cli typecheck -> VERDICT command-exit 0 (check:test-typecheck OK, debt unchanged) eslint --no-inline-config (the eight changed source files) -> exit 0 node scripts/check-test-source-alias.mjs (pnpm check:test-source-alias) -> exit 0 dispatch-gates --ran: 99 derived, 22 run (each exit 0), 0 NOT-MEASURED, 77 left to CI ``` The 22 run locally: `check-adr-0087-registration`, `check-changeset-no-major`, `check-empty-changeset`, `check-closing-keyword-parity`, `check-issue-citations` (both), `check-plugin-teardown-shape`, `check-tenant-audit-census`, `check-comment-mask-adoption`, `check:durability-log-level`, `check:startup-registry-verdict`, `check:nul-bytes`, `check:doc-authoring`, `check:engine-double-contract`, `check:test-source-alias`, `check:cross-package-test-inputs`, `check:optional-error-sink`, `check:system-context-census`, `check:keyed-text-bounds`, `check:undeclared-dep-imports`, `check:logger-receiver-detach` and `check:tier-file-adoption`. The derivation is taken against `main`, so it includes P4a's files, and the spec families are mostly P4a's. CI's `Lint & Repo Gates` runs the rest. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (No spec change here.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes (eslint on the changed files; the repo-wide run is CI's). - [x] 4. One issue, one branch, one pull request. (By the seat's slicing, this branch carries slice P4b1 of objectstack-ai#31908, stacked on P4a's branch until objectstack-ai#33476 merges.) - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` untouched: nothing to regenerate. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e411388 commit 4f0a5f3

9 files changed

Lines changed: 474 additions & 44 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/plugin-audit': patch
3+
'@objectstack/cli': patch
4+
---
5+
6+
fix(plugin-audit, cli): the audit sealer skips only the chain a chain-local fault belongs to; `os serve` hands its crypto provider to an AuditPlugin the app composed with none
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
**The sealer (ADR-0154 D3, S4).** A fault that belongs to one chain of a sealed object — a row a canonical rule refuses, or a malformed checkpoint of that chain (its head among them) — now skips that chain for the rest of the pass instead of stopping the whole object. Every other chain is still sealed. Each chain now resumes from its own oldest unsealed window, as `window` checkpoints, so a skipped chain catches up once its fault is fixed. No checkpoint's `sealed_through` passes a window a skipped chain leaves unsealed. The sealer reports each skipped chain once at `error`, naming the object, the chain, the fault and the window it is unsealed from, and again each hour while it lasts. A lock lapse, a signer, crypto-provider or storage fault still stops the object's pass, as before. `os audit verify` reads the skipped chain's rows in a window another chain sealed as `late` and unsealed, and fails.
12+
13+
**An app-supplied AuditPlugin (ADR-0154 D2, D6).** An app that puts its own `AuditPlugin` in its stack `plugins` (to turn on `readAudit`, for example) supersedes the one `os serve` composes, and so lost the host's crypto provider: its sealer sealed nothing and said so at `error`. `os serve` now hands it the host's provider when the app composed it with no `cryptoProvider`, and keeps its sealer off on an `OS_MIGRATE_AND_EXIT=1` boot, as for the instance it composes itself. A provider the app composed is never replaced, an app's `armSealer: false` stays off, and a plugin that only carries the AuditPlugin name is never handed anything. The new `AuditPlugin.adoptHostCryptoProvider(provider, { armSealer })` is the method a host calls to do this.

‎packages/cli/src/commands/serve-audit-registration.contract.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,18 @@ describe('os serve registers AuditPlugin with no config-derived options, above t
249249
expect(SERVE).toMatch(/cap === 'audit' && hostCrypto\s*\?\s*\{ \.\.\.\(arg \?\? \{\}\), cryptoProvider: hostCrypto\.provider, armSealer: !migrateAndExit \}/);
250250
});
251251

252+
it('hands the host crypto provider to an app-supplied AuditPlugin in the stack `plugins` loop, before the kernel takes it (seat ruling 6884540128 item 3)', () => {
253+
// The app's `plugins` entry supersedes the CLI's instance (last one wins), so without this hand-over an app
254+
// that composed its own AuditPlugin seals nothing. The same provider function, the same one-shot posture.
255+
const HAND = 'handHostCryptoToAppAuditPlugin(pluginToLoad, RealAuditPlugin, () => hostCrypto?.provider, !migrateAndExit)';
256+
const loop = soleOffset(SERVE, PLUGINS_LOOP, 'stack-plugins-loop');
257+
const hand = soleOffset(SERVE, HAND, 'app AuditPlugin hand-over');
258+
expect(hand).toBeGreaterThan(loop);
259+
expect(hand).toBeLessThan(soleOffset(SERVE, 'await kernel.use(pluginToLoad);', 'stack-plugin registration'));
260+
// Judged against the real class, loaded once ahead of the loop: never by name, so a lookalike is never fed.
261+
expect(soleOffset(SERVE, '({ AuditPlugin: RealAuditPlugin } = await import(', 'real AuditPlugin class')).toBeLessThan(loop);
262+
});
263+
252264
it('arms no sealer on an `OS_MIGRATE_AND_EXIT=1` boot, a one-shot job (ADR-0154 D3)', () => {
253265
// One reading of the variable, ahead of both constructions; the exit reads the same constant.
254266
const reading = "const migrateAndExit = process.env.OS_MIGRATE_AND_EXIT === '1';";

‎packages/cli/src/commands/serve.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { loadConfig, bundleConfigModule } from '../utils/config.js';
1010
import { mergeBootConfig } from '../utils/merge-boot-config.js';
1111
import { provisionTelemetryDatasource, standaloneTelemetryPrimary } from '../utils/telemetry-datasource.js';
1212
import { isHostConfig, shouldBootWithLibrary } from '../utils/plugin-detection.js';
13+
import { handHostCryptoToAppAuditPlugin } from '../utils/app-audit-plugin-host-crypto.js';
1314
import { mountsAiServicePlugin, resolveAiServiceLoad, resolveOptionalPluginLoad } from '../utils/ai-service-auto-inject.js';
1415
import { registerInstalledPlugins } from '../utils/installed-plugins-boot.js';
1516
import { readInternalArtifactPath, readInternalConfigOutputPath } from '../utils/internal-artifact-channel.js';
@@ -4978,6 +4979,17 @@ export default class Serve extends Command {
49784979
// got that far), for `refuseUnloadedCryptoProviderPlugins` below.
49794980
const unloadedStackPlugins: UnloadedStackPlugin[] = [];
49804981
if (plugins.length > 0) {
4982+
// [ADR-0154 D2, D6; seat ruling 6884540128 item 3] The class an app's
4983+
// own AuditPlugin is judged by, loaded as this host loads it: only an
4984+
// instance of it is handed the host's crypto provider below, never a
4985+
// plugin that merely carries its name. Optional, as at 5d.
4986+
let RealAuditPlugin: typeof import('@objectstack/plugin-audit').AuditPlugin | undefined;
4987+
try {
4988+
const auditPkg = '@objectstack/plugin-audit';
4989+
({ AuditPlugin: RealAuditPlugin } = await import(/* webpackIgnore: true */ auditPkg));
4990+
} catch {
4991+
RealAuditPlugin = undefined;
4992+
}
49814993
let index = -1;
49824994
for (const plugin of plugins) {
49834995
index += 1;
@@ -5014,6 +5026,14 @@ export default class Serve extends Command {
50145026
// declared contract (`packages/core/src/plugin-registration.ts`),
50155027
// with a `warn` naming both versions. That is how an app supplies
50165028
// options to a plugin this CLI mounts without them.
5029+
//
5030+
// [ADR-0154 D2, D6; seat ruling 6884540128 item 3] An app's own
5031+
// AuditPlugin composed with no crypto provider is handed the
5032+
// host's — the same provider function, and the same one-shot
5033+
// posture, as the instance at 5d and the `requires: ['audit']`
5034+
// resolver — so superseding the CLI's instance does not leave the
5035+
// sealed objects unsealed. An explicit provider is never replaced.
5036+
handHostCryptoToAppAuditPlugin(pluginToLoad, RealAuditPlugin, () => hostCrypto?.provider, !migrateAndExit);
50175037
await kernel.use(pluginToLoad);
50185038
stackMountedPlugins.push(pluginToLoad);
50195039
const pluginName = plugin.name || plugin.constructor?.name || 'unnamed';
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { describe, expect, it } from 'vitest';
4+
import { AuditPlugin } from '@objectstack/plugin-audit';
5+
import { handHostCryptoToAppAuditPlugin } from './app-audit-plugin-host-crypto.js';
6+
7+
/**
8+
* [ADR-0154 D2, D6; seat ruling 6884540128 item 3] `os serve` hands its one
9+
* crypto provider to an AuditPlugin the app put in its stack `plugins`: only
10+
* to an instance of the real class, only when the app composed it with none.
11+
*/
12+
describe('os serve hands its crypto provider to an app-supplied AuditPlugin', () => {
13+
const host = () => ({ label: 'host' }) as never;
14+
15+
it('hands it to a real AuditPlugin composed with no provider', () => {
16+
const plugin = new AuditPlugin({ readAudit: { objects: [] } });
17+
expect(handHostCryptoToAppAuditPlugin(plugin, AuditPlugin, host, true)).toBe(true);
18+
expect((plugin as unknown as { hostCryptoProvider: unknown }).hostCryptoProvider).toBe(host);
19+
});
20+
21+
it('never overrides a provider the app composed it with', () => {
22+
const own = { label: 'own' } as never;
23+
const plugin = new AuditPlugin({ cryptoProvider: own });
24+
expect(handHostCryptoToAppAuditPlugin(plugin, AuditPlugin, host, true)).toBe(false);
25+
expect((plugin as unknown as { hostCryptoProvider: unknown }).hostCryptoProvider).toBeUndefined();
26+
});
27+
28+
it('never feeds a same-named lookalike, whatever it answers to', () => {
29+
const calls: unknown[] = [];
30+
const lookalike = { name: 'com.objectstack.audit', adoptHostCryptoProvider: (...args: unknown[]) => (calls.push(args), true) };
31+
expect(handHostCryptoToAppAuditPlugin(lookalike, AuditPlugin, host, true)).toBe(false);
32+
expect(calls).toEqual([]);
33+
});
34+
35+
it('feeds nothing when the class could not be loaded, and never throws', () => {
36+
expect(handHostCryptoToAppAuditPlugin(new AuditPlugin(), undefined, host, true)).toBe(false);
37+
expect(handHostCryptoToAppAuditPlugin(undefined, AuditPlugin, host, true)).toBe(false);
38+
});
39+
40+
it("keeps the sealer off on a one-shot boot (`armSealer: false`)", () => {
41+
const plugin = new AuditPlugin();
42+
expect(handHostCryptoToAppAuditPlugin(plugin, AuditPlugin, host, false)).toBe(true);
43+
expect((plugin as unknown as { hostDisarmsSealer: boolean }).hostDisarmsSealer).toBe(true);
44+
});
45+
});
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import type { AuditPlugin } from '@objectstack/plugin-audit';
4+
import type { ICryptoProvider } from '@objectstack/spec/contracts';
5+
6+
/**
7+
* [ADR-0154 D2, D6; seat ruling 6884540128 item 3] Hand `os serve`'s one
8+
* crypto provider to an AuditPlugin the app put in its stack `plugins`.
9+
*
10+
* The app's entry supersedes the instance the CLI composes (the declared
11+
* last-one-wins registration), and an app composing its own instance for
12+
* `readAudit` rarely spells a crypto provider, so without this its sealer
13+
* seals nothing. The hand-over matches the capability resolver's
14+
* `requires: ['audit']` path: the same provider, and no sealer on a one-shot
15+
* boot (`armSealer: false`).
16+
*
17+
* Only an instance of the real class (`RealAuditPlugin`, as this host loads
18+
* it) is handed anything — never a plugin that merely carries its name — and
19+
* only one the app composed with no provider of its own (the class's
20+
* `adoptHostCryptoProvider` decides that). Nothing here throws or refuses the
21+
* boot: an instance left without a provider reports that once, at `error`,
22+
* from its sealer (ADR-0154 D3). Resolves whether the provider was handed.
23+
*/
24+
export function handHostCryptoToAppAuditPlugin(
25+
plugin: unknown,
26+
RealAuditPlugin: typeof AuditPlugin | undefined,
27+
provider: () => ICryptoProvider | undefined,
28+
armSealer: boolean,
29+
): boolean {
30+
if (RealAuditPlugin === undefined || !(plugin instanceof RealAuditPlugin)) return false;
31+
return plugin.adoptHostCryptoProvider(provider, { armSealer });
32+
}

‎packages/plugins/plugin-audit/src/audit-plugin.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,3 +580,47 @@ describe('AuditPlugin — sys_comment access gates are mounted', () => {
580580
expect(denials[0].reason).toMatchObject({ code: 'RECORD_NOT_ACCESSIBLE', status: 403 });
581581
});
582582
});
583+
584+
describe('AuditPlugin — a host hands an app-supplied instance its crypto provider (ADR-0154 D2, D6; seat ruling 6884540128 item 3)', () => {
585+
const crypto = (label: string) => ({ label }) as never;
586+
/** The sealer `startSealer` composes over a storage double whose registry holds no sealed object: its pass seals nothing. */
587+
const sealerOf = async (plugin: AuditPlugin): Promise<{ crypto?: unknown } | null> => {
588+
const engine = { getDriverForObject: () => undefined, registry: { getAllObjects: () => [] } };
589+
const ctx = { logger: { info() {}, warn() {}, error() {}, debug() {} }, getService: () => undefined };
590+
(plugin as unknown as { startSealer(e: unknown, c: unknown): void }).startSealer(engine, ctx);
591+
const sealer = (plugin as unknown as { sealer: { options: { crypto?: unknown }; stop(): Promise<void> } | null }).sealer;
592+
await sealer?.stop();
593+
return sealer && sealer.options;
594+
};
595+
596+
it('takes the host provider when it was composed with none, and seals under it', async () => {
597+
const plugin = new AuditPlugin({ readAudit: { objects: [] } });
598+
const host = crypto('host');
599+
expect(plugin.adoptHostCryptoProvider(() => host, { armSealer: true })).toBe(true);
600+
expect((await sealerOf(plugin))?.crypto).toBe(host);
601+
});
602+
603+
it('never overrides a provider the app composed it with', async () => {
604+
const own = crypto('own');
605+
const plugin = new AuditPlugin({ cryptoProvider: own });
606+
expect(plugin.adoptHostCryptoProvider(() => crypto('host'), { armSealer: true })).toBe(false);
607+
expect((await sealerOf(plugin))?.crypto).toBe(own);
608+
});
609+
610+
it("keeps the sealer off on a host's one-shot boot, and an app's own `armSealer: false` stands", async () => {
611+
const oneShot = new AuditPlugin();
612+
expect(oneShot.adoptHostCryptoProvider(() => crypto('host'), { armSealer: false })).toBe(true);
613+
expect(await sealerOf(oneShot)).toBeNull();
614+
const off = new AuditPlugin({ armSealer: false });
615+
expect(off.adoptHostCryptoProvider(() => crypto('host'), { armSealer: true })).toBe(true);
616+
expect(await sealerOf(off)).toBeNull();
617+
});
618+
619+
it('composes no provider when the host has none to hand: the sealer reports it once, at error (D3)', async () => {
620+
const plugin = new AuditPlugin();
621+
expect(plugin.adoptHostCryptoProvider(() => undefined, { armSealer: true })).toBe(true);
622+
const sealer = await sealerOf(plugin);
623+
expect(sealer).not.toBeNull();
624+
expect(sealer?.crypto).toBeUndefined();
625+
});
626+
});

‎packages/plugins/plugin-audit/src/audit-plugin.ts‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -325,9 +325,34 @@ export class AuditPlugin implements Plugin {
325325
* at `kernel:ready`; the activity door's writer reads it at each call.
326326
*/
327327
private actorSnapshotOf: ((api: unknown, userId: string) => Promise<AuditActorSnapshot>) | undefined;
328+
/** [ADR-0154 D2, D6] The provider a host handed over, for an instance composed with none. */
329+
private hostCryptoProvider: (() => ICryptoProvider | undefined) | undefined;
330+
/** [ADR-0154 D3] Set when a host that handed its provider over is a one-shot boot. */
331+
private hostDisarmsSealer = false;
328332

329333
constructor(private readonly options: AuditPluginOptions = {}) {}
330334

335+
/**
336+
* [ADR-0154 D2, D6; seat ruling 6884540128 item 3] A host hands an instance
337+
* the app composed (a stack `plugins` entry) the host's own crypto provider,
338+
* which the sealer then seals under. It is taken only when this instance was
339+
* composed with no `cryptoProvider`: one the app composed is never
340+
* overridden. `armSealer: false` — the host's one-shot boot — keeps the
341+
* sealer off; `true` leaves this instance's own `armSealer` standing, so an
342+
* app's `armSealer: false` is never turned on.
343+
*
344+
* The provider is read when the sealer starts (`kernel:ready`), so a host
345+
* hands it over before then. Resolves whether it was taken. A provider that
346+
* answers `undefined` is an absent one: the sealer reports it once, at
347+
* `error`, and seals nothing; the boot is never refused.
348+
*/
349+
adoptHostCryptoProvider(provider: () => ICryptoProvider | undefined, host: { armSealer: boolean }): boolean {
350+
if (this.options.cryptoProvider !== undefined) return false;
351+
this.hostCryptoProvider = provider;
352+
if (!host.armSealer) this.hostDisarmsSealer = true;
353+
return true;
354+
}
355+
331356
async init(ctx: PluginContext): Promise<void> {
332357
// Register audit system objects via the manifest service.
333358
ctx.getService<{ register(m: any): void }>('manifest').register({
@@ -768,11 +793,11 @@ export class AuditPlugin implements Plugin {
768793
* command's boot (`armSealer: false`).
769794
*/
770795
private startSealer(engine: IDataEngine, ctx: PluginContext): void {
771-
if (this.options.armSealer === false) return;
796+
if (this.options.armSealer === false || this.hostDisarmsSealer) return;
772797
const storage = engine as unknown as Partial<AuditSealerEngine>;
773798
if (typeof storage.getDriverForObject !== 'function' || typeof storage.registry?.getAllObjects !== 'function') return;
774799
const sealEngine = storage as AuditSealerEngine;
775-
const option = this.options.cryptoProvider;
800+
const option = this.options.cryptoProvider ?? this.hostCryptoProvider;
776801
const crypto = typeof option === 'function' ? option() : option;
777802
const localSigner = crypto ? new LocalCheckpointSigner({ engine: sealEngine, crypto }) : undefined;
778803
const optional = <T>(name: string): T | undefined => {

0 commit comments

Comments
 (0)