osuite 2.16.0 → 2.18.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_RECOVERY.md +6 -0
- package/GOVERNED_TOOLS.md +130 -25
- package/README.md +23 -0
- package/RELEASE_NOTES.md +11 -0
- package/cli.js +53 -14
- package/governed-tools/amount.mjs +27 -5
- package/governed-tools/authority.mjs +53 -10
- package/governed-tools/contract.mjs +39 -17
- package/governed-tools/executor.mjs +79 -31
- package/governed-tools/owner-receipt.mjs +75 -7
- package/governed-tools/proof-digest.mjs +16 -0
- package/installationIdentity.js +1 -0
- package/native-proof.mjs +56 -5
- package/nativeDoctor.mjs +4 -2
- package/onboardingCli.js +469 -0
- package/package.json +3 -1
- package/projectHooks.js +30 -10
- package/runtime/guard-timeout.mjs +3 -0
- package/runtime/protocol.mjs +6 -3
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { types } from 'node:util';
|
|
2
2
|
import { canonicalJson, safeId, sha256, validatedBaseUrl } from '../runtime/protocol.mjs';
|
|
3
|
-
import { NATIVE_AMOUNT_SCHEMA, agreesWithUsdAmount, usdMinorToMajor, validUsdMapping } from './amount.mjs';
|
|
3
|
+
import { NATIVE_AMOUNT_SCHEMA, agreesWithUsdAmount, nativeAmountIssue, usdMinorToMajor, validNativePath, validUsdMapping } from './amount.mjs';
|
|
4
4
|
|
|
5
5
|
export const CALL_SCHEMA = 'osuite.native_tool_call.v1';
|
|
6
6
|
export const COVERAGE = 'wrapped-call-only';
|
|
@@ -21,6 +21,11 @@ const recoveryMessages = Object.freeze({
|
|
|
21
21
|
});
|
|
22
22
|
|
|
23
23
|
function recoveryGuidance(code, state, details) {
|
|
24
|
+
const amountIssue = nativeAmountIssue(code);
|
|
25
|
+
if (amountIssue) {
|
|
26
|
+
return Object.freeze({ nextStep: code === 'NATIVE_AMOUNT_LEDGER_UNAVAILABLE' ? 'retry_same_operation' : 'inspect_configuration',
|
|
27
|
+
preserveOperationId: true, message: `${amountIssue.reason} ${amountIssue.configuration_hint}` });
|
|
28
|
+
}
|
|
24
29
|
let nextStep;
|
|
25
30
|
if (code === 'ALREADY_COMPLETED' || (state === 'completed' && code !== 'BINDING_MISMATCH')) nextStep = 'read_business_result';
|
|
26
31
|
else if (['OUTCOME_UNKNOWN', 'UNCERTAIN', 'BINDING_MISMATCH', 'CONFLICT'].includes(code)) nextStep = 'reconcile_without_resend';
|
|
@@ -41,13 +46,16 @@ function recoveryGuidance(code, state, details) {
|
|
|
41
46
|
export class GovernedToolError extends Error {
|
|
42
47
|
constructor(code, status = null, details = null) {
|
|
43
48
|
const recovery = recoveryGuidance(code, status?.state, details);
|
|
44
|
-
|
|
49
|
+
const reason = code === 'POLICY_DENIED' && typeof details?.reason === 'string'
|
|
50
|
+
? details.reason.trim().replace(/\s+/g, ' ').slice(0, 1000) : '';
|
|
51
|
+
super(`OSuite ${code}: ${reason ? `${reason} ` : ''}${recovery.message}`);
|
|
45
52
|
this.name = 'GovernedToolError';
|
|
46
53
|
this.code = code;
|
|
47
54
|
this.status = status === null ? null : Object.freeze({ ...status, recovery });
|
|
48
55
|
this.retryAutomatically = false;
|
|
49
56
|
this.recovery = recovery;
|
|
50
|
-
|
|
57
|
+
const hint = nativeAmountIssue(code)?.configuration_hint;
|
|
58
|
+
if (details || hint) this.details = Object.freeze({ ...details, ...(hint ? { configurationHint: hint } : {}) });
|
|
51
59
|
}
|
|
52
60
|
}
|
|
53
61
|
export function reject(code, status, details) { throw new GovernedToolError(code, status, details); }
|
|
@@ -125,22 +133,34 @@ function describe(binding, args) {
|
|
|
125
133
|
return value;
|
|
126
134
|
}
|
|
127
135
|
|
|
136
|
+
function readOwnPath(input, path) {
|
|
137
|
+
return path.reduce((object, key) => object && Object.hasOwn(object, key) ? object[key] : undefined, input);
|
|
138
|
+
}
|
|
139
|
+
|
|
128
140
|
function nativeAmount(binding, native, description, inputDigest) {
|
|
129
|
-
if (
|
|
130
|
-
if (!validUsdMapping(binding.amount))
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
}
|
|
135
|
-
const field = binding.amount.path.at(-1);
|
|
136
|
-
const value = owner && Object.hasOwn(owner, field) ? owner[field] : null;
|
|
141
|
+
if (binding.amount === undefined) return {};
|
|
142
|
+
if (!validUsdMapping(binding.amount)) return { issue: 'NATIVE_AMOUNT_UNSUPPORTED' };
|
|
143
|
+
const { path } = binding.amount;
|
|
144
|
+
const owner = readOwnPath(native.arguments, path.slice(0, -1));
|
|
145
|
+
const value = readOwnPath(owner, path.slice(-1));
|
|
137
146
|
// A binding may also describe non-financial variants. A monetary policy
|
|
138
147
|
// independently requires evidence before any of those variants can execute.
|
|
139
|
-
if (value == null
|
|
140
|
-
if (usdMinorToMajor(value) === null
|
|
141
|
-
|
|
142
|
-
|
|
148
|
+
if (value == null) return {};
|
|
149
|
+
if (value !== 0 && usdMinorToMajor(value) === null) return { issue: 'NATIVE_AMOUNT_INVALID' };
|
|
150
|
+
if (!agreesWithUsdAmount(owner, value) || !agreesWithUsdAmount(native.arguments, value)
|
|
151
|
+
|| !agreesWithUsdAmount(description.input_summary, value)) return { issue: 'NATIVE_AMOUNT_CONFLICT' };
|
|
152
|
+
if (value === 0) return {};
|
|
153
|
+
const amount = { schema_version: NATIVE_AMOUNT_SCHEMA, mapping: binding.amount, value,
|
|
143
154
|
tool_name: native.name, binding_revision: binding.revision, input_digest: inputDigest };
|
|
155
|
+
if (binding.businessKey === undefined) return { amount };
|
|
156
|
+
const keyPath = binding.businessKey?.path;
|
|
157
|
+
if (!validNativePath(keyPath) || Object.keys(binding.businessKey).length !== 1) return { issue: 'NATIVE_AMOUNT_KEY_INVALID' };
|
|
158
|
+
const key = readOwnPath(native.arguments, keyPath);
|
|
159
|
+
const name = keyPath.at(-1);
|
|
160
|
+
if (!id(key) || [native.arguments, description.input_summary].some(source => source && Object.hasOwn(source, name) && source[name] !== key)) {
|
|
161
|
+
return { issue: 'NATIVE_AMOUNT_KEY_INVALID' };
|
|
162
|
+
}
|
|
163
|
+
return { amount: { ...amount, business_key: { path: keyPath, value_digest: sha256(canonicalJson(key)) } } };
|
|
144
164
|
}
|
|
145
165
|
|
|
146
166
|
export function makeInvocation({ config, namespace, bindings, operationId, params }) {
|
|
@@ -156,9 +176,10 @@ export function makeInvocation({ config, namespace, bindings, operationId, param
|
|
|
156
176
|
// The historical Hook helper normalizes null to {}. Native calls must retain
|
|
157
177
|
// every JSON value exactly, including that distinction.
|
|
158
178
|
const inputDigest = sha256(canonicalJson({ tool_name: native.name, tool_input: native.arguments }));
|
|
159
|
-
const amount = nativeAmount(binding, native, description, inputDigest);
|
|
179
|
+
const { amount, issue } = nativeAmount(binding, native, description, inputDigest);
|
|
160
180
|
const bindingDigest = sha256(canonicalJson({ name: native.name, revision: binding.revision, description,
|
|
161
|
-
...(binding.amount ? { amountMapping: binding.amount }
|
|
181
|
+
...(binding.amount === undefined ? {} : { amountMapping: binding.amount }),
|
|
182
|
+
...(binding.businessKey === undefined ? {} : { businessKey: binding.businessKey }),
|
|
162
183
|
...(binding.ownerReceipt ? { nativeResource: binding.ownerReceipt.resource } : {}),
|
|
163
184
|
...(binding.delegation ? { delegationRequired: true } : {}),
|
|
164
185
|
...(binding.recovery ? { recovery: { revision: binding.recovery.revision,
|
|
@@ -171,6 +192,7 @@ export function makeInvocation({ config, namespace, bindings, operationId, param
|
|
|
171
192
|
const context = jsonSnapshot({ ...description, input_summary: inputSummary, action_id: actionId,
|
|
172
193
|
agent_id: config.agentId, runtime_session_id: sessionId, tool_use_id: toolUseId,
|
|
173
194
|
...(amount ? { native_amount: { ...amount, binding_digest: bindingDigest } } : {}),
|
|
195
|
+
...(issue ? { native_amount_issue: issue } : {}),
|
|
174
196
|
...(binding.ownerReceipt ? { native_resource: { ...binding.ownerReceipt.resource, input_digest: inputDigest } } : {}),
|
|
175
197
|
tool_input_digest: inputDigest, runtime_family: 'sdk_tool_runtime', adapter_mode: 'sdk_wrapper' });
|
|
176
198
|
return Object.freeze({ params: native, context, marker, record: Object.freeze({ scope, operationId,
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createPrivateKey, randomUUID } from 'node:crypto';
|
|
2
|
+
import { addAbortListener } from 'node:events';
|
|
2
3
|
import { types } from 'node:util';
|
|
3
4
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
4
5
|
import { canonicalJson, safeId, sha256, validatedBaseUrl } from '../runtime/protocol.mjs';
|
|
@@ -7,8 +8,7 @@ import { OperationJournal } from './journal.mjs';
|
|
|
7
8
|
import { createStudioAuthority } from './authority.mjs';
|
|
8
9
|
import { GovernedToolError, jsonSnapshot, makeInvocation, publicStatus, reject, scopeFor } from './contract.mjs';
|
|
9
10
|
import { recoveryAdapter, recoveryScope, makeRecoveryInvocation, observeEvidence, validateEvidence, checkRecoveryAuthority } from './recovery.mjs';
|
|
10
|
-
import {
|
|
11
|
-
import { ownerReceiptKey, verifyOwnerReceipt } from './owner-receipt.mjs';
|
|
11
|
+
import { ownerReceiptKey, verifyOwnerClosure, verifyOwnerReceipt, OWNER_CLOSURE_RECEIPT_SCHEMA, OWNER_RECEIPT_SCHEMA } from './owner-receipt.mjs';
|
|
12
12
|
|
|
13
13
|
const signalAborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
|
|
14
14
|
const terminalCodes = Object.freeze({ denied: 'POLICY_DENIED', expired: 'APPROVAL_EXPIRED', cancelled: 'CANCELLED' });
|
|
@@ -60,9 +60,13 @@ function registrySnapshot(bindings) {
|
|
|
60
60
|
|| typeof fields.describe.value !== 'function' || types.isProxy(fields.describe.value)) reject('INVALID_MAPPING');
|
|
61
61
|
let amount;
|
|
62
62
|
if (fields.amount) {
|
|
63
|
-
if (!Object.hasOwn(fields.amount, 'value')) reject('
|
|
64
|
-
try { amount = jsonSnapshot(fields.amount.value, 1024); } catch { reject('
|
|
65
|
-
|
|
63
|
+
if (!Object.hasOwn(fields.amount, 'value')) reject('NATIVE_AMOUNT_UNSUPPORTED');
|
|
64
|
+
try { amount = jsonSnapshot(fields.amount.value, 1024); } catch { reject('NATIVE_AMOUNT_UNSUPPORTED'); }
|
|
65
|
+
}
|
|
66
|
+
let businessKey;
|
|
67
|
+
if (fields.businessKey) {
|
|
68
|
+
if (!Object.hasOwn(fields.businessKey, 'value')) reject('NATIVE_AMOUNT_KEY_INVALID');
|
|
69
|
+
try { businessKey = jsonSnapshot(fields.businessKey.value, 1024); } catch { reject('NATIVE_AMOUNT_KEY_INVALID'); }
|
|
66
70
|
}
|
|
67
71
|
const receipt = fields.ownerReceipt;
|
|
68
72
|
const delegation = fields.delegation?.value;
|
|
@@ -72,16 +76,20 @@ function registrySnapshot(bindings) {
|
|
|
72
76
|
if (!Object.hasOwn(receipt, 'value') || !receipt.value || types.isProxy(receipt.value)
|
|
73
77
|
|| ![Object.prototype, null].includes(Object.getPrototypeOf(receipt.value))) reject('INVALID_MAPPING');
|
|
74
78
|
const properties = Object.getOwnPropertyDescriptors(receipt.value);
|
|
75
|
-
const
|
|
76
|
-
if (
|
|
77
|
-
||
|
|
78
|
-
|
|
79
|
+
const required = ['resourceId', 'publicKey', 'query'];
|
|
80
|
+
if (required.some(key => !Object.hasOwn(properties, key))
|
|
81
|
+
|| Reflect.ownKeys(properties).some(key => ![...required, 'schemaVersion'].includes(key)
|
|
82
|
+
|| !Object.hasOwn(properties[key], 'value'))) reject('INVALID_MAPPING');
|
|
83
|
+
const { resourceId, publicKey, query, schemaVersion = OWNER_RECEIPT_SCHEMA } = receipt.value;
|
|
79
84
|
const signer = ownerReceiptKey(publicKey);
|
|
80
|
-
if (!signer || !safeId(resourceId) || resourceId.length > 128 || typeof query !== 'function' || types.isProxy(query)
|
|
81
|
-
|
|
85
|
+
if (!signer || !safeId(resourceId) || resourceId.length > 128 || typeof query !== 'function' || types.isProxy(query)
|
|
86
|
+
|| ![OWNER_RECEIPT_SCHEMA, OWNER_CLOSURE_RECEIPT_SCHEMA].includes(schemaVersion)) reject('INVALID_MAPPING');
|
|
87
|
+
const resource = Object.freeze({ resource_id: resourceId, key_id: signer.id,
|
|
88
|
+
...(schemaVersion === OWNER_CLOSURE_RECEIPT_SCHEMA ? { receipt_schema: schemaVersion } : {}) });
|
|
89
|
+
ownerReceipt = Object.freeze({ resource, publicKey, query });
|
|
82
90
|
}
|
|
83
91
|
Object.defineProperty(result, name, { value: Object.freeze({ revision: fields.revision.value,
|
|
84
|
-
describe: fields.describe.value, amount, ownerReceipt, delegation, recovery: recoveryAdapter(fields.recovery) }), enumerable: true });
|
|
92
|
+
describe: fields.describe.value, amount, businessKey, ownerReceipt, delegation, recovery: recoveryAdapter(fields.recovery) }), enumerable: true });
|
|
85
93
|
}
|
|
86
94
|
return Object.freeze(result);
|
|
87
95
|
}
|
|
@@ -92,6 +100,29 @@ function publicError(error) {
|
|
|
92
100
|
reject('OUTCOME_UNKNOWN');
|
|
93
101
|
}
|
|
94
102
|
|
|
103
|
+
async function queryOwner(query, request, callerSignal) {
|
|
104
|
+
const deadline = new AbortController();
|
|
105
|
+
const signal = callerSignal ? AbortSignal.any([deadline.signal, callerSignal]) : deadline.signal;
|
|
106
|
+
const timer = setTimeout(() => deadline.abort(), 5000);
|
|
107
|
+
let subscription;
|
|
108
|
+
try {
|
|
109
|
+
if (signal.aborted) return null;
|
|
110
|
+
const stopped = new Promise(resolve => { subscription = addAbortListener(signal, () => resolve(null)); });
|
|
111
|
+
const pending = Promise.resolve().then(() => query(Object.freeze({ ...request, signal })));
|
|
112
|
+
const receipt = await Promise.race([pending, stopped]);
|
|
113
|
+
return signal.aborted ? null : jsonSnapshot(receipt, 8192);
|
|
114
|
+
} catch { return null; }
|
|
115
|
+
finally {
|
|
116
|
+
clearTimeout(timer);
|
|
117
|
+
subscription?.[Symbol.dispose]();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function ownerScope(resource, orgId, actionId) {
|
|
122
|
+
const { receipt_schema: _schema, ...scope } = resource;
|
|
123
|
+
return { ...scope, org_id: orgId, action_id: actionId };
|
|
124
|
+
}
|
|
125
|
+
|
|
95
126
|
export function createGovernedTools({ config: rawConfig, namespace, journalPath, bindings: rawBindings,
|
|
96
127
|
journalOptions = {}, initializeJournal = false } = {}) {
|
|
97
128
|
if (Number(process.versions.node.split('.')[0]) !== 24) reject('NODE_24_REQUIRED');
|
|
@@ -145,6 +176,10 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
|
|
|
145
176
|
|
|
146
177
|
async function perform(invocation, execute, { waitMs, signal, aborted }, recovery = null) {
|
|
147
178
|
const { scope, operationId } = invocation.record;
|
|
179
|
+
const resource = invocation.context.native_resource;
|
|
180
|
+
const args = resource?.receipt_schema === OWNER_CLOSURE_RECEIPT_SCHEMA
|
|
181
|
+
? [invocation.params, Object.freeze(ownerScope(resource, config.orgId, invocation.record.actionId))]
|
|
182
|
+
: [invocation.params];
|
|
148
183
|
const local = operationId => {
|
|
149
184
|
const record = journal.get(scope, operationId);
|
|
150
185
|
return record && { ...record, recovery: invocation.recovery, nativeAmount: invocation.context.native_amount,
|
|
@@ -187,7 +222,7 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
|
|
|
187
222
|
|| !action.approved_by || !action.approved_at) reject('OUTCOME_UNKNOWN', status(record));
|
|
188
223
|
}
|
|
189
224
|
let admitted;
|
|
190
|
-
try { admitted = await authority.admit(invocation, journal, owner, aborted); }
|
|
225
|
+
try { admitted = await authority.admit(invocation, journal, owner, aborted, signal); }
|
|
191
226
|
catch (error) {
|
|
192
227
|
if (error instanceof GovernedToolError) throw new GovernedToolError(error.code, status(local(operationId)), error.details);
|
|
193
228
|
reject('OUTCOME_UNKNOWN', status(local(operationId)));
|
|
@@ -222,7 +257,7 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
|
|
|
222
257
|
reject(aborted() ? 'ABORTED' : 'OUTCOME_UNKNOWN', status(local(operationId)));
|
|
223
258
|
}
|
|
224
259
|
let result, resultDigest = null, state = 'completed', thrown = false;
|
|
225
|
-
try { result = await execute(
|
|
260
|
+
try { result = await execute(...args); }
|
|
226
261
|
catch { thrown = true; state = 'uncertain'; }
|
|
227
262
|
if (!thrown) {
|
|
228
263
|
if (result !== null && typeof result === 'object') {
|
|
@@ -273,9 +308,9 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
|
|
|
273
308
|
const parent = makeInvocation({ config, namespace, bindings, operationId, params });
|
|
274
309
|
const settings = runOptions(options);
|
|
275
310
|
if (settings.aborted()) reject('ABORTED');
|
|
276
|
-
const adapter = bindings[parent.params.name]
|
|
311
|
+
const { recovery: adapter, ownerReceipt } = bindings[parent.params.name];
|
|
277
312
|
const record = journal.getBound((await bindDelegation(parent)).record);
|
|
278
|
-
if (!adapter) reject('RECOVERY_UNSUPPORTED', status(record));
|
|
313
|
+
if (!adapter || ownerReceipt?.resource.receipt_schema === OWNER_CLOSURE_RECEIPT_SCHEMA) reject('RECOVERY_UNSUPPORTED', status(record));
|
|
279
314
|
if (!record) reject('RECOVERY_UNAVAILABLE');
|
|
280
315
|
if (record.state !== 'uncertain') { stopForState(record); reject('RECOVERY_UNAVAILABLE', status(record)); }
|
|
281
316
|
const { invocation: childInvocation, request } = makeRecoveryInvocation(parent, adapter);
|
|
@@ -322,8 +357,10 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
|
|
|
322
357
|
if (terminal) failureCode = terminalCodes[terminal];
|
|
323
358
|
}
|
|
324
359
|
const attempt = recoveryStatus(operationId);
|
|
360
|
+
const legacyReceipt = observed.body?.owner_receipt?.claims?.schema_version === OWNER_RECEIPT_SCHEMA
|
|
361
|
+
? observed.body.owner_receipt : null;
|
|
325
362
|
return Object.freeze({ ...publicStatus(record, config.baseUrl, failureCode), ...(attempt ? { recoveryAttempt: attempt } : {}),
|
|
326
|
-
...(
|
|
363
|
+
...(legacyReceipt ? { ownerReceipt: legacyReceipt } : {}), remote: Object.freeze({ available: observed.available,
|
|
327
364
|
status: observed.available ? observed.action.status : null, bindingMismatch: observed.mismatch === true }) });
|
|
328
365
|
});
|
|
329
366
|
},
|
|
@@ -339,23 +376,34 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
|
|
|
339
376
|
if (settings.aborted()) reject('ABORTED', status(localRecord));
|
|
340
377
|
if (!['dispatching', 'uncertain', 'completed'].includes(localRecord.state)) return unknown;
|
|
341
378
|
const nativeResource = invocation.context.native_resource;
|
|
379
|
+
const schema = nativeResource.receipt_schema;
|
|
342
380
|
const record = { ...localRecord, nativeResource, nativeAmount: invocation.context.native_amount };
|
|
343
|
-
const expected =
|
|
381
|
+
const expected = ownerScope(nativeResource, config.orgId, record.actionId);
|
|
344
382
|
const observed = await authority.read(record);
|
|
345
|
-
if (!observed.available) return unknown;
|
|
346
|
-
const
|
|
347
|
-
|
|
348
|
-
if (
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
383
|
+
if (!observed.available || settings.aborted()) return unknown;
|
|
384
|
+
const startedAt = observed.action.timestamp_start;
|
|
385
|
+
const context = observed.body.owner_closure_context;
|
|
386
|
+
if (schema && (!/^sha256:[a-f0-9]{64}$/.test(context?.previous_proof_digest || '')
|
|
387
|
+
|| !/^[a-f0-9]{64}$/.test(context?.observation_digest || '') || !Number.isFinite(Date.parse(startedAt)))) return unknown;
|
|
388
|
+
const queryScope = { ...expected, ...(schema ? { schema_version: schema,
|
|
389
|
+
previous_proof_digest: context.previous_proof_digest, observation_digest: context.observation_digest } : {}) };
|
|
390
|
+
const validReceipt = receipt => verifyOwnerReceipt(receipt, queryScope, adapter.publicKey, { startedAt });
|
|
391
|
+
const validStored = body => schema
|
|
392
|
+
? body?.owner_receipt?.claims?.observation_digest === context.observation_digest
|
|
393
|
+
&& body?.owner_closure?.original?.timestamp_start === new Date(startedAt).toISOString()
|
|
394
|
+
&& verifyOwnerClosure(body.owner_closure, body.owner_receipt, expected, adapter.publicKey)
|
|
395
|
+
: validReceipt(body?.owner_receipt);
|
|
396
|
+
let body = observed.body;
|
|
397
|
+
if (!validStored(body)) {
|
|
398
|
+
const submitted = await queryOwner(adapter.query, { ...queryScope, operationId }, settings.signal);
|
|
399
|
+
if (!validReceipt(submitted) || settings.aborted()) return unknown;
|
|
400
|
+
body = await authority.closeOwnerOutcome(record, submitted);
|
|
401
|
+
if (!validStored(body) || body.owner_receipt.claims.outcome !== submitted.claims.outcome
|
|
402
|
+
|| body.owner_receipt.claims.resource_reference !== submitted.claims.resource_reference
|
|
403
|
+
|| body.owner_receipt.claims.previous_proof_digest !== submitted.claims.previous_proof_digest) return unknown;
|
|
357
404
|
}
|
|
358
|
-
return Object.freeze({ ...status(localRecord), outcome:
|
|
405
|
+
return Object.freeze({ ...status(localRecord), outcome: body.owner_receipt.claims.outcome, ownerReceipt: body.owner_receipt,
|
|
406
|
+
...(schema ? { ownerClosure: body.owner_closure } : {}) });
|
|
359
407
|
});
|
|
360
408
|
},
|
|
361
409
|
close() { if (!closed) { closed = true; if (inFlight === 0) journal.close(); } },
|
|
@@ -2,8 +2,24 @@ import { createPublicKey, verify } from 'node:crypto';
|
|
|
2
2
|
import { canonicalJson, isObject, safeId, sha256 } from '../runtime/protocol.mjs';
|
|
3
3
|
|
|
4
4
|
export const OWNER_RECEIPT_SCHEMA = 'osuite.native_owner_receipt.v1';
|
|
5
|
+
export const OWNER_CLOSURE_RECEIPT_SCHEMA = 'osuite.native_owner_receipt.v2';
|
|
6
|
+
const closureSchema = 'osuite.native_owner_closure.v1';
|
|
5
7
|
const digest = /^[a-f0-9]{64}$/;
|
|
8
|
+
const proofDigest = /^sha256:[a-f0-9]{64}$/;
|
|
6
9
|
const timestamp = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?Z$/;
|
|
10
|
+
const resourceReference = /^[A-Za-z0-9_:/.-]{1,240}$/;
|
|
11
|
+
const scopeIds = ['org_id', 'action_id', 'resource_id'];
|
|
12
|
+
const scopeDigests = ['input_digest', 'key_id'];
|
|
13
|
+
const receiptFields = [...scopeIds, ...scopeDigests, 'schema_version', 'complete', 'final', 'outcome', 'receipt_id', 'observed_at'];
|
|
14
|
+
const closureFields = ['resource_reference', 'previous_proof_digest', 'observation_digest'];
|
|
15
|
+
|
|
16
|
+
function exactFields(value, fields) {
|
|
17
|
+
return isObject(value) && Object.keys(value).length === fields.length && fields.every(field => Object.hasOwn(value, field));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function matches(value, pattern) {
|
|
21
|
+
return typeof value === 'string' && pattern.test(value);
|
|
22
|
+
}
|
|
7
23
|
|
|
8
24
|
function bytes(value, size) {
|
|
9
25
|
if (typeof value !== 'string' || value.length !== Math.ceil(size / 3) * 4) return null;
|
|
@@ -21,20 +37,72 @@ export function ownerReceiptKey(value) {
|
|
|
21
37
|
}
|
|
22
38
|
|
|
23
39
|
export function ownerReceiptPayload(claims) {
|
|
24
|
-
return Buffer.from(`${
|
|
40
|
+
return Buffer.from(`${claims.schema_version}\n${canonicalJson(claims)}`);
|
|
25
41
|
}
|
|
26
42
|
|
|
27
43
|
export function verifyOwnerReceipt(receipt, expected, publicKey, { startedAt, now = Date.now() } = {}) {
|
|
28
44
|
const { claims, signature } = receipt || {};
|
|
29
|
-
|
|
30
|
-
|
|
45
|
+
const schema = expected.schema_version ?? OWNER_RECEIPT_SCHEMA;
|
|
46
|
+
const closure = schema === OWNER_CLOSURE_RECEIPT_SCHEMA;
|
|
47
|
+
if ((!closure && schema !== OWNER_RECEIPT_SCHEMA) || !exactFields(receipt, ['claims', 'signature'])
|
|
48
|
+
|| !exactFields(claims, closure ? [...receiptFields, ...closureFields] : receiptFields)
|
|
49
|
+
|| claims.schema_version !== schema || claims.complete !== true || claims.final !== true
|
|
31
50
|
|| !['committed', 'absent'].includes(claims.outcome) || !safeId(claims.receipt_id)
|
|
32
|
-
|| !
|
|
33
|
-
|| !
|
|
34
|
-
|| !
|
|
51
|
+
|| !scopeIds.every(key => safeId(claims[key]) && claims[key] === expected[key])
|
|
52
|
+
|| !scopeDigests.every(key => matches(claims[key], digest) && claims[key] === expected[key])
|
|
53
|
+
|| !matches(claims.observed_at, timestamp)) return false;
|
|
54
|
+
if (closure && (!matches(claims.previous_proof_digest, proofDigest) || claims.previous_proof_digest !== expected.previous_proof_digest
|
|
55
|
+
|| !matches(claims.observation_digest, digest) || claims.observation_digest !== expected.observation_digest
|
|
56
|
+
|| (claims.outcome === 'absent' ? claims.resource_reference !== null : !matches(claims.resource_reference, resourceReference)))) return false;
|
|
35
57
|
const date = Date.parse(claims.observed_at);
|
|
36
|
-
|
|
58
|
+
const start = startedAt instanceof Date ? startedAt.getTime() : Date.parse(startedAt);
|
|
59
|
+
if (!Number.isFinite(date) || date > now + 30000 || (startedAt !== undefined && !(date >= start))) return false;
|
|
60
|
+
if (closure && (startedAt == null || claims.observed_at !== new Date(date).toISOString())) return false;
|
|
37
61
|
const signer = ownerReceiptKey(publicKey);
|
|
38
62
|
const sig = bytes(signature, 64);
|
|
39
63
|
return Boolean(signer?.id === claims.key_id && sig && verify(null, ownerReceiptPayload(claims), signer.key, sig));
|
|
40
64
|
}
|
|
65
|
+
|
|
66
|
+
function isoTime(value) {
|
|
67
|
+
const time = value instanceof Date ? value.getTime() : Date.parse(value);
|
|
68
|
+
return Number.isFinite(time) ? new Date(time).toISOString() : null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function ownerClosureObservation(action, routeDecision) {
|
|
72
|
+
return {
|
|
73
|
+
status: action.status,
|
|
74
|
+
timestamp_start: isoTime(action.timestamp_start),
|
|
75
|
+
timestamp_end: isoTime(action.timestamp_end),
|
|
76
|
+
error_message: action.error_message ?? null,
|
|
77
|
+
route_decision: routeDecision ?? null,
|
|
78
|
+
approval_decision: action.approval_decision ?? null,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function ownerClosureContext(previousProofDigest, original) {
|
|
83
|
+
return { previous_proof_digest: previousProofDigest, observation_digest: sha256(canonicalJson(original)) };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function buildOwnerClosure(claims, original) {
|
|
87
|
+
return {
|
|
88
|
+
schema_version: closureSchema,
|
|
89
|
+
source: 'resource_owner',
|
|
90
|
+
closed_by: { resource_id: claims.resource_id },
|
|
91
|
+
authentication: { method: 'ed25519', key_id: claims.key_id },
|
|
92
|
+
previous_proof_digest: claims.previous_proof_digest,
|
|
93
|
+
original,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function verifyOwnerClosure(closure, receipt, scope, publicKey) {
|
|
98
|
+
const original = closure?.original;
|
|
99
|
+
if (!isObject(original) || !['running', 'failed', 'completed'].includes(original.status)
|
|
100
|
+
|| !['allow', null].includes(original.approval_decision)
|
|
101
|
+
|| typeof original.route_decision !== 'string'
|
|
102
|
+
|| (original.error_message !== null && typeof original.error_message !== 'string')
|
|
103
|
+
|| canonicalJson(original) !== canonicalJson(ownerClosureObservation(original, original.route_decision))) return false;
|
|
104
|
+
const context = ownerClosureContext(closure.previous_proof_digest, original);
|
|
105
|
+
return verifyOwnerReceipt(receipt, { ...scope, ...context, schema_version: OWNER_CLOSURE_RECEIPT_SCHEMA }, publicKey,
|
|
106
|
+
{ startedAt: original.timestamp_start })
|
|
107
|
+
&& canonicalJson(closure) === canonicalJson(buildOwnerClosure(receipt.claims, original));
|
|
108
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export function proofManifestPayload(proof) {
|
|
2
|
+
return {
|
|
3
|
+
actionEnvelope: proof.action_envelope ?? null,
|
|
4
|
+
riskResult: proof.risk_result ?? null,
|
|
5
|
+
policySnapshot: proof.policy_snapshot ?? null,
|
|
6
|
+
actionCertificate: proof.action_certificate ?? null,
|
|
7
|
+
routeDecision: proof.route_decision ?? proof.action_certificate?.route_decision ?? proof.policy_snapshot?.effective_decision ?? null,
|
|
8
|
+
approvals: Array.isArray(proof.approvals) ? proof.approvals : [],
|
|
9
|
+
approval_receipts: Array.isArray(proof.approval_receipts) ? proof.approval_receipts : [],
|
|
10
|
+
runtime_receipts: Array.isArray(proof.runtime_receipts) ? proof.runtime_receipts : [],
|
|
11
|
+
attestation: proof.attestation ?? null,
|
|
12
|
+
execution: proof.execution ?? null,
|
|
13
|
+
outcome: proof.outcome ?? null,
|
|
14
|
+
external_verifier_refs: Array.isArray(proof.external_verifier_refs) ? proof.external_verifier_refs : [],
|
|
15
|
+
};
|
|
16
|
+
}
|
package/installationIdentity.js
CHANGED
|
@@ -6,6 +6,7 @@ import { prepareCredentialFile, readCredentialFile, removeCredentialFile, writeC
|
|
|
6
6
|
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
7
7
|
const PREFIX = { codex: 'codex-runtime', claude: 'claude-code-runtime', cursor: 'cursor-runtime', mcp: 'mcp-runtime', sdk: 'sdk-runtime' };
|
|
8
8
|
export const SDK_ENV_PATH = '.osuite/.env';
|
|
9
|
+
export const TERMINAL_ENV_PATH = '.osuite/terminal/.env';
|
|
9
10
|
export const MCP_ENV_PATH = '.osuite/mcp/.env';
|
|
10
11
|
export const MCP_MIGRATION_PATH = '.osuite/.env.migrate-mcp.json';
|
|
11
12
|
const BUNDLE_FILES = { env: '', identity: '.identity.json', journal: '.connect.json' };
|
package/native-proof.mjs
CHANGED
|
@@ -1,12 +1,56 @@
|
|
|
1
1
|
import { sign, verify } from 'node:crypto';
|
|
2
2
|
import { canonicalJson, isObject, sha256 } from './runtime/protocol.mjs';
|
|
3
|
-
import { ownerReceiptKey, verifyOwnerReceipt
|
|
3
|
+
import { ownerClosureObservation, ownerReceiptKey, verifyOwnerClosure, verifyOwnerReceipt,
|
|
4
|
+
OWNER_CLOSURE_RECEIPT_SCHEMA } from './governed-tools/owner-receipt.mjs';
|
|
5
|
+
import { proofManifestPayload } from './governed-tools/proof-digest.mjs';
|
|
6
|
+
|
|
7
|
+
export { OWNER_CLOSURE_RECEIPT_SCHEMA, ownerReceiptPayload } from './governed-tools/owner-receipt.mjs';
|
|
4
8
|
|
|
5
9
|
export const NATIVE_PROOF_TYPE = 'application/vnd.in-toto+json';
|
|
6
10
|
export const NATIVE_CHECKPOINT_TYPE = 'application/vnd.osuite.native-checkpoint+json';
|
|
7
11
|
export const NATIVE_CHECKPOINT_SCOPE = 'registered_native_tools';
|
|
8
12
|
const hex = /^[0-9a-f]{64}$/;
|
|
9
13
|
const actionId = /^act_[0-9a-f]{64}$/;
|
|
14
|
+
const fail = code => ({ verified: false, code });
|
|
15
|
+
const proofDigest = payload => `sha256:${sha256(canonicalJson(payload))}`;
|
|
16
|
+
|
|
17
|
+
export function verifyNativeOwnerClosure(bundle, ownerPublicKey) {
|
|
18
|
+
const exported = bundle?.export_type === 'osuite.proof_export.v1';
|
|
19
|
+
const proof = exported ? bundle.proof_bundle : bundle;
|
|
20
|
+
const outcome = proof?.outcome;
|
|
21
|
+
const { native_owner_closure: closure, native_owner_receipt: receipt, ...priorOutcome } = outcome || {};
|
|
22
|
+
if (!closure) return fail('OWNER_CLOSURE_MISSING');
|
|
23
|
+
const envelope = proof.action_envelope;
|
|
24
|
+
const resource = envelope?.native_resource;
|
|
25
|
+
let marker;
|
|
26
|
+
try { marker = JSON.parse(envelope.input_summary)?.osuite_native_call; } catch { return fail('INVALID_OWNER_CLOSURE'); }
|
|
27
|
+
const scope = { ...resource, org_id: envelope.org_id, action_id: envelope.action_id };
|
|
28
|
+
if (proof.schema_version !== 'osuite.proof_bundle.v1' || proof.derived_from_legacy
|
|
29
|
+
|| envelope.schema_version !== 'osuite.action_envelope.v1' || envelope.runtime_family !== 'sdk_tool_runtime'
|
|
30
|
+
|| envelope.adapter_mode !== 'sdk_wrapper' || !actionId.test(envelope.action_id || '')
|
|
31
|
+
|| resource?.receipt_schema !== OWNER_CLOSURE_RECEIPT_SCHEMA
|
|
32
|
+
|| marker?.schema_version !== 'osuite.native_tool_call.v1' || marker.input_digest !== resource.input_digest
|
|
33
|
+
|| !verifyOwnerClosure(closure, receipt, scope, ownerPublicKey)) return fail('INVALID_OWNER_CLOSURE');
|
|
34
|
+
const original = closure.original;
|
|
35
|
+
const payload = proofManifestPayload(proof);
|
|
36
|
+
if (original.route_decision !== payload.routeDecision || original.status !== outcome.status
|
|
37
|
+
|| original.status !== payload.execution?.status || original.timestamp_end !== (payload.execution.timestamp_end ?? null)
|
|
38
|
+
|| proof.manifest?.digest !== proofDigest(payload)) return fail('OWNER_CLOSURE_PROOF_MISMATCH');
|
|
39
|
+
if (exported && (bundle.action_id !== scope.action_id || bundle.org_id !== scope.org_id
|
|
40
|
+
|| bundle.action?.action_id !== scope.action_id || bundle.action?.org_id !== scope.org_id
|
|
41
|
+
|| canonicalJson(ownerClosureObservation(bundle.action, payload.routeDecision)) !== canonicalJson(original))) {
|
|
42
|
+
return fail('OWNER_CLOSURE_PROOF_MISMATCH');
|
|
43
|
+
}
|
|
44
|
+
const prior = { ...payload, outcome: priorOutcome };
|
|
45
|
+
if (proofDigest(prior) !== closure.previous_proof_digest) {
|
|
46
|
+
// A later reviewer can append a separate confirmation.
|
|
47
|
+
const { resource_confirmation: confirmation, ...beforeReview } = priorOutcome;
|
|
48
|
+
if (confirmation?.source !== 'workspace_reviewer'
|
|
49
|
+
|| proofDigest({ ...prior, outcome: beforeReview }) !== closure.previous_proof_digest) return fail('OWNER_CLOSURE_CHAIN_MISMATCH');
|
|
50
|
+
}
|
|
51
|
+
return { verified: true, actionId: scope.action_id, inputDigest: scope.input_digest, outcome: receipt.claims.outcome,
|
|
52
|
+
resourceReference: receipt.claims.resource_reference };
|
|
53
|
+
}
|
|
10
54
|
|
|
11
55
|
function pae(type, data) {
|
|
12
56
|
return Buffer.concat([Buffer.from(`DSSEv1 ${Buffer.byteLength(type)} ${type} ${data.length} `), data]);
|
|
@@ -67,7 +111,6 @@ function validDelegation(predicate, issuers) {
|
|
|
67
111
|
}
|
|
68
112
|
|
|
69
113
|
export function verifyNativeProofCohort(records, roots, checkpoint) {
|
|
70
|
-
const fail = code => ({ verified: false, code });
|
|
71
114
|
const proofKey = ownerReceiptKey(roots?.proof), checkpointKey = ownerReceiptKey(roots?.checkpoint);
|
|
72
115
|
if (!proofKey || !checkpointKey || proofKey.id === checkpointKey.id || !Array.isArray(roots.owners)) return fail('INVALID_TRUST_ROOTS');
|
|
73
116
|
const opened = open(checkpoint, NATIVE_CHECKPOINT_TYPE, checkpointKey);
|
|
@@ -92,14 +135,22 @@ export function verifyNativeProofCohort(records, roots, checkpoint) {
|
|
|
92
135
|
if (seen.has(p.action_id)) return fail('DUPLICATE_RECORD');
|
|
93
136
|
if (!validDelegation(p, roots.issuers)) return fail('INVALID_DELEGATION');
|
|
94
137
|
if (p.outcome === 'unknown') {
|
|
95
|
-
if (p.owner_receipt !== null) return fail('INVALID_OWNER_RECEIPT');
|
|
138
|
+
if (p.owner_receipt !== null || p.owner_closure != null) return fail('INVALID_OWNER_RECEIPT');
|
|
96
139
|
} else {
|
|
97
140
|
const resource = p.native_resource;
|
|
98
141
|
const pins = roots.owners.filter(root => root && resource && root.resource_id === resource.resource_id
|
|
99
142
|
&& ownerReceiptKey(root.public_key)?.id === resource.key_id);
|
|
100
143
|
if (!resource || resource.input_digest !== p.input_digest || pins.length !== 1 || [proofKey.id, checkpointKey.id].includes(resource.key_id)
|
|
101
|
-
|| p.owner_receipt?.claims?.outcome !== p.outcome
|
|
102
|
-
|
|
144
|
+
|| p.owner_receipt?.claims?.outcome !== p.outcome) return fail('INVALID_OWNER_RECEIPT');
|
|
145
|
+
const scope = { ...resource, org_id: p.org_id, action_id: p.action_id };
|
|
146
|
+
const publicKey = pins[0].public_key;
|
|
147
|
+
const valid = resource.receipt_schema === OWNER_CLOSURE_RECEIPT_SCHEMA
|
|
148
|
+
? verifyOwnerClosure(p.owner_closure, p.owner_receipt, scope, publicKey)
|
|
149
|
+
&& canonicalJson(p.owner_closure.original) === canonicalJson(ownerClosureObservation({
|
|
150
|
+
...p.execution, timestamp_start: p.timestamp_start,
|
|
151
|
+
}, p.route_decision))
|
|
152
|
+
: !p.owner_closure && verifyOwnerReceipt(p.owner_receipt, scope, publicKey, { startedAt: p.timestamp_start });
|
|
153
|
+
if (!valid) return fail('INVALID_OWNER_RECEIPT');
|
|
103
154
|
}
|
|
104
155
|
seen.set(p.action_id, decoded.digest);
|
|
105
156
|
outcomes[p.outcome]++;
|
package/nativeDoctor.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createPrivateKey } from 'node:crypto';
|
|
2
2
|
import { inspectCredentialFile, readCredentialFile } from './credentials.js';
|
|
3
|
-
import { MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH, parseInstallationIdentity, readMcpMigration } from './installationIdentity.js';
|
|
3
|
+
import { MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH, TERMINAL_ENV_PATH, parseInstallationIdentity, readMcpMigration } from './installationIdentity.js';
|
|
4
4
|
import { loadRuntimeConfig } from './runtime/config.mjs';
|
|
5
5
|
import { createApiClient, safeId, validatedBaseUrl } from './runtime/protocol.mjs';
|
|
6
6
|
import { resolveRemotePosture } from './runtime/posture.mjs';
|
|
@@ -26,8 +26,10 @@ function parse(raw) {
|
|
|
26
26
|
|
|
27
27
|
export function loadNativeDoctorConfig({ projectRoot = process.cwd(), runtime, shellEnv = process.env }) {
|
|
28
28
|
if (!['sdk', 'mcp'].includes(runtime)) fail('INVALID_RUNTIME_OPTIONS');
|
|
29
|
-
const envPath = runtime === 'mcp' ? MCP_ENV_PATH : SDK_ENV_PATH;
|
|
30
29
|
try {
|
|
30
|
+
const legacy = runtime === 'sdk' ? inspectCredentialFile(projectRoot, SDK_ENV_PATH) : null;
|
|
31
|
+
const envPath = runtime === 'mcp' ? MCP_ENV_PATH : !legacy.safe || legacy.exists
|
|
32
|
+
|| !inspectCredentialFile(projectRoot, TERMINAL_ENV_PATH).exists ? SDK_ENV_PATH : TERMINAL_ENV_PATH;
|
|
31
33
|
const files = [envPath, `${envPath}.identity.json`, `${envPath}.connect.json`, `${envPath}.connect.lock`, MCP_MIGRATION_PATH];
|
|
32
34
|
const checks = files.map(file => inspectCredentialFile(projectRoot, file));
|
|
33
35
|
if (checks.some(check => !check.safe)) fail('UNSAFE_CREDENTIALS');
|