osuite 2.17.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 +93 -25
- package/RELEASE_NOTES.md +11 -0
- package/governed-tools/authority.mjs +33 -8
- package/governed-tools/contract.mjs +3 -1
- package/governed-tools/executor.mjs +71 -26
- package/governed-tools/owner-receipt.mjs +75 -7
- package/governed-tools/proof-digest.mjs +16 -0
- package/native-proof.mjs +56 -5
- package/package.json +2 -1
- package/runtime/guard-timeout.mjs +3 -0
- package/runtime/protocol.mjs +3 -1
package/GOVERNED_RECOVERY.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Evidence-bound native recovery
|
|
2
2
|
|
|
3
|
+
For read-only closure after a restart, see
|
|
4
|
+
[Reconcile With The Resource Owner](GOVERNED_TOOLS.md#reconcile-with-the-resource-owner).
|
|
5
|
+
Call `reconcile` after reopening the same journal. A v2 owner receipt binding
|
|
6
|
+
allows a read-only lookup and keeps the original dispatch fence. The
|
|
7
|
+
write-capable recovery API below applies to other bindings.
|
|
8
|
+
|
|
3
9
|
Version 2.14.0 adds the opt-in
|
|
4
10
|
`tools.recover(operationId, unchangedParams, options)` API to
|
|
5
11
|
`createGovernedTools` on Node 24/POSIX. Confirm registry availability with
|
package/GOVERNED_TOOLS.md
CHANGED
|
@@ -135,28 +135,75 @@ have no key to associate with a reservation.
|
|
|
135
135
|
|
|
136
136
|
### Reconcile With The Resource Owner
|
|
137
137
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
`
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
138
|
+
Configure the binding before the first run.
|
|
139
|
+
|
|
140
|
+
```js
|
|
141
|
+
import { OWNER_CLOSURE_RECEIPT_SCHEMA } from 'osuite/native-proof';
|
|
142
|
+
|
|
143
|
+
const ownerReceipt = {
|
|
144
|
+
resourceId: 'billing-ledger',
|
|
145
|
+
publicKey: ownerPublicKey,
|
|
146
|
+
schemaVersion: OWNER_CLOSURE_RECEIPT_SCHEMA,
|
|
147
|
+
query: ({ operationId, signal, ...scope }) => owner.lookup(scope, { signal }),
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
const result = await tools.reconcile(operationId, unchangedParams);
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Add `ownerReceipt` to the tool binding when creating `tools`. Use base64 Ed25519
|
|
154
|
+
SPKI DER for `publicKey`. A workspace admin pins the same key in the workspace
|
|
155
|
+
setting `NATIVE_RESOURCE_OWNERS`. Set its value to a JSON array of
|
|
156
|
+
`{ resource_id, public_key }` entries. Keep the private key on the owner side.
|
|
157
|
+
Use a read credential scoped to the owner ledger. Give offline verifiers the
|
|
158
|
+
public key through a trusted channel.
|
|
159
|
+
|
|
160
|
+
With this binding, the `run` callback receives `(params, scope)`. Forward the
|
|
161
|
+
frozen scope to the resource and store it with the effect. The scope is
|
|
162
|
+
`org_id`, `action_id`, `input_digest`, `resource_id` and `key_id`. The key ID
|
|
163
|
+
is the SHA-256 digest of the public key's SPKI DER bytes.
|
|
164
|
+
|
|
165
|
+
Reopen the same journal after a dropped reply or restart. Call `reconcile`
|
|
166
|
+
with the original operation ID and arguments. The SDK checks for a recorded
|
|
167
|
+
owner receipt first. Otherwise it calls `query` once. The query also receives
|
|
168
|
+
`schema_version`, `previous_proof_digest` and `observation_digest` from Studio.
|
|
169
|
+
Pass these through to the owner's lookup along with the scope. The owner may
|
|
170
|
+
look up a receipt or read its ledger within that scope.
|
|
171
|
+
|
|
172
|
+
The owner returns `{ claims, signature }`. Copy the scope and the three
|
|
173
|
+
additional fields into `claims`. Add `receipt_id`, `observed_at` in UTC ISO
|
|
174
|
+
format with milliseconds, `complete: true`, `final: true`, and `outcome`.
|
|
175
|
+
Set `outcome` to `committed` and include the owner's `resource_reference`.
|
|
176
|
+
Use 1 to 240 letters, digits or characters from `_:/.-` in the reference.
|
|
177
|
+
For `absent`, set `resource_reference` to null. Issue absence only after a
|
|
178
|
+
complete authoritative read and a resource-side fence against delayed writes.
|
|
179
|
+
Use the time of the owner's read for `observed_at`.
|
|
180
|
+
|
|
181
|
+
Sign the schema version, a newline and canonical JSON of the claims with the
|
|
182
|
+
owner's Ed25519 key. `ownerReceiptPayload(claims)` from `osuite/native-proof`
|
|
183
|
+
builds these bytes. Encode the signature in base64. The owner signs the two
|
|
184
|
+
Studio digests as context for its own resource finding.
|
|
185
|
+
|
|
186
|
+
Incomplete, invalid and unavailable answers return `outcome: 'unknown'`.
|
|
187
|
+
The lookup has a five-second limit and accepts an optional `signal`.
|
|
188
|
+
Studio also verifies a receipt before accepting it. An acknowledged closure
|
|
189
|
+
returns `outcome`, `ownerReceipt` and `ownerClosure`. The journal retains its
|
|
190
|
+
dispatch fence. Reconcile again to read the persisted closure. A new call to
|
|
191
|
+
`run` with that ID cannot execute the callback. The write-capable `recover`
|
|
192
|
+
API is unavailable for this binding.
|
|
193
|
+
|
|
194
|
+
Omitting `schemaVersion` keeps the earlier v1 receipt contract. V1 receipts
|
|
195
|
+
remain readable. The v2 contract applies to actions created with the v2 binding.
|
|
196
|
+
|
|
197
|
+
Download the ordinary proof export with
|
|
198
|
+
`GET /api/proof/export?action_id=…`. Call
|
|
199
|
+
`verifyNativeOwnerClosure(bundle, ownerPublicKey)` from `osuite/native-proof`
|
|
200
|
+
offline. It accepts the export or its `proof_bundle` member. The Studio
|
|
201
|
+
record is tamper-evident. The owner's signature authenticates the scoped
|
|
202
|
+
resource finding and binds it to the earlier proof and the runtime observation.
|
|
203
|
+
|
|
204
|
+
For the native cohort export, use `GET /api/proof/export?format=native`
|
|
205
|
+
with `from` and `to` in UTC. Use `format=native-checkpoint` to obtain its
|
|
206
|
+
checkpoint separately.
|
|
160
207
|
The window includes registered, verified native actions by creation time.
|
|
161
208
|
Studio reads `OSUITE_NATIVE_PROOF_SIGNING_KEY` and
|
|
162
209
|
`OSUITE_NATIVE_CHECKPOINT_SIGNING_KEY` as separately provisioned base64
|
|
@@ -224,6 +271,27 @@ content; do not treat POST/GET hash inequality alone as a failed write. A requir
|
|
|
224
271
|
capability that this wrapper cannot satisfy must still stop execution; reducing
|
|
225
272
|
that requirement is an administrator's policy decision, not an SDK recovery step.
|
|
226
273
|
|
|
274
|
+
## Guard and approval options
|
|
275
|
+
|
|
276
|
+
`run` accepts `waitMs` and `signal`. `waitMs` is the approval wait in
|
|
277
|
+
milliseconds. It defaults to 0 and accepts integers through 600,000. `signal`
|
|
278
|
+
is an optional `AbortSignal`. It can cancel the Guard request or stop an
|
|
279
|
+
approval wait.
|
|
280
|
+
|
|
281
|
+
The SDK waits up to 15,000 ms for `POST /api/guard`. This covers Studio's
|
|
282
|
+
10,000 ms maximum callback timeout plus 5,000 ms for Studio and the network.
|
|
283
|
+
A callback timeout that blocks returns `POLICY_DENIED` with the reason in
|
|
284
|
+
`error.details.reason`. If Guard is unavailable, the SDK fails closed.
|
|
285
|
+
|
|
286
|
+
Action registration and approval redemption check policy again. When Guard
|
|
287
|
+
reports a callback, the SDK adds its budget to the registration limits of
|
|
288
|
+
2,500 ms for headers and 5,000 ms for the whole response.
|
|
289
|
+
|
|
290
|
+
If Guard is cancelled or its response is lost, retry with the same operation
|
|
291
|
+
ID, journal, and input. Studio can return the recorded initial Guard decision.
|
|
292
|
+
The SDK still needs fresh action registration before dispatch. The journal
|
|
293
|
+
prevents a second dispatch for the operation.
|
|
294
|
+
|
|
227
295
|
## Connected MCP Client
|
|
228
296
|
|
|
229
297
|
```js
|
|
@@ -361,9 +429,9 @@ database. Explicit initialization is a provisioning action, not recovery.
|
|
|
361
429
|
Version 2.11.2 changes the default `journalOptions.busyTimeoutMs`
|
|
362
430
|
from 100 to 1,000 ms; the supported range remains 0-5,000 ms. This is a bounded
|
|
363
431
|
local write-lock budget, not extra approval time or an operation retry policy.
|
|
364
|
-
After the dispatch fence commits, the
|
|
365
|
-
|
|
366
|
-
|
|
432
|
+
After the dispatch fence commits, the SDK checks the registration deadline
|
|
433
|
+
again immediately before calling the tool. An expired response leaves an
|
|
434
|
+
uncertain fence. The SDK never renews it or retries automatically.
|
|
367
435
|
Do not delete completed or unknown rows
|
|
368
436
|
to make room: they are replay tombstones. Plan scoped lifecycle/retention with
|
|
369
437
|
the operator, retain the WAL correctly, and never share this database over an
|
package/RELEASE_NOTES.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# SDK 2.18.0 release notes
|
|
2
|
+
|
|
3
|
+
- Reopen the same governed tools journal and call `reconcile` to read an authenticated owner closure.
|
|
4
|
+
- Opt in with `ownerReceipt.schemaVersion` set to `osuite.native_owner_receipt.v2`. A committed closure includes the owner's reference. An absent closure requires a complete scoped read and a resource-side write fence.
|
|
5
|
+
- Verify the tamper-evident Studio export offline with `verifyNativeOwnerClosure` and the owner's public key.
|
|
6
|
+
- The SDK keeps the original dispatch fence and returns `unknown` for incomplete, invalid or timed-out reads. Existing v1 receipts remain readable.
|
|
7
|
+
- Governed tools wait through Studio's callback timeout. A block returns `POLICY_DENIED` with the reason. An allow still needs current action registration before dispatch.
|
|
8
|
+
- If a Guard response is lost, retry with the same operation ID and input. The updated Studio can return its recorded decision. See [Guard and approval options](GOVERNED_TOOLS.md#guard-and-approval-options).
|
|
9
|
+
|
|
10
|
+
Use Node 24 on POSIX for the governed tools runtime. Use a Studio version
|
|
11
|
+
that supports v2 owner closure. See [native tool configuration](GOVERNED_TOOLS.md#reconcile-with-the-resource-owner).
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
3
|
import { canonicalJson, createApiClient, isTransientFailure, sha256 } from '../runtime/protocol.mjs';
|
|
4
|
+
import { MAX_GUARD_WEBHOOK_TIMEOUT_MS } from '../runtime/guard-timeout.mjs';
|
|
4
5
|
import { rejectionFenceUnchanged, resolveRemotePosture } from '../runtime/posture.mjs';
|
|
5
6
|
import { createStateStore } from '../runtime/state.mjs';
|
|
6
7
|
import { admitAction, actionAdmission, cavaFingerprint } from '../runtime/admission.mjs';
|
|
@@ -8,6 +9,20 @@ import { matchesStoredAction, reject } from './contract.mjs';
|
|
|
8
9
|
import { nativeAmountIssue } from './amount.mjs';
|
|
9
10
|
|
|
10
11
|
const receiptWindow = Object.freeze({ headersTimeoutMs: 2500, timeoutMs: 5000 });
|
|
12
|
+
const guardTimeoutMs = MAX_GUARD_WEBHOOK_TIMEOUT_MS + 5000;
|
|
13
|
+
|
|
14
|
+
function registrationWindow(guard) {
|
|
15
|
+
let budget = guard.webhook_timeout_ms;
|
|
16
|
+
if (!Number.isFinite(budget) || budget <= 0 || budget > MAX_GUARD_WEBHOOK_TIMEOUT_MS) {
|
|
17
|
+
// Older Studio versions report callback decisions without a budget.
|
|
18
|
+
if (!guard.policy_snapshot?.webhook_decisions?.length) return receiptWindow;
|
|
19
|
+
budget = MAX_GUARD_WEBHOOK_TIMEOUT_MS;
|
|
20
|
+
}
|
|
21
|
+
return {
|
|
22
|
+
headersTimeoutMs: receiptWindow.headersTimeoutMs + budget,
|
|
23
|
+
timeoutMs: receiptWindow.timeoutMs + budget,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
11
26
|
|
|
12
27
|
function failureDetails(phase, response, mayHaveRegistered = false) {
|
|
13
28
|
return {
|
|
@@ -75,7 +90,7 @@ export function createStudioAuthority(config, journalPath) {
|
|
|
75
90
|
return { available: true, body: response.body, action: response.body.action || response.body };
|
|
76
91
|
}
|
|
77
92
|
|
|
78
|
-
async function admit(invocation, journal, owner, aborted) {
|
|
93
|
+
async function admit(invocation, journal, owner, aborted, signal) {
|
|
79
94
|
const record = { ...journal.get(invocation.record.scope, invocation.record.operationId),
|
|
80
95
|
nativeAmount: invocation.context.native_amount,
|
|
81
96
|
nativeResource: invocation.context.native_resource,
|
|
@@ -93,7 +108,8 @@ export function createStudioAuthority(config, journalPath) {
|
|
|
93
108
|
if (!session.ok || actualSession?.runtime_session_id !== record.sessionId
|
|
94
109
|
|| actualSession?.org_id !== config.orgId || actualSession?.agent_id !== config.agentId
|
|
95
110
|
|| actualSession?.runtime_adapter_id !== config.runtimeId) reject('CURRENT_AUTHORITY_UNAVAILABLE', null, failureDetails('runtime_session', session));
|
|
96
|
-
let claimed = false,
|
|
111
|
+
let claimed = false, dispatchDeadline = null;
|
|
112
|
+
let actionWindow = receiptWindow;
|
|
97
113
|
const claim = () => {
|
|
98
114
|
if (claimed) reject('OUTCOME_UNKNOWN');
|
|
99
115
|
if (aborted()) reject('ABORTED');
|
|
@@ -107,12 +123,18 @@ export function createStudioAuthority(config, journalPath) {
|
|
|
107
123
|
api: { async request(method, endpoint, body, options) {
|
|
108
124
|
if (aborted()) reject('ABORTED');
|
|
109
125
|
const registering = method === 'POST' && endpoint === '/api/actions';
|
|
110
|
-
if (registering) { claim(); requestStartedAt = performance.now(); }
|
|
111
126
|
const guardRequest = endpoint === '/api/guard';
|
|
127
|
+
if (registering) {
|
|
128
|
+
claim();
|
|
129
|
+
dispatchDeadline = performance.now() + actionWindow.timeoutMs;
|
|
130
|
+
}
|
|
131
|
+
if (guardRequest && phase === 'requesting') body = { ...body, native_guard_replay: 'v1' };
|
|
132
|
+
const window = registering ? actionWindow : guardRequest ? { timeoutMs: guardTimeoutMs, signal } : options;
|
|
112
133
|
const response = await api.request(method, endpoint, body, {
|
|
113
|
-
...
|
|
134
|
+
...window, readForbiddenBody: registering || guardRequest,
|
|
114
135
|
});
|
|
115
136
|
if (guardRequest) {
|
|
137
|
+
if (aborted()) reject('ABORTED');
|
|
116
138
|
const issue = nativeAmountIssue(response.body?.code) || nativeAmountIssue(invocation.context.native_amount_issue);
|
|
117
139
|
if (issue && (!response.ok || invocation.context.native_amount_issue)) {
|
|
118
140
|
reject(issue.code, null, { ...failureDetails('guard', response), cause: issue.code,
|
|
@@ -122,12 +144,14 @@ export function createStudioAuthority(config, journalPath) {
|
|
|
122
144
|
reject(response.status === 403 && invocation.context.business_authority_assertion ? 'DELEGATION_REJECTED' : 'CURRENT_AUTHORITY_UNAVAILABLE',
|
|
123
145
|
null, failureDetails('guard', response));
|
|
124
146
|
}
|
|
147
|
+
actionWindow = registrationWindow(response.body);
|
|
125
148
|
}
|
|
126
149
|
if (registering) {
|
|
127
150
|
if (response.status === 403 && response.body?.decision?.decision === 'block'
|
|
128
151
|
&& response.body.action?.status === 'blocked' && matchesStoredAction(response.body, record, config)) {
|
|
129
152
|
const code = nativeAmountIssue(response.body.decision.code)?.code || 'POLICY_DENIED';
|
|
130
|
-
if (settle('denied')) reject(code, null, { ...failureDetails('action_registration', response),
|
|
153
|
+
if (settle('denied')) reject(code, null, { ...failureDetails('action_registration', response),
|
|
154
|
+
cause: code, reason: response.body.decision.reason });
|
|
131
155
|
}
|
|
132
156
|
if (!response.ok || !matchesStoredAction(response.body, record, config)
|
|
133
157
|
|| !cavaFingerprint(response.body)) {
|
|
@@ -145,13 +169,14 @@ export function createStudioAuthority(config, journalPath) {
|
|
|
145
169
|
{ actionId: record.actionId, fingerprint: record.fingerprint }).authorized);
|
|
146
170
|
},
|
|
147
171
|
});
|
|
148
|
-
if (result.authorized) return { phase, dispatchDeadline
|
|
172
|
+
if (result.authorized) return { phase, dispatchDeadline, response: result.response,
|
|
149
173
|
ruleExpiresAt: result.ruleRolloutBinding?.expires_at ?? null };
|
|
150
174
|
if (result.reason === 'policy_block') {
|
|
151
175
|
const issue = nativeAmountIssue(result.response?.code);
|
|
152
176
|
if (issue?.code === 'NATIVE_AMOUNT_LEDGER_UNAVAILABLE') reject(issue.code, null, { phase: 'guard', retrySameOperation: true });
|
|
153
177
|
if (!claimed) claim();
|
|
154
|
-
settle('denied')
|
|
178
|
+
if (!settle('denied')) reject('OPERATION_BUSY');
|
|
179
|
+
reject(issue?.code || 'POLICY_DENIED', null, { phase: 'guard', reason: result.response?.reason });
|
|
155
180
|
}
|
|
156
181
|
if (result.decision === 'require_approval' && result.response?.action?.status === 'pending_approval') {
|
|
157
182
|
if (!settle('held', { fingerprint: cavaFingerprint(result.response) })) reject('OUTCOME_UNKNOWN');
|
|
@@ -184,7 +209,7 @@ export function createStudioAuthority(config, journalPath) {
|
|
|
184
209
|
async function closeOwnerOutcome(record, receipt) {
|
|
185
210
|
const response = await baseApi.request('POST', `/api/actions/${encodeURIComponent(record.actionId)}/resource-confirmation`,
|
|
186
211
|
{ agent_id: config.agentId, native_owner_receipt: receipt }, receiptWindow);
|
|
187
|
-
return response.ok && response.body.action_id === record.actionId ? response.body
|
|
212
|
+
return response.ok && response.body.action_id === record.actionId ? response.body : null;
|
|
188
213
|
}
|
|
189
214
|
|
|
190
215
|
return { admit, read, report, closeOwnerOutcome };
|
|
@@ -46,7 +46,9 @@ function recoveryGuidance(code, state, details) {
|
|
|
46
46
|
export class GovernedToolError extends Error {
|
|
47
47
|
constructor(code, status = null, details = null) {
|
|
48
48
|
const recovery = recoveryGuidance(code, status?.state, details);
|
|
49
|
-
|
|
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}`);
|
|
50
52
|
this.name = 'GovernedToolError';
|
|
51
53
|
this.code = code;
|
|
52
54
|
this.status = status === null ? null : Object.freeze({ ...status, recovery });
|
|
@@ -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,7 +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 { ownerReceiptKey, verifyOwnerReceipt } from './owner-receipt.mjs';
|
|
11
|
+
import { ownerReceiptKey, verifyOwnerClosure, verifyOwnerReceipt, OWNER_CLOSURE_RECEIPT_SCHEMA, OWNER_RECEIPT_SCHEMA } from './owner-receipt.mjs';
|
|
11
12
|
|
|
12
13
|
const signalAborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
|
|
13
14
|
const terminalCodes = Object.freeze({ denied: 'POLICY_DENIED', expired: 'APPROVAL_EXPIRED', cancelled: 'CANCELLED' });
|
|
@@ -75,13 +76,17 @@ function registrySnapshot(bindings) {
|
|
|
75
76
|
if (!Object.hasOwn(receipt, 'value') || !receipt.value || types.isProxy(receipt.value)
|
|
76
77
|
|| ![Object.prototype, null].includes(Object.getPrototypeOf(receipt.value))) reject('INVALID_MAPPING');
|
|
77
78
|
const properties = Object.getOwnPropertyDescriptors(receipt.value);
|
|
78
|
-
const
|
|
79
|
-
if (
|
|
80
|
-
||
|
|
81
|
-
|
|
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;
|
|
82
84
|
const signer = ownerReceiptKey(publicKey);
|
|
83
|
-
if (!signer || !safeId(resourceId) || resourceId.length > 128 || typeof query !== 'function' || types.isProxy(query)
|
|
84
|
-
|
|
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 });
|
|
85
90
|
}
|
|
86
91
|
Object.defineProperty(result, name, { value: Object.freeze({ revision: fields.revision.value,
|
|
87
92
|
describe: fields.describe.value, amount, businessKey, ownerReceipt, delegation, recovery: recoveryAdapter(fields.recovery) }), enumerable: true });
|
|
@@ -95,6 +100,29 @@ function publicError(error) {
|
|
|
95
100
|
reject('OUTCOME_UNKNOWN');
|
|
96
101
|
}
|
|
97
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
|
+
|
|
98
126
|
export function createGovernedTools({ config: rawConfig, namespace, journalPath, bindings: rawBindings,
|
|
99
127
|
journalOptions = {}, initializeJournal = false } = {}) {
|
|
100
128
|
if (Number(process.versions.node.split('.')[0]) !== 24) reject('NODE_24_REQUIRED');
|
|
@@ -148,6 +176,10 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
|
|
|
148
176
|
|
|
149
177
|
async function perform(invocation, execute, { waitMs, signal, aborted }, recovery = null) {
|
|
150
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];
|
|
151
183
|
const local = operationId => {
|
|
152
184
|
const record = journal.get(scope, operationId);
|
|
153
185
|
return record && { ...record, recovery: invocation.recovery, nativeAmount: invocation.context.native_amount,
|
|
@@ -190,7 +222,7 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
|
|
|
190
222
|
|| !action.approved_by || !action.approved_at) reject('OUTCOME_UNKNOWN', status(record));
|
|
191
223
|
}
|
|
192
224
|
let admitted;
|
|
193
|
-
try { admitted = await authority.admit(invocation, journal, owner, aborted); }
|
|
225
|
+
try { admitted = await authority.admit(invocation, journal, owner, aborted, signal); }
|
|
194
226
|
catch (error) {
|
|
195
227
|
if (error instanceof GovernedToolError) throw new GovernedToolError(error.code, status(local(operationId)), error.details);
|
|
196
228
|
reject('OUTCOME_UNKNOWN', status(local(operationId)));
|
|
@@ -225,7 +257,7 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
|
|
|
225
257
|
reject(aborted() ? 'ABORTED' : 'OUTCOME_UNKNOWN', status(local(operationId)));
|
|
226
258
|
}
|
|
227
259
|
let result, resultDigest = null, state = 'completed', thrown = false;
|
|
228
|
-
try { result = await execute(
|
|
260
|
+
try { result = await execute(...args); }
|
|
229
261
|
catch { thrown = true; state = 'uncertain'; }
|
|
230
262
|
if (!thrown) {
|
|
231
263
|
if (result !== null && typeof result === 'object') {
|
|
@@ -276,9 +308,9 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
|
|
|
276
308
|
const parent = makeInvocation({ config, namespace, bindings, operationId, params });
|
|
277
309
|
const settings = runOptions(options);
|
|
278
310
|
if (settings.aborted()) reject('ABORTED');
|
|
279
|
-
const adapter = bindings[parent.params.name]
|
|
311
|
+
const { recovery: adapter, ownerReceipt } = bindings[parent.params.name];
|
|
280
312
|
const record = journal.getBound((await bindDelegation(parent)).record);
|
|
281
|
-
if (!adapter) reject('RECOVERY_UNSUPPORTED', status(record));
|
|
313
|
+
if (!adapter || ownerReceipt?.resource.receipt_schema === OWNER_CLOSURE_RECEIPT_SCHEMA) reject('RECOVERY_UNSUPPORTED', status(record));
|
|
282
314
|
if (!record) reject('RECOVERY_UNAVAILABLE');
|
|
283
315
|
if (record.state !== 'uncertain') { stopForState(record); reject('RECOVERY_UNAVAILABLE', status(record)); }
|
|
284
316
|
const { invocation: childInvocation, request } = makeRecoveryInvocation(parent, adapter);
|
|
@@ -325,8 +357,10 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
|
|
|
325
357
|
if (terminal) failureCode = terminalCodes[terminal];
|
|
326
358
|
}
|
|
327
359
|
const attempt = recoveryStatus(operationId);
|
|
360
|
+
const legacyReceipt = observed.body?.owner_receipt?.claims?.schema_version === OWNER_RECEIPT_SCHEMA
|
|
361
|
+
? observed.body.owner_receipt : null;
|
|
328
362
|
return Object.freeze({ ...publicStatus(record, config.baseUrl, failureCode), ...(attempt ? { recoveryAttempt: attempt } : {}),
|
|
329
|
-
...(
|
|
363
|
+
...(legacyReceipt ? { ownerReceipt: legacyReceipt } : {}), remote: Object.freeze({ available: observed.available,
|
|
330
364
|
status: observed.available ? observed.action.status : null, bindingMismatch: observed.mismatch === true }) });
|
|
331
365
|
});
|
|
332
366
|
},
|
|
@@ -342,23 +376,34 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
|
|
|
342
376
|
if (settings.aborted()) reject('ABORTED', status(localRecord));
|
|
343
377
|
if (!['dispatching', 'uncertain', 'completed'].includes(localRecord.state)) return unknown;
|
|
344
378
|
const nativeResource = invocation.context.native_resource;
|
|
379
|
+
const schema = nativeResource.receipt_schema;
|
|
345
380
|
const record = { ...localRecord, nativeResource, nativeAmount: invocation.context.native_amount };
|
|
346
|
-
const expected =
|
|
381
|
+
const expected = ownerScope(nativeResource, config.orgId, record.actionId);
|
|
347
382
|
const observed = await authority.read(record);
|
|
348
|
-
if (!observed.available) return unknown;
|
|
349
|
-
const
|
|
350
|
-
|
|
351
|
-
if (
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
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;
|
|
360
404
|
}
|
|
361
|
-
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 } : {}) });
|
|
362
407
|
});
|
|
363
408
|
},
|
|
364
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/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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "osuite",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.18.0",
|
|
4
4
|
"description": "OSuite governed action SDK for AI agents. Approve, replay, prove, and verify runtime decisions.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -48,6 +48,7 @@
|
|
|
48
48
|
"governed-tools/examples/*.mjs",
|
|
49
49
|
"GOVERNED_TOOLS.md",
|
|
50
50
|
"GOVERNED_RECOVERY.md",
|
|
51
|
+
"RELEASE_NOTES.md",
|
|
51
52
|
"business-evidence.mjs",
|
|
52
53
|
"BUSINESS_EVIDENCE.md",
|
|
53
54
|
"controlled-transfers.mjs",
|
package/runtime/protocol.mjs
CHANGED
|
@@ -77,6 +77,7 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
|
|
|
77
77
|
}
|
|
78
78
|
}
|
|
79
79
|
const controller = new AbortController();
|
|
80
|
+
const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
|
|
80
81
|
const totalMs = Math.max(1, Math.min(options.timeoutMs ?? timeoutMs, 30000));
|
|
81
82
|
const headMs = Math.max(1, Math.min(options.headersTimeoutMs ?? totalMs, totalMs));
|
|
82
83
|
const started = performance.now();
|
|
@@ -84,7 +85,7 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
|
|
|
84
85
|
let status = 0;
|
|
85
86
|
try {
|
|
86
87
|
const response = await fetchImpl(baseUrl + endpoint, {
|
|
87
|
-
method, redirect: 'manual', signal
|
|
88
|
+
method, redirect: 'manual', signal,
|
|
88
89
|
headers: { 'content-type': 'application/json', 'x-api-key': config.apiKey,
|
|
89
90
|
...(config.ruleRolloutCapability === RULE_ROLLOUT_CAPABILITY ? { 'x-osuite-runtime-capability': RULE_ROLLOUT_CAPABILITY } : {}),
|
|
90
91
|
...(config.ruleRollout?.enabled ? { 'x-osuite-rule-rollout-version': String(config.ruleRollout.version) } : {}) },
|
|
@@ -132,6 +133,7 @@ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutM
|
|
|
132
133
|
if (!isObject(parsed)) return { ok: false, status, error: 'invalid_response' };
|
|
133
134
|
return ok ? { ok, status, body: parsed } : { ok, status, body: parsed, error: 'http_error' };
|
|
134
135
|
} catch (error) {
|
|
136
|
+
if (signal.aborted && !controller.signal.aborted) return { ok: false, status, error: 'aborted' };
|
|
135
137
|
return { ok: false, status, error: status ? 'invalid_response' : controller.signal.aborted ? 'timeout'
|
|
136
138
|
: transientTransport(error) ? 'transport_failure' : 'request_failed' };
|
|
137
139
|
} finally { clearTimeout(timer); }
|