agent-envelope-assurance-sdk 0.0.0-stage → 0.1.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/README.md +47 -2
- package/examples/cold-chain.js +73 -0
- package/index.d.ts +69 -0
- package/package.json +26 -4
- package/src/index.js +196 -0
package/README.md
CHANGED
|
@@ -1,3 +1,48 @@
|
|
|
1
|
-
#
|
|
1
|
+
# AgentEnvelope Assurance SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Assurance SDK records events reported by a host system. It can capture a request at the boundary, including requests rejected before hosted AgentEnvelope sees them. The host makes permission, legitimacy and execution decisions and can report each one as a separate event. AgentEnvelope's signing and hashing primitives give the recorder verifiable provenance for those reports.
|
|
4
|
+
|
|
5
|
+
## Record and verify an event
|
|
6
|
+
|
|
7
|
+
Use a dedicated 32-byte reporting seed kept by the host. Assign an opaque chain ID to the boundary and distribute its reporter address to verifiers through a trusted channel. The host supplies a persistent store and an exclusive writer lock. The browser example below uses Web Locks for tabs on the same origin.
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
import { contentHash } from 'agent-envelope-sdk';
|
|
11
|
+
import { createEventRecorder, createStorageEventStore, verifyEventJournal } from 'agent-envelope-assurance-sdk';
|
|
12
|
+
|
|
13
|
+
const chainId = 'boundary_8f16c4';
|
|
14
|
+
const key = `assurance:${chainId}`;
|
|
15
|
+
const store = createStorageEventStore({
|
|
16
|
+
storage: localStorage,
|
|
17
|
+
key,
|
|
18
|
+
withLock: work => navigator.locks.request(key, work),
|
|
19
|
+
});
|
|
20
|
+
const recorder = createEventRecorder({ chainId, reporterSeed, store });
|
|
21
|
+
const { record, checkpoint } = await recorder.record({
|
|
22
|
+
eventId: crypto.randomUUID(),
|
|
23
|
+
kind: 'attempt.observed',
|
|
24
|
+
observedAt: Date.now(),
|
|
25
|
+
correlationId: commandId,
|
|
26
|
+
subjectDigest: contentHash(receivedCommand),
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
const verified = verifyEventJournal(store.read(), {
|
|
30
|
+
chainId,
|
|
31
|
+
reporterAddress: trustedReporterAddress,
|
|
32
|
+
checkpoint, // retain this independently if you need to detect local rollback
|
|
33
|
+
});
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`kind` is a host-defined event name. `observedAt` is the reporter's timestamp in Unix milliseconds. `correlationId`, `subjectDigest` and `reasonCode` are optional. Pass bounded digests of raw input and use event names and reason codes controlled by the reporting boundary. The journal stores signed event records and their chain, and checks both when reloaded. The same trust settings can verify one record via `verifyEvent` without reading a chain.
|
|
37
|
+
|
|
38
|
+
The alpha storage adapter reads, verifies and replaces a whole JSON snapshot, suited to small journals with one reporter key per chain. Persistent data stays with the configured store. An independently retained checkpoint lets a verifier detect a rewrite or truncation through that height. Each signature attests to a reporter's statement within the instrumented boundary.
|
|
39
|
+
|
|
40
|
+
## Cold-chain example
|
|
41
|
+
|
|
42
|
+
From this repository, run `npm ci` and `npm test`. With [`agent-envelope-cold-chain`](https://github.com/BlackBoxEngineering/agent-envelope-cold-chain) checked out beside this repository and its dependencies installed, run `npm run demo:cold-chain` on Node 22. Pass `-- <path-to-cold-chain-checkout>` for a checkout elsewhere.
|
|
43
|
+
|
|
44
|
+
The [example](examples/cold-chain.js) wraps the existing demo executor and uses an isolated local journal. It records `attempt.observed`, `attempt.rejected` and `execution.not_started` for the simulator's rejected 50°C request. It reopens the journal and verifies all three events. The output reports the journal path, verification checkpoint, and counts for hosted calls and simulated effects.
|
|
45
|
+
|
|
46
|
+
The [concept plan](https://github.com/BlackBoxEngineering/agent-envelope-assurance-sdk/blob/main/digest/assurance-sdk-concept-and-plan.md) and [evidence-pack draft](https://github.com/BlackBoxEngineering/agent-envelope-assurance-sdk/blob/main/digest/evidence-pack-contract.md) describe later work on reconciliation and external evidence.
|
|
47
|
+
|
|
48
|
+
Run `npm ci` and `npm test` to check the prototype.
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { randomBytes, randomUUID } from 'node:crypto';
|
|
3
|
+
import { mkdtempSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join, resolve } from 'node:path';
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
7
|
+
import { contentHash } from 'agent-envelope-sdk';
|
|
8
|
+
import { createEventRecorder, createStorageEventStore, verifyEventJournal } from 'agent-envelope-assurance-sdk';
|
|
9
|
+
|
|
10
|
+
const coldChain = process.argv[2] ?? fileURLToPath(new URL('../../agent-envelope-cold-chain/', import.meta.url));
|
|
11
|
+
const { createExecutor } = await import(pathToFileURL(resolve(coldChain, 'src/coldChainExecutor.js')));
|
|
12
|
+
const directory = mkdtempSync(join(tmpdir(), 'ae-assurance-cold-chain-'));
|
|
13
|
+
|
|
14
|
+
function fileStorage() {
|
|
15
|
+
return {
|
|
16
|
+
getItem(key) {
|
|
17
|
+
try { return readFileSync(join(directory, encodeURIComponent(key)), 'utf8'); }
|
|
18
|
+
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
19
|
+
},
|
|
20
|
+
setItem(key, value) {
|
|
21
|
+
const path = join(directory, encodeURIComponent(key));
|
|
22
|
+
const temporary = `${path}.tmp`;
|
|
23
|
+
writeFileSync(temporary, value, { mode: 0o600 });
|
|
24
|
+
renameSync(temporary, path);
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// A single process owns this isolated demo directory.
|
|
30
|
+
let pending = Promise.resolve();
|
|
31
|
+
const withLock = work => {
|
|
32
|
+
const operation = pending.then(work);
|
|
33
|
+
pending = operation.catch(() => {});
|
|
34
|
+
return operation;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
let hostedCalls = 0;
|
|
38
|
+
const executor = createExecutor({ storage: fileStorage(), withLock, hosted: {
|
|
39
|
+
prepare() { hostedCalls += 1; throw new Error('The demo must complete without reaching hosted minting'); },
|
|
40
|
+
} });
|
|
41
|
+
|
|
42
|
+
const chainId = `cold_chain_${randomUUID()}`;
|
|
43
|
+
const key = 'assurance.json';
|
|
44
|
+
const openStore = () => createStorageEventStore({ storage: fileStorage(), key, withLock });
|
|
45
|
+
const recorder = createEventRecorder({ chainId, reporterSeed: randomBytes(32), store: openStore() });
|
|
46
|
+
|
|
47
|
+
const correlationId = await executor.queue('attack', { mode: 'hosted' });
|
|
48
|
+
const { packet } = executor.snapshot().commands[correlationId];
|
|
49
|
+
const subjectDigest = contentHash({ payload: packet.payload, signature: packet.signature, record: packet.record });
|
|
50
|
+
const report = (kind, reasonCode) => recorder.record({
|
|
51
|
+
eventId: randomUUID(), kind, observedAt: Date.now(), correlationId, subjectDigest, reasonCode,
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
await report('attempt.observed');
|
|
55
|
+
const result = await executor.run(correlationId);
|
|
56
|
+
assert.equal(result.decision, 'denied');
|
|
57
|
+
assert.notEqual(result.evidence.reasonCode, 'hosted.admission_failed');
|
|
58
|
+
assert.equal(executor.snapshot().commands[correlationId].effectCount, 0);
|
|
59
|
+
assert.equal(hostedCalls, 0);
|
|
60
|
+
await report('attempt.rejected', result.evidence.reasonCode);
|
|
61
|
+
const { checkpoint } = await report('execution.not_started');
|
|
62
|
+
|
|
63
|
+
const reloaded = openStore().read();
|
|
64
|
+
const { reporterAddress } = recorder;
|
|
65
|
+
assert.equal(verifyEventJournal(reloaded, { chainId, reporterAddress, checkpoint }), true);
|
|
66
|
+
assert.deepEqual(reloaded.records.map(({ event }) => event.kind), [
|
|
67
|
+
'attempt.observed', 'attempt.rejected', 'execution.not_started',
|
|
68
|
+
]);
|
|
69
|
+
console.log(JSON.stringify({
|
|
70
|
+
journal: join(directory, key), reporterAddress, checkpoint, hostedCalls,
|
|
71
|
+
decision: result.evidence.reasonCode, effects: 0,
|
|
72
|
+
verifiedEvents: reloaded.records.map(({ event }) => event.kind),
|
|
73
|
+
}, null, 2));
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
export interface ChainEntry {
|
|
2
|
+
readonly type: 'agentenvelope.assurance.chainEntry';
|
|
3
|
+
readonly version: 1;
|
|
4
|
+
readonly chainId: string;
|
|
5
|
+
readonly height: number;
|
|
6
|
+
readonly prev: string | null;
|
|
7
|
+
readonly recordDigest: string | null;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface Checkpoint {
|
|
11
|
+
readonly chainId: string;
|
|
12
|
+
readonly height: number;
|
|
13
|
+
readonly tip: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface EventInput {
|
|
17
|
+
eventId: string;
|
|
18
|
+
kind: string;
|
|
19
|
+
observedAt: number;
|
|
20
|
+
correlationId?: string | null;
|
|
21
|
+
subjectDigest?: string | null;
|
|
22
|
+
reasonCode?: string | null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface EventRecord {
|
|
26
|
+
event: Required<EventInput> & {
|
|
27
|
+
type: 'agentenvelope.assurance.event';
|
|
28
|
+
version: 1;
|
|
29
|
+
chainId: string;
|
|
30
|
+
reporterAddress: string;
|
|
31
|
+
};
|
|
32
|
+
signature: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface EventJournal {
|
|
36
|
+
entries: ChainEntry[];
|
|
37
|
+
records: EventRecord[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface EventStore {
|
|
41
|
+
read(): unknown;
|
|
42
|
+
update(change: (current: unknown) => EventJournal): EventJournal | PromiseLike<EventJournal>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface EventTrust {
|
|
46
|
+
chainId: string;
|
|
47
|
+
reporterAddress: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function createGenesis(chainId: string): ChainEntry;
|
|
51
|
+
export function createNextEntry(previous: ChainEntry, recordDigest: string): ChainEntry;
|
|
52
|
+
export function checkpointFor(entry: ChainEntry): Checkpoint;
|
|
53
|
+
export function verifyChain(entries: unknown, expectedCheckpoint?: Checkpoint): boolean;
|
|
54
|
+
export function verifyEvent(record: unknown, trust: EventTrust): boolean;
|
|
55
|
+
export function verifyEventJournal(journal: unknown, trust: EventTrust & { checkpoint?: Checkpoint }): boolean;
|
|
56
|
+
export function createStorageEventStore(options: {
|
|
57
|
+
storage: { getItem(key: string): string | null; setItem(key: string, value: string): void };
|
|
58
|
+
key: string;
|
|
59
|
+
withLock(work: () => EventJournal): EventJournal | PromiseLike<EventJournal>;
|
|
60
|
+
}): EventStore;
|
|
61
|
+
export function createEventRecorder(options: {
|
|
62
|
+
chainId: string;
|
|
63
|
+
reporterSeed: Uint8Array;
|
|
64
|
+
store: EventStore;
|
|
65
|
+
}): {
|
|
66
|
+
reporterAddress: string;
|
|
67
|
+
record(event: EventInput): Promise<{ record: EventRecord; checkpoint: Checkpoint }>;
|
|
68
|
+
read(options?: { checkpoint?: Checkpoint }): Promise<EventJournal>;
|
|
69
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-envelope-assurance-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Application-neutral signed event recording and checkpoint verification using AgentEnvelope.",
|
|
6
|
+
"types": "./index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./index.d.ts",
|
|
10
|
+
"import": "./src/index.js"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"files": ["src/", "index.d.ts", "examples/cold-chain.js"],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"test": "node --test",
|
|
16
|
+
"demo:cold-chain": "node examples/cold-chain.js"
|
|
17
|
+
},
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=18"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"agent-envelope-sdk": "1.4.6"
|
|
23
|
+
},
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/BlackBoxEngineering/agent-envelope-assurance-sdk.git"
|
|
27
|
+
}
|
|
28
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { contentHash, seedAddress, signAction, verifyAction } from 'agent-envelope-sdk';
|
|
2
|
+
|
|
3
|
+
const ENTRY_TYPE = 'agentenvelope.assurance.chainEntry';
|
|
4
|
+
const CHAIN_ID = /^[a-zA-Z0-9_-]{1,80}$/u;
|
|
5
|
+
const HASH = /^[a-f0-9]{64}$/u;
|
|
6
|
+
const RECORD_DIGEST = /^0x[a-f0-9]{64}$/u;
|
|
7
|
+
const ENTRY_FIELDS = ['type', 'version', 'chainId', 'height', 'prev', 'recordDigest'];
|
|
8
|
+
const CHECKPOINT_FIELDS = ['chainId', 'height', 'tip'];
|
|
9
|
+
const EVENT_TYPE = 'agentenvelope.assurance.event';
|
|
10
|
+
const EVENT_TOKEN = /^[a-zA-Z0-9_.:-]{1,128}$/u;
|
|
11
|
+
const ADDRESS = /^0x[a-f0-9]{40}$/u;
|
|
12
|
+
const SIGNATURE = /^0x[a-f0-9]{130}$/u;
|
|
13
|
+
const EVENT_FIELDS = ['type', 'version', 'chainId', 'eventId', 'kind', 'observedAt',
|
|
14
|
+
'correlationId', 'subjectDigest', 'reasonCode', 'reporterAddress'];
|
|
15
|
+
|
|
16
|
+
function hasFields(value, fields) {
|
|
17
|
+
if (value === null || typeof value !== 'object') return false;
|
|
18
|
+
const prototype = Object.getPrototypeOf(value);
|
|
19
|
+
return (prototype === Object.prototype || prototype === null) &&
|
|
20
|
+
Object.keys(value).length === fields.length && fields.every((field) => {
|
|
21
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, field);
|
|
22
|
+
return descriptor?.enumerable && Object.hasOwn(descriptor, 'value');
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function isHeight(value) {
|
|
27
|
+
return Number.isSafeInteger(value) && value >= 0 && !Object.is(value, -0);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function matches(value, pattern) {
|
|
31
|
+
// Matching the whole value also excludes a final newline accepted by `$`.
|
|
32
|
+
return typeof value === 'string' && pattern.exec(value)?.[0] === value;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function isEntry(entry) {
|
|
36
|
+
if (!hasFields(entry, ENTRY_FIELDS) || entry.type !== ENTRY_TYPE || entry.version !== 1 ||
|
|
37
|
+
!matches(entry.chainId, CHAIN_ID) || !isHeight(entry.height)) return false;
|
|
38
|
+
|
|
39
|
+
return entry.height === 0
|
|
40
|
+
? entry.prev === null && entry.recordDigest === null
|
|
41
|
+
: matches(entry.prev, HASH) && matches(entry.recordDigest, RECORD_DIGEST);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function isCheckpoint(checkpoint) {
|
|
45
|
+
return hasFields(checkpoint, CHECKPOINT_FIELDS) && matches(checkpoint.chainId, CHAIN_ID) &&
|
|
46
|
+
isHeight(checkpoint.height) && matches(checkpoint.tip, HASH);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function entryHash(entry) {
|
|
50
|
+
return contentHash(entry).slice(2);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function entryFor(chainId, height, prev, recordDigest) {
|
|
54
|
+
return Object.freeze({ type: ENTRY_TYPE, version: 1, chainId, height, prev, recordDigest });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Create height zero for an opaque, host-assigned boundary chain ID. */
|
|
58
|
+
export function createGenesis(chainId) {
|
|
59
|
+
if (!matches(chainId, CHAIN_ID)) throw new TypeError('Invalid chain ID');
|
|
60
|
+
return entryFor(chainId, 0, null, null);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Construct the next entry from a validated head and an AE-format record digest. */
|
|
64
|
+
export function createNextEntry(previous, recordDigest) {
|
|
65
|
+
if (!isEntry(previous)) throw new TypeError('Invalid previous entry');
|
|
66
|
+
if (!matches(recordDigest, RECORD_DIGEST)) throw new TypeError('Invalid record digest');
|
|
67
|
+
if (previous.height === Number.MAX_SAFE_INTEGER) throw new RangeError('Chain height exhausted');
|
|
68
|
+
return entryFor(previous.chainId, previous.height + 1, entryHash(previous), recordDigest);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Produce the chain ID, height and bare SHA-256 tip for a selected entry. */
|
|
72
|
+
export function checkpointFor(entry) {
|
|
73
|
+
if (!isEntry(entry)) throw new TypeError('Invalid chain entry');
|
|
74
|
+
return Object.freeze({ chainId: entry.chainId, height: entry.height, tip: entryHash(entry) });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Verify a chain from genesis, optionally matching an independently retained checkpoint. */
|
|
78
|
+
export function verifyChain(entries, expectedCheckpoint) {
|
|
79
|
+
if (!Array.isArray(entries) || entries.length === 0) return false;
|
|
80
|
+
if (expectedCheckpoint !== undefined && !isCheckpoint(expectedCheckpoint)) return false;
|
|
81
|
+
|
|
82
|
+
let previousHash = null;
|
|
83
|
+
let chainId;
|
|
84
|
+
let matchedCheckpoint = expectedCheckpoint === undefined;
|
|
85
|
+
for (const [height, entry] of entries.entries()) {
|
|
86
|
+
if (!isEntry(entry) || entry.height !== height || entry.prev !== previousHash) return false;
|
|
87
|
+
if (height === 0) chainId = entry.chainId;
|
|
88
|
+
if (entry.chainId !== chainId) return false;
|
|
89
|
+
|
|
90
|
+
previousHash = entryHash(entry);
|
|
91
|
+
if (expectedCheckpoint?.height === height) {
|
|
92
|
+
matchedCheckpoint = expectedCheckpoint.chainId === chainId && expectedCheckpoint.tip === previousHash;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return matchedCheckpoint;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function isEvent(event) {
|
|
99
|
+
return hasFields(event, EVENT_FIELDS) && event.type === EVENT_TYPE && event.version === 1 &&
|
|
100
|
+
matches(event.chainId, CHAIN_ID) && matches(event.eventId, EVENT_TOKEN) &&
|
|
101
|
+
matches(event.kind, EVENT_TOKEN) && isHeight(event.observedAt) &&
|
|
102
|
+
(event.correlationId === null || matches(event.correlationId, EVENT_TOKEN)) &&
|
|
103
|
+
(event.subjectDigest === null || matches(event.subjectDigest, RECORD_DIGEST)) &&
|
|
104
|
+
(event.reasonCode === null || matches(event.reasonCode, EVENT_TOKEN)) &&
|
|
105
|
+
matches(event.reporterAddress, ADDRESS);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Verify a reporter's statement against the boundary and address trusted by the caller. */
|
|
109
|
+
export function verifyEvent(record, { chainId, reporterAddress } = {}) {
|
|
110
|
+
return matches(reporterAddress, ADDRESS) && hasFields(record, ['event', 'signature']) &&
|
|
111
|
+
isEvent(record.event) && record.event.chainId === chainId &&
|
|
112
|
+
record.event.reporterAddress === reporterAddress && matches(record.signature, SIGNATURE) &&
|
|
113
|
+
verifyAction({ message: record.event, signature: record.signature, expectedAddress: reporterAddress }).valid;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Verify the chain, the signed records it commits and any independently retained checkpoint. */
|
|
117
|
+
export function verifyEventJournal(journal, { chainId, reporterAddress, checkpoint } = {}) {
|
|
118
|
+
if (!matches(reporterAddress, ADDRESS) || !hasFields(journal, ['entries', 'records']) ||
|
|
119
|
+
!Array.isArray(journal.records) || !verifyChain(journal.entries, checkpoint) ||
|
|
120
|
+
journal.entries[0].chainId !== chainId || journal.entries.length !== journal.records.length + 1) return false;
|
|
121
|
+
|
|
122
|
+
const eventIds = new Set();
|
|
123
|
+
for (const [index, record] of journal.records.entries()) {
|
|
124
|
+
if (!verifyEvent(record, { chainId, reporterAddress }) || eventIds.has(record.event.eventId) ||
|
|
125
|
+
contentHash(record) !== journal.entries[index + 1].recordDigest) return false;
|
|
126
|
+
eventIds.add(record.event.eventId);
|
|
127
|
+
}
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Adapt a synchronous Storage-like object with a host-supplied exclusive lock for writers. */
|
|
132
|
+
export function createStorageEventStore({ storage, key, withLock }) {
|
|
133
|
+
if (typeof storage?.getItem !== 'function' || typeof storage?.setItem !== 'function' ||
|
|
134
|
+
typeof key !== 'string' || key.length === 0 || typeof withLock !== 'function') {
|
|
135
|
+
throw new TypeError('Storage, key and an exclusive writer lock are required');
|
|
136
|
+
}
|
|
137
|
+
const read = () => {
|
|
138
|
+
const raw = storage.getItem(key);
|
|
139
|
+
if (raw === null) return null;
|
|
140
|
+
const journal = JSON.parse(raw);
|
|
141
|
+
if (journal === null) throw new Error('Invalid stored Assurance journal');
|
|
142
|
+
return journal;
|
|
143
|
+
};
|
|
144
|
+
return {
|
|
145
|
+
read,
|
|
146
|
+
update(change) {
|
|
147
|
+
return withLock(() => {
|
|
148
|
+
const journal = change(read());
|
|
149
|
+
storage.setItem(key, JSON.stringify(journal));
|
|
150
|
+
return journal;
|
|
151
|
+
});
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Create a recorder with a dedicated, host-controlled reporting seed and persistent store. */
|
|
157
|
+
export function createEventRecorder({ chainId, reporterSeed, store }) {
|
|
158
|
+
const genesis = createGenesis(chainId);
|
|
159
|
+
if (!(reporterSeed instanceof Uint8Array) || reporterSeed.length !== 32) {
|
|
160
|
+
throw new TypeError('Reporter seed must be a 32-byte Uint8Array');
|
|
161
|
+
}
|
|
162
|
+
if (typeof store?.read !== 'function' || typeof store?.update !== 'function') {
|
|
163
|
+
throw new TypeError('An Assurance event store is required');
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const seed = Uint8Array.from(reporterSeed);
|
|
167
|
+
const reporterAddress = seedAddress(seed);
|
|
168
|
+
function verifiedJournal(stored, checkpoint) {
|
|
169
|
+
const journal = stored === null ? { entries: [genesis], records: [] } : stored;
|
|
170
|
+
if (!verifyEventJournal(journal, { chainId, reporterAddress, checkpoint })) {
|
|
171
|
+
throw new Error('Assurance journal verification failed');
|
|
172
|
+
}
|
|
173
|
+
return journal;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return {
|
|
177
|
+
reporterAddress,
|
|
178
|
+
async record({ eventId, kind, observedAt, correlationId = null, subjectDigest = null, reasonCode = null }) {
|
|
179
|
+
const event = { type: EVENT_TYPE, version: 1, chainId, eventId, kind, observedAt,
|
|
180
|
+
correlationId, subjectDigest, reasonCode, reporterAddress };
|
|
181
|
+
if (!isEvent(event)) throw new TypeError('Invalid Assurance event fields');
|
|
182
|
+
const record = { event, signature: signAction(seed, event) };
|
|
183
|
+
|
|
184
|
+
const updated = await store.update(stored => {
|
|
185
|
+
const { entries, records } = verifiedJournal(stored);
|
|
186
|
+
if (records.some(existing => existing.event.eventId === eventId)) throw new Error('Assurance event ID already recorded');
|
|
187
|
+
const entry = createNextEntry(entries.at(-1), contentHash(record));
|
|
188
|
+
return { entries: [...entries, entry], records: [...records, record] };
|
|
189
|
+
});
|
|
190
|
+
return { record, checkpoint: checkpointFor(updated.entries.at(-1)) };
|
|
191
|
+
},
|
|
192
|
+
async read({ checkpoint } = {}) {
|
|
193
|
+
return verifiedJournal(await store.read(), checkpoint);
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
}
|