osuite 2.10.2 → 2.11.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/GOVERNED_TOOLS.md +202 -0
- package/README.md +17 -11
- package/governed-tools/authority.mjs +134 -0
- package/governed-tools/contract.mjs +142 -0
- package/governed-tools/examples/native-client.mjs +47 -0
- package/governed-tools/executor.mjs +185 -0
- package/governed-tools/journal.mjs +448 -0
- package/governed-tools/mcp.mjs +95 -0
- package/governed-tools.mjs +10 -0
- package/package.json +8 -1
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { createPrivateKey, randomUUID } from 'node:crypto';
|
|
2
|
+
import { types } from 'node:util';
|
|
3
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
4
|
+
import { canonicalJson, safeId, sha256, validatedBaseUrl } from '../runtime/protocol.mjs';
|
|
5
|
+
import { cavaFingerprint } from '../runtime/admission.mjs';
|
|
6
|
+
import { OperationJournal } from './journal.mjs';
|
|
7
|
+
import { createStudioAuthority } from './authority.mjs';
|
|
8
|
+
import { GovernedToolError, jsonSnapshot, makeInvocation, publicStatus, reject, scopeFor } from './contract.mjs';
|
|
9
|
+
|
|
10
|
+
const signalAborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
|
|
11
|
+
function runOptions(options) {
|
|
12
|
+
if (!options || typeof options !== 'object' || types.isProxy(options)) reject('INVALID_OPTIONS');
|
|
13
|
+
const descriptors = Object.getOwnPropertyDescriptors(options);
|
|
14
|
+
if (Reflect.ownKeys(descriptors).some(key => !['waitMs', 'signal'].includes(key)
|
|
15
|
+
|| !Object.hasOwn(descriptors[key], 'value') || !descriptors[key].enumerable)) reject('INVALID_OPTIONS');
|
|
16
|
+
const waitMs = descriptors.waitMs?.value ?? 0, signal = descriptors.signal?.value;
|
|
17
|
+
if (!Number.isInteger(waitMs) || waitMs < 0 || waitMs > 600000) reject('INVALID_OPTIONS');
|
|
18
|
+
const aborted = () => {
|
|
19
|
+
if (signal === undefined) return false;
|
|
20
|
+
try { return Reflect.apply(signalAborted, signal, []); } catch { reject('INVALID_OPTIONS'); }
|
|
21
|
+
};
|
|
22
|
+
aborted();
|
|
23
|
+
return { waitMs, signal, aborted };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function checkedConfig(input) {
|
|
27
|
+
let config;
|
|
28
|
+
try { config = jsonSnapshot(input, 32768); } catch { reject('INVALID_CONFIGURATION'); }
|
|
29
|
+
if (!['enforce', 'strict'].includes(config?.mode) || config.signatureMode !== 'required'
|
|
30
|
+
|| config.guardFailureMode !== 'block' || typeof config.apiKey !== 'string' || !config.apiKey
|
|
31
|
+
|| typeof config.privateKeyBase64 !== 'string' || !config.privateKeyBase64
|
|
32
|
+
|| config.allowInsecureHttp || !validatedBaseUrl(config.baseUrl)) reject('INVALID_CONFIGURATION');
|
|
33
|
+
try { if (createPrivateKey(Buffer.from(config.privateKeyBase64, 'base64')).asymmetricKeyType !== 'rsa') throw new Error(); }
|
|
34
|
+
catch { reject('INVALID_CONFIGURATION'); }
|
|
35
|
+
return Object.freeze({ ...config, baseUrl: validatedBaseUrl(config.baseUrl), approvalWaitMs: 0 });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function registrySnapshot(bindings) {
|
|
39
|
+
if (!bindings || types.isProxy(bindings) || typeof bindings !== 'object') reject('INVALID_MAPPING');
|
|
40
|
+
const result = {};
|
|
41
|
+
for (const [name, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(bindings))) {
|
|
42
|
+
if (!Object.hasOwn(descriptor, 'value') || !safeId(name) || name.length > 128) reject('INVALID_MAPPING');
|
|
43
|
+
const binding = descriptor.value;
|
|
44
|
+
if (!binding || types.isProxy(binding) || typeof binding !== 'object') reject('INVALID_MAPPING');
|
|
45
|
+
const fields = Object.getOwnPropertyDescriptors(binding);
|
|
46
|
+
if (!Object.hasOwn(fields.revision || {}, 'value') || !Object.hasOwn(fields.describe || {}, 'value')
|
|
47
|
+
|| !safeId(fields.revision.value) || fields.revision.value.length > 128
|
|
48
|
+
|| typeof fields.describe.value !== 'function' || types.isProxy(fields.describe.value)) reject('INVALID_MAPPING');
|
|
49
|
+
Object.defineProperty(result, name, { value: Object.freeze({ revision: fields.revision.value, describe: fields.describe.value }), enumerable: true });
|
|
50
|
+
}
|
|
51
|
+
return Object.freeze(result);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function publicError(error) {
|
|
55
|
+
if (error instanceof GovernedToolError) throw error;
|
|
56
|
+
if (error?.name === 'OperationJournalError' && /^(CONFLICT|JOURNAL_[A-Z_]+)$/.test(error.code)) reject(error.code);
|
|
57
|
+
reject('OUTCOME_UNKNOWN');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function createGovernedTools({ config: rawConfig, namespace, journalPath, bindings: rawBindings,
|
|
61
|
+
journalOptions = {}, initializeJournal = false } = {}) {
|
|
62
|
+
if (Number(process.versions.node.split('.')[0]) !== 24) reject('NODE_24_REQUIRED');
|
|
63
|
+
const config = checkedConfig(rawConfig), scope = scopeFor(config, namespace), bindings = registrySnapshot(rawBindings);
|
|
64
|
+
const storage = jsonSnapshot(journalOptions);
|
|
65
|
+
if (typeof initializeJournal !== 'boolean' || !storage || Array.isArray(storage) || typeof storage !== 'object'
|
|
66
|
+
|| Object.keys(storage).some(key => !['maxOperations', 'busyTimeoutMs'].includes(key))) reject('INVALID_CONFIGURATION');
|
|
67
|
+
let journal;
|
|
68
|
+
try { journal = new OperationJournal(journalPath, { ...storage, create: initializeJournal }); } catch (error) { publicError(error); }
|
|
69
|
+
let authority;
|
|
70
|
+
try { authority = createStudioAuthority(config, journalPath); } catch { journal.close(); reject('JOURNAL_UNAVAILABLE'); }
|
|
71
|
+
let closed = false, inFlight = 0;
|
|
72
|
+
const local = operationId => journal.get(scope, operationId);
|
|
73
|
+
const status = record => publicStatus(record, config.baseUrl);
|
|
74
|
+
function stopForState(record) {
|
|
75
|
+
const codes = { completed: 'ALREADY_COMPLETED', denied: 'POLICY_DENIED', expired: 'APPROVAL_EXPIRED', cancelled: 'CANCELLED' };
|
|
76
|
+
if (codes[record.state]) reject(codes[record.state], status(record));
|
|
77
|
+
if (!['prepared', 'held', 'requesting', 'uncertain_request'].includes(record.state)) reject('OUTCOME_UNKNOWN', status(record));
|
|
78
|
+
}
|
|
79
|
+
function transitionHeld(record, next, owner) {
|
|
80
|
+
if (!journal.claim(scope, record.operationId, ['held'], 'redeeming', owner)
|
|
81
|
+
|| !journal.settle(scope, record.operationId, owner, 'redeeming', next)) reject('OPERATION_BUSY', status(local(record.operationId)));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return Object.freeze({
|
|
85
|
+
async run(operationId, params, execute, options = {}) {
|
|
86
|
+
if (closed) reject('CLOSED');
|
|
87
|
+
inFlight++;
|
|
88
|
+
try {
|
|
89
|
+
const invocation = makeInvocation({ config, namespace, bindings, operationId, params });
|
|
90
|
+
if (typeof execute !== 'function' || types.isProxy(execute)) reject('INVALID_EXECUTOR');
|
|
91
|
+
const { waitMs, signal, aborted } = runOptions(options);
|
|
92
|
+
if (aborted()) reject('ABORTED');
|
|
93
|
+
const started = performance.now(), deadline = started + waitMs, owner = randomUUID();
|
|
94
|
+
let record = journal.prepare(invocation.record);
|
|
95
|
+
const waiting = () => reject('AWAITING_APPROVAL', { ...status(local(operationId)), elapsedMs: Math.round(performance.now() - started) });
|
|
96
|
+
while (true) {
|
|
97
|
+
record = local(operationId); stopForState(record);
|
|
98
|
+
if (closed) reject('CLOSED');
|
|
99
|
+
if (aborted()) reject('ABORTED', status(record));
|
|
100
|
+
if (record.state !== 'prepared') {
|
|
101
|
+
const observed = await authority.read(record);
|
|
102
|
+
if (!observed.available) reject(record.state !== 'held' ? 'OUTCOME_UNKNOWN'
|
|
103
|
+
: observed.mismatch ? 'BINDING_MISMATCH' : 'CURRENT_AUTHORITY_UNAVAILABLE', status(record));
|
|
104
|
+
const action = observed.action;
|
|
105
|
+
if (['requesting', 'uncertain_request'].includes(record.state)) {
|
|
106
|
+
if (action.status !== 'pending_approval' || action.approval_redeemed_at != null || action.timestamp_end != null) reject('OUTCOME_UNKNOWN', status(record));
|
|
107
|
+
const fingerprint = cavaFingerprint(observed.body);
|
|
108
|
+
if (!fingerprint) reject('OUTCOME_UNKNOWN', status(record));
|
|
109
|
+
if (!journal.recoverHeld(scope, operationId, fingerprint)) reject('OPERATION_BUSY', status(local(operationId)));
|
|
110
|
+
record = local(operationId);
|
|
111
|
+
}
|
|
112
|
+
if (!record.fingerprint || record.fingerprint !== cavaFingerprint(observed.body)) reject('BINDING_MISMATCH', status(record));
|
|
113
|
+
if (action.status === 'pending_approval') {
|
|
114
|
+
if (performance.now() >= deadline) waiting();
|
|
115
|
+
try { await delay(Math.min(200, deadline - performance.now()), undefined, { signal }); }
|
|
116
|
+
catch { reject('ABORTED', status(record)); }
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (['blocked', 'denied', 'expired', 'cancelled'].includes(action.status)
|
|
120
|
+
|| ['denied', 'expired', 'cancelled'].includes(observed.body.approval?.state)) {
|
|
121
|
+
const state = action.status === 'expired' || observed.body.approval?.state === 'expired' ? 'expired'
|
|
122
|
+
: action.status === 'cancelled' ? 'cancelled' : 'denied';
|
|
123
|
+
transitionHeld(record, state, owner); stopForState(local(operationId));
|
|
124
|
+
}
|
|
125
|
+
if (action.status !== 'running' || action.timestamp_end != null || action.approval_redeemed_at != null
|
|
126
|
+
|| !action.approved_by || !action.approved_at) reject('OUTCOME_UNKNOWN', status(record));
|
|
127
|
+
}
|
|
128
|
+
let admitted;
|
|
129
|
+
try { admitted = await authority.admit(invocation, journal, owner, aborted); }
|
|
130
|
+
catch (error) {
|
|
131
|
+
if (error instanceof GovernedToolError) throw new GovernedToolError(error.code, status(local(operationId)));
|
|
132
|
+
reject('OUTCOME_UNKNOWN', status(local(operationId)));
|
|
133
|
+
}
|
|
134
|
+
if (!admitted) { if (performance.now() >= deadline) waiting(); continue; }
|
|
135
|
+
// No await or user observer between this last check, the durable fence,
|
|
136
|
+
// and invoking the original tool. This is not resource-side atomicity.
|
|
137
|
+
if (aborted() || closed || performance.now() - admitted.receivedAt > 5000) {
|
|
138
|
+
journal.settle(scope, operationId, owner, admitted.phase,
|
|
139
|
+
admitted.phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
|
|
140
|
+
reject(aborted() ? 'ABORTED' : 'OUTCOME_UNKNOWN', status(local(operationId)));
|
|
141
|
+
}
|
|
142
|
+
if (!journal.settle(scope, operationId, owner, admitted.phase, 'dispatching')) reject('OPERATION_BUSY', status(local(operationId)));
|
|
143
|
+
let result, resultDigest = null, state = 'completed', thrown = false;
|
|
144
|
+
try { result = await execute(invocation.params); }
|
|
145
|
+
catch { thrown = true; state = 'uncertain'; }
|
|
146
|
+
if (!thrown) {
|
|
147
|
+
if (result !== null && typeof result === 'object') {
|
|
148
|
+
if (types.isProxy(result)) state = 'uncertain';
|
|
149
|
+
else {
|
|
150
|
+
const errorFlag = Object.getOwnPropertyDescriptor(result, 'isError');
|
|
151
|
+
if (errorFlag && (!Object.hasOwn(errorFlag, 'value') || errorFlag.value !== false)) state = 'uncertain';
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
try {
|
|
155
|
+
const value = jsonSnapshot(result);
|
|
156
|
+
resultDigest = sha256(canonicalJson(value));
|
|
157
|
+
if (value?.isError === true) state = 'uncertain';
|
|
158
|
+
} catch { /* Opaque native returns are not serialized or independently verified. */ }
|
|
159
|
+
}
|
|
160
|
+
if (!journal.settle(scope, operationId, owner, 'dispatching', state, { resultDigest, reportState: 'uncertain' })) reject('OUTCOME_UNKNOWN', status(local(operationId)));
|
|
161
|
+
let confirmed = false;
|
|
162
|
+
try { confirmed = await authority.report(local(operationId), state, resultDigest); } catch { /* Keep the observed native outcome. */ }
|
|
163
|
+
try { if (confirmed) journal.settle(scope, operationId, owner, state, state, { reportState: 'confirmed' }); }
|
|
164
|
+
catch { /* Reporting bookkeeping cannot hide a durably observed native return. */ }
|
|
165
|
+
if (thrown) reject('OUTCOME_UNKNOWN', status(local(operationId)));
|
|
166
|
+
return result;
|
|
167
|
+
}
|
|
168
|
+
} catch (error) { publicError(error); }
|
|
169
|
+
finally {
|
|
170
|
+
inFlight--;
|
|
171
|
+
if (closed && inFlight === 0) journal.close();
|
|
172
|
+
}
|
|
173
|
+
},
|
|
174
|
+
async status(operationId) {
|
|
175
|
+
if (closed) reject('CLOSED');
|
|
176
|
+
if (!safeId(operationId) || operationId.length > 128) reject('INVALID_OPERATION_ID');
|
|
177
|
+
const record = local(operationId);
|
|
178
|
+
if (!record) return null;
|
|
179
|
+
const observed = await authority.read(record);
|
|
180
|
+
return Object.freeze({ ...status(record), remote: Object.freeze({ available: observed.available,
|
|
181
|
+
status: observed.available ? observed.action.status : null, bindingMismatch: observed.mismatch === true }) });
|
|
182
|
+
},
|
|
183
|
+
close() { if (!closed) { closed = true; if (inFlight === 0) journal.close(); } },
|
|
184
|
+
});
|
|
185
|
+
}
|
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
2
|
+
import {
|
|
3
|
+
constants, closeSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, realpathSync,
|
|
4
|
+
} from 'node:fs';
|
|
5
|
+
import { basename, dirname, isAbsolute, join, parse, sep } from 'node:path';
|
|
6
|
+
import { isProxy } from 'node:util/types';
|
|
7
|
+
|
|
8
|
+
const VERSION = 1;
|
|
9
|
+
const APPLICATION_ID = 0x4f53544a;
|
|
10
|
+
const MAX_DATABASE_BYTES = 256 * 1024 * 1024;
|
|
11
|
+
const MAX_WAL_BYTES = 16 * 1024 * 1024;
|
|
12
|
+
const WAIT = new Int32Array(new SharedArrayBuffer(4));
|
|
13
|
+
const DIGEST = /^[0-9a-f]{64}$/;
|
|
14
|
+
const SAFE_ID = /^[A-Za-z0-9_.-]{1,128}$/;
|
|
15
|
+
const FIELDS = {
|
|
16
|
+
scope: 'scope', operationId: 'operation_id', inputDigest: 'input_digest',
|
|
17
|
+
contextDigest: 'context_digest', bindingDigest: 'binding_digest',
|
|
18
|
+
actionId: 'action_id', sessionId: 'session_id', toolUseId: 'tool_use_id',
|
|
19
|
+
};
|
|
20
|
+
const PATCH_KEYS = ['fingerprint', 'resultDigest', 'reportState', 'errorCode'];
|
|
21
|
+
const REPORT_STATES = ['not_reported', 'confirmed', 'uncertain'];
|
|
22
|
+
const STATES = [
|
|
23
|
+
'prepared', 'requesting', 'held', 'redeeming', 'dispatching', 'completed',
|
|
24
|
+
'denied', 'expired', 'cancelled', 'uncertain_request', 'uncertain_redemption', 'uncertain',
|
|
25
|
+
];
|
|
26
|
+
const SETTLEMENTS = new Map([
|
|
27
|
+
['requesting', ['held', 'denied', 'expired', 'uncertain_request', 'dispatching']],
|
|
28
|
+
['redeeming', ['held', 'denied', 'expired', 'cancelled', 'uncertain_redemption', 'dispatching']],
|
|
29
|
+
['dispatching', ['completed', 'uncertain']],
|
|
30
|
+
]);
|
|
31
|
+
|
|
32
|
+
class JournalError extends Error {
|
|
33
|
+
constructor(code) {
|
|
34
|
+
super(code);
|
|
35
|
+
this.name = 'OperationJournalError';
|
|
36
|
+
this.code = code;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function fail(code) { throw new JournalError(code); }
|
|
41
|
+
|
|
42
|
+
function sanitize(error) {
|
|
43
|
+
if (error instanceof JournalError) return error;
|
|
44
|
+
const sqliteCode = typeof error?.errcode === 'number' ? error.errcode & 0xff : null;
|
|
45
|
+
if (sqliteCode === 5 || sqliteCode === 6) return new JournalError('JOURNAL_BUSY');
|
|
46
|
+
if (sqliteCode === 11 || sqliteCode === 26) return new JournalError('JOURNAL_CORRUPT');
|
|
47
|
+
if (sqliteCode === 13) return new JournalError('JOURNAL_CAPACITY');
|
|
48
|
+
return new JournalError('JOURNAL_UNAVAILABLE');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function dataObject(value, keys, code, required = []) {
|
|
52
|
+
if (!value || typeof value !== 'object' || isProxy(value) || Array.isArray(value)) fail(code);
|
|
53
|
+
const prototype = Object.getPrototypeOf(value);
|
|
54
|
+
if (prototype !== Object.prototype && prototype !== null) fail(code);
|
|
55
|
+
const snapshot = Object.create(null);
|
|
56
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
57
|
+
if (!keys.includes(key)) fail(code);
|
|
58
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
59
|
+
if (!descriptor || !Object.hasOwn(descriptor, 'value')) fail(code);
|
|
60
|
+
snapshot[key] = descriptor.value;
|
|
61
|
+
}
|
|
62
|
+
if (required.some(key => !Object.hasOwn(snapshot, key))) fail(code);
|
|
63
|
+
return snapshot;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function isId(value) {
|
|
67
|
+
return typeof value === 'string' && SAFE_ID.test(value) && !value.includes('..');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function isDigest(value) { return typeof value === 'string' && DIGEST.test(value); }
|
|
71
|
+
|
|
72
|
+
function identity(scope, operationId) {
|
|
73
|
+
if (!isDigest(scope) || !isId(operationId)) fail('JOURNAL_RECORD');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function validateRecord(record) {
|
|
77
|
+
const value = dataObject(record, Object.keys(FIELDS), 'JOURNAL_RECORD', Object.keys(FIELDS));
|
|
78
|
+
for (const key of Object.keys(FIELDS)) {
|
|
79
|
+
if (!(key === 'scope' || key.endsWith('Digest') ? isDigest(value[key]) : isId(value[key]))) {
|
|
80
|
+
fail('JOURNAL_RECORD');
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return value;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function validatePatch(patch, reporting) {
|
|
87
|
+
const value = dataObject(patch, PATCH_KEYS, 'JOURNAL_PATCH');
|
|
88
|
+
if (reporting && (Object.keys(value).length !== 1 || !Object.hasOwn(value, 'reportState'))) fail('JOURNAL_PATCH');
|
|
89
|
+
if (Object.hasOwn(value, 'fingerprint') && value.fingerprint !== null
|
|
90
|
+
&& (typeof value.fingerprint !== 'string' || value.fingerprint.length > 200 || !value.fingerprint.isWellFormed())) fail('JOURNAL_PATCH');
|
|
91
|
+
if (Object.hasOwn(value, 'resultDigest') && value.resultDigest !== null && !isDigest(value.resultDigest)) fail('JOURNAL_PATCH');
|
|
92
|
+
if (Object.hasOwn(value, 'reportState') && !REPORT_STATES.includes(value.reportState)) fail('JOURNAL_PATCH');
|
|
93
|
+
if (Object.hasOwn(value, 'errorCode') && value.errorCode !== null && !isId(value.errorCode)) fail('JOURNAL_PATCH');
|
|
94
|
+
return value;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function maybeStat(path) {
|
|
98
|
+
try { return lstatSync(path); }
|
|
99
|
+
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function checkFile(stat) {
|
|
103
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1
|
|
104
|
+
|| stat.uid !== process.getuid() || (stat.mode & 0o077)) fail('JOURNAL_PERMISSIONS');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function checkAncestor(stat) {
|
|
108
|
+
if (!stat.isDirectory() || ![0, process.getuid()].includes(stat.uid)) fail('JOURNAL_PERMISSIONS');
|
|
109
|
+
// A root-owned sticky temporary directory is safe above an owner-only directory.
|
|
110
|
+
if ((stat.mode & 0o022) && !(stat.uid === 0 && (stat.mode & 0o1000))) fail('JOURNAL_PERMISSIONS');
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function syncDirectory(path) {
|
|
114
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
|
115
|
+
try { fsyncSync(fd); } finally { closeSync(fd); }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function walkDirectory(path, create, aliases = true) {
|
|
119
|
+
const root = parse(path).root;
|
|
120
|
+
let current = root;
|
|
121
|
+
checkAncestor(lstatSync(root));
|
|
122
|
+
for (const part of path.slice(root.length).split(sep).filter(Boolean)) {
|
|
123
|
+
const next = join(current, part);
|
|
124
|
+
let stat = maybeStat(next);
|
|
125
|
+
if (!stat) {
|
|
126
|
+
if (!create) fail('JOURNAL_PERMISSIONS');
|
|
127
|
+
try { mkdirSync(next, { mode: 0o700 }); }
|
|
128
|
+
catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
129
|
+
stat = lstatSync(next);
|
|
130
|
+
syncDirectory(current);
|
|
131
|
+
}
|
|
132
|
+
if (stat.isSymbolicLink()) {
|
|
133
|
+
// System-owned root aliases (including macOS /Users) are not user links.
|
|
134
|
+
if (!aliases || current !== root || stat.uid !== 0) fail('JOURNAL_PERMISSIONS');
|
|
135
|
+
current = walkDirectory(realpathSync(next), false, false).path;
|
|
136
|
+
} else {
|
|
137
|
+
checkAncestor(stat);
|
|
138
|
+
current = next;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return { path: current, stat: lstatSync(current) };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function privateDirectory(path, create) {
|
|
145
|
+
const directory = walkDirectory(path, create);
|
|
146
|
+
if (directory.stat.uid !== process.getuid() || (directory.stat.mode & 0o077)) fail('JOURNAL_PERMISSIONS');
|
|
147
|
+
return directory;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function sameFile(left, right) { return left.dev === right.dev && left.ino === right.ino; }
|
|
151
|
+
|
|
152
|
+
const digestColumn = name => `${name} TEXT NOT NULL CHECK(length(${name})=64 AND ${name} NOT GLOB '*[^0-9a-f]*')`;
|
|
153
|
+
const idCheck = name => `length(${name}) BETWEEN 1 AND 128 AND ${name} NOT GLOB '*[^A-Za-z0-9_.-]*' AND instr(${name},'..')=0`;
|
|
154
|
+
const idColumn = name => `${name} TEXT NOT NULL CHECK(${idCheck(name)})`;
|
|
155
|
+
const stateList = STATES.map(state => `'${state}'`).join(',');
|
|
156
|
+
const metadataColumns = `
|
|
157
|
+
state TEXT NOT NULL CHECK(state IN (${stateList})),
|
|
158
|
+
owner TEXT CHECK(owner IS NULL OR (${idCheck('owner')})),
|
|
159
|
+
fingerprint TEXT CHECK(fingerprint IS NULL OR length(fingerprint)<=200),
|
|
160
|
+
result_digest TEXT CHECK(result_digest IS NULL OR (length(result_digest)=64 AND result_digest NOT GLOB '*[^0-9a-f]*')),
|
|
161
|
+
report_state TEXT NOT NULL CHECK(report_state IN ('not_reported','confirmed','uncertain')),
|
|
162
|
+
error_code TEXT CHECK(error_code IS NULL OR (${idCheck('error_code')}))`;
|
|
163
|
+
const SCHEMA = new Map([
|
|
164
|
+
['operations', `CREATE TABLE operations (
|
|
165
|
+
${digestColumn('scope')}, ${idColumn('operation_id')},
|
|
166
|
+
${digestColumn('input_digest')}, ${digestColumn('context_digest')}, ${digestColumn('binding_digest')},
|
|
167
|
+
${idColumn('action_id')}, ${idColumn('session_id')}, ${idColumn('tool_use_id')},
|
|
168
|
+
${metadataColumns},
|
|
169
|
+
created_at INTEGER NOT NULL CHECK(created_at>=0),
|
|
170
|
+
updated_at INTEGER NOT NULL CHECK(updated_at>=created_at),
|
|
171
|
+
PRIMARY KEY(scope,operation_id),
|
|
172
|
+
CHECK((state IN ('prepared','held') AND owner IS NULL) OR (state NOT IN ('prepared','held') AND owner IS NOT NULL))
|
|
173
|
+
) STRICT`],
|
|
174
|
+
['evidence', `CREATE TABLE evidence (
|
|
175
|
+
id INTEGER PRIMARY KEY,
|
|
176
|
+
${digestColumn('scope')}, ${idColumn('operation_id')},
|
|
177
|
+
kind TEXT NOT NULL CHECK(kind IN ('prepare','claim','settle','recover_held')),
|
|
178
|
+
from_state TEXT CHECK(from_state IS NULL OR from_state IN (${stateList})),
|
|
179
|
+
previous_owner TEXT CHECK(previous_owner IS NULL OR (${idCheck('previous_owner')})),
|
|
180
|
+
${metadataColumns},
|
|
181
|
+
at INTEGER NOT NULL CHECK(at>=0),
|
|
182
|
+
FOREIGN KEY(scope,operation_id) REFERENCES operations(scope,operation_id)
|
|
183
|
+
) STRICT`],
|
|
184
|
+
['evidence_operation', 'CREATE INDEX evidence_operation ON evidence(scope,operation_id,id)'],
|
|
185
|
+
]);
|
|
186
|
+
|
|
187
|
+
export class OperationJournal {
|
|
188
|
+
#db = null;
|
|
189
|
+
#path;
|
|
190
|
+
#file;
|
|
191
|
+
#directory;
|
|
192
|
+
#maxOperations;
|
|
193
|
+
#busyTimeoutMs;
|
|
194
|
+
|
|
195
|
+
constructor(path, options = {}) {
|
|
196
|
+
let fd;
|
|
197
|
+
try {
|
|
198
|
+
const config = dataObject(options, ['maxOperations', 'busyTimeoutMs', 'create'], 'JOURNAL_CONFIG');
|
|
199
|
+
const create = config.create === undefined ? true : config.create;
|
|
200
|
+
this.#maxOperations = config.maxOperations === undefined ? 10000 : config.maxOperations;
|
|
201
|
+
this.#busyTimeoutMs = config.busyTimeoutMs === undefined ? 100 : config.busyTimeoutMs;
|
|
202
|
+
if (typeof create !== 'boolean' || !Number.isSafeInteger(this.#maxOperations) || this.#maxOperations < 1
|
|
203
|
+
|| !Number.isSafeInteger(this.#busyTimeoutMs) || this.#busyTimeoutMs < 0 || this.#busyTimeoutMs > 5000) fail('JOURNAL_CONFIG');
|
|
204
|
+
if (typeof path !== 'string' || !isAbsolute(path) || path.length > 4096 || path.includes('\0')
|
|
205
|
+
|| path.includes('?') || path.endsWith(sep) || path.split(sep).some(part => part === '..' || part === '.')) fail('JOURNAL_PATH');
|
|
206
|
+
if (typeof process.getuid !== 'function') fail('JOURNAL_PERMISSIONS');
|
|
207
|
+
if (!create && !maybeStat(path)) fail('JOURNAL_MISSING');
|
|
208
|
+
this.#directory = privateDirectory(dirname(path), create);
|
|
209
|
+
this.#path = join(this.#directory.path, basename(path));
|
|
210
|
+
this.#checkFiles();
|
|
211
|
+
// Closing a non-SQLite fd for an existing DB releases this process's POSIX locks.
|
|
212
|
+
// Exclusively precreate new files only, and close before SQLite opens them.
|
|
213
|
+
if (!maybeStat(this.#path)) {
|
|
214
|
+
if (!create) fail('JOURNAL_MISSING');
|
|
215
|
+
try {
|
|
216
|
+
fd = openSync(this.#path, constants.O_CREAT | constants.O_EXCL | constants.O_RDWR | constants.O_NOFOLLOW, 0o600);
|
|
217
|
+
} catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
218
|
+
if (fd !== undefined) {
|
|
219
|
+
this.#file = fstatSync(fd);
|
|
220
|
+
checkFile(this.#file);
|
|
221
|
+
this.#checkFiles();
|
|
222
|
+
closeSync(fd);
|
|
223
|
+
fd = undefined;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
this.#file ??= lstatSync(this.#path);
|
|
227
|
+
checkFile(this.#file);
|
|
228
|
+
this.#checkFiles();
|
|
229
|
+
if (!create && this.#file.size === 0) fail('JOURNAL_SCHEMA');
|
|
230
|
+
syncDirectory(this.#directory.path);
|
|
231
|
+
this.#db = new DatabaseSync(this.#path, { enableForeignKeyConstraints: true, enableDoubleQuotedStringLiterals: false });
|
|
232
|
+
this.#checkFiles();
|
|
233
|
+
this.#db.exec(`PRAGMA busy_timeout=${this.#busyTimeoutMs}; PRAGMA trusted_schema=OFF; PRAGMA foreign_keys=ON;`);
|
|
234
|
+
// Reopening must not turn an uninitialized or truncated file into a journal.
|
|
235
|
+
if (!create && (this.#db.prepare('PRAGMA user_version').get().user_version !== VERSION
|
|
236
|
+
|| this.#db.prepare('PRAGMA application_id').get().application_id !== APPLICATION_ID)) fail('JOURNAL_SCHEMA');
|
|
237
|
+
this.#startup(() => {
|
|
238
|
+
if (this.#db.prepare('PRAGMA journal_mode=WAL').get().journal_mode !== 'wal') fail('JOURNAL_UNAVAILABLE');
|
|
239
|
+
});
|
|
240
|
+
this.#db.exec('PRAGMA synchronous=FULL; PRAGMA wal_autocheckpoint=64; PRAGMA journal_size_limit=1048576;');
|
|
241
|
+
const pageSize = this.#db.prepare('PRAGMA page_size').get().page_size;
|
|
242
|
+
const maxPages = Math.floor(MAX_DATABASE_BYTES / pageSize);
|
|
243
|
+
if (this.#db.prepare(`PRAGMA max_page_count=${maxPages}`).get().max_page_count > maxPages) fail('JOURNAL_CAPACITY');
|
|
244
|
+
this.#transaction(() => this.#schema(create), true);
|
|
245
|
+
this.#checkFiles();
|
|
246
|
+
} catch (error) {
|
|
247
|
+
try { this.#db?.close(); } catch { /* Never expose storage causes or paths. */ }
|
|
248
|
+
this.#db = null;
|
|
249
|
+
throw sanitize(error);
|
|
250
|
+
} finally {
|
|
251
|
+
if (fd !== undefined) {
|
|
252
|
+
try { closeSync(fd); } catch { /* Cleanup must not leak an unsanitized error. */ }
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
#checkFiles() {
|
|
258
|
+
const current = privateDirectory(this.#directory.path, false);
|
|
259
|
+
if (!sameFile(current.stat, this.#directory.stat)) fail('JOURNAL_PERMISSIONS');
|
|
260
|
+
for (const suffix of ['', '-wal', '-shm', '-journal']) {
|
|
261
|
+
const stat = maybeStat(`${this.#path}${suffix}`);
|
|
262
|
+
if (stat) {
|
|
263
|
+
checkFile(stat);
|
|
264
|
+
if (!suffix && this.#file && !sameFile(stat, this.#file)) fail('JOURNAL_PERMISSIONS');
|
|
265
|
+
} else if (!suffix && this.#file) fail('JOURNAL_PERMISSIONS');
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
#run(fn) {
|
|
270
|
+
try {
|
|
271
|
+
if (!this.#db) fail('JOURNAL_CLOSED');
|
|
272
|
+
this.#checkFiles();
|
|
273
|
+
return fn();
|
|
274
|
+
} catch (error) { throw sanitize(error); }
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
#startup(fn) {
|
|
278
|
+
const deadline = performance.now() + this.#busyTimeoutMs;
|
|
279
|
+
try {
|
|
280
|
+
for (;;) {
|
|
281
|
+
this.#db.exec(`PRAGMA busy_timeout=${Math.max(0, Math.ceil(deadline - performance.now()))};`);
|
|
282
|
+
try { return fn(); }
|
|
283
|
+
catch (error) {
|
|
284
|
+
const remaining = deadline - performance.now();
|
|
285
|
+
if (sanitize(error).code !== 'JOURNAL_BUSY' || remaining <= 0) throw error;
|
|
286
|
+
Atomics.wait(WAIT, 0, 0, Math.min(5, remaining));
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
} finally {
|
|
290
|
+
this.#db.exec(`PRAGMA busy_timeout=${this.#busyTimeoutMs};`);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
#transaction(fn, startup = false) {
|
|
295
|
+
// Retry only startup lock acquisition. Never replay an operation or its evidence.
|
|
296
|
+
if (startup) this.#startup(() => this.#db.exec('BEGIN IMMEDIATE'));
|
|
297
|
+
else this.#db.exec('BEGIN IMMEDIATE');
|
|
298
|
+
try {
|
|
299
|
+
this.#checkFiles();
|
|
300
|
+
if (lstatSync(this.#path).size > MAX_DATABASE_BYTES
|
|
301
|
+
|| (maybeStat(`${this.#path}-wal`)?.size ?? 0) > MAX_WAL_BYTES) fail('JOURNAL_CAPACITY');
|
|
302
|
+
const result = fn();
|
|
303
|
+
this.#db.exec('COMMIT');
|
|
304
|
+
return result;
|
|
305
|
+
} catch (error) {
|
|
306
|
+
try { this.#db.exec('ROLLBACK'); } catch { /* Preserve the original sanitized failure. */ }
|
|
307
|
+
throw error;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
#schema(create) {
|
|
312
|
+
const version = this.#db.prepare('PRAGMA user_version').get().user_version;
|
|
313
|
+
const application = this.#db.prepare('PRAGMA application_id').get().application_id;
|
|
314
|
+
const objects = () => this.#db.prepare("SELECT name,sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%'").all();
|
|
315
|
+
if (version === 0 && application === 0 && objects().length === 0) {
|
|
316
|
+
if (!create) fail('JOURNAL_SCHEMA');
|
|
317
|
+
for (const sql of SCHEMA.values()) this.#db.exec(sql);
|
|
318
|
+
this.#db.exec(`PRAGMA user_version=${VERSION}; PRAGMA application_id=${APPLICATION_ID};`);
|
|
319
|
+
} else if (version !== VERSION || application !== APPLICATION_ID) fail('JOURNAL_SCHEMA');
|
|
320
|
+
const actual = objects();
|
|
321
|
+
if (actual.length !== SCHEMA.size || actual.some(row => SCHEMA.get(row.name) !== row.sql)) fail('JOURNAL_SCHEMA');
|
|
322
|
+
const check = this.#db.prepare('PRAGMA quick_check').all();
|
|
323
|
+
if (check.length !== 1 || check[0].quick_check !== 'ok') fail('JOURNAL_CORRUPT');
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
#read(scope, operationId) {
|
|
327
|
+
return this.#db.prepare('SELECT * FROM operations WHERE scope=? AND operation_id=?').get(scope, operationId);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
#row(row) {
|
|
331
|
+
if (!row) return null;
|
|
332
|
+
return Object.freeze({
|
|
333
|
+
...Object.fromEntries(Object.entries(FIELDS).map(([field, column]) => [field, row[column]])),
|
|
334
|
+
state: row.state, owner: row.owner, fingerprint: row.fingerprint, resultDigest: row.result_digest,
|
|
335
|
+
reportState: row.report_state, errorCode: row.error_code, createdAt: row.created_at, updatedAt: row.updated_at,
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
#event(kind, before, after) {
|
|
340
|
+
this.#db.prepare(`INSERT INTO evidence(scope,operation_id,kind,from_state,previous_owner,
|
|
341
|
+
state,owner,fingerprint,result_digest,report_state,error_code,at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`)
|
|
342
|
+
.run(after.scope, after.operation_id, kind, before?.state ?? null, before?.owner ?? null,
|
|
343
|
+
after.state, after.owner, after.fingerprint, after.result_digest, after.report_state, after.error_code, after.updated_at);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
prepare(record) {
|
|
347
|
+
return this.#run(() => {
|
|
348
|
+
const value = validateRecord(record);
|
|
349
|
+
return this.#transaction(() => {
|
|
350
|
+
const prior = this.#read(value.scope, value.operationId);
|
|
351
|
+
if (prior) {
|
|
352
|
+
if (Object.entries(FIELDS).some(([field, column]) => value[field] !== prior[column])) fail('CONFLICT');
|
|
353
|
+
return this.#row(prior);
|
|
354
|
+
}
|
|
355
|
+
if (this.#db.prepare('SELECT count(*) AS n FROM operations').get().n >= this.#maxOperations) fail('JOURNAL_CAPACITY');
|
|
356
|
+
const now = Date.now();
|
|
357
|
+
this.#db.prepare(`INSERT INTO operations(scope,operation_id,input_digest,context_digest,binding_digest,
|
|
358
|
+
action_id,session_id,tool_use_id,state,owner,fingerprint,result_digest,report_state,error_code,created_at,updated_at)
|
|
359
|
+
VALUES (?,?,?,?,?,?,?,?,'prepared',NULL,NULL,NULL,'not_reported',NULL,?,?)`)
|
|
360
|
+
.run(...Object.keys(FIELDS).map(field => value[field]), now, now);
|
|
361
|
+
const after = this.#read(value.scope, value.operationId);
|
|
362
|
+
this.#event('prepare', null, after);
|
|
363
|
+
return this.#row(after);
|
|
364
|
+
});
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
get(scope, operationId) {
|
|
369
|
+
return this.#run(() => {
|
|
370
|
+
identity(scope, operationId);
|
|
371
|
+
return this.#row(this.#read(scope, operationId));
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
claim(scope, operationId, fromStates, nextState, owner) {
|
|
376
|
+
return this.#run(() => {
|
|
377
|
+
identity(scope, operationId);
|
|
378
|
+
if (!isId(owner)) fail('JOURNAL_RECORD');
|
|
379
|
+
if (isProxy(fromStates) || !Array.isArray(fromStates) || fromStates.length !== 1) fail('JOURNAL_TRANSITION');
|
|
380
|
+
const descriptor = Object.getOwnPropertyDescriptor(fromStates, '0');
|
|
381
|
+
if (!descriptor || !Object.hasOwn(descriptor, 'value')) fail('JOURNAL_TRANSITION');
|
|
382
|
+
const fromState = descriptor.value;
|
|
383
|
+
if (!((fromState === 'prepared' && nextState === 'requesting')
|
|
384
|
+
|| (fromState === 'held' && nextState === 'redeeming'))) fail('JOURNAL_TRANSITION');
|
|
385
|
+
return this.#transaction(() => {
|
|
386
|
+
const before = this.#read(scope, operationId);
|
|
387
|
+
if (!before || before.state !== fromState || before.owner !== null) return false;
|
|
388
|
+
const changed = this.#db.prepare(`UPDATE operations SET state=?,owner=?,updated_at=?
|
|
389
|
+
WHERE scope=? AND operation_id=? AND state=? AND owner IS NULL`)
|
|
390
|
+
.run(nextState, owner, Math.max(Date.now(), before.updated_at), scope, operationId, fromState).changes;
|
|
391
|
+
if (changed !== 1) return false;
|
|
392
|
+
this.#event('claim', before, this.#read(scope, operationId));
|
|
393
|
+
return true;
|
|
394
|
+
});
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
settle(scope, operationId, owner, fromState, nextState, patch = {}) {
|
|
399
|
+
return this.#run(() => {
|
|
400
|
+
identity(scope, operationId);
|
|
401
|
+
if (!isId(owner)) fail('JOURNAL_RECORD');
|
|
402
|
+
const reporting = fromState === nextState && ['completed', 'uncertain'].includes(fromState);
|
|
403
|
+
if (!reporting && !SETTLEMENTS.get(fromState)?.includes(nextState)) fail('JOURNAL_TRANSITION');
|
|
404
|
+
const value = validatePatch(patch, reporting);
|
|
405
|
+
return this.#transaction(() => {
|
|
406
|
+
const before = this.#read(scope, operationId);
|
|
407
|
+
if (!before || before.state !== fromState || before.owner !== owner) return false;
|
|
408
|
+
const metadata = { fingerprint: before.fingerprint, resultDigest: before.result_digest,
|
|
409
|
+
reportState: before.report_state, errorCode: before.error_code, ...value };
|
|
410
|
+
const changed = this.#db.prepare(`UPDATE operations SET state=?,owner=?,fingerprint=?,result_digest=?,
|
|
411
|
+
report_state=?,error_code=?,updated_at=? WHERE scope=? AND operation_id=? AND state=? AND owner=?`)
|
|
412
|
+
.run(nextState, nextState === 'held' ? null : owner, metadata.fingerprint, metadata.resultDigest,
|
|
413
|
+
metadata.reportState, metadata.errorCode, Math.max(Date.now(), before.updated_at),
|
|
414
|
+
scope, operationId, fromState, owner).changes;
|
|
415
|
+
if (changed !== 1) return false;
|
|
416
|
+
this.#event('settle', before, this.#read(scope, operationId));
|
|
417
|
+
return true;
|
|
418
|
+
});
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
recoverHeld(scope, operationId, fingerprint) {
|
|
423
|
+
// The caller must independently prove that this exact server action is still pending.
|
|
424
|
+
return this.#run(() => {
|
|
425
|
+
identity(scope, operationId);
|
|
426
|
+
const patch = validatePatch(fingerprint === undefined ? {} : { fingerprint });
|
|
427
|
+
return this.#transaction(() => {
|
|
428
|
+
const before = this.#read(scope, operationId);
|
|
429
|
+
if (!before || !['requesting', 'uncertain_request'].includes(before.state)) return false;
|
|
430
|
+
const nextFingerprint = Object.hasOwn(patch, 'fingerprint') ? patch.fingerprint : before.fingerprint;
|
|
431
|
+
if (before.fingerprint !== null && nextFingerprint !== before.fingerprint) fail('CONFLICT');
|
|
432
|
+
const changed = this.#db.prepare(`UPDATE operations SET state='held',owner=NULL,fingerprint=?,updated_at=?
|
|
433
|
+
WHERE scope=? AND operation_id=? AND state IN ('requesting','uncertain_request')`)
|
|
434
|
+
.run(nextFingerprint, Math.max(Date.now(), before.updated_at), scope, operationId).changes;
|
|
435
|
+
if (changed !== 1) return false;
|
|
436
|
+
this.#event('recover_held', before, this.#read(scope, operationId));
|
|
437
|
+
return true;
|
|
438
|
+
});
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
close() {
|
|
443
|
+
if (!this.#db) return;
|
|
444
|
+
try { this.#db.close(); }
|
|
445
|
+
catch (error) { throw sanitize(error); }
|
|
446
|
+
finally { this.#db = null; }
|
|
447
|
+
}
|
|
448
|
+
}
|