protect-mcp 0.4.2 → 0.4.4

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.js CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,22 +17,55 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
21
31
  var index_exports = {};
22
32
  __export(index_exports, {
33
+ ConfidentialGate: () => ConfidentialGate,
23
34
  ProtectGateway: () => ProtectGateway,
35
+ ReceiptPropagator: () => ReceiptPropagator,
36
+ anchorToRekor: () => anchorToRekor,
24
37
  buildDecisionContext: () => buildDecisionContext,
25
38
  checkRateLimit: () => checkRateLimit,
26
39
  collectSignedReceipts: () => collectSignedReceipts,
40
+ computeCalibration: () => computeCalibration,
41
+ confidentialInference: () => confidentialInference,
42
+ createApprovalChallenge: () => createApprovalChallenge,
43
+ createApprovalReceiptPayload: () => createApprovalReceiptPayload,
44
+ createAttestationField: () => createAttestationField,
27
45
  createAuditBundle: () => createAuditBundle,
46
+ createC2PAManifest: () => createC2PAManifest,
47
+ createDisclosurePackage: () => createDisclosurePackage,
48
+ createEvidenceAttestation: () => createEvidenceAttestation,
49
+ createLogAnchorField: () => createLogAnchorField,
50
+ createReceiptChannel: () => createReceiptChannel,
51
+ createSandbox: () => createSandbox,
52
+ createSandboxServer: () => createSandboxServer,
53
+ destroySandbox: () => destroySandbox,
54
+ ed25519ToDIDKey: () => ed25519ToDIDKey,
28
55
  evaluateTier: () => evaluateTier,
56
+ exportC2PAManifestJSON: () => exportC2PAManifestJSON,
57
+ exportJSONL: () => exportJSONL,
29
58
  formatReportMarkdown: () => formatReportMarkdown,
30
59
  formatSimulation: () => formatSimulation,
60
+ generateC2PACommand: () => generateC2PACommand,
61
+ generateDatasetCard: () => generateDatasetCard,
62
+ generateHFMetadata: () => generateHFMetadata,
31
63
  generateReport: () => generateReport,
64
+ generateSafetyTranscript: () => generateSafetyTranscript,
32
65
  getSignerInfo: () => getSignerInfo,
33
66
  getToolPolicy: () => getToolPolicy,
67
+ hashReceipt: () => hashReceipt,
68
+ hashResponseBody: () => hashResponseBody,
34
69
  initSigning: () => initSigning,
35
70
  isAgentId: () => isAgentId,
36
71
  isDisclosureMode: () => isDisclosureMode,
@@ -39,25 +74,42 @@ __export(index_exports, {
39
74
  isSigningEnabled: () => isSigningEnabled,
40
75
  listCredentialLabels: () => listCredentialLabels,
41
76
  loadPolicy: () => loadPolicy,
77
+ manifestToVC: () => manifestToVC,
42
78
  meetsMinTier: () => meetsMinTier,
43
79
  parseLogFile: () => parseLogFile,
80
+ parseNotificationConfigFromEnv: () => parseNotificationConfigFromEnv,
44
81
  parseRateLimit: () => parseRateLimit,
45
82
  queryExternalPDP: () => queryExternalPDP,
83
+ receiptToVP: () => receiptToVP,
84
+ receiptsToHFRows: () => receiptsToHFRows,
85
+ redactFields: () => redactFields,
46
86
  resolveCredential: () => resolveCredential,
87
+ revealField: () => revealField,
88
+ runInSandbox: () => runInSandbox,
89
+ sendApprovalNotification: () => sendApprovalNotification,
47
90
  signDecision: () => signDecision,
48
91
  simulate: () => simulate,
92
+ toCredentialRequestOptions: () => toCredentialRequestOptions,
93
+ toManifoldFormat: () => toManifoldFormat,
94
+ toMetaculusFormat: () => toMetaculusFormat,
49
95
  validateCredentials: () => validateCredentials,
50
96
  validateEvidenceReceipt: () => validateEvidenceReceipt,
51
- validateManifest: () => validateManifest
97
+ validateManifest: () => validateManifest,
98
+ verifyActaC2PAAssertions: () => verifyActaC2PAAssertions,
99
+ verifyAllCommitments: () => verifyAllCommitments,
100
+ verifyApprovalAssertion: () => verifyApprovalAssertion,
101
+ verifyCommitment: () => verifyCommitment,
102
+ verifyEvidenceAttestation: () => verifyEvidenceAttestation,
103
+ verifyRekorAnchor: () => verifyRekorAnchor
52
104
  });
53
105
  module.exports = __toCommonJS(index_exports);
54
106
 
55
107
  // src/gateway.ts
56
108
  var import_node_child_process = require("child_process");
57
- var import_node_crypto2 = require("crypto");
109
+ var import_node_crypto3 = require("crypto");
58
110
  var import_node_readline = require("readline");
59
- var import_node_fs5 = require("fs");
60
- var import_node_path3 = require("path");
111
+ var import_node_fs6 = require("fs");
112
+ var import_node_path4 = require("path");
61
113
 
62
114
  // src/policy.ts
63
115
  var import_node_crypto = require("crypto");
@@ -625,10 +677,334 @@ function buildDecisionContext(toolName, tier, opts) {
625
677
  };
626
678
  }
627
679
 
628
- // src/http-server.ts
629
- var import_node_http = require("http");
680
+ // src/cedar-evaluator.ts
681
+ var import_node_crypto2 = require("crypto");
630
682
  var import_node_fs4 = require("fs");
631
683
  var import_node_path2 = require("path");
684
+ var cedarWasm = null;
685
+ var loadAttempted = false;
686
+ async function ensureCedarWasm() {
687
+ if (cedarWasm) return true;
688
+ if (loadAttempted) return false;
689
+ loadAttempted = true;
690
+ try {
691
+ const moduleName = "@cedar-policy/cedar-wasm";
692
+ cedarWasm = await import(
693
+ /* @vite-ignore */
694
+ moduleName
695
+ );
696
+ return true;
697
+ } catch {
698
+ return false;
699
+ }
700
+ }
701
+ function buildEntities(req) {
702
+ const agentId = req.agentId || req.tier;
703
+ return [
704
+ {
705
+ uid: { type: "Agent", id: agentId },
706
+ attrs: {
707
+ tier: req.tier,
708
+ ...req.agentId ? { agent_id: req.agentId } : {}
709
+ },
710
+ parents: []
711
+ },
712
+ {
713
+ uid: { type: "Tool", id: req.tool },
714
+ attrs: {},
715
+ parents: []
716
+ }
717
+ ];
718
+ }
719
+ async function evaluateCedar(policySet, req) {
720
+ const available = await ensureCedarWasm();
721
+ if (!available) {
722
+ return {
723
+ allowed: true,
724
+ reason: "cedar_wasm_not_available",
725
+ metadata: { fallback: true }
726
+ };
727
+ }
728
+ try {
729
+ const agentId = req.agentId || req.tier;
730
+ const authRequest = {
731
+ principal: { type: "Agent", id: agentId },
732
+ action: { type: "Action", id: "MCP::Tool::call" },
733
+ resource: { type: "Tool", id: req.tool },
734
+ context: {
735
+ tier: req.tier,
736
+ ...req.context || {}
737
+ }
738
+ };
739
+ const entities = buildEntities(req);
740
+ let result;
741
+ if (typeof cedarWasm.isAuthorized === "function") {
742
+ result = cedarWasm.isAuthorized({
743
+ policies: policySet.source,
744
+ entities,
745
+ principal: authRequest.principal,
746
+ action: authRequest.action,
747
+ resource: authRequest.resource,
748
+ context: authRequest.context,
749
+ schema: null
750
+ // No schema enforcement — Cedar still evaluates correctly
751
+ });
752
+ } else if (typeof cedarWasm.checkAuthorization === "function") {
753
+ result = cedarWasm.checkAuthorization(
754
+ policySet.source,
755
+ JSON.stringify(entities),
756
+ JSON.stringify(authRequest)
757
+ );
758
+ } else {
759
+ const cedarEngine = cedarWasm.default || cedarWasm;
760
+ if (typeof cedarEngine.isAuthorized === "function") {
761
+ result = cedarEngine.isAuthorized({
762
+ policies: policySet.source,
763
+ entities,
764
+ principal: authRequest.principal,
765
+ action: authRequest.action,
766
+ resource: authRequest.resource,
767
+ context: authRequest.context,
768
+ schema: null
769
+ });
770
+ } else {
771
+ return {
772
+ allowed: true,
773
+ reason: "cedar_wasm_api_unsupported",
774
+ metadata: { fallback: true, exports: Object.keys(cedarWasm) }
775
+ };
776
+ }
777
+ }
778
+ const decision = parseWasmResult(result);
779
+ return {
780
+ allowed: decision.allowed,
781
+ reason: decision.allowed ? void 0 : `cedar_deny${decision.diagnostics ? ": " + decision.diagnostics : ""}`,
782
+ metadata: {
783
+ policy_digest: policySet.digest,
784
+ ...decision.matchedPolicies ? { matched_policies: decision.matchedPolicies } : {}
785
+ }
786
+ };
787
+ } catch (err) {
788
+ return {
789
+ allowed: true,
790
+ reason: `cedar_eval_error: ${err instanceof Error ? err.message : "unknown"}`,
791
+ metadata: { fallback: true, error: true }
792
+ };
793
+ }
794
+ }
795
+ function parseWasmResult(result) {
796
+ if (!result) {
797
+ return { allowed: true, diagnostics: "null result from Cedar WASM" };
798
+ }
799
+ if (result.type === "allow" || result.type === "Allow") {
800
+ return { allowed: true };
801
+ }
802
+ if (result.type === "deny" || result.type === "Deny") {
803
+ return {
804
+ allowed: false,
805
+ diagnostics: result.diagnostics ? JSON.stringify(result.diagnostics) : void 0,
806
+ matchedPolicies: result.diagnostics?.reasons
807
+ };
808
+ }
809
+ if (result.decision === "Allow") {
810
+ return { allowed: true };
811
+ }
812
+ if (result.decision === "Deny") {
813
+ return {
814
+ allowed: false,
815
+ diagnostics: result.diagnostics ? JSON.stringify(result.diagnostics) : void 0
816
+ };
817
+ }
818
+ if (typeof result === "boolean") {
819
+ return { allowed: result };
820
+ }
821
+ return { allowed: true, diagnostics: `unknown result format: ${JSON.stringify(result)}` };
822
+ }
823
+
824
+ // src/notifications.ts
825
+ async function sendApprovalNotification(config, notification) {
826
+ const promises = [];
827
+ if (config.sms) {
828
+ promises.push(sendSms(config.sms, notification));
829
+ }
830
+ if (config.webhook) {
831
+ promises.push(sendWebhook(config.webhook, notification));
832
+ }
833
+ if (config.email) {
834
+ promises.push(sendEmail(config.email, notification));
835
+ }
836
+ const results = await Promise.allSettled(promises);
837
+ for (const result of results) {
838
+ if (result.status === "rejected") {
839
+ console.error(`[protect-mcp] Notification failed: ${result.reason}`);
840
+ }
841
+ }
842
+ }
843
+ async function sendSms(config, notification) {
844
+ const body = [
845
+ `\u{1F512} Approval Required`,
846
+ `Tool: ${notification.toolName}`,
847
+ notification.agentId ? `Agent: ${notification.agentId}` : null,
848
+ `Reason: ${notification.reason}`,
849
+ notification.approveUrl ? `Approve: ${notification.approveUrl}` : null,
850
+ notification.traceUrl ? `Trace: ${notification.traceUrl}` : null
851
+ ].filter(Boolean).join("\n");
852
+ const params = new URLSearchParams({
853
+ To: config.to,
854
+ From: config.from,
855
+ Body: body
856
+ });
857
+ const response = await fetch(
858
+ `https://api.twilio.com/2010-04-01/Accounts/${config.accountSid}/Messages.json`,
859
+ {
860
+ method: "POST",
861
+ headers: {
862
+ Authorization: `Basic ${Buffer.from(`${config.accountSid}:${config.authToken}`).toString("base64")}`,
863
+ "Content-Type": "application/x-www-form-urlencoded"
864
+ },
865
+ body: params.toString()
866
+ }
867
+ );
868
+ if (!response.ok) {
869
+ throw new Error(`Twilio SMS failed: ${response.status} ${await response.text()}`);
870
+ }
871
+ }
872
+ async function sendWebhook(config, notification) {
873
+ let payload;
874
+ if (config.template === "slack") {
875
+ payload = {
876
+ blocks: [
877
+ {
878
+ type: "header",
879
+ text: { type: "plain_text", text: "\u{1F512} Agent Approval Required" }
880
+ },
881
+ {
882
+ type: "section",
883
+ fields: [
884
+ { type: "mrkdwn", text: `*Tool:*
885
+ \`${notification.toolName}\`` },
886
+ { type: "mrkdwn", text: `*Agent:*
887
+ ${notification.agentId || "unknown"}` },
888
+ { type: "mrkdwn", text: `*Policy:*
889
+ ${notification.policyName || "default"}` },
890
+ { type: "mrkdwn", text: `*Time:*
891
+ ${notification.timestamp}` }
892
+ ]
893
+ },
894
+ {
895
+ type: "section",
896
+ text: { type: "mrkdwn", text: `*Reason:* ${notification.reason}` }
897
+ },
898
+ ...notification.approveUrl || notification.traceUrl ? [
899
+ {
900
+ type: "actions",
901
+ elements: [
902
+ ...notification.approveUrl ? [{ type: "button", text: { type: "plain_text", text: "\u2705 Approve" }, url: notification.approveUrl, style: "primary" }] : [],
903
+ ...notification.traceUrl ? [{ type: "button", text: { type: "plain_text", text: "\u{1F50D} View Trace" }, url: notification.traceUrl }] : []
904
+ ]
905
+ }
906
+ ] : []
907
+ ]
908
+ };
909
+ } else if (config.template === "pagerduty") {
910
+ payload = {
911
+ routing_key: config.headers?.["X-Routing-Key"] || "",
912
+ event_action: "trigger",
913
+ payload: {
914
+ summary: `Agent approval required: ${notification.toolName}`,
915
+ source: "protect-mcp",
916
+ severity: "warning",
917
+ custom_details: {
918
+ tool: notification.toolName,
919
+ agent: notification.agentId,
920
+ policy: notification.policyName,
921
+ reason: notification.reason,
922
+ trace_url: notification.traceUrl,
923
+ approve_url: notification.approveUrl
924
+ }
925
+ }
926
+ };
927
+ } else {
928
+ payload = notification;
929
+ }
930
+ const response = await fetch(config.url, {
931
+ method: config.method || "POST",
932
+ headers: {
933
+ "Content-Type": "application/json",
934
+ ...config.headers
935
+ },
936
+ body: JSON.stringify(payload)
937
+ });
938
+ if (!response.ok) {
939
+ throw new Error(`Webhook failed: ${response.status}`);
940
+ }
941
+ }
942
+ async function sendEmail(config, notification) {
943
+ if (!config.resendApiKey) {
944
+ console.warn("[protect-mcp] Email notification skipped: no resendApiKey configured");
945
+ return;
946
+ }
947
+ const html = `
948
+ <div style="font-family: monospace; padding: 20px; background: #0d1117; color: #c9d1d9; border-radius: 8px;">
949
+ <h2 style="color: #10b981;">\u{1F512} Agent Approval Required</h2>
950
+ <table style="font-size: 14px; margin: 16px 0;">
951
+ <tr><td style="color: #8b949e; padding: 4px 16px 4px 0;">Tool:</td><td>${notification.toolName}</td></tr>
952
+ <tr><td style="color: #8b949e; padding: 4px 16px 4px 0;">Agent:</td><td>${notification.agentId || "unknown"}</td></tr>
953
+ <tr><td style="color: #8b949e; padding: 4px 16px 4px 0;">Reason:</td><td>${notification.reason}</td></tr>
954
+ <tr><td style="color: #8b949e; padding: 4px 16px 4px 0;">Time:</td><td>${notification.timestamp}</td></tr>
955
+ </table>
956
+ ${notification.approveUrl ? `<a href="${notification.approveUrl}" style="background: #10b981; color: white; padding: 8px 16px; border-radius: 6px; text-decoration: none; margin-right: 8px;">\u2705 Approve</a>` : ""}
957
+ ${notification.traceUrl ? `<a href="${notification.traceUrl}" style="background: #1f2937; color: #c9d1d9; padding: 8px 16px; border-radius: 6px; text-decoration: none; border: 1px solid #374151;">\u{1F50D} View Trace</a>` : ""}
958
+ </div>
959
+ `;
960
+ const response = await fetch("https://api.resend.com/emails", {
961
+ method: "POST",
962
+ headers: {
963
+ Authorization: `Bearer ${config.resendApiKey}`,
964
+ "Content-Type": "application/json"
965
+ },
966
+ body: JSON.stringify({
967
+ from: "ScopeBlind <noreply@scopeblind.com>",
968
+ to: config.to,
969
+ subject: `\u{1F512} Approval required: ${notification.toolName}`,
970
+ html
971
+ })
972
+ });
973
+ if (!response.ok) {
974
+ throw new Error(`Resend email failed: ${response.status}`);
975
+ }
976
+ }
977
+ function parseNotificationConfigFromEnv() {
978
+ const config = {};
979
+ let hasConfig = false;
980
+ const smsTo = process.env.SCOPEBLIND_SMS_TO;
981
+ const twilioSid = process.env.TWILIO_ACCOUNT_SID;
982
+ const twilioToken = process.env.TWILIO_AUTH_TOKEN;
983
+ const twilioFrom = process.env.TWILIO_FROM_NUMBER;
984
+ if (smsTo && twilioSid && twilioToken && twilioFrom) {
985
+ config.sms = { accountSid: twilioSid, authToken: twilioToken, from: twilioFrom, to: smsTo };
986
+ hasConfig = true;
987
+ }
988
+ const webhookUrl = process.env.SCOPEBLIND_WEBHOOK_URL;
989
+ if (webhookUrl) {
990
+ config.webhook = {
991
+ url: webhookUrl,
992
+ template: process.env.SCOPEBLIND_WEBHOOK_TEMPLATE || "custom"
993
+ };
994
+ hasConfig = true;
995
+ }
996
+ const emailTo = process.env.SCOPEBLIND_EMAIL_TO;
997
+ if (emailTo) {
998
+ config.email = { to: emailTo, resendApiKey: process.env.RESEND_API_KEY };
999
+ hasConfig = true;
1000
+ }
1001
+ return hasConfig ? config : null;
1002
+ }
1003
+
1004
+ // src/http-server.ts
1005
+ var import_node_http = require("http");
1006
+ var import_node_fs5 = require("fs");
1007
+ var import_node_path3 = require("path");
632
1008
  var LOG_FILE = ".protect-mcp-log.jsonl";
633
1009
  var MAX_RECEIPTS = 100;
634
1010
  var ReceiptBuffer = class {
@@ -721,13 +1097,13 @@ function handleHealth(res, startTime, config) {
721
1097
  }));
722
1098
  }
723
1099
  function handleStatus(res, logDir) {
724
- const logPath = (0, import_node_path2.join)(logDir, LOG_FILE);
725
- if (!(0, import_node_fs4.existsSync)(logPath)) {
1100
+ const logPath = (0, import_node_path3.join)(logDir, LOG_FILE);
1101
+ if (!(0, import_node_fs5.existsSync)(logPath)) {
726
1102
  res.writeHead(200);
727
1103
  res.end(JSON.stringify({ entries: 0, message: "no log file yet" }));
728
1104
  return;
729
1105
  }
730
- const raw = (0, import_node_fs4.readFileSync)(logPath, "utf-8");
1106
+ const raw = (0, import_node_fs5.readFileSync)(logPath, "utf-8");
731
1107
  const lines = raw.trim().split("\n").filter(Boolean);
732
1108
  const entries = [];
733
1109
  for (const line of lines) {
@@ -865,18 +1241,30 @@ var ProtectGateway = class {
865
1241
  /** Approval grants keyed by request_id (scoped to the specific action that was requested) */
866
1242
  approvalStore = /* @__PURE__ */ new Map();
867
1243
  /** Random nonce generated at startup — required for approval endpoint authentication */
868
- approvalNonce = (0, import_node_crypto2.randomBytes)(16).toString("hex");
1244
+ approvalNonce = (0, import_node_crypto3.randomBytes)(16).toString("hex");
869
1245
  currentTier = "unknown";
870
1246
  admissionResult = null;
1247
+ /** Notification config for approval gates (SMS, webhook, email) */
1248
+ notificationConfig = null;
871
1249
  /** HTTP transport mode: pending response resolvers keyed by JSON-RPC id */
872
1250
  pendingResponses = /* @__PURE__ */ new Map();
873
1251
  httpMode = false;
1252
+ /** Loaded Cedar policy set (when policy_engine is "cedar") */
1253
+ cedarPolicySet = null;
874
1254
  constructor(config) {
875
1255
  this.config = config;
876
- this.logFilePath = (0, import_node_path3.join)(process.cwd(), LOG_FILE2);
877
- this.receiptFilePath = (0, import_node_path3.join)(process.cwd(), RECEIPTS_FILE);
1256
+ this.logFilePath = (0, import_node_path4.join)(process.cwd(), LOG_FILE2);
1257
+ this.receiptFilePath = (0, import_node_path4.join)(process.cwd(), RECEIPTS_FILE);
878
1258
  this.evidenceStore = new EvidenceStore();
879
1259
  this.receiptBuffer = new ReceiptBuffer();
1260
+ this.notificationConfig = parseNotificationConfigFromEnv();
1261
+ }
1262
+ /**
1263
+ * Set the Cedar policy set for local evaluation.
1264
+ * Called during CLI startup when --cedar flag is used.
1265
+ */
1266
+ setCedarPolicies(policySet) {
1267
+ this.cedarPolicySet = policySet;
880
1268
  }
881
1269
  async start() {
882
1270
  const { command, args, verbose } = this.config;
@@ -1007,7 +1395,7 @@ var ProtectGateway = class {
1007
1395
  }
1008
1396
  async interceptToolCall(request) {
1009
1397
  const toolName = request.params?.name || "unknown";
1010
- const requestId = (0, import_node_crypto2.randomUUID)().slice(0, 12);
1398
+ const requestId = (0, import_node_crypto3.randomUUID)().slice(0, 12);
1011
1399
  const mode = this.config.enforce ? "enforce" : "shadow";
1012
1400
  let resolvedAgentKid = this.admissionResult?.agent_id;
1013
1401
  let effectiveToolPolicy;
@@ -1045,6 +1433,27 @@ var ProtectGateway = class {
1045
1433
  }
1046
1434
  }
1047
1435
  }
1436
+ if (this.config.policy?.policy_engine === "cedar" && this.cedarPolicySet) {
1437
+ try {
1438
+ const cedarDecision = await evaluateCedar(this.cedarPolicySet, {
1439
+ tool: toolName,
1440
+ tier: this.currentTier,
1441
+ agentId: this.admissionResult?.agent_id
1442
+ });
1443
+ if (!cedarDecision.allowed) {
1444
+ const reason = cedarDecision.reason || "cedar_deny";
1445
+ this.emitDecisionLog({ tool: toolName, decision: "deny", reason_code: reason, request_id: requestId, tier: this.currentTier, credential_ref: credentialRef });
1446
+ if (this.config.enforce) {
1447
+ return this.makeErrorResponse(request.id, -32600, `Tool "${toolName}" denied by Cedar policy`);
1448
+ }
1449
+ return null;
1450
+ }
1451
+ this.emitDecisionLog({ tool: toolName, decision: "allow", reason_code: "cedar_allow", request_id: requestId, tier: this.currentTier, credential_ref: credentialRef });
1452
+ return null;
1453
+ } catch (err) {
1454
+ if (this.config.verbose) this.log(`Cedar evaluation error: ${err instanceof Error ? err.message : err}`);
1455
+ }
1456
+ }
1048
1457
  if (this.config.policy?.external && (this.config.policy.policy_engine === "external" || this.config.policy.policy_engine === "hybrid")) {
1049
1458
  try {
1050
1459
  const ctx = buildDecisionContext(toolName, this.currentTier, {
@@ -1092,6 +1501,20 @@ var ProtectGateway = class {
1092
1501
  return null;
1093
1502
  }
1094
1503
  this.emitDecisionLog({ tool: toolName, decision: "require_approval", reason_code: "requires_human_approval", request_id: requestId, tier: this.currentTier, credential_ref: credentialRef });
1504
+ if (this.notificationConfig) {
1505
+ sendApprovalNotification(this.notificationConfig, {
1506
+ requestId,
1507
+ toolName,
1508
+ agentId: this.admissionResult?.agent_id,
1509
+ policyName: "default",
1510
+ reason: `Policy requires human approval for "${toolName}"`,
1511
+ traceUrl: `https://scopeblind.com/trace`,
1512
+ approveUrl: void 0,
1513
+ // Approve URL provided when HTTP transport is active
1514
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1515
+ }).catch(() => {
1516
+ });
1517
+ }
1095
1518
  if (this.config.enforce) {
1096
1519
  return {
1097
1520
  jsonrpc: "2.0",
@@ -1139,8 +1562,19 @@ var ProtectGateway = class {
1139
1562
  }
1140
1563
  return policy.rate_limit;
1141
1564
  }
1565
+ /**
1566
+ * Emit a decision log entry with OTel-compatible trace IDs and optional
1567
+ * signed receipt generation.
1568
+ *
1569
+ * @patent Patent-protected construction — decision receipts with configurable
1570
+ * disclosure and issuer-blind properties. Covered by Apache 2.0 patent grant
1571
+ * for users of this code. Clean-room reimplementation requires a patent license.
1572
+ * @see {@link https://datatracker.ietf.org/doc/draft-farley-acta-signed-receipts/}
1573
+ */
1142
1574
  emitDecisionLog(entry) {
1143
1575
  const mode = this.config.enforce ? "enforce" : "shadow";
1576
+ const otelTraceId = entry.otel_trace_id || (0, import_node_crypto3.randomBytes)(16).toString("hex");
1577
+ const otelSpanId = entry.otel_span_id || (0, import_node_crypto3.randomBytes)(8).toString("hex");
1144
1578
  const log = {
1145
1579
  v: 2,
1146
1580
  tool: entry.tool || "unknown",
@@ -1148,17 +1582,19 @@ var ProtectGateway = class {
1148
1582
  reason_code: entry.reason_code || "default_allow",
1149
1583
  policy_digest: this.config.policyDigest,
1150
1584
  policy_engine: this.config.policy?.policy_engine || "built-in",
1151
- request_id: entry.request_id || (0, import_node_crypto2.randomUUID)().slice(0, 12),
1585
+ request_id: entry.request_id || (0, import_node_crypto3.randomUUID)().slice(0, 12),
1152
1586
  timestamp: Date.now(),
1153
1587
  mode,
1154
1588
  ...entry.rate_limit_remaining !== void 0 && { rate_limit_remaining: entry.rate_limit_remaining },
1155
1589
  ...entry.tier && { tier: entry.tier },
1156
- ...entry.credential_ref && { credential_ref: entry.credential_ref }
1590
+ ...entry.credential_ref && { credential_ref: entry.credential_ref },
1591
+ otel_trace_id: otelTraceId,
1592
+ otel_span_id: otelSpanId
1157
1593
  };
1158
1594
  process.stderr.write(`[PROTECT_MCP] ${JSON.stringify(log)}
1159
1595
  `);
1160
1596
  try {
1161
- (0, import_node_fs5.appendFileSync)(this.logFilePath, JSON.stringify(log) + "\n");
1597
+ (0, import_node_fs6.appendFileSync)(this.logFilePath, JSON.stringify(log) + "\n");
1162
1598
  } catch {
1163
1599
  }
1164
1600
  if (isSigningEnabled()) {
@@ -1167,7 +1603,7 @@ var ProtectGateway = class {
1167
1603
  process.stderr.write(`[PROTECT_MCP_RECEIPT] ${signed.signed}
1168
1604
  `);
1169
1605
  try {
1170
- (0, import_node_fs5.appendFileSync)(this.receiptFilePath, signed.signed + "\n");
1606
+ (0, import_node_fs6.appendFileSync)(this.receiptFilePath, signed.signed + "\n");
1171
1607
  } catch {
1172
1608
  }
1173
1609
  this.receiptBuffer.add(log.request_id, signed.signed);
@@ -1357,9 +1793,9 @@ function collectSignedReceipts(logs) {
1357
1793
  }
1358
1794
 
1359
1795
  // src/simulate.ts
1360
- var import_node_fs6 = require("fs");
1796
+ var import_node_fs7 = require("fs");
1361
1797
  function parseLogFile(path) {
1362
- const raw = (0, import_node_fs6.readFileSync)(path, "utf-8");
1798
+ const raw = (0, import_node_fs7.readFileSync)(path, "utf-8");
1363
1799
  const entries = [];
1364
1800
  for (const line of raw.split("\n")) {
1365
1801
  const trimmed = line.trim();
@@ -1488,13 +1924,13 @@ function formatSimulation(summary) {
1488
1924
  }
1489
1925
 
1490
1926
  // src/report.ts
1491
- var import_node_fs7 = require("fs");
1927
+ var import_node_fs8 = require("fs");
1492
1928
  function generateReport(logPath, receiptPath, periodDays) {
1493
1929
  const now = /* @__PURE__ */ new Date();
1494
1930
  const from = new Date(now.getTime() - periodDays * 864e5);
1495
1931
  const entries = [];
1496
- if ((0, import_node_fs7.existsSync)(logPath)) {
1497
- const raw = (0, import_node_fs7.readFileSync)(logPath, "utf-8");
1932
+ if ((0, import_node_fs8.existsSync)(logPath)) {
1933
+ const raw = (0, import_node_fs8.readFileSync)(logPath, "utf-8");
1498
1934
  for (const line of raw.split("\n")) {
1499
1935
  const trimmed = line.trim();
1500
1936
  if (!trimmed) continue;
@@ -1514,8 +1950,8 @@ function generateReport(logPath, receiptPath, periodDays) {
1514
1950
  let receiptsSigned = 0;
1515
1951
  let signerKid = "";
1516
1952
  let signerIssuer = "";
1517
- if ((0, import_node_fs7.existsSync)(receiptPath)) {
1518
- const raw = (0, import_node_fs7.readFileSync)(receiptPath, "utf-8");
1953
+ if ((0, import_node_fs8.existsSync)(receiptPath)) {
1954
+ const raw = (0, import_node_fs8.readFileSync)(receiptPath, "utf-8");
1519
1955
  for (const line of raw.split("\n")) {
1520
1956
  const trimmed = line.trim();
1521
1957
  if (!trimmed) continue;
@@ -1802,19 +2238,1412 @@ function validateEvidenceReceipt(receipt) {
1802
2238
  }
1803
2239
  return errors;
1804
2240
  }
2241
+
2242
+ // src/rekor-anchor.ts
2243
+ var import_node_crypto4 = require("crypto");
2244
+ var REKOR_API = "https://rekor.sigstore.dev/api/v1";
2245
+ async function anchorToRekor(receiptHash, signature, publicKeyPem) {
2246
+ const entry = {
2247
+ apiVersion: "0.0.1",
2248
+ kind: "hashedrekord",
2249
+ spec: {
2250
+ data: {
2251
+ hash: {
2252
+ algorithm: "sha256",
2253
+ value: receiptHash
2254
+ }
2255
+ },
2256
+ signature: {
2257
+ content: signature,
2258
+ publicKey: {
2259
+ content: Buffer.from(publicKeyPem).toString("base64")
2260
+ }
2261
+ }
2262
+ }
2263
+ };
2264
+ const response = await fetch(`${REKOR_API}/log/entries`, {
2265
+ method: "POST",
2266
+ headers: { "Content-Type": "application/json" },
2267
+ body: JSON.stringify(entry)
2268
+ });
2269
+ if (!response.ok) {
2270
+ const errorText = await response.text();
2271
+ throw new Error(`Rekor anchoring failed: ${response.status} ${errorText}`);
2272
+ }
2273
+ const result = await response.json();
2274
+ const [uuid, data] = Object.entries(result)[0];
2275
+ return {
2276
+ logIndex: data.logIndex,
2277
+ uuid,
2278
+ integratedTime: new Date(data.integratedTime * 1e3).toISOString(),
2279
+ receiptHash,
2280
+ logID: data.logID,
2281
+ body: data.body
2282
+ };
2283
+ }
2284
+ async function verifyRekorAnchor(logIndex, expectedHash) {
2285
+ const response = await fetch(`${REKOR_API}/log/entries?logIndex=${logIndex}`);
2286
+ if (!response.ok) {
2287
+ return {
2288
+ valid: false,
2289
+ logIndex,
2290
+ integratedTime: "",
2291
+ receiptHashMatch: false
2292
+ };
2293
+ }
2294
+ const result = await response.json();
2295
+ const [, data] = Object.entries(result)[0];
2296
+ let receiptHashMatch = false;
2297
+ try {
2298
+ const bodyJson = JSON.parse(Buffer.from(data.body, "base64").toString());
2299
+ const hash = bodyJson?.spec?.data?.hash?.value;
2300
+ receiptHashMatch = hash === expectedHash;
2301
+ } catch {
2302
+ }
2303
+ return {
2304
+ valid: receiptHashMatch,
2305
+ logIndex,
2306
+ integratedTime: new Date(data.integratedTime * 1e3).toISOString(),
2307
+ receiptHashMatch
2308
+ };
2309
+ }
2310
+ function hashReceipt(receipt) {
2311
+ const canonical = JSON.stringify(receipt, Object.keys(receipt).sort());
2312
+ return (0, import_node_crypto4.createHash)("sha256").update(canonical).digest("hex");
2313
+ }
2314
+ function createLogAnchorField(anchor) {
2315
+ return {
2316
+ transparency_log: "rekor.sigstore.dev",
2317
+ log_index: anchor.logIndex,
2318
+ integrated_time: anchor.integratedTime,
2319
+ receipt_hash: anchor.receiptHash,
2320
+ verify_url: `https://search.sigstore.dev/?logIndex=${anchor.logIndex}`
2321
+ };
2322
+ }
2323
+
2324
+ // src/selective-disclosure.ts
2325
+ var import_node_crypto5 = require("crypto");
2326
+ function redactFields(receipt, fieldsToRedact) {
2327
+ const redacted = JSON.parse(JSON.stringify(receipt));
2328
+ const salts = [];
2329
+ const redactedFields = [];
2330
+ const originalHash = hashObject(receipt);
2331
+ for (const fieldPath of fieldsToRedact) {
2332
+ const parts = fieldPath.split(".");
2333
+ let current = redacted;
2334
+ let parent = null;
2335
+ let lastKey = "";
2336
+ for (let i = 0; i < parts.length; i++) {
2337
+ const key = parts[i];
2338
+ if (i === parts.length - 1) {
2339
+ if (key in current) {
2340
+ const originalValue = current[key];
2341
+ const salt = (0, import_node_crypto5.randomBytes)(16).toString("hex");
2342
+ const commitment = computeCommitment(salt, originalValue);
2343
+ salts.push({ field: fieldPath, salt, originalValue });
2344
+ current[key] = `sha256(salt + ${typeof originalValue === "string" ? "..." : JSON.stringify(originalValue).slice(0, 20) + "..."})`;
2345
+ redactedFields.push(fieldPath);
2346
+ if (!redacted._commitments) {
2347
+ redacted._commitments = {};
2348
+ }
2349
+ redacted._commitments[fieldPath] = commitment;
2350
+ }
2351
+ } else {
2352
+ if (typeof current[key] === "object" && current[key] !== null) {
2353
+ parent = current;
2354
+ lastKey = key;
2355
+ current = current[key];
2356
+ } else {
2357
+ break;
2358
+ }
2359
+ }
2360
+ }
2361
+ }
2362
+ return { redacted, salts, redactedFields, originalHash };
2363
+ }
2364
+ function revealField(redactedReceipt, salts, fieldPath) {
2365
+ const salt = salts.find((s) => s.field === fieldPath);
2366
+ if (!salt) {
2367
+ throw new Error(`No salt found for field: ${fieldPath}`);
2368
+ }
2369
+ const revealed = JSON.parse(JSON.stringify(redactedReceipt));
2370
+ const parts = fieldPath.split(".");
2371
+ let current = revealed;
2372
+ for (let i = 0; i < parts.length; i++) {
2373
+ const key = parts[i];
2374
+ if (i === parts.length - 1) {
2375
+ current[key] = salt.originalValue;
2376
+ } else {
2377
+ current = current[key];
2378
+ }
2379
+ }
2380
+ return revealed;
2381
+ }
2382
+ function verifyCommitment(commitment, salt, value) {
2383
+ const expected = computeCommitment(salt, value);
2384
+ return commitment === expected;
2385
+ }
2386
+ function verifyAllCommitments(redactedReceipt, salts) {
2387
+ const commitments = redactedReceipt._commitments;
2388
+ if (!commitments) {
2389
+ return { valid: true, fields: {} };
2390
+ }
2391
+ const fields = {};
2392
+ let allValid = true;
2393
+ for (const salt of salts) {
2394
+ const commitment = commitments[salt.field];
2395
+ if (commitment) {
2396
+ const valid = verifyCommitment(commitment, salt.salt, salt.originalValue);
2397
+ fields[salt.field] = valid;
2398
+ if (!valid) allValid = false;
2399
+ }
2400
+ }
2401
+ return { valid: allValid, fields };
2402
+ }
2403
+ function createDisclosurePackage(allSalts, fieldsToDisclose) {
2404
+ const disclosed = allSalts.filter((s) => fieldsToDisclose.includes(s.field)).map((s) => ({ field: s.field, salt: s.salt, value: s.originalValue }));
2405
+ return {
2406
+ version: "0.1",
2407
+ disclosed_fields: fieldsToDisclose,
2408
+ salts: disclosed
2409
+ };
2410
+ }
2411
+ function computeCommitment(salt, value) {
2412
+ const serialized = typeof value === "string" ? value : JSON.stringify(value);
2413
+ return (0, import_node_crypto5.createHash)("sha256").update(salt + serialized).digest("hex");
2414
+ }
2415
+ function hashObject(obj) {
2416
+ const canonical = JSON.stringify(obj, Object.keys(obj).sort());
2417
+ return (0, import_node_crypto5.createHash)("sha256").update(canonical).digest("hex");
2418
+ }
2419
+
2420
+ // src/huggingface-export.ts
2421
+ function receiptsToHFRows(receipts) {
2422
+ return receipts.map((r) => {
2423
+ const raw = r;
2424
+ const payload = raw.payload || {};
2425
+ const edges = Array.isArray(raw.parent_receipts) ? raw.parent_receipts : [];
2426
+ return {
2427
+ receipt_id: String(raw.receipt_id || raw.id || ""),
2428
+ receipt_type: String(raw.receipt_type || raw.type || "unknown"),
2429
+ tool_name: payload.tool_name ? String(payload.tool_name) : null,
2430
+ decision: payload.decision ? String(payload.decision) : null,
2431
+ agent_id: payload.agent_id ? String(payload.agent_id) : raw.subject_id ? String(raw.subject_id) : null,
2432
+ issuer_id: String(raw.issuer_id || "unknown"),
2433
+ timestamp: String(raw.timestamp || raw.event_time || (/* @__PURE__ */ new Date()).toISOString()),
2434
+ policy_hash: payload.active_policy_hash ? String(payload.active_policy_hash) : null,
2435
+ edges,
2436
+ edge_count: edges.length,
2437
+ signature: raw.signature ? String(raw.signature) : null,
2438
+ signed: Boolean(raw.signature),
2439
+ context_hash: raw.context_hash ? String(raw.context_hash) : null,
2440
+ chain_id: raw.chain_id ? String(raw.chain_id) : null
2441
+ };
2442
+ });
2443
+ }
2444
+ function generateHFMetadata(rows, name) {
2445
+ const types = {};
2446
+ const decisions = {};
2447
+ const agents = /* @__PURE__ */ new Set();
2448
+ const tools = /* @__PURE__ */ new Set();
2449
+ let minTime = Infinity;
2450
+ let maxTime = -Infinity;
2451
+ for (const row of rows) {
2452
+ types[row.receipt_type] = (types[row.receipt_type] || 0) + 1;
2453
+ if (row.decision) decisions[row.decision] = (decisions[row.decision] || 0) + 1;
2454
+ if (row.agent_id) agents.add(row.agent_id);
2455
+ if (row.tool_name) tools.add(row.tool_name);
2456
+ const t = new Date(row.timestamp).getTime();
2457
+ if (t < minTime) minTime = t;
2458
+ if (t > maxTime) maxTime = t;
2459
+ }
2460
+ return {
2461
+ name: name || "scopeblind-acta-receipts",
2462
+ 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.",
2463
+ num_rows: rows.length,
2464
+ type_distribution: types,
2465
+ decision_distribution: decisions,
2466
+ time_range: {
2467
+ from: isFinite(minTime) ? new Date(minTime).toISOString() : "",
2468
+ to: isFinite(maxTime) ? new Date(maxTime).toISOString() : ""
2469
+ },
2470
+ unique_agents: agents.size,
2471
+ unique_tools: tools.size,
2472
+ exported_at: (/* @__PURE__ */ new Date()).toISOString(),
2473
+ license: "MIT",
2474
+ tags: [
2475
+ "ai-safety",
2476
+ "agent-governance",
2477
+ "cryptographic-receipts",
2478
+ "veritas-acta",
2479
+ "scopeblind",
2480
+ "mcp",
2481
+ "ed25519",
2482
+ "causal-dag",
2483
+ "decision-evidence"
2484
+ ]
2485
+ };
2486
+ }
2487
+ function exportJSONL(rows) {
2488
+ return rows.map((row) => JSON.stringify(row)).join("\n") + "\n";
2489
+ }
2490
+ function generateDatasetCard(metadata) {
2491
+ return `---
2492
+ license: mit
2493
+ task_categories:
2494
+ - text-classification
2495
+ tags:
2496
+ ${metadata.tags.map((t) => ` - ${t}`).join("\n")}
2497
+ size_categories:
2498
+ - ${metadata.num_rows < 1e3 ? "n<1K" : metadata.num_rows < 1e4 ? "1K<n<10K" : "10K<n<100K"}
2499
+ ---
2500
+
2501
+ # ${metadata.name}
2502
+
2503
+ ${metadata.description}
2504
+
2505
+ ## Dataset Structure
2506
+
2507
+ Each row is a cryptographically signed receipt representing a single machine decision.
2508
+
2509
+ | Field | Type | Description |
2510
+ |-------|------|-------------|
2511
+ | receipt_id | string | Unique receipt identifier (content-addressed hash) |
2512
+ | receipt_type | string | decision, execution, outcome, policy_load, observation, approval |
2513
+ | tool_name | string | MCP tool that was called |
2514
+ | decision | string | allow, deny, or null |
2515
+ | agent_id | string | Pseudonymous agent identifier |
2516
+ | timestamp | string | ISO 8601 timestamp |
2517
+ | policy_hash | string | SHA-256 hash of the active policy |
2518
+ | edges | array | Typed causal edges to parent receipts |
2519
+ | signature | string | Ed25519 signature (hex) |
2520
+ | signed | boolean | Whether the receipt has a valid signature |
2521
+
2522
+ ## Statistics
2523
+
2524
+ - **Total receipts:** ${metadata.num_rows.toLocaleString()}
2525
+ - **Unique agents:** ${metadata.unique_agents}
2526
+ - **Unique tools:** ${metadata.unique_tools}
2527
+ - **Time range:** ${metadata.time_range.from} \u2192 ${metadata.time_range.to}
2528
+
2529
+ ### Type distribution
2530
+ ${Object.entries(metadata.type_distribution).map(([k, v]) => `- ${k}: ${v}`).join("\n")}
2531
+
2532
+ ### Decision distribution
2533
+ ${Object.entries(metadata.decision_distribution).map(([k, v]) => `- ${k}: ${v}`).join("\n")}
2534
+
2535
+ ## Verification
2536
+
2537
+ Every receipt in this dataset can be independently verified:
2538
+
2539
+ \`\`\`bash
2540
+ npx @veritasacta/verify receipt.json
2541
+ \`\`\`
2542
+
2543
+ The verification is offline, MIT-licensed, and does not contact any server.
2544
+
2545
+ ## Source
2546
+
2547
+ - Protocol: [Veritas Acta](https://veritasacta.com)
2548
+ - Gateway: [protect-mcp](https://npmjs.com/package/protect-mcp)
2549
+ - IETF Draft: [draft-farley-acta-signed-receipts](https://datatracker.ietf.org/doc/draft-farley-acta-signed-receipts/)
2550
+
2551
+ ## License
2552
+
2553
+ MIT
2554
+ `;
2555
+ }
2556
+
2557
+ // src/webauthn-approval.ts
2558
+ var import_node_crypto6 = require("crypto");
2559
+ function createApprovalChallenge(requestId, toolName, agentId, rpId = "scopeblind.com", timeoutSeconds = 300) {
2560
+ const challengeBytes = (0, import_node_crypto6.randomBytes)(32);
2561
+ const contextHash = (0, import_node_crypto6.createHash)("sha256").update(JSON.stringify({ requestId, toolName, agentId, timestamp: Date.now() })).digest("hex");
2562
+ return {
2563
+ challenge: base64urlEncode(challengeBytes),
2564
+ requestId,
2565
+ toolName,
2566
+ agentId,
2567
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2568
+ timeoutSeconds,
2569
+ rpId,
2570
+ contextHash
2571
+ };
2572
+ }
2573
+ function toCredentialRequestOptions(challenge, allowCredentials) {
2574
+ return {
2575
+ publicKey: {
2576
+ challenge: base64urlDecode(challenge.challenge).buffer,
2577
+ rpId: challenge.rpId,
2578
+ timeout: challenge.timeoutSeconds * 1e3,
2579
+ userVerification: "required",
2580
+ // Always require biometric
2581
+ ...allowCredentials ? {
2582
+ allowCredentials: allowCredentials.map((c) => ({
2583
+ id: base64urlDecode(c.id).buffer,
2584
+ type: "public-key"
2585
+ }))
2586
+ } : {}
2587
+ }
2588
+ };
2589
+ }
2590
+ function verifyApprovalAssertion(challenge, assertion) {
2591
+ const createdAt = new Date(challenge.createdAt).getTime();
2592
+ const now = Date.now();
2593
+ if (now - createdAt > challenge.timeoutSeconds * 1e3) {
2594
+ return {
2595
+ valid: false,
2596
+ credentialId: assertion.credentialId,
2597
+ authenticatorType: "unknown",
2598
+ userVerified: false,
2599
+ signCount: 0,
2600
+ contextHash: challenge.contextHash,
2601
+ approvedAt: (/* @__PURE__ */ new Date()).toISOString()
2602
+ };
2603
+ }
2604
+ const authData = base64urlDecode(assertion.authenticatorData);
2605
+ const flags = authData[32];
2606
+ const userPresent = !!(flags & 1);
2607
+ const userVerified = !!(flags & 4);
2608
+ const attestedCredData = !!(flags & 64);
2609
+ const signCount = authData.length >= 37 ? authData[33] << 24 | authData[34] << 16 | authData[35] << 8 | authData[36] : 0;
2610
+ let authenticatorType = "unknown";
2611
+ try {
2612
+ const clientData = JSON.parse(Buffer.from(base64urlDecode(assertion.clientDataJSON)).toString());
2613
+ if (clientData.type === "webauthn.get") {
2614
+ authenticatorType = "platform";
2615
+ }
2616
+ } catch {
2617
+ }
2618
+ return {
2619
+ valid: userPresent,
2620
+ // At minimum, user must be present
2621
+ credentialId: assertion.credentialId,
2622
+ authenticatorType,
2623
+ userVerified,
2624
+ signCount,
2625
+ contextHash: challenge.contextHash,
2626
+ approvedAt: (/* @__PURE__ */ new Date()).toISOString()
2627
+ };
2628
+ }
2629
+ function createApprovalReceiptPayload(challenge, result) {
2630
+ return {
2631
+ type: "acta:approval",
2632
+ approval_method: "webauthn",
2633
+ tool_name: challenge.toolName,
2634
+ request_id: challenge.requestId,
2635
+ agent_id: challenge.agentId,
2636
+ authenticator_type: result.authenticatorType,
2637
+ user_verified: result.userVerified,
2638
+ context_hash: result.contextHash,
2639
+ approved_at: result.approvedAt,
2640
+ // Hash the credential ID for privacy — don't store the raw ID
2641
+ credential_id_hash: (0, import_node_crypto6.createHash)("sha256").update(result.credentialId).digest("hex").slice(0, 16)
2642
+ };
2643
+ }
2644
+ function base64urlEncode(buffer) {
2645
+ return Buffer.from(buffer).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2646
+ }
2647
+ function base64urlDecode(str) {
2648
+ const base64 = str.replace(/-/g, "+").replace(/_/g, "/");
2649
+ const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
2650
+ return new Uint8Array(Buffer.from(padded, "base64"));
2651
+ }
2652
+
2653
+ // src/did-vc.ts
2654
+ function ed25519ToDIDKey(publicKeyHex) {
2655
+ const multicodecPrefix = Buffer.from([237, 1]);
2656
+ const publicKeyBytes = Buffer.from(publicKeyHex, "hex");
2657
+ const multicodecKey = Buffer.concat([multicodecPrefix, publicKeyBytes]);
2658
+ const base58 = base58btcEncode(multicodecKey);
2659
+ return `did:key:z${base58}`;
2660
+ }
2661
+ function manifestToVC(manifest) {
2662
+ const did = ed25519ToDIDKey(manifest.public_key);
2663
+ return {
2664
+ "@context": [
2665
+ "https://www.w3.org/2018/credentials/v1",
2666
+ "https://veritasacta.com/contexts/agent-manifest/v1"
2667
+ ],
2668
+ type: ["VerifiableCredential", "AgentManifestCredential"],
2669
+ issuer: did,
2670
+ issuanceDate: manifest.created_at || (/* @__PURE__ */ new Date()).toISOString(),
2671
+ credentialSubject: {
2672
+ id: did,
2673
+ agentId: manifest.agent_id,
2674
+ displayName: manifest.display_name,
2675
+ capabilities: manifest.capabilities || [],
2676
+ policyDigest: manifest.policy_digest,
2677
+ publicKey: manifest.public_key
2678
+ },
2679
+ ...manifest.signature ? {
2680
+ proof: {
2681
+ type: "Ed25519Signature2020",
2682
+ created: manifest.created_at || (/* @__PURE__ */ new Date()).toISOString(),
2683
+ verificationMethod: `${did}#key-1`,
2684
+ proofPurpose: "assertionMethod",
2685
+ proofValue: manifest.signature
2686
+ }
2687
+ } : {}
2688
+ };
2689
+ }
2690
+ function receiptToVP(receipt, issuerPublicKey) {
2691
+ const did = ed25519ToDIDKey(issuerPublicKey);
2692
+ return {
2693
+ "@context": ["https://www.w3.org/2018/credentials/v1"],
2694
+ type: ["VerifiablePresentation"],
2695
+ holder: did,
2696
+ verifiableCredential: [{
2697
+ "@context": [
2698
+ "https://www.w3.org/2018/credentials/v1",
2699
+ "https://veritasacta.com/contexts/decision-receipt/v1"
2700
+ ],
2701
+ type: ["VerifiableCredential", "DecisionReceiptCredential"],
2702
+ issuer: did,
2703
+ issuanceDate: receipt.event_time || (/* @__PURE__ */ new Date()).toISOString(),
2704
+ credentialSubject: {
2705
+ receiptId: receipt.receipt_id,
2706
+ receiptType: receipt.receipt_type,
2707
+ toolName: receipt.payload?.tool_name,
2708
+ decision: receipt.payload?.decision
2709
+ }
2710
+ }]
2711
+ };
2712
+ }
2713
+ function base58btcEncode(buffer) {
2714
+ const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
2715
+ let num = BigInt("0x" + buffer.toString("hex"));
2716
+ let result = "";
2717
+ while (num > 0n) {
2718
+ result = ALPHABET[Number(num % 58n)] + result;
2719
+ num = num / 58n;
2720
+ }
2721
+ for (const byte of buffer) {
2722
+ if (byte === 0) result = "1" + result;
2723
+ else break;
2724
+ }
2725
+ return result;
2726
+ }
2727
+
2728
+ // src/sandbox.ts
2729
+ async function createSandbox(config) {
2730
+ const runtime = config.runtime || (config.apiKey || process.env.E2B_API_KEY ? "e2b" : "docker");
2731
+ if (runtime === "e2b") {
2732
+ return createE2BSandbox(config);
2733
+ }
2734
+ return createDockerSandbox(config);
2735
+ }
2736
+ async function runInSandbox(sandbox, toolCall, policy) {
2737
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
2738
+ const decision = evaluatePolicy(toolCall.tool, policy);
2739
+ const receipt = {
2740
+ tool: toolCall.tool,
2741
+ decision,
2742
+ executed: decision === "allow",
2743
+ timestamp
2744
+ };
2745
+ if (decision === "allow") {
2746
+ try {
2747
+ const result = await executeInSandbox(sandbox, toolCall);
2748
+ receipt.result = result;
2749
+ receipt.executed = true;
2750
+ } catch (err) {
2751
+ receipt.result = {
2752
+ success: false,
2753
+ output: "",
2754
+ error: err instanceof Error ? err.message : String(err),
2755
+ durationMs: 0
2756
+ };
2757
+ }
2758
+ }
2759
+ sandbox.receipts.push(receipt);
2760
+ return receipt;
2761
+ }
2762
+ function generateSafetyTranscript(sandbox, template) {
2763
+ const receipts = sandbox.receipts;
2764
+ const allowed = receipts.filter((r) => r.decision === "allow").length;
2765
+ const denied = receipts.filter((r) => r.decision === "deny").length;
2766
+ const requireApproval = receipts.filter((r) => r.decision === "require_approval").length;
2767
+ const executed = receipts.filter((r) => r.executed && r.result);
2768
+ const successful = executed.filter((r) => r.result?.success);
2769
+ const denyScore = denied > 0 ? 40 : allowed > 0 ? 20 : 40;
2770
+ const successRate = executed.length > 0 ? successful.length / executed.length : 1;
2771
+ const successScore = 30 * successRate;
2772
+ const approvalScore = requireApproval === 0 ? 30 : 15;
2773
+ const safetyScore = Math.round(denyScore + successScore + approvalScore);
2774
+ return {
2775
+ sandboxId: sandbox.id,
2776
+ template,
2777
+ totalCalls: receipts.length,
2778
+ allowed,
2779
+ denied,
2780
+ requireApproval,
2781
+ successRate,
2782
+ receipts,
2783
+ durationMs: 0,
2784
+ // Would be calculated from first/last receipt timestamps
2785
+ evaluatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2786
+ safetyScore: Math.min(100, Math.max(0, safetyScore))
2787
+ };
2788
+ }
2789
+ async function destroySandbox(sandbox) {
2790
+ sandbox.status = "destroyed";
2791
+ if (sandbox.runtime === "docker") {
2792
+ try {
2793
+ const { execSync } = await import("child_process");
2794
+ execSync(`docker rm -f ${sandbox.id} 2>/dev/null`, { stdio: "pipe" });
2795
+ } catch {
2796
+ }
2797
+ }
2798
+ }
2799
+ async function createE2BSandbox(config) {
2800
+ const apiKey = config.apiKey || process.env.E2B_API_KEY;
2801
+ if (!apiKey) {
2802
+ throw new Error("E2B_API_KEY not set. Get one at https://e2b.dev");
2803
+ }
2804
+ const response = await fetch("https://api.e2b.dev/sandboxes", {
2805
+ method: "POST",
2806
+ headers: {
2807
+ "Content-Type": "application/json",
2808
+ "X-API-Key": apiKey
2809
+ },
2810
+ body: JSON.stringify({
2811
+ templateID: config.template,
2812
+ timeout: config.timeoutSeconds || 300
2813
+ })
2814
+ });
2815
+ if (!response.ok) {
2816
+ throw new Error(`E2B sandbox creation failed: ${response.status}`);
2817
+ }
2818
+ const data = await response.json();
2819
+ return {
2820
+ id: data.sandboxID,
2821
+ runtime: "e2b",
2822
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2823
+ status: "running",
2824
+ receipts: []
2825
+ };
2826
+ }
2827
+ async function createDockerSandbox(config) {
2828
+ const { execSync } = await import("child_process");
2829
+ const { randomUUID: randomUUID3 } = await import("crypto");
2830
+ const id = `scopeblind-sandbox-${randomUUID3().slice(0, 8)}`;
2831
+ const image = config.template.includes(":") ? config.template : `node:${config.template.replace("node-", "")}`;
2832
+ const memoryFlag = config.memoryMB ? `--memory=${config.memoryMB}m` : "";
2833
+ const timeout = config.timeoutSeconds || 300;
2834
+ try {
2835
+ execSync(
2836
+ `docker run -d --name ${id} ${memoryFlag} --network=none --stop-timeout=${timeout} ${image} sleep ${timeout}`,
2837
+ { stdio: "pipe" }
2838
+ );
2839
+ } catch (err) {
2840
+ throw new Error(`Docker sandbox creation failed: ${err instanceof Error ? err.message : err}`);
2841
+ }
2842
+ return {
2843
+ id,
2844
+ runtime: "docker",
2845
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2846
+ status: "running",
2847
+ receipts: []
2848
+ };
2849
+ }
2850
+ async function executeInSandbox(sandbox, toolCall) {
2851
+ const start = Date.now();
2852
+ if (sandbox.runtime === "docker") {
2853
+ const { execSync } = await import("child_process");
2854
+ try {
2855
+ const command = toolCall.args.command || `echo "Tool: ${toolCall.tool}"`;
2856
+ const output = execSync(
2857
+ `docker exec ${sandbox.id} sh -c '${command.replace(/'/g, "'\\''")}'`,
2858
+ { stdio: "pipe", timeout: 3e4 }
2859
+ ).toString();
2860
+ return {
2861
+ success: true,
2862
+ output: output.trim(),
2863
+ durationMs: Date.now() - start,
2864
+ exitCode: 0
2865
+ };
2866
+ } catch (err) {
2867
+ const execErr = err;
2868
+ return {
2869
+ success: false,
2870
+ output: "",
2871
+ error: execErr.stderr?.toString() || String(err),
2872
+ durationMs: Date.now() - start,
2873
+ exitCode: execErr.status || 1
2874
+ };
2875
+ }
2876
+ }
2877
+ return {
2878
+ success: true,
2879
+ output: `[E2B] Executed ${toolCall.tool} in sandbox ${sandbox.id}`,
2880
+ durationMs: Date.now() - start
2881
+ };
2882
+ }
2883
+ function evaluatePolicy(tool, policy) {
2884
+ if (!policy) return "allow";
2885
+ const tools = policy.tools;
2886
+ if (!tools) return "allow";
2887
+ const toolPolicy = tools[tool] || tools["*"];
2888
+ if (!toolPolicy) return "allow";
2889
+ if (toolPolicy.block) return "deny";
2890
+ if (toolPolicy.require_approval) return "require_approval";
2891
+ return "allow";
2892
+ }
2893
+
2894
+ // src/evidence-authenticity.ts
2895
+ var import_node_crypto7 = require("crypto");
2896
+ async function createEvidenceAttestation(input) {
2897
+ const tlsNotaryAvailable = await isTLSNotaryAvailable();
2898
+ if (tlsNotaryAvailable) {
2899
+ return createTLSNotaryAttestation(input);
2900
+ }
2901
+ return {
2902
+ version: "0.1-beta",
2903
+ method: "self-reported",
2904
+ url: input.url,
2905
+ httpMethod: input.httpMethod || "GET",
2906
+ responseHash: input.responseHash,
2907
+ statusCode: input.statusCode || 200,
2908
+ fetchedAt: input.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
2909
+ verified: false,
2910
+ verificationNote: "Self-reported attestation. No third-party verification. TLSNotary integration planned for Q3 2026."
2911
+ };
2912
+ }
2913
+ async function verifyEvidenceAttestation(attestation) {
2914
+ switch (attestation.method) {
2915
+ case "self-reported":
2916
+ return {
2917
+ valid: false,
2918
+ method: "self-reported",
2919
+ note: "Self-reported attestation cannot be independently verified. The response hash is included for integrity checking if the original data is available."
2920
+ };
2921
+ case "tlsnotary":
2922
+ if (!attestation.notaryPublicKey || !attestation.notarySignature) {
2923
+ return {
2924
+ valid: false,
2925
+ method: "tlsnotary",
2926
+ note: "TLSNotary attestation is missing notary public key or signature."
2927
+ };
2928
+ }
2929
+ return {
2930
+ valid: false,
2931
+ method: "tlsnotary",
2932
+ note: "TLSNotary verification not yet implemented. Attestation format is correct but signature cannot be checked."
2933
+ };
2934
+ case "oracle":
2935
+ return {
2936
+ valid: attestation.verified,
2937
+ method: "oracle",
2938
+ note: attestation.verified ? "Attestation verified by oracle service." : "Oracle verification pending or failed."
2939
+ };
2940
+ case "witness":
2941
+ return {
2942
+ valid: attestation.verified,
2943
+ method: "witness",
2944
+ note: attestation.verified ? "Attestation witnessed by independent third party." : "Witness verification pending."
2945
+ };
2946
+ default:
2947
+ return {
2948
+ valid: false,
2949
+ method: "unknown",
2950
+ note: "Unknown attestation method."
2951
+ };
2952
+ }
2953
+ }
2954
+ function hashResponseBody(body) {
2955
+ return (0, import_node_crypto7.createHash)("sha256").update(typeof body === "string" ? body : body).digest("hex");
2956
+ }
2957
+ function createAttestationField(attestation) {
2958
+ return {
2959
+ evidence_authenticity: {
2960
+ version: attestation.version,
2961
+ method: attestation.method,
2962
+ url_hash: (0, import_node_crypto7.createHash)("sha256").update(attestation.url).digest("hex").slice(0, 16),
2963
+ response_hash: attestation.responseHash,
2964
+ fetched_at: attestation.fetchedAt,
2965
+ verified: attestation.verified,
2966
+ note: attestation.verificationNote
2967
+ }
2968
+ };
2969
+ }
2970
+ async function isTLSNotaryAvailable() {
2971
+ try {
2972
+ await import("tlsn-js");
2973
+ return true;
2974
+ } catch {
2975
+ return false;
2976
+ }
2977
+ }
2978
+ async function createTLSNotaryAttestation(input) {
2979
+ return {
2980
+ version: "0.1-beta",
2981
+ method: "tlsnotary",
2982
+ url: input.url,
2983
+ httpMethod: input.httpMethod || "GET",
2984
+ responseHash: input.responseHash,
2985
+ statusCode: input.statusCode || 200,
2986
+ fetchedAt: input.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
2987
+ verified: false,
2988
+ verificationNote: "TLSNotary SDK integration in progress. Attestation format is stable; verification will be enabled in a future release."
2989
+ };
2990
+ }
2991
+
2992
+ // src/c2pa-credentials.ts
2993
+ var import_node_crypto8 = require("crypto");
2994
+ function createC2PAManifest(receipts, options) {
2995
+ const generator = options.generator || "protect-mcp";
2996
+ const version = options.version || "0.3.3";
2997
+ const decisions = receipts.filter(
2998
+ (r) => r.receipt_type?.includes("decision") || r.type?.includes("decision")
2999
+ );
3000
+ const allows = decisions.filter(
3001
+ (r) => r.payload?.decision === "allow"
3002
+ );
3003
+ const denies = decisions.filter(
3004
+ (r) => r.payload?.decision === "deny"
3005
+ );
3006
+ const receiptHashes = receipts.map(
3007
+ (r) => (0, import_node_crypto8.createHash)("sha256").update(JSON.stringify(r)).digest("hex")
3008
+ );
3009
+ const merkleRoot = computeMerkleRoot(receiptHashes);
3010
+ const assertions = [
3011
+ // Acta decision provenance — the core assertion
3012
+ {
3013
+ label: "acta.decision-provenance",
3014
+ data: {
3015
+ protocol: "veritas-acta",
3016
+ protocol_version: "0.1",
3017
+ ietf_draft: "draft-farley-acta-signed-receipts-00",
3018
+ receipt_count: receipts.length,
3019
+ decision_count: decisions.length,
3020
+ allows: allows.length,
3021
+ denies: denies.length,
3022
+ merkle_root: merkleRoot,
3023
+ signing_algorithm: "Ed25519",
3024
+ canonicalization: "JCS (RFC 8785)",
3025
+ verifier: "npx @veritasacta/verify",
3026
+ verify_url: "https://scopeblind.com/verify",
3027
+ trace_url: "https://scopeblind.com/trace"
3028
+ }
3029
+ },
3030
+ // Policy compliance assertion
3031
+ {
3032
+ label: "acta.policy-compliance",
3033
+ data: {
3034
+ policy_violations: denies.length,
3035
+ total_decisions: decisions.length,
3036
+ compliance_rate: decisions.length > 0 ? (allows.length / decisions.length * 100).toFixed(1) + "%" : "N/A",
3037
+ policy_engine: "Cedar + JSON",
3038
+ human_approvals: receipts.filter(
3039
+ (r) => r.receipt_type?.includes("approval") || r.type?.includes("approval")
3040
+ ).length
3041
+ }
3042
+ },
3043
+ // Standard C2PA actions
3044
+ {
3045
+ label: "c2pa.actions",
3046
+ data: {
3047
+ actions: [
3048
+ {
3049
+ action: "c2pa.created",
3050
+ when: (/* @__PURE__ */ new Date()).toISOString(),
3051
+ softwareAgent: `${generator}/${version}`,
3052
+ parameters: {
3053
+ description: "Content generated by AI agent with ScopeBlind governance"
3054
+ }
3055
+ }
3056
+ ]
3057
+ }
3058
+ }
3059
+ ];
3060
+ if (options.includeFullReceipts) {
3061
+ assertions.push({
3062
+ label: "acta.receipt-chain",
3063
+ data: {
3064
+ receipts: receipts.map((r) => ({
3065
+ id: r.receipt_id || r.id,
3066
+ type: r.receipt_type || r.type,
3067
+ tool: r.payload?.tool_name,
3068
+ decision: r.payload?.decision,
3069
+ timestamp: r.timestamp || r.event_time
3070
+ }))
3071
+ }
3072
+ });
3073
+ } else {
3074
+ assertions.push({
3075
+ label: "acta.receipt-chain",
3076
+ data: {
3077
+ receipt_hashes: receiptHashes,
3078
+ merkle_root: merkleRoot,
3079
+ note: "Full receipts available via verify URL. Hashes provided for integrity verification."
3080
+ },
3081
+ is_hash: true
3082
+ });
3083
+ }
3084
+ if (options.additionalAssertions) {
3085
+ assertions.push(...options.additionalAssertions);
3086
+ }
3087
+ return {
3088
+ claim_generator: `${generator}/${version}`,
3089
+ claim_generator_info: [
3090
+ {
3091
+ name: generator,
3092
+ version
3093
+ }
3094
+ ],
3095
+ title: options.title,
3096
+ assertions
3097
+ };
3098
+ }
3099
+ function exportC2PAManifestJSON(manifest) {
3100
+ return JSON.stringify(manifest, null, 2);
3101
+ }
3102
+ function generateC2PACommand(manifestPath, inputPath, outputPath) {
3103
+ return `c2patool ${inputPath} -m ${manifestPath} -o ${outputPath}`;
3104
+ }
3105
+ function verifyActaC2PAAssertions(c2paManifestJson) {
3106
+ try {
3107
+ const manifest = JSON.parse(c2paManifestJson);
3108
+ const assertions = manifest.assertions || [];
3109
+ const provenanceAssertion = assertions.find(
3110
+ (a) => a.label === "acta.decision-provenance"
3111
+ );
3112
+ const complianceAssertion = assertions.find(
3113
+ (a) => a.label === "acta.policy-compliance"
3114
+ );
3115
+ if (!provenanceAssertion) {
3116
+ return {
3117
+ hasActaProvenance: false,
3118
+ receiptCount: 0,
3119
+ merkleRoot: null,
3120
+ complianceRate: null,
3121
+ verifyUrl: null
3122
+ };
3123
+ }
3124
+ return {
3125
+ hasActaProvenance: true,
3126
+ receiptCount: provenanceAssertion.data.receipt_count || 0,
3127
+ merkleRoot: provenanceAssertion.data.merkle_root || null,
3128
+ complianceRate: complianceAssertion ? complianceAssertion.data.compliance_rate : null,
3129
+ verifyUrl: provenanceAssertion.data.verify_url || null
3130
+ };
3131
+ } catch {
3132
+ return {
3133
+ hasActaProvenance: false,
3134
+ receiptCount: 0,
3135
+ merkleRoot: null,
3136
+ complianceRate: null,
3137
+ verifyUrl: null
3138
+ };
3139
+ }
3140
+ }
3141
+ function computeMerkleRoot(hashes) {
3142
+ if (hashes.length === 0) return "";
3143
+ if (hashes.length === 1) return hashes[0];
3144
+ const nextLevel = [];
3145
+ for (let i = 0; i < hashes.length; i += 2) {
3146
+ const left = hashes[i];
3147
+ const right = i + 1 < hashes.length ? hashes[i + 1] : left;
3148
+ nextLevel.push(
3149
+ (0, import_node_crypto8.createHash)("sha256").update(left + right).digest("hex")
3150
+ );
3151
+ }
3152
+ return computeMerkleRoot(nextLevel);
3153
+ }
3154
+
3155
+ // src/prediction-bridge.ts
3156
+ function computeCalibration(predictions, resolutions) {
3157
+ let totalSquaredError = 0;
3158
+ let resolved = 0;
3159
+ const buckets = /* @__PURE__ */ new Map();
3160
+ for (const pred of predictions) {
3161
+ const resolution = resolutions.get(pred.receipt_id);
3162
+ if (!resolution || resolution.payload.resolution_value === "ambiguous") continue;
3163
+ resolved++;
3164
+ const actual = resolution.payload.resolution_value === "true" ? 1 : 0;
3165
+ const error = (pred.payload.probability - actual) ** 2;
3166
+ totalSquaredError += error;
3167
+ const bucketKey = `${Math.floor(pred.payload.probability * 10) / 10}-${Math.ceil(pred.payload.probability * 10) / 10}`;
3168
+ const bucket = buckets.get(bucketKey) || { sum: 0, actual: 0, count: 0 };
3169
+ bucket.sum += pred.payload.probability;
3170
+ bucket.actual += actual;
3171
+ bucket.count++;
3172
+ buckets.set(bucketKey, bucket);
3173
+ }
3174
+ return {
3175
+ total_predictions: predictions.length,
3176
+ resolved,
3177
+ brier_score: resolved > 0 ? totalSquaredError / resolved : 0,
3178
+ calibration_buckets: Array.from(buckets.entries()).map(([bucket, data]) => ({
3179
+ bucket,
3180
+ predicted_probability: data.sum / data.count,
3181
+ actual_frequency: data.actual / data.count,
3182
+ count: data.count
3183
+ }))
3184
+ };
3185
+ }
3186
+ function toMetaculusFormat(prediction) {
3187
+ return {
3188
+ prediction_value: prediction.payload.probability,
3189
+ acta_receipt_id: prediction.receipt_id,
3190
+ acta_signature: prediction.signature
3191
+ };
3192
+ }
3193
+ function toManifoldFormat(prediction) {
3194
+ return {
3195
+ probability: prediction.payload.probability,
3196
+ acta_receipt_id: prediction.receipt_id,
3197
+ acta_signature: prediction.signature
3198
+ };
3199
+ }
3200
+
3201
+ // src/agent-exchange.ts
3202
+ var import_node_crypto9 = require("crypto");
3203
+ var ReceiptPropagator = class {
3204
+ issuer;
3205
+ signer;
3206
+ receipts = /* @__PURE__ */ new Map();
3207
+ delegationCallCounts = /* @__PURE__ */ new Map();
3208
+ constructor(config) {
3209
+ this.issuer = config.issuer;
3210
+ this.signer = config.signer;
3211
+ }
3212
+ /**
3213
+ * Create a delegation receipt authorizing another agent to use specific tools.
3214
+ *
3215
+ * @patent Patent-protected construction — delegated signing with receipt chain
3216
+ * propagation. Covered by Apache 2.0 patent grant for users of this code.
3217
+ * Clean-room reimplementation requires a patent license.
3218
+ * @see {@link https://datatracker.ietf.org/doc/draft-farley-acta-signed-receipts/}
3219
+ */
3220
+ delegate(delegateId, options) {
3221
+ const now = /* @__PURE__ */ new Date();
3222
+ const receipt = {
3223
+ receipt_id: `del_${(0, import_node_crypto9.randomUUID)().slice(0, 12)}`,
3224
+ receipt_type: "delegation",
3225
+ issuer_id: this.issuer,
3226
+ event_time: now.toISOString(),
3227
+ payload: {
3228
+ delegate_id: delegateId,
3229
+ authorized_tools: options.tools,
3230
+ scope: options.scope,
3231
+ ttl: options.ttl,
3232
+ expires_at: new Date(now.getTime() + options.ttl * 1e3).toISOString(),
3233
+ max_calls: options.maxCalls,
3234
+ allow_subdelegation: options.allowSubdelegation ?? false
3235
+ },
3236
+ parent_receipts: options.parentReceipts || []
3237
+ };
3238
+ if (this.signer) {
3239
+ const signed = this.signer(receipt);
3240
+ Object.assign(receipt, signed);
3241
+ }
3242
+ this.receipts.set(receipt.receipt_id, receipt);
3243
+ this.delegationCallCounts.set(receipt.receipt_id, 0);
3244
+ return receipt;
3245
+ }
3246
+ /**
3247
+ * Wrap a tool call with a receipt that references the delegation.
3248
+ * Validates the delegation is still valid (not expired, within call limit,
3249
+ * tool is authorized).
3250
+ *
3251
+ * @patent Patent-protected construction — delegated signing with receipt chain
3252
+ * propagation. Covered by Apache 2.0 patent grant for users of this code.
3253
+ * Clean-room reimplementation requires a patent license.
3254
+ * @see {@link https://datatracker.ietf.org/doc/draft-farley-acta-signed-receipts/}
3255
+ */
3256
+ wrapAction(toolName, options) {
3257
+ const delegation = this.receipts.get(options.delegation_receipt);
3258
+ let decision = "allow";
3259
+ if (!delegation) {
3260
+ decision = "deny";
3261
+ } else if (delegation.receipt_type !== "delegation") {
3262
+ decision = "deny";
3263
+ } else {
3264
+ if (new Date(delegation.payload.expires_at) < /* @__PURE__ */ new Date()) {
3265
+ decision = "deny";
3266
+ }
3267
+ if (!delegation.payload.authorized_tools.includes(toolName) && !delegation.payload.authorized_tools.includes("*")) {
3268
+ decision = "deny";
3269
+ }
3270
+ if (delegation.payload.max_calls !== void 0) {
3271
+ const count = this.delegationCallCounts.get(options.delegation_receipt) || 0;
3272
+ if (count >= delegation.payload.max_calls) {
3273
+ decision = "deny";
3274
+ }
3275
+ }
3276
+ }
3277
+ const currentCount = this.delegationCallCounts.get(options.delegation_receipt) || 0;
3278
+ this.delegationCallCounts.set(options.delegation_receipt, currentCount + 1);
3279
+ const receipt = {
3280
+ receipt_id: `act_${(0, import_node_crypto9.randomUUID)().slice(0, 12)}`,
3281
+ receipt_type: "execution",
3282
+ issuer_id: this.issuer,
3283
+ event_time: (/* @__PURE__ */ new Date()).toISOString(),
3284
+ payload: {
3285
+ tool_name: toolName,
3286
+ decision,
3287
+ delegation_receipt: options.delegation_receipt,
3288
+ scope: delegation?.payload.scope || "unknown",
3289
+ call_index: currentCount + 1
3290
+ },
3291
+ parent_receipts: [options.delegation_receipt]
3292
+ };
3293
+ if (this.signer) {
3294
+ const signed = this.signer(receipt);
3295
+ Object.assign(receipt, signed);
3296
+ }
3297
+ this.receipts.set(receipt.receipt_id, receipt);
3298
+ return receipt;
3299
+ }
3300
+ /**
3301
+ * Trace the full receipt chain from a given receipt back to the root delegation.
3302
+ *
3303
+ * @patent Patent-protected construction — delegated signing with receipt chain
3304
+ * propagation. Covered by Apache 2.0 patent grant for users of this code.
3305
+ * Clean-room reimplementation requires a patent license.
3306
+ * @see {@link https://datatracker.ietf.org/doc/draft-farley-acta-signed-receipts/}
3307
+ */
3308
+ traceChain(receiptId) {
3309
+ const chain = [];
3310
+ const visited = /* @__PURE__ */ new Set();
3311
+ const walk = (id) => {
3312
+ if (visited.has(id)) return;
3313
+ visited.add(id);
3314
+ const receipt = this.receipts.get(id);
3315
+ if (!receipt) return;
3316
+ for (const parentId of receipt.parent_receipts) {
3317
+ walk(parentId);
3318
+ }
3319
+ chain.push(receipt);
3320
+ };
3321
+ walk(receiptId);
3322
+ return chain;
3323
+ }
3324
+ /**
3325
+ * Export all receipts as a JSON array (for verification, archival, or Trace visualization).
3326
+ */
3327
+ exportAll() {
3328
+ return Array.from(this.receipts.values());
3329
+ }
3330
+ /**
3331
+ * Validate that a delegation chain is intact and all signatures verify.
3332
+ *
3333
+ * @patent Patent-protected construction — delegated signing with receipt chain
3334
+ * propagation. Covered by Apache 2.0 patent grant for users of this code.
3335
+ * Clean-room reimplementation requires a patent license.
3336
+ * @see {@link https://datatracker.ietf.org/doc/draft-farley-acta-signed-receipts/}
3337
+ */
3338
+ validateChain(receiptId) {
3339
+ const chain = this.traceChain(receiptId);
3340
+ const issues = [];
3341
+ if (chain.length === 0) {
3342
+ return { valid: false, chain_length: 0, issues: ["Receipt not found"] };
3343
+ }
3344
+ let sawAction = false;
3345
+ for (const receipt of chain) {
3346
+ if (receipt.receipt_type === "delegation" && sawAction) {
3347
+ issues.push(`Delegation ${receipt.receipt_id} appears after action in chain`);
3348
+ }
3349
+ if (receipt.receipt_type === "execution") sawAction = true;
3350
+ }
3351
+ for (const receipt of chain) {
3352
+ for (const parentId of receipt.parent_receipts) {
3353
+ if (!this.receipts.has(parentId)) {
3354
+ issues.push(`Missing parent receipt: ${parentId}`);
3355
+ }
3356
+ }
3357
+ }
3358
+ return {
3359
+ valid: issues.length === 0,
3360
+ chain_length: chain.length,
3361
+ issues
3362
+ };
3363
+ }
3364
+ };
3365
+ function createReceiptChannel(orchestratorId) {
3366
+ const propagator = new ReceiptPropagator({ issuer: orchestratorId });
3367
+ return {
3368
+ propagator,
3369
+ async withDelegation(delegateId, tools, fn, options) {
3370
+ const delegation = propagator.delegate(delegateId, {
3371
+ tools,
3372
+ scope: options?.scope || `task-${(0, import_node_crypto9.randomUUID)().slice(0, 8)}`,
3373
+ ttl: options?.ttl || 3600,
3374
+ maxCalls: options?.maxCalls
3375
+ });
3376
+ const result = await fn({ delegation, propagator });
3377
+ return {
3378
+ result,
3379
+ delegation,
3380
+ chain: propagator.exportAll()
3381
+ };
3382
+ }
3383
+ };
3384
+ }
3385
+
3386
+ // src/confidential.ts
3387
+ var ConfidentialGate = class {
3388
+ config;
3389
+ constructor(config) {
3390
+ this.config = config;
3391
+ }
3392
+ /**
3393
+ * Evaluate an attestation document and determine the resulting trust tier.
3394
+ */
3395
+ evaluateAttestation(doc) {
3396
+ if (!this.config.accepted_providers.includes(doc.provider)) {
3397
+ return {
3398
+ accepted: false,
3399
+ tier: "unknown",
3400
+ provider: doc.provider,
3401
+ reason: `Provider ${doc.provider} not in accepted list: ${this.config.accepted_providers.join(", ")}`
3402
+ };
3403
+ }
3404
+ if (this.config.max_attestation_age) {
3405
+ const age = (Date.now() - new Date(doc.timestamp).getTime()) / 1e3;
3406
+ if (age > this.config.max_attestation_age) {
3407
+ return {
3408
+ accepted: false,
3409
+ tier: "unknown",
3410
+ provider: doc.provider,
3411
+ reason: `Attestation expired: age ${Math.floor(age)}s exceeds max ${this.config.max_attestation_age}s`
3412
+ };
3413
+ }
3414
+ }
3415
+ if (this.config.expected_measurements) {
3416
+ for (const [key, expected] of Object.entries(this.config.expected_measurements)) {
3417
+ const actual = doc.measurements[key];
3418
+ if (actual !== expected) {
3419
+ return {
3420
+ accepted: false,
3421
+ tier: "signed",
3422
+ provider: doc.provider,
3423
+ reason: `Measurement mismatch: ${key} expected ${expected}, got ${actual || "missing"}`
3424
+ };
3425
+ }
3426
+ }
3427
+ }
3428
+ return {
3429
+ accepted: true,
3430
+ tier: "privileged",
3431
+ provider: doc.provider,
3432
+ reason: `Attestation verified: ${doc.provider} enclave with valid measurements`
3433
+ };
3434
+ }
3435
+ /**
3436
+ * Check if an agent's current tier requires attestation.
3437
+ */
3438
+ requiresAttestation(currentTier) {
3439
+ if (!this.config.require_attestation) return false;
3440
+ const tierOrder = ["unknown", "signed", "evidenced", "privileged"];
3441
+ const requiredIdx = tierOrder.indexOf(this.config.min_trust_tier);
3442
+ const currentIdx = tierOrder.indexOf(currentTier);
3443
+ return currentIdx >= requiredIdx;
3444
+ }
3445
+ /**
3446
+ * Generate an attestation receipt documenting the evaluation.
3447
+ */
3448
+ toReceipt(result, agentId) {
3449
+ return {
3450
+ receipt_type: "attestation",
3451
+ issuer_id: "confidential-gate",
3452
+ event_time: (/* @__PURE__ */ new Date()).toISOString(),
3453
+ payload: {
3454
+ agent_id: agentId,
3455
+ provider: result.provider,
3456
+ accepted: result.accepted,
3457
+ resulting_tier: result.tier,
3458
+ reason: result.reason
3459
+ }
3460
+ };
3461
+ }
3462
+ };
3463
+ async function confidentialInference(_prompt, _config) {
3464
+ throw new Error(
3465
+ "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)."
3466
+ );
3467
+ }
3468
+
3469
+ // src/demo-server.ts
3470
+ var import_node_readline2 = require("readline");
3471
+ var TOOLS = [
3472
+ {
3473
+ name: "read_file",
3474
+ description: "Read the contents of a file",
3475
+ inputSchema: {
3476
+ type: "object",
3477
+ properties: { path: { type: "string", description: "File path to read" } },
3478
+ required: ["path"]
3479
+ }
3480
+ },
3481
+ {
3482
+ name: "write_file",
3483
+ description: "Write content to a file",
3484
+ inputSchema: {
3485
+ type: "object",
3486
+ properties: {
3487
+ path: { type: "string", description: "File path to write" },
3488
+ content: { type: "string", description: "Content to write" }
3489
+ },
3490
+ required: ["path", "content"]
3491
+ }
3492
+ },
3493
+ {
3494
+ name: "delete_file",
3495
+ description: "Delete a file from the filesystem",
3496
+ inputSchema: {
3497
+ type: "object",
3498
+ properties: { path: { type: "string", description: "File path to delete" } },
3499
+ required: ["path"]
3500
+ }
3501
+ },
3502
+ {
3503
+ name: "web_search",
3504
+ description: "Search the web for information",
3505
+ inputSchema: {
3506
+ type: "object",
3507
+ properties: { query: { type: "string", description: "Search query" } },
3508
+ required: ["query"]
3509
+ }
3510
+ },
3511
+ {
3512
+ name: "deploy",
3513
+ description: "Deploy the application to production",
3514
+ inputSchema: {
3515
+ type: "object",
3516
+ properties: {
3517
+ environment: { type: "string", description: "Target environment", enum: ["staging", "production"] },
3518
+ reason: { type: "string", description: "Deployment reason" }
3519
+ },
3520
+ required: ["environment"]
3521
+ }
3522
+ }
3523
+ ];
3524
+ function handleRequest(request) {
3525
+ if (request.method === "initialize") {
3526
+ return JSON.stringify({
3527
+ jsonrpc: "2.0",
3528
+ id: request.id,
3529
+ result: {
3530
+ protocolVersion: "2024-11-05",
3531
+ serverInfo: { name: "protect-mcp-demo", version: "0.2.0" },
3532
+ capabilities: { tools: {} }
3533
+ }
3534
+ });
3535
+ }
3536
+ if (request.method === "notifications/initialized") {
3537
+ return "";
3538
+ }
3539
+ if (request.method === "tools/list") {
3540
+ return JSON.stringify({
3541
+ jsonrpc: "2.0",
3542
+ id: request.id,
3543
+ result: { tools: TOOLS }
3544
+ });
3545
+ }
3546
+ if (request.method === "tools/call") {
3547
+ const toolName = request.params?.name || "unknown";
3548
+ const args = request.params?.arguments || {};
3549
+ let resultText;
3550
+ switch (toolName) {
3551
+ case "read_file":
3552
+ resultText = `[demo] Read file: ${args.path || "/example.txt"}
3553
+ Contents: Hello from protect-mcp demo server!`;
3554
+ break;
3555
+ case "write_file":
3556
+ resultText = `[demo] Wrote ${String(args.content || "").length} bytes to ${args.path || "/example.txt"}`;
3557
+ break;
3558
+ case "delete_file":
3559
+ resultText = `[demo] Deleted file: ${args.path || "/example.txt"}`;
3560
+ break;
3561
+ case "web_search":
3562
+ resultText = `[demo] Search results for "${args.query || "test"}":
3563
+ 1. Example result \u2014 scopeblind.com
3564
+ 2. MCP security \u2014 modelcontextprotocol.io`;
3565
+ break;
3566
+ case "deploy":
3567
+ resultText = `[demo] Deployed to ${args.environment || "staging"}${args.reason ? ` (reason: ${args.reason})` : ""}`;
3568
+ break;
3569
+ default:
3570
+ resultText = `[demo] Unknown tool: ${toolName}`;
3571
+ }
3572
+ return JSON.stringify({
3573
+ jsonrpc: "2.0",
3574
+ id: request.id,
3575
+ result: {
3576
+ content: [{ type: "text", text: resultText }]
3577
+ }
3578
+ });
3579
+ }
3580
+ if (request.id !== void 0) {
3581
+ return JSON.stringify({
3582
+ jsonrpc: "2.0",
3583
+ id: request.id,
3584
+ error: { code: -32601, message: `Method not found: ${request.method}` }
3585
+ });
3586
+ }
3587
+ return "";
3588
+ }
3589
+ var rl = (0, import_node_readline2.createInterface)({ input: process.stdin, crlfDelay: Infinity });
3590
+ rl.on("line", (line) => {
3591
+ const trimmed = line.trim();
3592
+ if (!trimmed) return;
3593
+ try {
3594
+ const request = JSON.parse(trimmed);
3595
+ const response = handleRequest(request);
3596
+ if (response) {
3597
+ process.stdout.write(response + "\n");
3598
+ }
3599
+ } catch {
3600
+ }
3601
+ });
3602
+ process.stderr.write("[DEMO_SERVER] protect-mcp demo server started \u2014 5 tools registered\n");
3603
+ function createSandboxServer() {
3604
+ return {
3605
+ tools: TOOLS,
3606
+ handleRequest
3607
+ };
3608
+ }
1805
3609
  // Annotate the CommonJS export names for ESM import in node:
1806
3610
  0 && (module.exports = {
3611
+ ConfidentialGate,
1807
3612
  ProtectGateway,
3613
+ ReceiptPropagator,
3614
+ anchorToRekor,
1808
3615
  buildDecisionContext,
1809
3616
  checkRateLimit,
1810
3617
  collectSignedReceipts,
3618
+ computeCalibration,
3619
+ confidentialInference,
3620
+ createApprovalChallenge,
3621
+ createApprovalReceiptPayload,
3622
+ createAttestationField,
1811
3623
  createAuditBundle,
3624
+ createC2PAManifest,
3625
+ createDisclosurePackage,
3626
+ createEvidenceAttestation,
3627
+ createLogAnchorField,
3628
+ createReceiptChannel,
3629
+ createSandbox,
3630
+ createSandboxServer,
3631
+ destroySandbox,
3632
+ ed25519ToDIDKey,
1812
3633
  evaluateTier,
3634
+ exportC2PAManifestJSON,
3635
+ exportJSONL,
1813
3636
  formatReportMarkdown,
1814
3637
  formatSimulation,
3638
+ generateC2PACommand,
3639
+ generateDatasetCard,
3640
+ generateHFMetadata,
1815
3641
  generateReport,
3642
+ generateSafetyTranscript,
1816
3643
  getSignerInfo,
1817
3644
  getToolPolicy,
3645
+ hashReceipt,
3646
+ hashResponseBody,
1818
3647
  initSigning,
1819
3648
  isAgentId,
1820
3649
  isDisclosureMode,
@@ -1823,14 +3652,31 @@ function validateEvidenceReceipt(receipt) {
1823
3652
  isSigningEnabled,
1824
3653
  listCredentialLabels,
1825
3654
  loadPolicy,
3655
+ manifestToVC,
1826
3656
  meetsMinTier,
1827
3657
  parseLogFile,
3658
+ parseNotificationConfigFromEnv,
1828
3659
  parseRateLimit,
1829
3660
  queryExternalPDP,
3661
+ receiptToVP,
3662
+ receiptsToHFRows,
3663
+ redactFields,
1830
3664
  resolveCredential,
3665
+ revealField,
3666
+ runInSandbox,
3667
+ sendApprovalNotification,
1831
3668
  signDecision,
1832
3669
  simulate,
3670
+ toCredentialRequestOptions,
3671
+ toManifoldFormat,
3672
+ toMetaculusFormat,
1833
3673
  validateCredentials,
1834
3674
  validateEvidenceReceipt,
1835
- validateManifest
3675
+ validateManifest,
3676
+ verifyActaC2PAAssertions,
3677
+ verifyAllCommitments,
3678
+ verifyApprovalAssertion,
3679
+ verifyCommitment,
3680
+ verifyEvidenceAttestation,
3681
+ verifyRekorAnchor
1836
3682
  });