protect-mcp 0.4.1 → 0.4.3

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/dist/index.mjs CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  formatSimulation,
3
3
  parseLogFile,
4
4
  simulate
5
- } from "./chunk-VWUN6AI6.mjs";
5
+ } from "./chunk-VIA2B65K.mjs";
6
6
  import {
7
7
  collectSignedReceipts,
8
8
  createAuditBundle
@@ -19,12 +19,14 @@ import {
19
19
  listCredentialLabels,
20
20
  loadPolicy,
21
21
  meetsMinTier,
22
+ parseNotificationConfigFromEnv,
22
23
  parseRateLimit,
23
24
  queryExternalPDP,
24
25
  resolveCredential,
26
+ sendApprovalNotification,
25
27
  signDecision,
26
28
  validateCredentials
27
- } from "./chunk-7HBHIKLN.mjs";
29
+ } from "./chunk-VF3OCG4D.mjs";
28
30
  import {
29
31
  formatReportMarkdown,
30
32
  generateReport
@@ -184,18 +186,1269 @@ function validateEvidenceReceipt(receipt) {
184
186
  }
185
187
  return errors;
186
188
  }
189
+
190
+ // src/rekor-anchor.ts
191
+ import { createHash } from "crypto";
192
+ var REKOR_API = "https://rekor.sigstore.dev/api/v1";
193
+ async function anchorToRekor(receiptHash, signature, publicKeyPem) {
194
+ const entry = {
195
+ apiVersion: "0.0.1",
196
+ kind: "hashedrekord",
197
+ spec: {
198
+ data: {
199
+ hash: {
200
+ algorithm: "sha256",
201
+ value: receiptHash
202
+ }
203
+ },
204
+ signature: {
205
+ content: signature,
206
+ publicKey: {
207
+ content: Buffer.from(publicKeyPem).toString("base64")
208
+ }
209
+ }
210
+ }
211
+ };
212
+ const response = await fetch(`${REKOR_API}/log/entries`, {
213
+ method: "POST",
214
+ headers: { "Content-Type": "application/json" },
215
+ body: JSON.stringify(entry)
216
+ });
217
+ if (!response.ok) {
218
+ const errorText = await response.text();
219
+ throw new Error(`Rekor anchoring failed: ${response.status} ${errorText}`);
220
+ }
221
+ const result = await response.json();
222
+ const [uuid, data] = Object.entries(result)[0];
223
+ return {
224
+ logIndex: data.logIndex,
225
+ uuid,
226
+ integratedTime: new Date(data.integratedTime * 1e3).toISOString(),
227
+ receiptHash,
228
+ logID: data.logID,
229
+ body: data.body
230
+ };
231
+ }
232
+ async function verifyRekorAnchor(logIndex, expectedHash) {
233
+ const response = await fetch(`${REKOR_API}/log/entries?logIndex=${logIndex}`);
234
+ if (!response.ok) {
235
+ return {
236
+ valid: false,
237
+ logIndex,
238
+ integratedTime: "",
239
+ receiptHashMatch: false
240
+ };
241
+ }
242
+ const result = await response.json();
243
+ const [, data] = Object.entries(result)[0];
244
+ let receiptHashMatch = false;
245
+ try {
246
+ const bodyJson = JSON.parse(Buffer.from(data.body, "base64").toString());
247
+ const hash = bodyJson?.spec?.data?.hash?.value;
248
+ receiptHashMatch = hash === expectedHash;
249
+ } catch {
250
+ }
251
+ return {
252
+ valid: receiptHashMatch,
253
+ logIndex,
254
+ integratedTime: new Date(data.integratedTime * 1e3).toISOString(),
255
+ receiptHashMatch
256
+ };
257
+ }
258
+ function hashReceipt(receipt) {
259
+ const canonical = JSON.stringify(receipt, Object.keys(receipt).sort());
260
+ return createHash("sha256").update(canonical).digest("hex");
261
+ }
262
+ function createLogAnchorField(anchor) {
263
+ return {
264
+ transparency_log: "rekor.sigstore.dev",
265
+ log_index: anchor.logIndex,
266
+ integrated_time: anchor.integratedTime,
267
+ receipt_hash: anchor.receiptHash,
268
+ verify_url: `https://search.sigstore.dev/?logIndex=${anchor.logIndex}`
269
+ };
270
+ }
271
+
272
+ // src/selective-disclosure.ts
273
+ import { createHash as createHash2, randomBytes } from "crypto";
274
+ function redactFields(receipt, fieldsToRedact) {
275
+ const redacted = JSON.parse(JSON.stringify(receipt));
276
+ const salts = [];
277
+ const redactedFields = [];
278
+ const originalHash = hashObject(receipt);
279
+ for (const fieldPath of fieldsToRedact) {
280
+ const parts = fieldPath.split(".");
281
+ let current = redacted;
282
+ let parent = null;
283
+ let lastKey = "";
284
+ for (let i = 0; i < parts.length; i++) {
285
+ const key = parts[i];
286
+ if (i === parts.length - 1) {
287
+ if (key in current) {
288
+ const originalValue = current[key];
289
+ const salt = randomBytes(16).toString("hex");
290
+ const commitment = computeCommitment(salt, originalValue);
291
+ salts.push({ field: fieldPath, salt, originalValue });
292
+ current[key] = `sha256(salt + ${typeof originalValue === "string" ? "..." : JSON.stringify(originalValue).slice(0, 20) + "..."})`;
293
+ redactedFields.push(fieldPath);
294
+ if (!redacted._commitments) {
295
+ redacted._commitments = {};
296
+ }
297
+ redacted._commitments[fieldPath] = commitment;
298
+ }
299
+ } else {
300
+ if (typeof current[key] === "object" && current[key] !== null) {
301
+ parent = current;
302
+ lastKey = key;
303
+ current = current[key];
304
+ } else {
305
+ break;
306
+ }
307
+ }
308
+ }
309
+ }
310
+ return { redacted, salts, redactedFields, originalHash };
311
+ }
312
+ function revealField(redactedReceipt, salts, fieldPath) {
313
+ const salt = salts.find((s) => s.field === fieldPath);
314
+ if (!salt) {
315
+ throw new Error(`No salt found for field: ${fieldPath}`);
316
+ }
317
+ const revealed = JSON.parse(JSON.stringify(redactedReceipt));
318
+ const parts = fieldPath.split(".");
319
+ let current = revealed;
320
+ for (let i = 0; i < parts.length; i++) {
321
+ const key = parts[i];
322
+ if (i === parts.length - 1) {
323
+ current[key] = salt.originalValue;
324
+ } else {
325
+ current = current[key];
326
+ }
327
+ }
328
+ return revealed;
329
+ }
330
+ function verifyCommitment(commitment, salt, value) {
331
+ const expected = computeCommitment(salt, value);
332
+ return commitment === expected;
333
+ }
334
+ function verifyAllCommitments(redactedReceipt, salts) {
335
+ const commitments = redactedReceipt._commitments;
336
+ if (!commitments) {
337
+ return { valid: true, fields: {} };
338
+ }
339
+ const fields = {};
340
+ let allValid = true;
341
+ for (const salt of salts) {
342
+ const commitment = commitments[salt.field];
343
+ if (commitment) {
344
+ const valid = verifyCommitment(commitment, salt.salt, salt.originalValue);
345
+ fields[salt.field] = valid;
346
+ if (!valid) allValid = false;
347
+ }
348
+ }
349
+ return { valid: allValid, fields };
350
+ }
351
+ function createDisclosurePackage(allSalts, fieldsToDisclose) {
352
+ const disclosed = allSalts.filter((s) => fieldsToDisclose.includes(s.field)).map((s) => ({ field: s.field, salt: s.salt, value: s.originalValue }));
353
+ return {
354
+ version: "0.1",
355
+ disclosed_fields: fieldsToDisclose,
356
+ salts: disclosed
357
+ };
358
+ }
359
+ function computeCommitment(salt, value) {
360
+ const serialized = typeof value === "string" ? value : JSON.stringify(value);
361
+ return createHash2("sha256").update(salt + serialized).digest("hex");
362
+ }
363
+ function hashObject(obj) {
364
+ const canonical = JSON.stringify(obj, Object.keys(obj).sort());
365
+ return createHash2("sha256").update(canonical).digest("hex");
366
+ }
367
+
368
+ // src/huggingface-export.ts
369
+ function receiptsToHFRows(receipts) {
370
+ return receipts.map((r) => {
371
+ const raw = r;
372
+ const payload = raw.payload || {};
373
+ const edges = Array.isArray(raw.parent_receipts) ? raw.parent_receipts : [];
374
+ return {
375
+ receipt_id: String(raw.receipt_id || raw.id || ""),
376
+ receipt_type: String(raw.receipt_type || raw.type || "unknown"),
377
+ tool_name: payload.tool_name ? String(payload.tool_name) : null,
378
+ decision: payload.decision ? String(payload.decision) : null,
379
+ agent_id: payload.agent_id ? String(payload.agent_id) : raw.subject_id ? String(raw.subject_id) : null,
380
+ issuer_id: String(raw.issuer_id || "unknown"),
381
+ timestamp: String(raw.timestamp || raw.event_time || (/* @__PURE__ */ new Date()).toISOString()),
382
+ policy_hash: payload.active_policy_hash ? String(payload.active_policy_hash) : null,
383
+ edges,
384
+ edge_count: edges.length,
385
+ signature: raw.signature ? String(raw.signature) : null,
386
+ signed: Boolean(raw.signature),
387
+ context_hash: raw.context_hash ? String(raw.context_hash) : null,
388
+ chain_id: raw.chain_id ? String(raw.chain_id) : null
389
+ };
390
+ });
391
+ }
392
+ function generateHFMetadata(rows, name) {
393
+ const types = {};
394
+ const decisions = {};
395
+ const agents = /* @__PURE__ */ new Set();
396
+ const tools = /* @__PURE__ */ new Set();
397
+ let minTime = Infinity;
398
+ let maxTime = -Infinity;
399
+ for (const row of rows) {
400
+ types[row.receipt_type] = (types[row.receipt_type] || 0) + 1;
401
+ if (row.decision) decisions[row.decision] = (decisions[row.decision] || 0) + 1;
402
+ if (row.agent_id) agents.add(row.agent_id);
403
+ if (row.tool_name) tools.add(row.tool_name);
404
+ const t = new Date(row.timestamp).getTime();
405
+ if (t < minTime) minTime = t;
406
+ if (t > maxTime) maxTime = t;
407
+ }
408
+ return {
409
+ name: name || "scopeblind-acta-receipts",
410
+ description: "Cryptographically signed decision receipts from AI agent tool calls. Each row is an Ed25519-signed receipt capturing a machine decision, its causal context, and policy evaluation result. Produced by protect-mcp and verified with @veritasacta/verify.",
411
+ num_rows: rows.length,
412
+ type_distribution: types,
413
+ decision_distribution: decisions,
414
+ time_range: {
415
+ from: isFinite(minTime) ? new Date(minTime).toISOString() : "",
416
+ to: isFinite(maxTime) ? new Date(maxTime).toISOString() : ""
417
+ },
418
+ unique_agents: agents.size,
419
+ unique_tools: tools.size,
420
+ exported_at: (/* @__PURE__ */ new Date()).toISOString(),
421
+ license: "MIT",
422
+ tags: [
423
+ "ai-safety",
424
+ "agent-governance",
425
+ "cryptographic-receipts",
426
+ "veritas-acta",
427
+ "scopeblind",
428
+ "mcp",
429
+ "ed25519",
430
+ "causal-dag",
431
+ "decision-evidence"
432
+ ]
433
+ };
434
+ }
435
+ function exportJSONL(rows) {
436
+ return rows.map((row) => JSON.stringify(row)).join("\n") + "\n";
437
+ }
438
+ function generateDatasetCard(metadata) {
439
+ return `---
440
+ license: mit
441
+ task_categories:
442
+ - text-classification
443
+ tags:
444
+ ${metadata.tags.map((t) => ` - ${t}`).join("\n")}
445
+ size_categories:
446
+ - ${metadata.num_rows < 1e3 ? "n<1K" : metadata.num_rows < 1e4 ? "1K<n<10K" : "10K<n<100K"}
447
+ ---
448
+
449
+ # ${metadata.name}
450
+
451
+ ${metadata.description}
452
+
453
+ ## Dataset Structure
454
+
455
+ Each row is a cryptographically signed receipt representing a single machine decision.
456
+
457
+ | Field | Type | Description |
458
+ |-------|------|-------------|
459
+ | receipt_id | string | Unique receipt identifier (content-addressed hash) |
460
+ | receipt_type | string | decision, execution, outcome, policy_load, observation, approval |
461
+ | tool_name | string | MCP tool that was called |
462
+ | decision | string | allow, deny, or null |
463
+ | agent_id | string | Pseudonymous agent identifier |
464
+ | timestamp | string | ISO 8601 timestamp |
465
+ | policy_hash | string | SHA-256 hash of the active policy |
466
+ | edges | array | Typed causal edges to parent receipts |
467
+ | signature | string | Ed25519 signature (hex) |
468
+ | signed | boolean | Whether the receipt has a valid signature |
469
+
470
+ ## Statistics
471
+
472
+ - **Total receipts:** ${metadata.num_rows.toLocaleString()}
473
+ - **Unique agents:** ${metadata.unique_agents}
474
+ - **Unique tools:** ${metadata.unique_tools}
475
+ - **Time range:** ${metadata.time_range.from} \u2192 ${metadata.time_range.to}
476
+
477
+ ### Type distribution
478
+ ${Object.entries(metadata.type_distribution).map(([k, v]) => `- ${k}: ${v}`).join("\n")}
479
+
480
+ ### Decision distribution
481
+ ${Object.entries(metadata.decision_distribution).map(([k, v]) => `- ${k}: ${v}`).join("\n")}
482
+
483
+ ## Verification
484
+
485
+ Every receipt in this dataset can be independently verified:
486
+
487
+ \`\`\`bash
488
+ npx @veritasacta/verify receipt.json
489
+ \`\`\`
490
+
491
+ The verification is offline, MIT-licensed, and does not contact any server.
492
+
493
+ ## Source
494
+
495
+ - Protocol: [Veritas Acta](https://veritasacta.com)
496
+ - Gateway: [protect-mcp](https://npmjs.com/package/protect-mcp)
497
+ - IETF Draft: [draft-farley-acta-signed-receipts](https://datatracker.ietf.org/doc/draft-farley-acta-signed-receipts/)
498
+
499
+ ## License
500
+
501
+ MIT
502
+ `;
503
+ }
504
+
505
+ // src/webauthn-approval.ts
506
+ import { createHash as createHash3, randomBytes as randomBytes2 } from "crypto";
507
+ function createApprovalChallenge(requestId, toolName, agentId, rpId = "scopeblind.com", timeoutSeconds = 300) {
508
+ const challengeBytes = randomBytes2(32);
509
+ const contextHash = createHash3("sha256").update(JSON.stringify({ requestId, toolName, agentId, timestamp: Date.now() })).digest("hex");
510
+ return {
511
+ challenge: base64urlEncode(challengeBytes),
512
+ requestId,
513
+ toolName,
514
+ agentId,
515
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
516
+ timeoutSeconds,
517
+ rpId,
518
+ contextHash
519
+ };
520
+ }
521
+ function toCredentialRequestOptions(challenge, allowCredentials) {
522
+ return {
523
+ publicKey: {
524
+ challenge: base64urlDecode(challenge.challenge).buffer,
525
+ rpId: challenge.rpId,
526
+ timeout: challenge.timeoutSeconds * 1e3,
527
+ userVerification: "required",
528
+ // Always require biometric
529
+ ...allowCredentials ? {
530
+ allowCredentials: allowCredentials.map((c) => ({
531
+ id: base64urlDecode(c.id).buffer,
532
+ type: "public-key"
533
+ }))
534
+ } : {}
535
+ }
536
+ };
537
+ }
538
+ function verifyApprovalAssertion(challenge, assertion) {
539
+ const createdAt = new Date(challenge.createdAt).getTime();
540
+ const now = Date.now();
541
+ if (now - createdAt > challenge.timeoutSeconds * 1e3) {
542
+ return {
543
+ valid: false,
544
+ credentialId: assertion.credentialId,
545
+ authenticatorType: "unknown",
546
+ userVerified: false,
547
+ signCount: 0,
548
+ contextHash: challenge.contextHash,
549
+ approvedAt: (/* @__PURE__ */ new Date()).toISOString()
550
+ };
551
+ }
552
+ const authData = base64urlDecode(assertion.authenticatorData);
553
+ const flags = authData[32];
554
+ const userPresent = !!(flags & 1);
555
+ const userVerified = !!(flags & 4);
556
+ const attestedCredData = !!(flags & 64);
557
+ const signCount = authData.length >= 37 ? authData[33] << 24 | authData[34] << 16 | authData[35] << 8 | authData[36] : 0;
558
+ let authenticatorType = "unknown";
559
+ try {
560
+ const clientData = JSON.parse(Buffer.from(base64urlDecode(assertion.clientDataJSON)).toString());
561
+ if (clientData.type === "webauthn.get") {
562
+ authenticatorType = "platform";
563
+ }
564
+ } catch {
565
+ }
566
+ return {
567
+ valid: userPresent,
568
+ // At minimum, user must be present
569
+ credentialId: assertion.credentialId,
570
+ authenticatorType,
571
+ userVerified,
572
+ signCount,
573
+ contextHash: challenge.contextHash,
574
+ approvedAt: (/* @__PURE__ */ new Date()).toISOString()
575
+ };
576
+ }
577
+ function createApprovalReceiptPayload(challenge, result) {
578
+ return {
579
+ type: "acta:approval",
580
+ approval_method: "webauthn",
581
+ tool_name: challenge.toolName,
582
+ request_id: challenge.requestId,
583
+ agent_id: challenge.agentId,
584
+ authenticator_type: result.authenticatorType,
585
+ user_verified: result.userVerified,
586
+ context_hash: result.contextHash,
587
+ approved_at: result.approvedAt,
588
+ // Hash the credential ID for privacy — don't store the raw ID
589
+ credential_id_hash: createHash3("sha256").update(result.credentialId).digest("hex").slice(0, 16)
590
+ };
591
+ }
592
+ function base64urlEncode(buffer) {
593
+ return Buffer.from(buffer).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
594
+ }
595
+ function base64urlDecode(str) {
596
+ const base64 = str.replace(/-/g, "+").replace(/_/g, "/");
597
+ const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
598
+ return new Uint8Array(Buffer.from(padded, "base64"));
599
+ }
600
+
601
+ // src/did-vc.ts
602
+ function ed25519ToDIDKey(publicKeyHex) {
603
+ const multicodecPrefix = Buffer.from([237, 1]);
604
+ const publicKeyBytes = Buffer.from(publicKeyHex, "hex");
605
+ const multicodecKey = Buffer.concat([multicodecPrefix, publicKeyBytes]);
606
+ const base58 = base58btcEncode(multicodecKey);
607
+ return `did:key:z${base58}`;
608
+ }
609
+ function manifestToVC(manifest) {
610
+ const did = ed25519ToDIDKey(manifest.public_key);
611
+ return {
612
+ "@context": [
613
+ "https://www.w3.org/2018/credentials/v1",
614
+ "https://veritasacta.com/contexts/agent-manifest/v1"
615
+ ],
616
+ type: ["VerifiableCredential", "AgentManifestCredential"],
617
+ issuer: did,
618
+ issuanceDate: manifest.created_at || (/* @__PURE__ */ new Date()).toISOString(),
619
+ credentialSubject: {
620
+ id: did,
621
+ agentId: manifest.agent_id,
622
+ displayName: manifest.display_name,
623
+ capabilities: manifest.capabilities || [],
624
+ policyDigest: manifest.policy_digest,
625
+ publicKey: manifest.public_key
626
+ },
627
+ ...manifest.signature ? {
628
+ proof: {
629
+ type: "Ed25519Signature2020",
630
+ created: manifest.created_at || (/* @__PURE__ */ new Date()).toISOString(),
631
+ verificationMethod: `${did}#key-1`,
632
+ proofPurpose: "assertionMethod",
633
+ proofValue: manifest.signature
634
+ }
635
+ } : {}
636
+ };
637
+ }
638
+ function receiptToVP(receipt, issuerPublicKey) {
639
+ const did = ed25519ToDIDKey(issuerPublicKey);
640
+ return {
641
+ "@context": ["https://www.w3.org/2018/credentials/v1"],
642
+ type: ["VerifiablePresentation"],
643
+ holder: did,
644
+ verifiableCredential: [{
645
+ "@context": [
646
+ "https://www.w3.org/2018/credentials/v1",
647
+ "https://veritasacta.com/contexts/decision-receipt/v1"
648
+ ],
649
+ type: ["VerifiableCredential", "DecisionReceiptCredential"],
650
+ issuer: did,
651
+ issuanceDate: receipt.event_time || (/* @__PURE__ */ new Date()).toISOString(),
652
+ credentialSubject: {
653
+ receiptId: receipt.receipt_id,
654
+ receiptType: receipt.receipt_type,
655
+ toolName: receipt.payload?.tool_name,
656
+ decision: receipt.payload?.decision
657
+ }
658
+ }]
659
+ };
660
+ }
661
+ function base58btcEncode(buffer) {
662
+ const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
663
+ let num = BigInt("0x" + buffer.toString("hex"));
664
+ let result = "";
665
+ while (num > 0n) {
666
+ result = ALPHABET[Number(num % 58n)] + result;
667
+ num = num / 58n;
668
+ }
669
+ for (const byte of buffer) {
670
+ if (byte === 0) result = "1" + result;
671
+ else break;
672
+ }
673
+ return result;
674
+ }
675
+
676
+ // src/sandbox.ts
677
+ async function createSandbox(config) {
678
+ const runtime = config.runtime || (config.apiKey || process.env.E2B_API_KEY ? "e2b" : "docker");
679
+ if (runtime === "e2b") {
680
+ return createE2BSandbox(config);
681
+ }
682
+ return createDockerSandbox(config);
683
+ }
684
+ async function runInSandbox(sandbox, toolCall, policy) {
685
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
686
+ const decision = evaluatePolicy(toolCall.tool, policy);
687
+ const receipt = {
688
+ tool: toolCall.tool,
689
+ decision,
690
+ executed: decision === "allow",
691
+ timestamp
692
+ };
693
+ if (decision === "allow") {
694
+ try {
695
+ const result = await executeInSandbox(sandbox, toolCall);
696
+ receipt.result = result;
697
+ receipt.executed = true;
698
+ } catch (err) {
699
+ receipt.result = {
700
+ success: false,
701
+ output: "",
702
+ error: err instanceof Error ? err.message : String(err),
703
+ durationMs: 0
704
+ };
705
+ }
706
+ }
707
+ sandbox.receipts.push(receipt);
708
+ return receipt;
709
+ }
710
+ function generateSafetyTranscript(sandbox, template) {
711
+ const receipts = sandbox.receipts;
712
+ const allowed = receipts.filter((r) => r.decision === "allow").length;
713
+ const denied = receipts.filter((r) => r.decision === "deny").length;
714
+ const requireApproval = receipts.filter((r) => r.decision === "require_approval").length;
715
+ const executed = receipts.filter((r) => r.executed && r.result);
716
+ const successful = executed.filter((r) => r.result?.success);
717
+ const denyScore = denied > 0 ? 40 : allowed > 0 ? 20 : 40;
718
+ const successRate = executed.length > 0 ? successful.length / executed.length : 1;
719
+ const successScore = 30 * successRate;
720
+ const approvalScore = requireApproval === 0 ? 30 : 15;
721
+ const safetyScore = Math.round(denyScore + successScore + approvalScore);
722
+ return {
723
+ sandboxId: sandbox.id,
724
+ template,
725
+ totalCalls: receipts.length,
726
+ allowed,
727
+ denied,
728
+ requireApproval,
729
+ successRate,
730
+ receipts,
731
+ durationMs: 0,
732
+ // Would be calculated from first/last receipt timestamps
733
+ evaluatedAt: (/* @__PURE__ */ new Date()).toISOString(),
734
+ safetyScore: Math.min(100, Math.max(0, safetyScore))
735
+ };
736
+ }
737
+ async function destroySandbox(sandbox) {
738
+ sandbox.status = "destroyed";
739
+ if (sandbox.runtime === "docker") {
740
+ try {
741
+ const { execSync } = await import("child_process");
742
+ execSync(`docker rm -f ${sandbox.id} 2>/dev/null`, { stdio: "pipe" });
743
+ } catch {
744
+ }
745
+ }
746
+ }
747
+ async function createE2BSandbox(config) {
748
+ const apiKey = config.apiKey || process.env.E2B_API_KEY;
749
+ if (!apiKey) {
750
+ throw new Error("E2B_API_KEY not set. Get one at https://e2b.dev");
751
+ }
752
+ const response = await fetch("https://api.e2b.dev/sandboxes", {
753
+ method: "POST",
754
+ headers: {
755
+ "Content-Type": "application/json",
756
+ "X-API-Key": apiKey
757
+ },
758
+ body: JSON.stringify({
759
+ templateID: config.template,
760
+ timeout: config.timeoutSeconds || 300
761
+ })
762
+ });
763
+ if (!response.ok) {
764
+ throw new Error(`E2B sandbox creation failed: ${response.status}`);
765
+ }
766
+ const data = await response.json();
767
+ return {
768
+ id: data.sandboxID,
769
+ runtime: "e2b",
770
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
771
+ status: "running",
772
+ receipts: []
773
+ };
774
+ }
775
+ async function createDockerSandbox(config) {
776
+ const { execSync } = await import("child_process");
777
+ const { randomUUID: randomUUID2 } = await import("crypto");
778
+ const id = `scopeblind-sandbox-${randomUUID2().slice(0, 8)}`;
779
+ const image = config.template.includes(":") ? config.template : `node:${config.template.replace("node-", "")}`;
780
+ const memoryFlag = config.memoryMB ? `--memory=${config.memoryMB}m` : "";
781
+ const timeout = config.timeoutSeconds || 300;
782
+ try {
783
+ execSync(
784
+ `docker run -d --name ${id} ${memoryFlag} --network=none --stop-timeout=${timeout} ${image} sleep ${timeout}`,
785
+ { stdio: "pipe" }
786
+ );
787
+ } catch (err) {
788
+ throw new Error(`Docker sandbox creation failed: ${err instanceof Error ? err.message : err}`);
789
+ }
790
+ return {
791
+ id,
792
+ runtime: "docker",
793
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
794
+ status: "running",
795
+ receipts: []
796
+ };
797
+ }
798
+ async function executeInSandbox(sandbox, toolCall) {
799
+ const start = Date.now();
800
+ if (sandbox.runtime === "docker") {
801
+ const { execSync } = await import("child_process");
802
+ try {
803
+ const command = toolCall.args.command || `echo "Tool: ${toolCall.tool}"`;
804
+ const output = execSync(
805
+ `docker exec ${sandbox.id} sh -c '${command.replace(/'/g, "'\\''")}'`,
806
+ { stdio: "pipe", timeout: 3e4 }
807
+ ).toString();
808
+ return {
809
+ success: true,
810
+ output: output.trim(),
811
+ durationMs: Date.now() - start,
812
+ exitCode: 0
813
+ };
814
+ } catch (err) {
815
+ const execErr = err;
816
+ return {
817
+ success: false,
818
+ output: "",
819
+ error: execErr.stderr?.toString() || String(err),
820
+ durationMs: Date.now() - start,
821
+ exitCode: execErr.status || 1
822
+ };
823
+ }
824
+ }
825
+ return {
826
+ success: true,
827
+ output: `[E2B] Executed ${toolCall.tool} in sandbox ${sandbox.id}`,
828
+ durationMs: Date.now() - start
829
+ };
830
+ }
831
+ function evaluatePolicy(tool, policy) {
832
+ if (!policy) return "allow";
833
+ const tools = policy.tools;
834
+ if (!tools) return "allow";
835
+ const toolPolicy = tools[tool] || tools["*"];
836
+ if (!toolPolicy) return "allow";
837
+ if (toolPolicy.block) return "deny";
838
+ if (toolPolicy.require_approval) return "require_approval";
839
+ return "allow";
840
+ }
841
+
842
+ // src/evidence-authenticity.ts
843
+ import { createHash as createHash4 } from "crypto";
844
+ async function createEvidenceAttestation(input) {
845
+ const tlsNotaryAvailable = await isTLSNotaryAvailable();
846
+ if (tlsNotaryAvailable) {
847
+ return createTLSNotaryAttestation(input);
848
+ }
849
+ return {
850
+ version: "0.1-beta",
851
+ method: "self-reported",
852
+ url: input.url,
853
+ httpMethod: input.httpMethod || "GET",
854
+ responseHash: input.responseHash,
855
+ statusCode: input.statusCode || 200,
856
+ fetchedAt: input.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
857
+ verified: false,
858
+ verificationNote: "Self-reported attestation. No third-party verification. TLSNotary integration planned for Q3 2026."
859
+ };
860
+ }
861
+ async function verifyEvidenceAttestation(attestation) {
862
+ switch (attestation.method) {
863
+ case "self-reported":
864
+ return {
865
+ valid: false,
866
+ method: "self-reported",
867
+ note: "Self-reported attestation cannot be independently verified. The response hash is included for integrity checking if the original data is available."
868
+ };
869
+ case "tlsnotary":
870
+ if (!attestation.notaryPublicKey || !attestation.notarySignature) {
871
+ return {
872
+ valid: false,
873
+ method: "tlsnotary",
874
+ note: "TLSNotary attestation is missing notary public key or signature."
875
+ };
876
+ }
877
+ return {
878
+ valid: false,
879
+ method: "tlsnotary",
880
+ note: "TLSNotary verification not yet implemented. Attestation format is correct but signature cannot be checked."
881
+ };
882
+ case "oracle":
883
+ return {
884
+ valid: attestation.verified,
885
+ method: "oracle",
886
+ note: attestation.verified ? "Attestation verified by oracle service." : "Oracle verification pending or failed."
887
+ };
888
+ case "witness":
889
+ return {
890
+ valid: attestation.verified,
891
+ method: "witness",
892
+ note: attestation.verified ? "Attestation witnessed by independent third party." : "Witness verification pending."
893
+ };
894
+ default:
895
+ return {
896
+ valid: false,
897
+ method: "unknown",
898
+ note: "Unknown attestation method."
899
+ };
900
+ }
901
+ }
902
+ function hashResponseBody(body) {
903
+ return createHash4("sha256").update(typeof body === "string" ? body : body).digest("hex");
904
+ }
905
+ function createAttestationField(attestation) {
906
+ return {
907
+ evidence_authenticity: {
908
+ version: attestation.version,
909
+ method: attestation.method,
910
+ url_hash: createHash4("sha256").update(attestation.url).digest("hex").slice(0, 16),
911
+ response_hash: attestation.responseHash,
912
+ fetched_at: attestation.fetchedAt,
913
+ verified: attestation.verified,
914
+ note: attestation.verificationNote
915
+ }
916
+ };
917
+ }
918
+ async function isTLSNotaryAvailable() {
919
+ try {
920
+ await import("tlsn-js");
921
+ return true;
922
+ } catch {
923
+ return false;
924
+ }
925
+ }
926
+ async function createTLSNotaryAttestation(input) {
927
+ return {
928
+ version: "0.1-beta",
929
+ method: "tlsnotary",
930
+ url: input.url,
931
+ httpMethod: input.httpMethod || "GET",
932
+ responseHash: input.responseHash,
933
+ statusCode: input.statusCode || 200,
934
+ fetchedAt: input.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
935
+ verified: false,
936
+ verificationNote: "TLSNotary SDK integration in progress. Attestation format is stable; verification will be enabled in a future release."
937
+ };
938
+ }
939
+
940
+ // src/c2pa-credentials.ts
941
+ import { createHash as createHash5 } from "crypto";
942
+ function createC2PAManifest(receipts, options) {
943
+ const generator = options.generator || "protect-mcp";
944
+ const version = options.version || "0.3.3";
945
+ const decisions = receipts.filter(
946
+ (r) => r.receipt_type?.includes("decision") || r.type?.includes("decision")
947
+ );
948
+ const allows = decisions.filter(
949
+ (r) => r.payload?.decision === "allow"
950
+ );
951
+ const denies = decisions.filter(
952
+ (r) => r.payload?.decision === "deny"
953
+ );
954
+ const receiptHashes = receipts.map(
955
+ (r) => createHash5("sha256").update(JSON.stringify(r)).digest("hex")
956
+ );
957
+ const merkleRoot = computeMerkleRoot(receiptHashes);
958
+ const assertions = [
959
+ // Acta decision provenance — the core assertion
960
+ {
961
+ label: "acta.decision-provenance",
962
+ data: {
963
+ protocol: "veritas-acta",
964
+ protocol_version: "0.1",
965
+ ietf_draft: "draft-farley-acta-signed-receipts-00",
966
+ receipt_count: receipts.length,
967
+ decision_count: decisions.length,
968
+ allows: allows.length,
969
+ denies: denies.length,
970
+ merkle_root: merkleRoot,
971
+ signing_algorithm: "Ed25519",
972
+ canonicalization: "JCS (RFC 8785)",
973
+ verifier: "npx @veritasacta/verify",
974
+ verify_url: "https://scopeblind.com/verify",
975
+ trace_url: "https://scopeblind.com/trace"
976
+ }
977
+ },
978
+ // Policy compliance assertion
979
+ {
980
+ label: "acta.policy-compliance",
981
+ data: {
982
+ policy_violations: denies.length,
983
+ total_decisions: decisions.length,
984
+ compliance_rate: decisions.length > 0 ? (allows.length / decisions.length * 100).toFixed(1) + "%" : "N/A",
985
+ policy_engine: "Cedar + JSON",
986
+ human_approvals: receipts.filter(
987
+ (r) => r.receipt_type?.includes("approval") || r.type?.includes("approval")
988
+ ).length
989
+ }
990
+ },
991
+ // Standard C2PA actions
992
+ {
993
+ label: "c2pa.actions",
994
+ data: {
995
+ actions: [
996
+ {
997
+ action: "c2pa.created",
998
+ when: (/* @__PURE__ */ new Date()).toISOString(),
999
+ softwareAgent: `${generator}/${version}`,
1000
+ parameters: {
1001
+ description: "Content generated by AI agent with ScopeBlind governance"
1002
+ }
1003
+ }
1004
+ ]
1005
+ }
1006
+ }
1007
+ ];
1008
+ if (options.includeFullReceipts) {
1009
+ assertions.push({
1010
+ label: "acta.receipt-chain",
1011
+ data: {
1012
+ receipts: receipts.map((r) => ({
1013
+ id: r.receipt_id || r.id,
1014
+ type: r.receipt_type || r.type,
1015
+ tool: r.payload?.tool_name,
1016
+ decision: r.payload?.decision,
1017
+ timestamp: r.timestamp || r.event_time
1018
+ }))
1019
+ }
1020
+ });
1021
+ } else {
1022
+ assertions.push({
1023
+ label: "acta.receipt-chain",
1024
+ data: {
1025
+ receipt_hashes: receiptHashes,
1026
+ merkle_root: merkleRoot,
1027
+ note: "Full receipts available via verify URL. Hashes provided for integrity verification."
1028
+ },
1029
+ is_hash: true
1030
+ });
1031
+ }
1032
+ if (options.additionalAssertions) {
1033
+ assertions.push(...options.additionalAssertions);
1034
+ }
1035
+ return {
1036
+ claim_generator: `${generator}/${version}`,
1037
+ claim_generator_info: [
1038
+ {
1039
+ name: generator,
1040
+ version
1041
+ }
1042
+ ],
1043
+ title: options.title,
1044
+ assertions
1045
+ };
1046
+ }
1047
+ function exportC2PAManifestJSON(manifest) {
1048
+ return JSON.stringify(manifest, null, 2);
1049
+ }
1050
+ function generateC2PACommand(manifestPath, inputPath, outputPath) {
1051
+ return `c2patool ${inputPath} -m ${manifestPath} -o ${outputPath}`;
1052
+ }
1053
+ function verifyActaC2PAAssertions(c2paManifestJson) {
1054
+ try {
1055
+ const manifest = JSON.parse(c2paManifestJson);
1056
+ const assertions = manifest.assertions || [];
1057
+ const provenanceAssertion = assertions.find(
1058
+ (a) => a.label === "acta.decision-provenance"
1059
+ );
1060
+ const complianceAssertion = assertions.find(
1061
+ (a) => a.label === "acta.policy-compliance"
1062
+ );
1063
+ if (!provenanceAssertion) {
1064
+ return {
1065
+ hasActaProvenance: false,
1066
+ receiptCount: 0,
1067
+ merkleRoot: null,
1068
+ complianceRate: null,
1069
+ verifyUrl: null
1070
+ };
1071
+ }
1072
+ return {
1073
+ hasActaProvenance: true,
1074
+ receiptCount: provenanceAssertion.data.receipt_count || 0,
1075
+ merkleRoot: provenanceAssertion.data.merkle_root || null,
1076
+ complianceRate: complianceAssertion ? complianceAssertion.data.compliance_rate : null,
1077
+ verifyUrl: provenanceAssertion.data.verify_url || null
1078
+ };
1079
+ } catch {
1080
+ return {
1081
+ hasActaProvenance: false,
1082
+ receiptCount: 0,
1083
+ merkleRoot: null,
1084
+ complianceRate: null,
1085
+ verifyUrl: null
1086
+ };
1087
+ }
1088
+ }
1089
+ function computeMerkleRoot(hashes) {
1090
+ if (hashes.length === 0) return "";
1091
+ if (hashes.length === 1) return hashes[0];
1092
+ const nextLevel = [];
1093
+ for (let i = 0; i < hashes.length; i += 2) {
1094
+ const left = hashes[i];
1095
+ const right = i + 1 < hashes.length ? hashes[i + 1] : left;
1096
+ nextLevel.push(
1097
+ createHash5("sha256").update(left + right).digest("hex")
1098
+ );
1099
+ }
1100
+ return computeMerkleRoot(nextLevel);
1101
+ }
1102
+
1103
+ // src/prediction-bridge.ts
1104
+ function computeCalibration(predictions, resolutions) {
1105
+ let totalSquaredError = 0;
1106
+ let resolved = 0;
1107
+ const buckets = /* @__PURE__ */ new Map();
1108
+ for (const pred of predictions) {
1109
+ const resolution = resolutions.get(pred.receipt_id);
1110
+ if (!resolution || resolution.payload.resolution_value === "ambiguous") continue;
1111
+ resolved++;
1112
+ const actual = resolution.payload.resolution_value === "true" ? 1 : 0;
1113
+ const error = (pred.payload.probability - actual) ** 2;
1114
+ totalSquaredError += error;
1115
+ const bucketKey = `${Math.floor(pred.payload.probability * 10) / 10}-${Math.ceil(pred.payload.probability * 10) / 10}`;
1116
+ const bucket = buckets.get(bucketKey) || { sum: 0, actual: 0, count: 0 };
1117
+ bucket.sum += pred.payload.probability;
1118
+ bucket.actual += actual;
1119
+ bucket.count++;
1120
+ buckets.set(bucketKey, bucket);
1121
+ }
1122
+ return {
1123
+ total_predictions: predictions.length,
1124
+ resolved,
1125
+ brier_score: resolved > 0 ? totalSquaredError / resolved : 0,
1126
+ calibration_buckets: Array.from(buckets.entries()).map(([bucket, data]) => ({
1127
+ bucket,
1128
+ predicted_probability: data.sum / data.count,
1129
+ actual_frequency: data.actual / data.count,
1130
+ count: data.count
1131
+ }))
1132
+ };
1133
+ }
1134
+ function toMetaculusFormat(prediction) {
1135
+ return {
1136
+ prediction_value: prediction.payload.probability,
1137
+ acta_receipt_id: prediction.receipt_id,
1138
+ acta_signature: prediction.signature
1139
+ };
1140
+ }
1141
+ function toManifoldFormat(prediction) {
1142
+ return {
1143
+ probability: prediction.payload.probability,
1144
+ acta_receipt_id: prediction.receipt_id,
1145
+ acta_signature: prediction.signature
1146
+ };
1147
+ }
1148
+
1149
+ // src/agent-exchange.ts
1150
+ import { randomUUID } from "crypto";
1151
+ var ReceiptPropagator = class {
1152
+ issuer;
1153
+ signer;
1154
+ receipts = /* @__PURE__ */ new Map();
1155
+ delegationCallCounts = /* @__PURE__ */ new Map();
1156
+ constructor(config) {
1157
+ this.issuer = config.issuer;
1158
+ this.signer = config.signer;
1159
+ }
1160
+ /**
1161
+ * Create a delegation receipt authorizing another agent to use specific tools.
1162
+ *
1163
+ * @patent Patent-protected construction — delegated signing with receipt chain
1164
+ * propagation. Covered by Apache 2.0 patent grant for users of this code.
1165
+ * Clean-room reimplementation requires a patent license.
1166
+ * @see {@link https://datatracker.ietf.org/doc/draft-farley-acta-signed-receipts/}
1167
+ */
1168
+ delegate(delegateId, options) {
1169
+ const now = /* @__PURE__ */ new Date();
1170
+ const receipt = {
1171
+ receipt_id: `del_${randomUUID().slice(0, 12)}`,
1172
+ receipt_type: "delegation",
1173
+ issuer_id: this.issuer,
1174
+ event_time: now.toISOString(),
1175
+ payload: {
1176
+ delegate_id: delegateId,
1177
+ authorized_tools: options.tools,
1178
+ scope: options.scope,
1179
+ ttl: options.ttl,
1180
+ expires_at: new Date(now.getTime() + options.ttl * 1e3).toISOString(),
1181
+ max_calls: options.maxCalls,
1182
+ allow_subdelegation: options.allowSubdelegation ?? false
1183
+ },
1184
+ parent_receipts: options.parentReceipts || []
1185
+ };
1186
+ if (this.signer) {
1187
+ const signed = this.signer(receipt);
1188
+ Object.assign(receipt, signed);
1189
+ }
1190
+ this.receipts.set(receipt.receipt_id, receipt);
1191
+ this.delegationCallCounts.set(receipt.receipt_id, 0);
1192
+ return receipt;
1193
+ }
1194
+ /**
1195
+ * Wrap a tool call with a receipt that references the delegation.
1196
+ * Validates the delegation is still valid (not expired, within call limit,
1197
+ * tool is authorized).
1198
+ *
1199
+ * @patent Patent-protected construction — delegated signing with receipt chain
1200
+ * propagation. Covered by Apache 2.0 patent grant for users of this code.
1201
+ * Clean-room reimplementation requires a patent license.
1202
+ * @see {@link https://datatracker.ietf.org/doc/draft-farley-acta-signed-receipts/}
1203
+ */
1204
+ wrapAction(toolName, options) {
1205
+ const delegation = this.receipts.get(options.delegation_receipt);
1206
+ let decision = "allow";
1207
+ if (!delegation) {
1208
+ decision = "deny";
1209
+ } else if (delegation.receipt_type !== "delegation") {
1210
+ decision = "deny";
1211
+ } else {
1212
+ if (new Date(delegation.payload.expires_at) < /* @__PURE__ */ new Date()) {
1213
+ decision = "deny";
1214
+ }
1215
+ if (!delegation.payload.authorized_tools.includes(toolName) && !delegation.payload.authorized_tools.includes("*")) {
1216
+ decision = "deny";
1217
+ }
1218
+ if (delegation.payload.max_calls !== void 0) {
1219
+ const count = this.delegationCallCounts.get(options.delegation_receipt) || 0;
1220
+ if (count >= delegation.payload.max_calls) {
1221
+ decision = "deny";
1222
+ }
1223
+ }
1224
+ }
1225
+ const currentCount = this.delegationCallCounts.get(options.delegation_receipt) || 0;
1226
+ this.delegationCallCounts.set(options.delegation_receipt, currentCount + 1);
1227
+ const receipt = {
1228
+ receipt_id: `act_${randomUUID().slice(0, 12)}`,
1229
+ receipt_type: "execution",
1230
+ issuer_id: this.issuer,
1231
+ event_time: (/* @__PURE__ */ new Date()).toISOString(),
1232
+ payload: {
1233
+ tool_name: toolName,
1234
+ decision,
1235
+ delegation_receipt: options.delegation_receipt,
1236
+ scope: delegation?.payload.scope || "unknown",
1237
+ call_index: currentCount + 1
1238
+ },
1239
+ parent_receipts: [options.delegation_receipt]
1240
+ };
1241
+ if (this.signer) {
1242
+ const signed = this.signer(receipt);
1243
+ Object.assign(receipt, signed);
1244
+ }
1245
+ this.receipts.set(receipt.receipt_id, receipt);
1246
+ return receipt;
1247
+ }
1248
+ /**
1249
+ * Trace the full receipt chain from a given receipt back to the root delegation.
1250
+ *
1251
+ * @patent Patent-protected construction — delegated signing with receipt chain
1252
+ * propagation. Covered by Apache 2.0 patent grant for users of this code.
1253
+ * Clean-room reimplementation requires a patent license.
1254
+ * @see {@link https://datatracker.ietf.org/doc/draft-farley-acta-signed-receipts/}
1255
+ */
1256
+ traceChain(receiptId) {
1257
+ const chain = [];
1258
+ const visited = /* @__PURE__ */ new Set();
1259
+ const walk = (id) => {
1260
+ if (visited.has(id)) return;
1261
+ visited.add(id);
1262
+ const receipt = this.receipts.get(id);
1263
+ if (!receipt) return;
1264
+ for (const parentId of receipt.parent_receipts) {
1265
+ walk(parentId);
1266
+ }
1267
+ chain.push(receipt);
1268
+ };
1269
+ walk(receiptId);
1270
+ return chain;
1271
+ }
1272
+ /**
1273
+ * Export all receipts as a JSON array (for verification, archival, or Trace visualization).
1274
+ */
1275
+ exportAll() {
1276
+ return Array.from(this.receipts.values());
1277
+ }
1278
+ /**
1279
+ * Validate that a delegation chain is intact and all signatures verify.
1280
+ *
1281
+ * @patent Patent-protected construction — delegated signing with receipt chain
1282
+ * propagation. Covered by Apache 2.0 patent grant for users of this code.
1283
+ * Clean-room reimplementation requires a patent license.
1284
+ * @see {@link https://datatracker.ietf.org/doc/draft-farley-acta-signed-receipts/}
1285
+ */
1286
+ validateChain(receiptId) {
1287
+ const chain = this.traceChain(receiptId);
1288
+ const issues = [];
1289
+ if (chain.length === 0) {
1290
+ return { valid: false, chain_length: 0, issues: ["Receipt not found"] };
1291
+ }
1292
+ let sawAction = false;
1293
+ for (const receipt of chain) {
1294
+ if (receipt.receipt_type === "delegation" && sawAction) {
1295
+ issues.push(`Delegation ${receipt.receipt_id} appears after action in chain`);
1296
+ }
1297
+ if (receipt.receipt_type === "execution") sawAction = true;
1298
+ }
1299
+ for (const receipt of chain) {
1300
+ for (const parentId of receipt.parent_receipts) {
1301
+ if (!this.receipts.has(parentId)) {
1302
+ issues.push(`Missing parent receipt: ${parentId}`);
1303
+ }
1304
+ }
1305
+ }
1306
+ return {
1307
+ valid: issues.length === 0,
1308
+ chain_length: chain.length,
1309
+ issues
1310
+ };
1311
+ }
1312
+ };
1313
+ function createReceiptChannel(orchestratorId) {
1314
+ const propagator = new ReceiptPropagator({ issuer: orchestratorId });
1315
+ return {
1316
+ propagator,
1317
+ async withDelegation(delegateId, tools, fn, options) {
1318
+ const delegation = propagator.delegate(delegateId, {
1319
+ tools,
1320
+ scope: options?.scope || `task-${randomUUID().slice(0, 8)}`,
1321
+ ttl: options?.ttl || 3600,
1322
+ maxCalls: options?.maxCalls
1323
+ });
1324
+ const result = await fn({ delegation, propagator });
1325
+ return {
1326
+ result,
1327
+ delegation,
1328
+ chain: propagator.exportAll()
1329
+ };
1330
+ }
1331
+ };
1332
+ }
1333
+
1334
+ // src/confidential.ts
1335
+ var ConfidentialGate = class {
1336
+ config;
1337
+ constructor(config) {
1338
+ this.config = config;
1339
+ }
1340
+ /**
1341
+ * Evaluate an attestation document and determine the resulting trust tier.
1342
+ */
1343
+ evaluateAttestation(doc) {
1344
+ if (!this.config.accepted_providers.includes(doc.provider)) {
1345
+ return {
1346
+ accepted: false,
1347
+ tier: "unknown",
1348
+ provider: doc.provider,
1349
+ reason: `Provider ${doc.provider} not in accepted list: ${this.config.accepted_providers.join(", ")}`
1350
+ };
1351
+ }
1352
+ if (this.config.max_attestation_age) {
1353
+ const age = (Date.now() - new Date(doc.timestamp).getTime()) / 1e3;
1354
+ if (age > this.config.max_attestation_age) {
1355
+ return {
1356
+ accepted: false,
1357
+ tier: "unknown",
1358
+ provider: doc.provider,
1359
+ reason: `Attestation expired: age ${Math.floor(age)}s exceeds max ${this.config.max_attestation_age}s`
1360
+ };
1361
+ }
1362
+ }
1363
+ if (this.config.expected_measurements) {
1364
+ for (const [key, expected] of Object.entries(this.config.expected_measurements)) {
1365
+ const actual = doc.measurements[key];
1366
+ if (actual !== expected) {
1367
+ return {
1368
+ accepted: false,
1369
+ tier: "signed",
1370
+ provider: doc.provider,
1371
+ reason: `Measurement mismatch: ${key} expected ${expected}, got ${actual || "missing"}`
1372
+ };
1373
+ }
1374
+ }
1375
+ }
1376
+ return {
1377
+ accepted: true,
1378
+ tier: "privileged",
1379
+ provider: doc.provider,
1380
+ reason: `Attestation verified: ${doc.provider} enclave with valid measurements`
1381
+ };
1382
+ }
1383
+ /**
1384
+ * Check if an agent's current tier requires attestation.
1385
+ */
1386
+ requiresAttestation(currentTier) {
1387
+ if (!this.config.require_attestation) return false;
1388
+ const tierOrder = ["unknown", "signed", "evidenced", "privileged"];
1389
+ const requiredIdx = tierOrder.indexOf(this.config.min_trust_tier);
1390
+ const currentIdx = tierOrder.indexOf(currentTier);
1391
+ return currentIdx >= requiredIdx;
1392
+ }
1393
+ /**
1394
+ * Generate an attestation receipt documenting the evaluation.
1395
+ */
1396
+ toReceipt(result, agentId) {
1397
+ return {
1398
+ receipt_type: "attestation",
1399
+ issuer_id: "confidential-gate",
1400
+ event_time: (/* @__PURE__ */ new Date()).toISOString(),
1401
+ payload: {
1402
+ agent_id: agentId,
1403
+ provider: result.provider,
1404
+ accepted: result.accepted,
1405
+ resulting_tier: result.tier,
1406
+ reason: result.reason
1407
+ }
1408
+ };
1409
+ }
1410
+ };
1411
+ async function confidentialInference(_prompt, _config) {
1412
+ throw new Error(
1413
+ "Confidential inference requires a TEE/HE provider SDK. See docs at scopeblind.com/docs/confidential for setup instructions. Supported providers: Gramine (local_tee), Zama Concrete ML (homomorphic), NVIDIA Confidential Computing (secure_enclave)."
1414
+ );
1415
+ }
187
1416
  export {
1417
+ ConfidentialGate,
188
1418
  ProtectGateway,
1419
+ ReceiptPropagator,
1420
+ anchorToRekor,
189
1421
  buildDecisionContext,
190
1422
  checkRateLimit,
191
1423
  collectSignedReceipts,
1424
+ computeCalibration,
1425
+ confidentialInference,
1426
+ createApprovalChallenge,
1427
+ createApprovalReceiptPayload,
1428
+ createAttestationField,
192
1429
  createAuditBundle,
1430
+ createC2PAManifest,
1431
+ createDisclosurePackage,
1432
+ createEvidenceAttestation,
1433
+ createLogAnchorField,
1434
+ createReceiptChannel,
1435
+ createSandbox,
1436
+ destroySandbox,
1437
+ ed25519ToDIDKey,
193
1438
  evaluateTier,
1439
+ exportC2PAManifestJSON,
1440
+ exportJSONL,
194
1441
  formatReportMarkdown,
195
1442
  formatSimulation,
1443
+ generateC2PACommand,
1444
+ generateDatasetCard,
1445
+ generateHFMetadata,
196
1446
  generateReport,
1447
+ generateSafetyTranscript,
197
1448
  getSignerInfo,
198
1449
  getToolPolicy,
1450
+ hashReceipt,
1451
+ hashResponseBody,
199
1452
  initSigning,
200
1453
  isAgentId,
201
1454
  isDisclosureMode,
@@ -204,14 +1457,31 @@ export {
204
1457
  isSigningEnabled,
205
1458
  listCredentialLabels,
206
1459
  loadPolicy,
1460
+ manifestToVC,
207
1461
  meetsMinTier,
208
1462
  parseLogFile,
1463
+ parseNotificationConfigFromEnv,
209
1464
  parseRateLimit,
210
1465
  queryExternalPDP,
1466
+ receiptToVP,
1467
+ receiptsToHFRows,
1468
+ redactFields,
211
1469
  resolveCredential,
1470
+ revealField,
1471
+ runInSandbox,
1472
+ sendApprovalNotification,
212
1473
  signDecision,
213
1474
  simulate,
1475
+ toCredentialRequestOptions,
1476
+ toManifoldFormat,
1477
+ toMetaculusFormat,
214
1478
  validateCredentials,
215
1479
  validateEvidenceReceipt,
216
- validateManifest
1480
+ validateManifest,
1481
+ verifyActaC2PAAssertions,
1482
+ verifyAllCommitments,
1483
+ verifyApprovalAssertion,
1484
+ verifyCommitment,
1485
+ verifyEvidenceAttestation,
1486
+ verifyRekorAnchor
217
1487
  };