osuite 2.17.0 → 2.19.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.
@@ -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,35 +135,178 @@ have no key to associate with a reservation.
135
135
 
136
136
  ### Reconcile With The Resource Owner
137
137
 
138
- Bind `ownerReceipt: { resourceId, publicKey, query }` to the tool. `publicKey`
139
- is the resource owner's Ed25519 SPKI DER encoded as base64. A workspace admin
140
- pins the same key for `resourceId` in the `NATIVE_RESOURCE_OWNERS` setting,
141
- an array of `{ resource_id, public_key }` entries. The owner should keep its
142
- signing key separate from OSuite and the executing agent.
143
-
144
- After a dropped reply or restart, call `tools.reconcile(operationId, params)`
145
- with the same operation and arguments. `query` receives `operationId`, a
146
- timeout signal and the signed receipt scope (`org_id`, `action_id`,
147
- `input_digest`, `resource_id`, `key_id`). It performs the resource owner's
148
- authenticated lookup and returns `{ claims, signature }`. The claims contain
149
- that scope, `schema_version: 'osuite.native_owner_receipt.v1'`, `receipt_id`,
150
- UTC `observed_at`, `complete: true`, `final: true` and `outcome` (`committed`
151
- or `absent`). The signature is base64 Ed25519 over the schema version, a newline
152
- and the canonical JSON claims. An `absent` receipt requires a complete scoped
153
- read and a fence against a later submission for that action. The SDK returns
154
- `unknown` while the receipt is incomplete, untrusted or unavailable. The
155
- journal continues to prevent a second execution.
156
-
157
- Studio's `GET /api/proof/export?format=native&action_id=…` returns a signed
158
- native proof. Use `from` and `to` in UTC in place of `action_id` for a cohort
159
- and `format=native-checkpoint` for its independently obtained checkpoint.
160
- The window includes registered, verified native actions by creation time.
161
- Studio reads `OSUITE_NATIVE_PROOF_SIGNING_KEY` and
162
- `OSUITE_NATIVE_CHECKPOINT_SIGNING_KEY` as separately provisioned base64
163
- Ed25519 PKCS8 DER keys. Give the reviewer the public keys through a trusted
164
- channel along with the pinned owner keys. `verifyNativeProofCohort` from
165
- `osuite/native-proof` verifies the signed records and checkpoint offline and
166
- counts committed, absent and unknown outcomes.
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
+ ### Native proof packages and independent checkpoints
205
+
206
+ Use Studio with the native proof log migration and SDK 2.19 or later.
207
+ Configure distinct base64 Ed25519 PKCS8 DER keys in
208
+ `OSUITE_NATIVE_PROOF_SIGNING_KEY` and `OSUITE_NATIVE_CHECKPOINT_SIGNING_KEY`.
209
+ Enroll the runtime RSA identity in the workspace. Configure the resource owner's
210
+ v2 closure adapter. Call `reconcile` to collect its committed or absent finding.
211
+
212
+ Use a workspace evidence credential for these requests.
213
+
214
+ | GET `/api/proof/export` query | Result |
215
+ | --- | --- |
216
+ | `format=native-log` | Workspace ID, log UUID, and latest assigned position. |
217
+ | `format=native&first=1&last=100` | Ordered `osuite.native_proof_package.v2` records for an inclusive interval. |
218
+ | `format=native-checkpoint&first=1&last=100` | Studio's checkpoint candidate for the same interval. |
219
+
220
+ Each workspace log starts at position 1. An action gets a position when its
221
+ insert commits. Earlier actions get positions in creation order during migration.
222
+ Use up to 1,000 positions per request. An export with missing evidence fails.
223
+ An action update can change the record digest while keeping its position. Export
224
+ after the intended owner findings have settled. Freeze the package and the
225
+ checkpoint together.
226
+
227
+ The Studio candidate is Ed25519 DSSE with payload type
228
+ `application/vnd.osuite.native-checkpoint.v2+json`. Its
229
+ `osuite.native_checkpoint.v2` payload carries `scope`, `count`, and `head`.
230
+ Scope contains `org_id`, `log_id`, `first_position`, and `last_position`.
231
+ The head starts with SHA-256 of canonical JSON `[checkpoint_schema, scope]`.
232
+ For each record in order, hash canonical JSON `[previous_head, record_digest]`.
233
+ The record digest covers the full canonical record, including its DSSE envelope.
234
+ Canonical JSON sorts object keys, preserves array order, and uses UTF-8.
235
+ Hashes and public key fingerprints are lowercase SHA-256 hex.
236
+
237
+ ### Run the witness offline
238
+
239
+ The custodian controls a separate machine or account and an Ed25519 key.
240
+ Keep the private key in that domain. Give the verifier the witness public key
241
+ through a separate trusted channel. Get Studio, runtime and owner public keys
242
+ from their authorities. Pin them before collecting the package.
243
+
244
+ Choose the workspace and position interval under the custodian's own procedure.
245
+ Read the log UUID through a workspace evidence credential the custodian controls.
246
+ Save the chosen scope in `scope.json`. Collect `bundles.json` and `candidate.json`
247
+ for those positions. The witness tool checks the pinned Studio signature, the
248
+ chosen scope, and the head over the files it receives. Store its output in the
249
+ custodian's archive. Each output path is written once.
250
+
251
+ ```sh
252
+ umask 077
253
+ openssl genpkey -algorithm Ed25519 -out witness.pem
254
+ openssl pkey -in witness.pem -pubout -out witness.pub.pem
255
+ osuite checkpoint witness --bundles bundles.json --candidate candidate.json \
256
+ --checkpoint-key studio-checkpoint.pub.pem --scope scope.json \
257
+ --witness-key witness.pem --out witnessed.json
258
+ ```
259
+
260
+ The witnessed checkpoint is DSSE with payload type
261
+ `application/vnd.osuite.witnessed-native-checkpoint.v1+json`. Its payload is
262
+ the entire Studio candidate, including the Studio signature. The witness states
263
+ which exact range and bytes it observed. A claim about events that never reached
264
+ the log requires the custodian's own intake evidence.
265
+
266
+ ### Verify a package offline
267
+
268
+ Give the verifier the packages, the authority keys, and the witnessed checkpoint.
269
+ Deliver `witnessed.json` and `witness.pub.pem` from the custodian's archive.
270
+ The optional scope file pins the independently planned range on the verifier too.
271
+
272
+ ```sh
273
+ osuite checkpoint verify --bundles bundles.json --checkpoint witnessed.json \
274
+ --keys authority-keys.json --witness-key witness.pub.pem --scope scope.json
275
+ ```
276
+
277
+ Use a JSON key file in this shape. Studio and runtime keys can be PEM or base64
278
+ SPKI DER. Owner keys use base64 SPKI DER. Keep old runtime pins for records that
279
+ precede a key rotation. Add `issuers` with `id`, `org_id` and `public_key` for
280
+ delegated records.
281
+
282
+ ```json
283
+ {
284
+ "proof": "STUDIO_PROOF_PUBLIC_KEY",
285
+ "checkpoint": "STUDIO_CHECKPOINT_PUBLIC_KEY",
286
+ "runtimes": [{ "agent_id": "runtime-1", "public_key": "RUNTIME_RSA_PUBLIC_KEY" }],
287
+ "owners": [{ "resource_id": "refund-ledger", "public_key": "OWNER_ED25519_PUBLIC_KEY" }]
288
+ }
289
+ ```
290
+
291
+ `verifyNativeProofPackage({ bundles, roots, checkpoint, witnessPublicKey, scope })`
292
+ from `osuite/native-proof` returns the same JSON as the CLI. It reports the
293
+ overall result and reasons for each record. The CLI exits with status 1 on
294
+ failure. Studio's records are tamper-evident. The runtime DSSE binds the actor
295
+ and input. Each v2 owner signature binds the workspace, action, resource, and
296
+ input digest to the original observation and proof. A committed finding names the
297
+ resource reference. An absent finding comes from a complete read with a write
298
+ fence in that same scope.
299
+
300
+ `RUNTIME_SIGNING_NOT_CONFIGURED` means the action had no configured signing
301
+ identity. `RUNTIME_SIGNATURE_MISSING` means the record lacks the runtime DSSE
302
+ evidence. This includes historical native records with only HTTP signatures.
303
+ `PROOF_SIGNING_NOT_CONFIGURED` reports a missing Studio export key.
304
+ The overall result fails if any required signature or owner finding is missing.
305
+ The outcome stays `unknown` when the owner finding cannot be verified.
306
+
307
+ Existing single-action exports still use `verifyNativeOwnerClosure`. Existing
308
+ `from` and `to` native windows still use `verifyNativeProofCohort` and their
309
+ Studio checkpoint. Independent verification uses the position-based format.
167
310
 
168
311
  ### Delegated Calls
169
312
 
@@ -224,6 +367,27 @@ content; do not treat POST/GET hash inequality alone as a failed write. A requir
224
367
  capability that this wrapper cannot satisfy must still stop execution; reducing
225
368
  that requirement is an administrator's policy decision, not an SDK recovery step.
226
369
 
370
+ ## Guard and approval options
371
+
372
+ `run` accepts `waitMs` and `signal`. `waitMs` is the approval wait in
373
+ milliseconds. It defaults to 0 and accepts integers through 600,000. `signal`
374
+ is an optional `AbortSignal`. It can cancel the Guard request or stop an
375
+ approval wait.
376
+
377
+ The SDK waits up to 15,000 ms for `POST /api/guard`. This covers Studio's
378
+ 10,000 ms maximum callback timeout plus 5,000 ms for Studio and the network.
379
+ A callback timeout that blocks returns `POLICY_DENIED` with the reason in
380
+ `error.details.reason`. If Guard is unavailable, the SDK fails closed.
381
+
382
+ Action registration and approval redemption check policy again. When Guard
383
+ reports a callback, the SDK adds its budget to the registration limits of
384
+ 2,500 ms for headers and 5,000 ms for the whole response.
385
+
386
+ If Guard is cancelled or its response is lost, retry with the same operation
387
+ ID, journal, and input. Studio can return the recorded initial Guard decision.
388
+ The SDK still needs fresh action registration before dispatch. The journal
389
+ prevents a second dispatch for the operation.
390
+
227
391
  ## Connected MCP Client
228
392
 
229
393
  ```js
@@ -361,9 +525,9 @@ database. Explicit initialization is a provisioning action, not recovery.
361
525
  Version 2.11.2 changes the default `journalOptions.busyTimeoutMs`
362
526
  from 100 to 1,000 ms; the supported range remains 0-5,000 ms. This is a bounded
363
527
  local write-lock budget, not extra approval time or an operation retry policy.
364
- After the dispatch fence commits, the existing five-second admission-receipt
365
- age limit is checked again immediately before the callback. An expired receipt
366
- leaves an uncertain fence; it is never renewed or automatically retried.
528
+ After the dispatch fence commits, the SDK checks the registration deadline
529
+ again immediately before calling the tool. An expired response leaves an
530
+ uncertain fence. The SDK never renews it or retries automatically.
367
531
  Do not delete completed or unknown rows
368
532
  to make room: they are replay tombstones. Plan scoped lifecycle/retention with
369
533
  the operator, retain the WAL correctly, and never share this database over an
package/README.md CHANGED
@@ -191,6 +191,7 @@ The v2 SDK exposes the core governance loop plus first-class PCAA, replay, proof
191
191
  - `verifyGovernanceProof(actionId)` -- Verify attestation/proof integrity and return structured checks.
192
192
  - `getComplianceEvidence({ window })` -- Pull live evidence aggregates for compliance and PCAA health.
193
193
  - `exportProof({ actionId, bundleId })` -- Export the portable verifier-facing proof package.
194
+ - [Native proof packages](GOVERNED_TOOLS.md#native-proof-packages-and-independent-checkpoints) support offline verification with an independent custodian.
194
195
  - The opt-in [business evidence reader](BUSINESS_EVIDENCE.md) links a refund
195
196
  to independently signed approval and resource-close records. A Studio proof
196
197
  on its own does not establish that a refund posted. This is an experimental
@@ -0,0 +1,18 @@
1
+ # SDK 2.19.0 release notes
2
+
3
+ - Export continuous ranges of tamper-evident native records from a Studio with the proof log migration.
4
+ - The runtime adds DSSE evidence for the actor and input. Native packages carry v2 owner findings for committed and absent outcomes.
5
+ - Run `osuite checkpoint witness` in the custodian's own environment. Run `osuite checkpoint verify` with the custodian's public key, checkpoint, and pinned authority keys.
6
+ - Keep using the existing verification functions for older proof formats. See [native proof packages](GOVERNED_TOOLS.md#native-proof-packages-and-independent-checkpoints).
7
+
8
+ # SDK 2.18.0 release notes
9
+
10
+ - Reopen the same governed tools journal and call `reconcile` to read an authenticated owner closure.
11
+ - 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.
12
+ - Verify the tamper-evident Studio export offline with `verifyNativeOwnerClosure` and the owner's public key.
13
+ - The SDK keeps the original dispatch fence and returns `unknown` for incomplete, invalid or timed-out reads. Existing v1 receipts remain readable.
14
+ - 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.
15
+ - 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).
16
+
17
+ Use Node 24 on POSIX for the governed tools runtime. Use a Studio version
18
+ that supports v2 owner closure. See [native tool configuration](GOVERNED_TOOLS.md#reconcile-with-the-resource-owner).
@@ -0,0 +1,36 @@
1
+ import { readFileSync, writeFileSync } from 'node:fs';
2
+ import { parseArgs } from 'node:util';
3
+ import { verifyNativeProofPackage, witnessNativeCheckpoint } from './native-proof.mjs';
4
+
5
+ const help = `osuite checkpoint witness --bundles FILE --candidate FILE --checkpoint-key FILE --scope FILE --witness-key PRIVATE_PEM --out FILE
6
+ osuite checkpoint verify --bundles FILE --checkpoint FILE --keys FILE --witness-key PUBLIC_PEM [--scope FILE]`;
7
+
8
+ const read = file => readFileSync(file, 'utf8');
9
+ const json = file => JSON.parse(read(file));
10
+
11
+ export function runCheckpointCommand([command, ...args], write) {
12
+ if (!command || ['--help', '-h'].includes(command) || args.includes('--help')) return write(help);
13
+ const shared = ['bundles', 'witness-key'];
14
+ const required = command === 'witness' ? [...shared, 'candidate', 'checkpoint-key', 'scope', 'out']
15
+ : [...shared, 'checkpoint', 'keys'];
16
+ if (!['verify', 'witness'].includes(command)) throw new Error(help);
17
+ const options = Object.fromEntries([...new Set([...required, 'scope'])].map(name => [name, { type: 'string', multiple: true }]));
18
+ const { values } = parseArgs({ args, options });
19
+ if (required.some(name => values[name]?.length !== 1) || Object.values(values).some(value => value.length !== 1 || !value[0])) {
20
+ throw new Error(help);
21
+ }
22
+ const bundles = json(values.bundles[0]);
23
+ const scope = values.scope && json(values.scope[0]);
24
+ const witnessKey = read(values['witness-key'][0]);
25
+ if (command === 'witness') {
26
+ const checkpoint = witnessNativeCheckpoint(json(values.candidate[0]), {
27
+ bundles, scope, checkpointPublicKey: read(values['checkpoint-key'][0]), witnessPrivateKey: witnessKey,
28
+ });
29
+ writeFileSync(values.out[0], `${JSON.stringify(checkpoint, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
30
+ return write(`Witnessed checkpoint saved to ${values.out[0]}`);
31
+ }
32
+ const result = verifyNativeProofPackage({ bundles, scope, checkpoint: json(values.checkpoint[0]),
33
+ roots: json(values.keys[0]), witnessPublicKey: witnessKey });
34
+ write(JSON.stringify(result, null, 2));
35
+ if (!result.verified) process.exitCode = 1;
36
+ }
package/cli.js CHANGED
@@ -177,7 +177,7 @@ const CONTROLLED_TRANSFER_CLI = ['doctor', 'mcp'].includes(process.argv[2])
177
177
  && process.argv.slice(3).some(value => /^--(?:controlled-transfers|require-controlled-transfers)(?:=|$)/.test(value));
178
178
  const NATIVE_RUNTIME_DOCTOR = process.argv[2] === 'doctor'
179
179
  && process.argv.slice(3).some(value => /^--runtime(?:=|$)/.test(value));
180
- loadProjectEnvironment();
180
+ if (process.argv[2] !== 'checkpoint') loadProjectEnvironment();
181
181
 
182
182
  function envValue(name, fallback) {
183
183
  return process.env[name] || process.env[fallback] || '';
@@ -800,6 +800,7 @@ function printHelp() {
800
800
  write(' osuite adapters [status|coverage] Explain Runtime Coverage tiers and next steps');
801
801
  write(' osuite adapter init <name> Scaffold an enterprise custom adapter mapping');
802
802
  write(' osuite adapter test <file> Validate an enterprise custom adapter mapping');
803
+ write(' osuite checkpoint witness|verify Countersign or verify a native checkpoint offline');
803
804
  write(' osuite external status Show external verifier network setup and usage');
804
805
  write(' osuite external configure --provider babyblue_invinoveritas --mode shadow --api-key <key> --expected-source-class independent_mediator');
805
806
  write(' osuite connect [auto|codex|claude|cursor|sdk|mcp] Detect runtime and start browser handoff');
@@ -1890,6 +1891,10 @@ async function main() {
1890
1891
  if (!command) return onboardingWelcome();
1891
1892
  if (['help', '--help', '-h'].includes(command)) return printHelp();
1892
1893
  if (['version', '--version', '-v'].includes(command)) return write(pkg.version);
1894
+ if (command === 'checkpoint') {
1895
+ const { runCheckpointCommand } = await import('./checkpointCli.mjs');
1896
+ return runCheckpointCommand(process.argv.slice(3), write);
1897
+ }
1893
1898
  if (CONTROLLED_TRANSFER_CLI) return controlledTransferCommand(command, args);
1894
1899
  if (NATIVE_RUNTIME_DOCTOR) {
1895
1900
  if (args._.length || !['sdk', 'mcp'].includes(args.runtime) || Object.keys(args).some(key => !['_', 'runtime'].includes(key))) {
@@ -1,6 +1,8 @@
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 { signNativeRuntimeCall } from './native-evidence.mjs';
5
+ import { MAX_GUARD_WEBHOOK_TIMEOUT_MS } from '../runtime/guard-timeout.mjs';
4
6
  import { rejectionFenceUnchanged, resolveRemotePosture } from '../runtime/posture.mjs';
5
7
  import { createStateStore } from '../runtime/state.mjs';
6
8
  import { admitAction, actionAdmission, cavaFingerprint } from '../runtime/admission.mjs';
@@ -8,6 +10,20 @@ import { matchesStoredAction, reject } from './contract.mjs';
8
10
  import { nativeAmountIssue } from './amount.mjs';
9
11
 
10
12
  const receiptWindow = Object.freeze({ headersTimeoutMs: 2500, timeoutMs: 5000 });
13
+ const guardTimeoutMs = MAX_GUARD_WEBHOOK_TIMEOUT_MS + 5000;
14
+
15
+ function registrationWindow(guard) {
16
+ let budget = guard.webhook_timeout_ms;
17
+ if (!Number.isFinite(budget) || budget <= 0 || budget > MAX_GUARD_WEBHOOK_TIMEOUT_MS) {
18
+ // Older Studio versions report callback decisions without a budget.
19
+ if (!guard.policy_snapshot?.webhook_decisions?.length) return receiptWindow;
20
+ budget = MAX_GUARD_WEBHOOK_TIMEOUT_MS;
21
+ }
22
+ return {
23
+ headersTimeoutMs: receiptWindow.headersTimeoutMs + budget,
24
+ timeoutMs: receiptWindow.timeoutMs + budget,
25
+ };
26
+ }
11
27
 
12
28
  function failureDetails(phase, response, mayHaveRegistered = false) {
13
29
  return {
@@ -75,7 +91,7 @@ export function createStudioAuthority(config, journalPath) {
75
91
  return { available: true, body: response.body, action: response.body.action || response.body };
76
92
  }
77
93
 
78
- async function admit(invocation, journal, owner, aborted) {
94
+ async function admit(invocation, journal, owner, aborted, signal) {
79
95
  const record = { ...journal.get(invocation.record.scope, invocation.record.operationId),
80
96
  nativeAmount: invocation.context.native_amount,
81
97
  nativeResource: invocation.context.native_resource,
@@ -84,6 +100,7 @@ export function createStudioAuthority(config, journalPath) {
84
100
  const phase = record.state === 'held' ? 'redeeming' : 'requesting';
85
101
  const { api, effective } = await current(aborted);
86
102
  if (aborted()) reject('ABORTED');
103
+ const runtimeEvidence = signNativeRuntimeCall(effective, { ...record, operationDigest: sha256(record.operationId) });
87
104
  const session = await api.request('POST', '/api/runtime-sessions', {
88
105
  runtime_session_id: record.sessionId, agent_id: config.agentId, runtime_adapter_id: config.runtimeId,
89
106
  runtime_family: 'sdk_tool_runtime', adapter_mode: 'sdk_wrapper', client_name: 'osuite/governed-tools',
@@ -93,7 +110,8 @@ export function createStudioAuthority(config, journalPath) {
93
110
  if (!session.ok || actualSession?.runtime_session_id !== record.sessionId
94
111
  || actualSession?.org_id !== config.orgId || actualSession?.agent_id !== config.agentId
95
112
  || actualSession?.runtime_adapter_id !== config.runtimeId) reject('CURRENT_AUTHORITY_UNAVAILABLE', null, failureDetails('runtime_session', session));
96
- let claimed = false, requestStartedAt = null;
113
+ let claimed = false, dispatchDeadline = null;
114
+ let actionWindow = receiptWindow;
97
115
  const claim = () => {
98
116
  if (claimed) reject('OUTCOME_UNKNOWN');
99
117
  if (aborted()) reject('ABORTED');
@@ -107,12 +125,19 @@ export function createStudioAuthority(config, journalPath) {
107
125
  api: { async request(method, endpoint, body, options) {
108
126
  if (aborted()) reject('ABORTED');
109
127
  const registering = method === 'POST' && endpoint === '/api/actions';
110
- if (registering) { claim(); requestStartedAt = performance.now(); }
111
128
  const guardRequest = endpoint === '/api/guard';
129
+ if (registering) {
130
+ claim();
131
+ dispatchDeadline = performance.now() + actionWindow.timeoutMs;
132
+ }
133
+ if (guardRequest || registering) body = { ...body, native_runtime_evidence: runtimeEvidence };
134
+ if (guardRequest && phase === 'requesting') body.native_guard_replay = 'v1';
135
+ const window = registering ? actionWindow : guardRequest ? { timeoutMs: guardTimeoutMs, signal } : options;
112
136
  const response = await api.request(method, endpoint, body, {
113
- ...(registering ? receiptWindow : options), readForbiddenBody: registering || guardRequest,
137
+ ...window, readForbiddenBody: registering || guardRequest,
114
138
  });
115
139
  if (guardRequest) {
140
+ if (aborted()) reject('ABORTED');
116
141
  const issue = nativeAmountIssue(response.body?.code) || nativeAmountIssue(invocation.context.native_amount_issue);
117
142
  if (issue && (!response.ok || invocation.context.native_amount_issue)) {
118
143
  reject(issue.code, null, { ...failureDetails('guard', response), cause: issue.code,
@@ -122,12 +147,14 @@ export function createStudioAuthority(config, journalPath) {
122
147
  reject(response.status === 403 && invocation.context.business_authority_assertion ? 'DELEGATION_REJECTED' : 'CURRENT_AUTHORITY_UNAVAILABLE',
123
148
  null, failureDetails('guard', response));
124
149
  }
150
+ actionWindow = registrationWindow(response.body);
125
151
  }
126
152
  if (registering) {
127
153
  if (response.status === 403 && response.body?.decision?.decision === 'block'
128
154
  && response.body.action?.status === 'blocked' && matchesStoredAction(response.body, record, config)) {
129
155
  const code = nativeAmountIssue(response.body.decision.code)?.code || 'POLICY_DENIED';
130
- if (settle('denied')) reject(code, null, { ...failureDetails('action_registration', response), cause: code });
156
+ if (settle('denied')) reject(code, null, { ...failureDetails('action_registration', response),
157
+ cause: code, reason: response.body.decision.reason });
131
158
  }
132
159
  if (!response.ok || !matchesStoredAction(response.body, record, config)
133
160
  || !cavaFingerprint(response.body)) {
@@ -145,13 +172,14 @@ export function createStudioAuthority(config, journalPath) {
145
172
  { actionId: record.actionId, fingerprint: record.fingerprint }).authorized);
146
173
  },
147
174
  });
148
- if (result.authorized) return { phase, dispatchDeadline: requestStartedAt + receiptWindow.timeoutMs, response: result.response,
175
+ if (result.authorized) return { phase, dispatchDeadline, response: result.response,
149
176
  ruleExpiresAt: result.ruleRolloutBinding?.expires_at ?? null };
150
177
  if (result.reason === 'policy_block') {
151
178
  const issue = nativeAmountIssue(result.response?.code);
152
179
  if (issue?.code === 'NATIVE_AMOUNT_LEDGER_UNAVAILABLE') reject(issue.code, null, { phase: 'guard', retrySameOperation: true });
153
180
  if (!claimed) claim();
154
- settle('denied'); reject(issue?.code || 'POLICY_DENIED');
181
+ if (!settle('denied')) reject('OPERATION_BUSY');
182
+ reject(issue?.code || 'POLICY_DENIED', null, { phase: 'guard', reason: result.response?.reason });
155
183
  }
156
184
  if (result.decision === 'require_approval' && result.response?.action?.status === 'pending_approval') {
157
185
  if (!settle('held', { fingerprint: cavaFingerprint(result.response) })) reject('OUTCOME_UNKNOWN');
@@ -184,7 +212,7 @@ export function createStudioAuthority(config, journalPath) {
184
212
  async function closeOwnerOutcome(record, receipt) {
185
213
  const response = await baseApi.request('POST', `/api/actions/${encodeURIComponent(record.actionId)}/resource-confirmation`,
186
214
  { agent_id: config.agentId, native_owner_receipt: receipt }, receiptWindow);
187
- return response.ok && response.body.action_id === record.actionId ? response.body.owner_receipt : null;
215
+ return response.ok && response.body.action_id === record.actionId ? response.body : null;
188
216
  }
189
217
 
190
218
  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
- super(`OSuite ${code}: ${recovery.message}`);
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 });
@@ -0,0 +1,57 @@
1
+ import { createPublicKey, sign, verify } from 'node:crypto';
2
+ import { canonicalJson, isObject, sha256 } from '../runtime/protocol.mjs';
3
+
4
+ export function exactFields(value, fields) {
5
+ return isObject(value) && Object.keys(value).length === fields.length && fields.every(field => Object.hasOwn(value, field));
6
+ }
7
+
8
+ export function keyPin(key) {
9
+ const publicKey = key.type === 'public' ? key : createPublicKey(key);
10
+ return { key, id: sha256(publicKey.export({ format: 'der', type: 'spki' })) };
11
+ }
12
+
13
+ export function publicKeyPin(value, algorithm) {
14
+ if (typeof value !== 'string' || value.length > 2500) return null;
15
+ try {
16
+ const pem = value.trim();
17
+ const der = Buffer.from(pem, 'base64');
18
+ const key = pem.startsWith('-----BEGIN PUBLIC KEY-----')
19
+ ? createPublicKey(pem)
20
+ : der.toString('base64') === pem && createPublicKey({ key: der, format: 'der', type: 'spki' });
21
+ return key?.asymmetricKeyType === algorithm ? keyPin(key) : null;
22
+ } catch { return null; }
23
+ }
24
+
25
+ function pae(type, data) {
26
+ return Buffer.concat([Buffer.from(`DSSEv1 ${Buffer.byteLength(type)} ${type} ${data.length} `), data]);
27
+ }
28
+
29
+ const algorithm = key => key.asymmetricKeyType === 'ed25519' ? null : 'sha256';
30
+
31
+ export function signDsse(payloadType, value, signer) {
32
+ const data = Buffer.from(canonicalJson(value));
33
+ const signatures = signer
34
+ ? [{ keyid: signer.id, sig: sign(algorithm(signer.key), pae(payloadType, data), signer.key).toString('base64') }]
35
+ : [];
36
+ return { payloadType, payload: data.toString('base64'), signatures };
37
+ }
38
+
39
+ export function openDsse(envelope, payloadType, pin) {
40
+ if (!exactFields(envelope, ['payloadType', 'payload', 'signatures']) || envelope.payloadType !== payloadType
41
+ || typeof envelope.payload !== 'string' || envelope.payload.length > 1_500_000 || !Array.isArray(envelope.signatures)) return null;
42
+ try {
43
+ const data = Buffer.from(envelope.payload, 'base64');
44
+ if (data.toString('base64') !== envelope.payload) return null;
45
+ if (pin) {
46
+ const [signature] = envelope.signatures;
47
+ if (envelope.signatures.length !== 1 || !exactFields(signature, ['keyid', 'sig']) || signature.keyid !== pin.id
48
+ || typeof signature.sig !== 'string' || signature.sig.length > 1500) return null;
49
+ const bytes = Buffer.from(signature.sig, 'base64');
50
+ if (bytes.toString('base64') !== signature.sig
51
+ || !verify(algorithm(pin.key), pae(payloadType, data), pin.key, bytes)) return null;
52
+ } else if (envelope.signatures.length !== 0) return null;
53
+ const value = JSON.parse(data);
54
+ if (!isObject(value) || !Buffer.from(canonicalJson(value)).equals(data)) return null;
55
+ return { value, digest: sha256(data) };
56
+ } catch { return null; }
57
+ }
@@ -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 expected = ['resourceId', 'publicKey', 'query'];
79
- if (Reflect.ownKeys(properties).length !== expected.length
80
- || expected.some(key => !Object.hasOwn(properties[key] || {}, 'value'))) reject('INVALID_MAPPING');
81
- const { resourceId, publicKey, query } = Object.fromEntries(expected.map(key => [key, properties[key].value]));
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)) reject('INVALID_MAPPING');
84
- ownerReceipt = Object.freeze({ resource: Object.freeze({ resource_id: resourceId, key_id: signer.id }), publicKey, query });
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(invocation.params); }
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].recovery;
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
- ...(observed.body?.owner_receipt ? { ownerReceipt: observed.body.owner_receipt } : {}), remote: Object.freeze({ available: observed.available,
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 = Object.freeze({ ...nativeResource, org_id: config.orgId, action_id: record.actionId });
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 valid = receipt => verifyOwnerReceipt(receipt, expected, adapter.publicKey, { startedAt: observed.action.timestamp_start });
350
- let receipt = observed.body.owner_receipt;
351
- if (!valid(receipt)) {
352
- const timeout = AbortSignal.timeout(5000);
353
- const signal = settings.signal ? AbortSignal.any([timeout, settings.signal]) : timeout;
354
- try { receipt = jsonSnapshot(await adapter.query({ ...expected, operationId, signal }), 8192); }
355
- catch { return unknown; }
356
- if (signal.aborted || !valid(receipt)) return unknown;
357
- const submitted = receipt;
358
- receipt = await authority.closeOwnerOutcome(record, submitted);
359
- if (!valid(receipt) || receipt.claims.outcome !== submitted.claims.outcome) return unknown;
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: receipt.claims.outcome, ownerReceipt: receipt });
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(); } },
@@ -0,0 +1,24 @@
1
+ import { createPrivateKey } from 'node:crypto';
2
+ import { canonicalJson } from '../runtime/protocol.mjs';
3
+ import { keyPin, openDsse, signDsse } from './dsse.mjs';
4
+
5
+ export const NATIVE_RUNTIME_TYPE = 'application/vnd.osuite.native-runtime-call+json';
6
+
7
+ function runtimeClaims(orgId, agentId, actionId, marker) {
8
+ return {
9
+ schema_version: 'osuite.native_runtime_call.v1', org_id: orgId, agent_id: agentId, action_id: actionId,
10
+ input_digest: marker.input_digest, binding_digest: marker.binding_digest, operation_digest: marker.operation_digest,
11
+ };
12
+ }
13
+
14
+ export function signNativeRuntimeCall(config, { actionId, inputDigest, bindingDigest, operationDigest }) {
15
+ const signer = keyPin(createPrivateKey(Buffer.from(config.privateKeyBase64, 'base64')));
16
+ return signDsse(NATIVE_RUNTIME_TYPE, runtimeClaims(config.orgId, config.agentId, actionId, {
17
+ input_digest: inputDigest, binding_digest: bindingDigest, operation_digest: operationDigest,
18
+ }), signer);
19
+ }
20
+
21
+ export function verifyNativeRuntimeCall(envelope, pin, { orgId, agentId, actionId, marker }) {
22
+ const opened = pin && openDsse(envelope, NATIVE_RUNTIME_TYPE, pin);
23
+ return Boolean(opened && canonicalJson(opened.value) === canonicalJson(runtimeClaims(orgId, agentId, actionId, marker)));
24
+ }
@@ -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(`${OWNER_RECEIPT_SCHEMA}\n${canonicalJson(claims)}`);
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
- if (!isObject(receipt) || Object.keys(receipt).length !== 2 || !isObject(claims) || Object.keys(claims).length !== 11
30
- || claims.schema_version !== OWNER_RECEIPT_SCHEMA || claims.complete !== true || claims.final !== true
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
- || !['org_id', 'action_id', 'resource_id'].every(key => safeId(claims[key]) && claims[key] === expected[key])
33
- || !['input_digest', 'key_id'].every(key => digest.test(claims[key] || '') && claims[key] === expected[key])
34
- || !timestamp.test(claims.observed_at || '')) return false;
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
- if (!Number.isFinite(date) || date > now + 30000 || (startedAt !== undefined && !(date >= Date.parse(startedAt)))) return false;
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,37 +1,74 @@
1
- import { sign, verify } from 'node:crypto';
2
- import { canonicalJson, isObject, sha256 } from './runtime/protocol.mjs';
3
- import { ownerReceiptKey, verifyOwnerReceipt } from './governed-tools/owner-receipt.mjs';
1
+ import { createPrivateKey, verify } from 'node:crypto';
2
+ import { canonicalJson, isObject, safeId, sha256 } from './runtime/protocol.mjs';
3
+ import { exactFields, keyPin, openDsse, publicKeyPin, signDsse } from './governed-tools/dsse.mjs';
4
+ import { verifyNativeRuntimeCall } from './governed-tools/native-evidence.mjs';
5
+ import { ownerClosureObservation, ownerReceiptKey, verifyOwnerClosure, verifyOwnerReceipt,
6
+ OWNER_CLOSURE_RECEIPT_SCHEMA } from './governed-tools/owner-receipt.mjs';
7
+ import { proofManifestPayload } from './governed-tools/proof-digest.mjs';
8
+
9
+ export { OWNER_CLOSURE_RECEIPT_SCHEMA, ownerReceiptPayload } from './governed-tools/owner-receipt.mjs';
4
10
 
5
11
  export const NATIVE_PROOF_TYPE = 'application/vnd.in-toto+json';
6
12
  export const NATIVE_CHECKPOINT_TYPE = 'application/vnd.osuite.native-checkpoint+json';
7
13
  export const NATIVE_CHECKPOINT_SCOPE = 'registered_native_tools';
14
+ export const NATIVE_RANGE_CHECKPOINT_TYPE = 'application/vnd.osuite.native-checkpoint.v2+json';
15
+ export const NATIVE_WITNESS_TYPE = 'application/vnd.osuite.witnessed-native-checkpoint.v1+json';
16
+ export const NATIVE_PACKAGE_SCHEMA = 'osuite.native_proof_package.v2';
17
+ export const NATIVE_RANGE_RECORD_SCHEMA = 'osuite.native_proof.v2';
18
+ export const NATIVE_RANGE_CHECKPOINT_SCHEMA = 'osuite.native_checkpoint.v2';
19
+ export const NATIVE_RANGE_PREDICATE = 'https://osuite.ai/attestations/native-tool/v2';
20
+ export const NATIVE_RANGE_LIMIT = 1000;
8
21
  const hex = /^[0-9a-f]{64}$/;
9
22
  const actionId = /^act_[0-9a-f]{64}$/;
23
+ const fail = code => ({ verified: false, code });
24
+ const proofDigest = payload => `sha256:${sha256(canonicalJson(payload))}`;
10
25
 
11
- function pae(type, data) {
12
- return Buffer.concat([Buffer.from(`DSSEv1 ${Buffer.byteLength(type)} ${type} ${data.length} `), data]);
26
+ export function verifyNativeOwnerClosure(bundle, ownerPublicKey) {
27
+ const exported = bundle?.export_type === 'osuite.proof_export.v1';
28
+ const proof = exported ? bundle.proof_bundle : bundle;
29
+ const outcome = proof?.outcome;
30
+ const { native_owner_closure: closure, native_owner_receipt: receipt, ...priorOutcome } = outcome || {};
31
+ if (!closure) return fail('OWNER_CLOSURE_MISSING');
32
+ const envelope = proof.action_envelope;
33
+ const resource = envelope?.native_resource;
34
+ let marker;
35
+ try { marker = JSON.parse(envelope.input_summary)?.osuite_native_call; } catch { return fail('INVALID_OWNER_CLOSURE'); }
36
+ const scope = { ...resource, org_id: envelope.org_id, action_id: envelope.action_id };
37
+ if (proof.schema_version !== 'osuite.proof_bundle.v1' || proof.derived_from_legacy
38
+ || envelope.schema_version !== 'osuite.action_envelope.v1' || envelope.runtime_family !== 'sdk_tool_runtime'
39
+ || envelope.adapter_mode !== 'sdk_wrapper' || !actionId.test(envelope.action_id || '')
40
+ || resource?.receipt_schema !== OWNER_CLOSURE_RECEIPT_SCHEMA
41
+ || marker?.schema_version !== 'osuite.native_tool_call.v1' || marker.input_digest !== resource.input_digest
42
+ || !verifyOwnerClosure(closure, receipt, scope, ownerPublicKey)) return fail('INVALID_OWNER_CLOSURE');
43
+ const original = closure.original;
44
+ const payload = proofManifestPayload(proof);
45
+ if (original.route_decision !== payload.routeDecision || original.status !== outcome.status
46
+ || original.status !== payload.execution?.status || original.timestamp_end !== (payload.execution.timestamp_end ?? null)
47
+ || proof.manifest?.digest !== proofDigest(payload)) return fail('OWNER_CLOSURE_PROOF_MISMATCH');
48
+ if (exported && (bundle.action_id !== scope.action_id || bundle.org_id !== scope.org_id
49
+ || bundle.action?.action_id !== scope.action_id || bundle.action?.org_id !== scope.org_id
50
+ || canonicalJson(ownerClosureObservation(bundle.action, payload.routeDecision)) !== canonicalJson(original))) {
51
+ return fail('OWNER_CLOSURE_PROOF_MISMATCH');
52
+ }
53
+ const prior = { ...payload, outcome: priorOutcome };
54
+ if (proofDigest(prior) !== closure.previous_proof_digest) {
55
+ // A later reviewer can append a separate confirmation.
56
+ const { resource_confirmation: confirmation, ...beforeReview } = priorOutcome;
57
+ if (confirmation?.source !== 'workspace_reviewer'
58
+ || proofDigest({ ...prior, outcome: beforeReview }) !== closure.previous_proof_digest) return fail('OWNER_CLOSURE_CHAIN_MISMATCH');
59
+ }
60
+ return { verified: true, actionId: scope.action_id, inputDigest: scope.input_digest, outcome: receipt.claims.outcome,
61
+ resourceReference: receipt.claims.resource_reference };
13
62
  }
14
63
 
15
- export function signNativeEvidence(payloadType, value, signer) {
16
- const payload = Buffer.from(canonicalJson(value));
17
- return { payloadType, payload: payload.toString('base64'),
18
- signatures: [{ keyid: signer.id, sig: sign(null, pae(payloadType, payload), signer.key).toString('base64') }] };
19
- }
64
+ export { signDsse as signNativeEvidence };
20
65
 
21
- function open(envelope, payloadType, pin) {
22
- if (envelope?.payloadType !== payloadType || typeof envelope.payload !== 'string' || envelope.payload.length > 1500000
23
- || !Array.isArray(envelope.signatures) || envelope.signatures.length !== 1) return null;
24
- if (!isObject(envelope.signatures[0])) return null;
25
- const { keyid, sig } = envelope.signatures[0];
26
- if (!pin || keyid !== pin.id || typeof sig !== 'string' || sig.length !== 88) return null;
27
- try {
28
- const data = Buffer.from(envelope.payload, 'base64'), signature = Buffer.from(sig, 'base64');
29
- if (data.toString('base64') !== envelope.payload || signature.length !== 64 || signature.toString('base64') !== sig
30
- || !verify(null, pae(payloadType, data), pin.key, signature)) return null;
31
- const value = JSON.parse(data);
32
- if (!isObject(value) || !Buffer.from(canonicalJson(value)).equals(data)) return null;
33
- return { value, digest: sha256(data) };
34
- } catch { return null; }
66
+ function openLegacy(envelope, payloadType, pin) {
67
+ if (!pin) return null;
68
+ const { payload, signatures, payloadType: type } = envelope || {};
69
+ if (!Array.isArray(signatures) || signatures.length !== 1) return null;
70
+ const { keyid, sig } = signatures[0] || {};
71
+ return openDsse({ payloadType: type, payload, signatures: [{ keyid, sig }] }, payloadType, pin);
35
72
  }
36
73
 
37
74
  export function nativeProofRoot(entries) {
@@ -67,10 +104,9 @@ function validDelegation(predicate, issuers) {
67
104
  }
68
105
 
69
106
  export function verifyNativeProofCohort(records, roots, checkpoint) {
70
- const fail = code => ({ verified: false, code });
71
107
  const proofKey = ownerReceiptKey(roots?.proof), checkpointKey = ownerReceiptKey(roots?.checkpoint);
72
108
  if (!proofKey || !checkpointKey || proofKey.id === checkpointKey.id || !Array.isArray(roots.owners)) return fail('INVALID_TRUST_ROOTS');
73
- const opened = open(checkpoint, NATIVE_CHECKPOINT_TYPE, checkpointKey);
109
+ const opened = openLegacy(checkpoint, NATIVE_CHECKPOINT_TYPE, checkpointKey);
74
110
  const scope = opened?.value;
75
111
  const from = Date.parse(scope?.from), to = Date.parse(scope?.to);
76
112
  if (scope?.schema_version !== 'osuite.native_checkpoint.v1' || scope.scope !== NATIVE_CHECKPOINT_SCOPE
@@ -81,7 +117,7 @@ export function verifyNativeProofCohort(records, roots, checkpoint) {
81
117
  const seen = new Map();
82
118
  const outcomes = { committed: 0, absent: 0, unknown: 0 };
83
119
  for (const record of records) {
84
- const decoded = open(record?.dsse_envelope, NATIVE_PROOF_TYPE, proofKey);
120
+ const decoded = openLegacy(record?.dsse_envelope, NATIVE_PROOF_TYPE, proofKey);
85
121
  const statement = decoded?.value, p = statement?.predicate, subject = statement?.subject;
86
122
  const created = Date.parse(p?.created_at);
87
123
  if (!decoded || record.schema_version !== 'osuite.native_proof.v1' || decoded.digest !== record.payload_sha256
@@ -92,14 +128,22 @@ export function verifyNativeProofCohort(records, roots, checkpoint) {
92
128
  if (seen.has(p.action_id)) return fail('DUPLICATE_RECORD');
93
129
  if (!validDelegation(p, roots.issuers)) return fail('INVALID_DELEGATION');
94
130
  if (p.outcome === 'unknown') {
95
- if (p.owner_receipt !== null) return fail('INVALID_OWNER_RECEIPT');
131
+ if (p.owner_receipt !== null || p.owner_closure != null) return fail('INVALID_OWNER_RECEIPT');
96
132
  } else {
97
133
  const resource = p.native_resource;
98
134
  const pins = roots.owners.filter(root => root && resource && root.resource_id === resource.resource_id
99
135
  && ownerReceiptKey(root.public_key)?.id === resource.key_id);
100
136
  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 || !verifyOwnerReceipt(p.owner_receipt,
102
- { ...resource, org_id: p.org_id, action_id: p.action_id }, pins[0].public_key, { startedAt: p.timestamp_start })) return fail('INVALID_OWNER_RECEIPT');
137
+ || p.owner_receipt?.claims?.outcome !== p.outcome) return fail('INVALID_OWNER_RECEIPT');
138
+ const scope = { ...resource, org_id: p.org_id, action_id: p.action_id };
139
+ const publicKey = pins[0].public_key;
140
+ const valid = resource.receipt_schema === OWNER_CLOSURE_RECEIPT_SCHEMA
141
+ ? verifyOwnerClosure(p.owner_closure, p.owner_receipt, scope, publicKey)
142
+ && canonicalJson(p.owner_closure.original) === canonicalJson(ownerClosureObservation({
143
+ ...p.execution, timestamp_start: p.timestamp_start,
144
+ }, p.route_decision))
145
+ : !p.owner_closure && verifyOwnerReceipt(p.owner_receipt, scope, publicKey, { startedAt: p.timestamp_start });
146
+ if (!valid) return fail('INVALID_OWNER_RECEIPT');
103
147
  }
104
148
  seen.set(p.action_id, decoded.digest);
105
149
  outcomes[p.outcome]++;
@@ -107,3 +151,161 @@ export function verifyNativeProofCohort(records, roots, checkpoint) {
107
151
  if (nativeProofRoot(seen) !== scope.root) return fail('CHECKPOINT_MISMATCH');
108
152
  return { verified: true, count: seen.size, outcomes };
109
153
  }
154
+
155
+ export function validNativeRange(first, last) {
156
+ return Number.isSafeInteger(first) && Number.isSafeInteger(last) && first > 0 && last >= first && last - first < NATIVE_RANGE_LIMIT;
157
+ }
158
+
159
+ function validRangeScope(scope) {
160
+ return exactFields(scope, ['org_id', 'log_id', 'first_position', 'last_position']) && safeId(scope.org_id)
161
+ && typeof scope.log_id === 'string' && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(scope.log_id)
162
+ && validNativeRange(scope.first_position, scope.last_position);
163
+ }
164
+
165
+ export function nativeRangeHead(records, scope) {
166
+ let head = sha256(canonicalJson([NATIVE_RANGE_CHECKPOINT_SCHEMA, scope]));
167
+ for (const record of records) head = sha256(canonicalJson([head, sha256(canonicalJson(record))]));
168
+ return head;
169
+ }
170
+
171
+ function openRangeCheckpoint(candidate, pin) {
172
+ const value = pin && openDsse(candidate, NATIVE_RANGE_CHECKPOINT_TYPE, pin)?.value;
173
+ if (!exactFields(value, ['schema_version', 'scope', 'count', 'head']) || value.schema_version !== NATIVE_RANGE_CHECKPOINT_SCHEMA
174
+ || !validRangeScope(value.scope) || typeof value.head !== 'string' || !hex.test(value.head)
175
+ || value.count !== value.scope.last_position - value.scope.first_position + 1) return null;
176
+ return value;
177
+ }
178
+
179
+ function packageRecords(bundles) {
180
+ if (Array.isArray(bundles)) return bundles;
181
+ return exactFields(bundles, ['schema_version', 'records']) && bundles.schema_version === NATIVE_PACKAGE_SCHEMA
182
+ && Array.isArray(bundles.records) ? bundles.records : null;
183
+ }
184
+
185
+ export function witnessNativeCheckpoint(candidate, { bundles, checkpointPublicKey, witnessPrivateKey, scope } = {}) {
186
+ const authority = publicKeyPin(checkpointPublicKey, 'ed25519');
187
+ const checkpoint = openRangeCheckpoint(candidate, authority);
188
+ if (!checkpoint) throw new Error('INVALID_STUDIO_CHECKPOINT');
189
+ if (!validRangeScope(scope) || canonicalJson(scope) !== canonicalJson(checkpoint.scope)) throw new Error('CHECKPOINT_SCOPE_MISMATCH');
190
+ const records = packageRecords(bundles);
191
+ if (records?.length !== checkpoint.count || nativeRangeHead(records, scope) !== checkpoint.head) throw new Error('CHECKPOINT_HEAD_MISMATCH');
192
+ const key = witnessPrivateKey?.type === 'private' ? witnessPrivateKey : createPrivateKey(witnessPrivateKey);
193
+ if (key.asymmetricKeyType !== 'ed25519') throw new Error('INVALID_WITNESS_KEY');
194
+ const witness = keyPin(key);
195
+ if (authority.id === witness.id) throw new Error('WITNESS_MUST_USE_OWN_KEY');
196
+ return signDsse(NATIVE_WITNESS_TYPE, candidate, witness);
197
+ }
198
+
199
+ function checkRuntime(record, envelope, marker, roots) {
200
+ const signing = envelope.native_runtime_signing;
201
+ const status = signing?.status ?? 'missing';
202
+ if (record.runtime_signing !== status) return 'RUNTIME_SIGNING_STATUS_MISMATCH';
203
+ if (status === 'not_configured' && !signing.dsse_envelope) return 'RUNTIME_SIGNING_NOT_CONFIGURED';
204
+ const dsse = signing?.dsse_envelope;
205
+ if (!dsse?.signatures?.length) return 'RUNTIME_SIGNATURE_MISSING';
206
+ const pins = (roots?.runtimes || []).filter(root => root?.agent_id === envelope.agent_id)
207
+ .map(root => publicKeyPin(root.public_key, 'rsa')).filter(pin => pin?.id === dsse.signatures[0]?.keyid);
208
+ const scope = { orgId: envelope.org_id, agentId: envelope.agent_id, actionId: envelope.action_id, marker };
209
+ if (status !== 'signed' || pins.length !== 1 || !verifyNativeRuntimeCall(dsse, pins[0], scope)) return 'INVALID_RUNTIME_SIGNATURE';
210
+ return null;
211
+ }
212
+
213
+ function checkOwner(proof, predicate, roots, authorityIds) {
214
+ if (!proof.outcome?.native_owner_receipt || !proof.outcome?.native_owner_closure) return fail('OWNER_CLOSURE_MISSING');
215
+ const { native_resource: resource, business_authority: businessAuthority } = proof.action_envelope;
216
+ const owners = (roots?.owners || []).filter(root => root?.resource_id === resource?.resource_id
217
+ && ownerReceiptKey(root.public_key)?.id === resource?.key_id);
218
+ if (!resource?.key_id || owners.length !== 1 || authorityIds.includes(resource.key_id)) return fail('INVALID_OWNER_KEY');
219
+ const observation = proof.outcome.native_owner_closure.original;
220
+ const outcome = verifyNativeOwnerClosure(proof, owners[0].public_key);
221
+ if (!outcome.verified) return outcome;
222
+ if (canonicalJson(observation) !== canonicalJson(predicate.observation)) return fail('OWNER_CLOSURE_PROOF_MISMATCH');
223
+ if (!validDelegation({ ...predicate, timestamp_start: observation.timestamp_start, business_authority: businessAuthority,
224
+ approval_receipts: proof.approval_receipts }, roots.issuers)) return fail('INVALID_DELEGATION');
225
+ return outcome;
226
+ }
227
+
228
+ function checkRecord(record, proofPin, roots, authorityIds) {
229
+ const reasons = [];
230
+ const failRecord = code => ({ reasons: [...reasons, code], outcome: 'unknown' });
231
+ if (!exactFields(record, ['schema_version', 'payload_sha256', 'proof_signing', 'runtime_signing', 'dsse_envelope'])
232
+ || record.schema_version !== NATIVE_RANGE_RECORD_SCHEMA) return failRecord('INVALID_RECORD');
233
+ const unsigned = record.proof_signing === 'not_configured';
234
+ const envelope = record.dsse_envelope;
235
+ if (unsigned) reasons.push('PROOF_SIGNING_NOT_CONFIGURED');
236
+ else if (!envelope?.signatures?.length) reasons.push('PROOF_SIGNATURE_MISSING');
237
+ const opened = unsigned ? openDsse(envelope, NATIVE_PROOF_TYPE) : proofPin && openDsse(envelope, NATIVE_PROOF_TYPE, proofPin);
238
+ if (!opened || (!unsigned && record.proof_signing !== 'signed')) {
239
+ return reasons.length ? { reasons, outcome: 'unknown' } : failRecord('INVALID_PROOF_SIGNATURE');
240
+ }
241
+ const statement = opened.value;
242
+ const p = statement.predicate;
243
+ const proof = p?.proof_bundle;
244
+ const action = proof?.action_envelope;
245
+ let marker;
246
+ try { marker = JSON.parse(action?.input_summary)?.osuite_native_call; } catch { return failRecord('INVALID_RECORD_BINDING'); }
247
+ if (opened.digest !== record.payload_sha256 || statement._type !== 'https://in-toto.io/Statement/v1'
248
+ || statement.predicateType !== NATIVE_RANGE_PREDICATE || proof.schema_version !== 'osuite.proof_bundle.v1'
249
+ || proof.derived_from_legacy || action.runtime_family !== 'sdk_tool_runtime' || action.adapter_mode !== 'sdk_wrapper'
250
+ || !actionId.test(p.action_id || '') || !safeId(p.agent_id) || !safeId(p.org_id)
251
+ || action.action_id !== p.action_id || action.agent_id !== p.agent_id || action.org_id !== p.org_id
252
+ || marker?.schema_version !== 'osuite.native_tool_call.v1'
253
+ || ![marker.input_digest, marker.binding_digest, marker.operation_digest].every(value => typeof value === 'string' && hex.test(value))
254
+ || !Array.isArray(statement.subject) || statement.subject.length !== 1 || statement.subject[0]?.name !== p.action_id
255
+ || proof.manifest?.digest !== proofDigest(proofManifestPayload(proof))
256
+ || `sha256:${statement.subject[0]?.digest?.sha256}` !== proof.manifest.digest) return failRecord('INVALID_RECORD_BINDING');
257
+ const runtime = checkRuntime(record, action, marker, roots);
258
+ if (runtime) reasons.push(runtime);
259
+ const owner = checkOwner(proof, { ...p, input_digest: marker.input_digest }, roots, authorityIds);
260
+ if (!owner.verified) reasons.push(owner.code);
261
+ return { action_id: p.action_id, org_id: p.org_id, log_id: p.log_id, position: p.position, reasons,
262
+ outcome: owner.outcome ?? 'unknown' };
263
+ }
264
+
265
+ export function verifyNativeProofPackage({ bundles, roots, checkpoint, witnessPublicKey, scope: expectedScope } = {}) {
266
+ const reasons = [];
267
+ const proofPin = publicKeyPin(roots?.proof, 'ed25519');
268
+ const checkpointPin = publicKeyPin(roots?.checkpoint, 'ed25519');
269
+ const witnessPin = publicKeyPin(witnessPublicKey, 'ed25519');
270
+ const authorityIds = [proofPin?.id, checkpointPin?.id, witnessPin?.id];
271
+ const validRoots = new Set(authorityIds).size === 3 && authorityIds.every(Boolean)
272
+ && Array.isArray(roots?.runtimes) && Array.isArray(roots?.owners);
273
+ if (!validRoots) reasons.push('INVALID_TRUST_ROOTS');
274
+ const witnessed = witnessPin && openDsse(checkpoint, NATIVE_WITNESS_TYPE, witnessPin);
275
+ if (!witnessed) reasons.push('INVALID_WITNESS_SIGNATURE');
276
+ const claim = witnessed && openRangeCheckpoint(witnessed.value, checkpointPin);
277
+ if (witnessed && !claim) reasons.push('INVALID_STUDIO_CHECKPOINT');
278
+ const scope = claim?.scope ?? null;
279
+ if (scope && expectedScope !== undefined && (!validRangeScope(expectedScope) || canonicalJson(scope) !== canonicalJson(expectedScope))) {
280
+ reasons.push('CHECKPOINT_SCOPE_MISMATCH');
281
+ }
282
+ const records = packageRecords(bundles);
283
+ if (!records || records.length > NATIVE_RANGE_LIMIT) {
284
+ return { verified: false, scope, reasons: [...reasons, 'INVALID_PACKAGE'], count: 0, records: [] };
285
+ }
286
+ if (claim) {
287
+ if (records.length !== claim.count) reasons.push('INCOMPLETE_RANGE');
288
+ try {
289
+ if (nativeRangeHead(records, scope) !== claim.head) reasons.push('CHECKPOINT_HEAD_MISMATCH');
290
+ } catch { reasons.push('INVALID_PACKAGE'); }
291
+ }
292
+ const seen = new Set();
293
+ const outcomes = { committed: 0, absent: 0, unknown: 0 };
294
+ const results = Array.from(records, (record, index) => {
295
+ let result;
296
+ try { result = checkRecord(record, proofPin, roots, authorityIds); }
297
+ catch { result = { reasons: ['INVALID_RECORD'], outcome: 'unknown' }; }
298
+ const { action_id, org_id, log_id, position, outcome, reasons: issues } = result;
299
+ if (action_id) {
300
+ if (seen.has(action_id)) issues.push('DUPLICATE_RECORD');
301
+ seen.add(action_id);
302
+ if (scope && (org_id !== scope.org_id || log_id !== scope.log_id || !Number.isSafeInteger(position)
303
+ || position < scope.first_position || position > scope.last_position)) issues.push('RECORD_OUTSIDE_CHECKPOINT');
304
+ else if (scope && position !== scope.first_position + index) issues.push('RECORD_OUT_OF_ORDER');
305
+ }
306
+ outcomes[outcome]++;
307
+ return { index, position: position ?? null, action_id: action_id ?? null, outcome, verified: issues.length === 0, reasons: issues };
308
+ });
309
+ if (results.some(record => !record.verified)) reasons.push('RECORD_VERIFICATION_FAILED');
310
+ return { verified: reasons.length === 0, scope, reasons, count: records.length, outcomes, records: results };
311
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osuite",
3
- "version": "2.17.0",
3
+ "version": "2.19.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": {
@@ -35,6 +35,7 @@
35
35
  },
36
36
  "files": [
37
37
  "cli.js",
38
+ "checkpointCli.mjs",
38
39
  "onboardingCli.js",
39
40
  "credentials.js",
40
41
  "installationIdentity.js",
@@ -48,6 +49,7 @@
48
49
  "governed-tools/examples/*.mjs",
49
50
  "GOVERNED_TOOLS.md",
50
51
  "GOVERNED_RECOVERY.md",
52
+ "RELEASE_NOTES.md",
51
53
  "business-evidence.mjs",
52
54
  "BUSINESS_EVIDENCE.md",
53
55
  "controlled-transfers.mjs",
@@ -0,0 +1,3 @@
1
+ export const MIN_GUARD_WEBHOOK_TIMEOUT_MS = 1000;
2
+ export const DEFAULT_GUARD_WEBHOOK_TIMEOUT_MS = 5000;
3
+ export const MAX_GUARD_WEBHOOK_TIMEOUT_MS = 10000;
@@ -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: controller.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); }