@coreguard/agent-commerce 0.2.0 → 0.2.1
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/README.md +1 -1
- package/bin/trust-card.mjs +12 -0
- package/observations.mjs +24 -3
- package/package.json +7 -2
- package/server.json +2 -2
- package/trust-card-cli.mjs +289 -0
- package/trust-card.mjs +252 -0
- package/wave3.mjs +97 -11
package/README.md
CHANGED
|
@@ -349,7 +349,7 @@ License: MIT.
|
|
|
349
349
|
|
|
350
350
|
## Release readiness / MCPRush evidence
|
|
351
351
|
|
|
352
|
-
- **Release notes:** `docs/releases/0.1.
|
|
352
|
+
- **Release notes:** `docs/releases/0.2.1.md` (latest) · `docs/releases/0.2.0.md`
|
|
353
353
|
- **Publish readiness checklist:** `docs/releases/0.1.3-publish-readiness.md`
|
|
354
354
|
- **Security & threat model:** `docs/agent-commerce-mcp-security.md`
|
|
355
355
|
- **Client compatibility matrix + run log:** `docs/agent-commerce-mcp-compatibility.md`
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* bin wrapper — coreguard-trust-card
|
|
4
|
+
*
|
|
5
|
+
* MCP server listings get a publishable trust card from one command:
|
|
6
|
+
* npx -y @coreguard/agent-commerce trust-card --server-json server.json --stdio "npx -y @scope/server"
|
|
7
|
+
*/
|
|
8
|
+
import { runTrustCardCli } from "../trust-card-cli.mjs";
|
|
9
|
+
|
|
10
|
+
runTrustCardCli().then(({ code }) => {
|
|
11
|
+
process.exitCode = code;
|
|
12
|
+
});
|
package/observations.mjs
CHANGED
|
@@ -383,22 +383,32 @@ export function accrue(ledger, { action_id, subject_digest } = {}) {
|
|
|
383
383
|
|
|
384
384
|
const observers = [...byObserver.values()].map((entry) => {
|
|
385
385
|
const latest = entry.history[entry.history.length - 1];
|
|
386
|
+
const lastVerified = [...entry.history].reverse().find((e) => e.outcome === "verified") ?? null;
|
|
387
|
+
const failedAfterVerified = lastVerified
|
|
388
|
+
? entry.history.some((e) => at(e) > at(lastVerified) && e.outcome === "verification_failed")
|
|
389
|
+
: false;
|
|
386
390
|
return Object.freeze({
|
|
387
391
|
observer: entry.observer,
|
|
388
392
|
latest_outcome: latest.outcome,
|
|
389
393
|
latest_code: latest.code,
|
|
390
394
|
latest_reason: latest.reason,
|
|
391
395
|
latest_checked_at: latest.checked_at,
|
|
396
|
+
verified_at: lastVerified?.checked_at ?? null,
|
|
397
|
+
verified_observation_id: lastVerified?.observation_id ?? null,
|
|
398
|
+
confirmation_stands: lastVerified !== null && !failedAfterVerified,
|
|
392
399
|
scopes: Object.freeze([...entry.scopes]),
|
|
393
400
|
reads: entry.history.length,
|
|
394
401
|
observation_ids: Object.freeze(entry.history.map((e) => e.observation_id)),
|
|
395
402
|
});
|
|
396
403
|
});
|
|
397
404
|
|
|
398
|
-
|
|
405
|
+
// A confirmation stands unless the same observer later refused the bytes.
|
|
406
|
+
// Losing access after a verified read is not a contradiction: the observer
|
|
407
|
+
// matched the bytes earlier and cannot fetch them now — both true.
|
|
408
|
+
const verifiedBy = observers.filter((o) => o.confirmation_stands).map((o) => o.observer);
|
|
399
409
|
const notCheckedBy = observers
|
|
400
410
|
.filter((o) => o.latest_outcome === "not_checked")
|
|
401
|
-
.map((o) => Object.freeze({ observer: o.observer, reason: o.latest_reason, at: o.latest_checked_at }));
|
|
411
|
+
.map((o) => Object.freeze({ observer: o.observer, reason: o.latest_reason, at: o.latest_checked_at, confirmed_before: o.confirmation_stands }));
|
|
402
412
|
const failedBy = observers.filter((o) => o.latest_outcome === "verification_failed").map((o) => o.observer);
|
|
403
413
|
const absentBy = observers.filter((o) => o.latest_outcome === "absent").map((o) => o.observer);
|
|
404
414
|
|
|
@@ -456,10 +466,21 @@ export function describeAccrual(accrual) {
|
|
|
456
466
|
// bytes", and burying that after two observers who could not read invites the
|
|
457
467
|
// reader to scan for the refusal and stop there.
|
|
458
468
|
const ordered = [...accrual.observers].sort((a, b) => {
|
|
459
|
-
const rank = (o) => (o.
|
|
469
|
+
const rank = (o) => (o.confirmation_stands ? 0 : o.latest_outcome === "not_checked" ? 2 : 1);
|
|
460
470
|
return rank(a) - rank(b) || a.observer.localeCompare(b.observer);
|
|
461
471
|
});
|
|
462
472
|
const parts = ordered.map((o) => {
|
|
473
|
+
if (o.confirmation_stands && o.latest_outcome !== "verified") {
|
|
474
|
+
const tail =
|
|
475
|
+
o.latest_outcome === "not_checked"
|
|
476
|
+
? `later did not check (${o.latest_reason}) at ${o.latest_checked_at}`
|
|
477
|
+
: o.latest_outcome === "verification_failed"
|
|
478
|
+
? `later refused (${o.latest_code}) at ${o.latest_checked_at}`
|
|
479
|
+
: o.latest_outcome === "absent"
|
|
480
|
+
? `later found nothing to read at ${o.latest_checked_at}`
|
|
481
|
+
: `later could not resolve the record at ${o.latest_checked_at}`;
|
|
482
|
+
return `${o.observer} matched the bytes at ${o.verified_at}; ${tail}`;
|
|
483
|
+
}
|
|
463
484
|
const verb =
|
|
464
485
|
o.latest_outcome === "verified"
|
|
465
486
|
? "matched the bytes"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@coreguard/agent-commerce",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "CoreGuard Agent Commerce: consent receipts (CGCR/1) and fail-closed execution verification (AGR/1) for agentic purchases — SDK, REST surface, and a stdio MCP server (46 tools, JSON-RPC 2.0, offline, zero keys)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.mjs",
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
"./client.mjs": "./client.mjs",
|
|
12
12
|
"./firewall.mjs": "./firewall.mjs",
|
|
13
13
|
"./risk.mjs": "./risk.mjs",
|
|
14
|
+
"./trust-card.mjs": "./trust-card.mjs",
|
|
14
15
|
"./risk-cli.mjs": "./risk-cli.mjs",
|
|
15
16
|
"./outcomes.mjs": "./outcomes.mjs",
|
|
16
17
|
"./outcomes-bridge.mjs": "./outcomes-bridge.mjs",
|
|
@@ -38,7 +39,8 @@
|
|
|
38
39
|
"./cgcp-mcp-tools.mjs": "./cgcp-mcp-tools.mjs"
|
|
39
40
|
},
|
|
40
41
|
"bin": {
|
|
41
|
-
"coreguard-agent-commerce-mcp": "./bin/mcp.mjs"
|
|
42
|
+
"coreguard-agent-commerce-mcp": "./bin/mcp.mjs",
|
|
43
|
+
"coreguard-trust-card": "./bin/trust-card.mjs"
|
|
42
44
|
},
|
|
43
45
|
"files": [
|
|
44
46
|
"aer1.mjs",
|
|
@@ -78,6 +80,9 @@
|
|
|
78
80
|
"server.json",
|
|
79
81
|
"spend.mjs",
|
|
80
82
|
"trust.mjs",
|
|
83
|
+
"trust-card-cli.mjs",
|
|
84
|
+
"trust-card.mjs",
|
|
85
|
+
"bin/trust-card.mjs",
|
|
81
86
|
"wave3.mjs"
|
|
82
87
|
],
|
|
83
88
|
"engines": {
|
package/server.json
CHANGED
|
@@ -6,12 +6,12 @@
|
|
|
6
6
|
"url": "https://github.com/coreguard-global/CoreGuard",
|
|
7
7
|
"source": "github"
|
|
8
8
|
},
|
|
9
|
-
"version": "0.2.
|
|
9
|
+
"version": "0.2.1",
|
|
10
10
|
"packages": [
|
|
11
11
|
{
|
|
12
12
|
"registryType": "npm",
|
|
13
13
|
"identifier": "@coreguard/agent-commerce",
|
|
14
|
-
"version": "0.2.
|
|
14
|
+
"version": "0.2.1",
|
|
15
15
|
"transport": {
|
|
16
16
|
"type": "stdio"
|
|
17
17
|
}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* coreguard-trust-card — one command, one publishable trust card.
|
|
4
|
+
*
|
|
5
|
+
* coreguard-trust-card --server-json server.json --tools-list tools.json --out trust-card.md
|
|
6
|
+
* coreguard-trust-card --server-json server.json --stdio "npx -y @scope/server" --out card.md
|
|
7
|
+
*
|
|
8
|
+
* Inputs:
|
|
9
|
+
* --server-json <file> an MCP registry record (server.json)
|
|
10
|
+
* --tools-list <file> a tools/list result: array, {tools:[...]} or JSON-RPC
|
|
11
|
+
* --stdio "<command>" alternatively, run a stdio MCP server and read tools/list
|
|
12
|
+
* --name <label> override the name printed on the card
|
|
13
|
+
* --date <YYYY-MM-DD> card date; omitted by default so runs stay byte-identical
|
|
14
|
+
* --url <https://…> published card URL, embedded in the paste-ready summary
|
|
15
|
+
* --out <file|-> markdown destination (default: stdout)
|
|
16
|
+
* --json <file> also write the machine-readable sidecar
|
|
17
|
+
* --tools-out <file> also write the normalised tools/list used for the card
|
|
18
|
+
* --check do not write: fail if the existing --out/--json files differ
|
|
19
|
+
* --fail-on none|medium|high gate (default none; the GitHub Action defaults to high)
|
|
20
|
+
* --timeout <ms> stdio handshake timeout (default 45000)
|
|
21
|
+
*
|
|
22
|
+
* Exit codes:
|
|
23
|
+
* 0 card generated (and the gate, if any, passed)
|
|
24
|
+
* 1 gate tripped, or --check found drift
|
|
25
|
+
* 2 usage or input error — no card is written
|
|
26
|
+
*
|
|
27
|
+
* Offline by construction except for an explicitly requested --stdio command,
|
|
28
|
+
* which runs locally. No wall clock is read; --date is caller-supplied.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
32
|
+
import { dirname, resolve } from "node:path";
|
|
33
|
+
import { fileURLToPath } from "node:url";
|
|
34
|
+
import { spawn } from "node:child_process";
|
|
35
|
+
|
|
36
|
+
import { buildTrustCard, parseToolsList, toolsListShape, exitCodeFor, TRUST_CARD_SPEC } from "./trust-card.mjs";
|
|
37
|
+
|
|
38
|
+
const USAGE = `coreguard-trust-card (${TRUST_CARD_SPEC})
|
|
39
|
+
|
|
40
|
+
usage:
|
|
41
|
+
coreguard-trust-card --server-json <file> (--tools-list <file> | --stdio "<command>") [options]
|
|
42
|
+
|
|
43
|
+
required:
|
|
44
|
+
--server-json <file> MCP registry server record
|
|
45
|
+
one of:
|
|
46
|
+
--tools-list <file> tools/list JSON (array, {tools} or JSON-RPC response)
|
|
47
|
+
--stdio "<command>" run a stdio MCP server and request tools/list
|
|
48
|
+
|
|
49
|
+
options:
|
|
50
|
+
--name <label> override the server name on the card
|
|
51
|
+
--date <YYYY-MM-DD> card date (omitted by default: output stays deterministic)
|
|
52
|
+
--url <https://…> published card URL in the paste-ready summary
|
|
53
|
+
--out <file|-> markdown destination (default stdout)
|
|
54
|
+
--json <file> machine-readable sidecar
|
|
55
|
+
--tools-out <file> normalised tools/list used for the card
|
|
56
|
+
--check compare with existing --out/--json instead of writing
|
|
57
|
+
--fail-on none|medium|high exit 1 at this verdict (default none)
|
|
58
|
+
--timeout <ms> stdio handshake timeout (default 45000)
|
|
59
|
+
-h, --help
|
|
60
|
+
|
|
61
|
+
exit: 0 card produced · 1 gate tripped or drift · 2 usage/input error`;
|
|
62
|
+
|
|
63
|
+
function usageError(message) {
|
|
64
|
+
const err = new Error(message);
|
|
65
|
+
err.code = 2;
|
|
66
|
+
return err;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function parseArgs(argv) {
|
|
70
|
+
const opts = { out: "-", failOn: "none", timeout: 45000, check: false };
|
|
71
|
+
for (let i = 0; i < argv.length; i++) {
|
|
72
|
+
const a = argv[i];
|
|
73
|
+
const next = () => {
|
|
74
|
+
const v = argv[++i];
|
|
75
|
+
if (v === undefined) throw usageError(`${a} needs a value`);
|
|
76
|
+
return v;
|
|
77
|
+
};
|
|
78
|
+
if (a === "--server-json") opts.serverJson = next();
|
|
79
|
+
else if (a === "--tools-list") opts.toolsList = next();
|
|
80
|
+
else if (a === "--stdio") opts.stdio = next();
|
|
81
|
+
else if (a === "--name") opts.name = next();
|
|
82
|
+
else if (a === "--date") opts.date = next();
|
|
83
|
+
else if (a === "--url") opts.url = next();
|
|
84
|
+
else if (a === "--out") opts.out = next();
|
|
85
|
+
else if (a === "--json") opts.jsonOut = next();
|
|
86
|
+
else if (a === "--tools-out") opts.toolsOut = next();
|
|
87
|
+
else if (a === "--fail-on") opts.failOn = next();
|
|
88
|
+
else if (a === "--timeout") opts.timeout = Number(next());
|
|
89
|
+
else if (a === "--check") opts.check = true;
|
|
90
|
+
else if (a === "--help" || a === "-h") opts.help = true;
|
|
91
|
+
else throw usageError(`unknown argument: ${a}`);
|
|
92
|
+
}
|
|
93
|
+
return opts;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function readJson(file, label) {
|
|
97
|
+
let text;
|
|
98
|
+
try {
|
|
99
|
+
text = readFileSync(resolve(file), "utf8");
|
|
100
|
+
} catch (err) {
|
|
101
|
+
throw usageError(`${label}: cannot read ${file}: ${err?.message ?? err}`);
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
return { text, value: JSON.parse(text) };
|
|
105
|
+
} catch (err) {
|
|
106
|
+
throw usageError(`${label}: ${file} is not valid JSON: ${err?.message ?? err}`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Minimal stdio MCP handshake: initialize, initialized, tools/list.
|
|
112
|
+
* Anything the server writes on stderr is kept for the failure message.
|
|
113
|
+
*/
|
|
114
|
+
export function captureToolsList(command, { timeoutMs = 45000, spawnImpl = spawn } = {}) {
|
|
115
|
+
return new Promise((resolvePromise, reject) => {
|
|
116
|
+
const child = spawnImpl(command, { shell: true, stdio: ["pipe", "pipe", "pipe"] });
|
|
117
|
+
let stdout = "";
|
|
118
|
+
let stderr = "";
|
|
119
|
+
let done = false;
|
|
120
|
+
let initialized = false;
|
|
121
|
+
const timer = setTimeout(() => finish(new Error(`stdio handshake timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
122
|
+
|
|
123
|
+
const send = (message) => {
|
|
124
|
+
child.stdin.write(JSON.stringify(message) + "\n");
|
|
125
|
+
};
|
|
126
|
+
function finish(err, value) {
|
|
127
|
+
if (done) return;
|
|
128
|
+
done = true;
|
|
129
|
+
clearTimeout(timer);
|
|
130
|
+
try {
|
|
131
|
+
child.stdin.end();
|
|
132
|
+
child.kill("SIGTERM");
|
|
133
|
+
} catch {
|
|
134
|
+
/* already gone */
|
|
135
|
+
}
|
|
136
|
+
if (err) reject(err);
|
|
137
|
+
else resolvePromise(value);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
child.on("error", (err) => finish(new Error(`cannot start stdio command: ${err?.message ?? err}`)));
|
|
141
|
+
child.on("exit", (code) => {
|
|
142
|
+
if (!done) finish(new Error(`stdio server exited (code ${code}) before returning tools/list${stderr ? `: ${stderr.trim().slice(-400)}` : ""}`));
|
|
143
|
+
});
|
|
144
|
+
child.stderr.on("data", (chunk) => {
|
|
145
|
+
stderr += chunk;
|
|
146
|
+
});
|
|
147
|
+
child.stdout.on("data", (chunk) => {
|
|
148
|
+
stdout += chunk;
|
|
149
|
+
let newline;
|
|
150
|
+
while ((newline = stdout.indexOf("\n")) !== -1) {
|
|
151
|
+
const line = stdout.slice(0, newline).trim();
|
|
152
|
+
stdout = stdout.slice(newline + 1);
|
|
153
|
+
if (!line) continue;
|
|
154
|
+
let msg;
|
|
155
|
+
try {
|
|
156
|
+
msg = JSON.parse(line);
|
|
157
|
+
} catch {
|
|
158
|
+
continue; // servers may log on stdout; only JSON-RPC lines matter
|
|
159
|
+
}
|
|
160
|
+
if (msg.id === 1 && msg.result && !initialized) {
|
|
161
|
+
initialized = true;
|
|
162
|
+
send({ jsonrpc: "2.0", method: "notifications/initialized" });
|
|
163
|
+
send({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} });
|
|
164
|
+
} else if (msg.id === 2) {
|
|
165
|
+
if (msg.error) return finish(new Error(`tools/list failed: ${JSON.stringify(msg.error)}`));
|
|
166
|
+
if (!Array.isArray(msg.result?.tools)) return finish(new Error("tools/list result has no tools array"));
|
|
167
|
+
finish(null, msg.result.tools);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
send({
|
|
173
|
+
jsonrpc: "2.0",
|
|
174
|
+
id: 1,
|
|
175
|
+
method: "initialize",
|
|
176
|
+
params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "coreguard-trust-card", version: "1.0.0" } },
|
|
177
|
+
});
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function ensureDir(file) {
|
|
182
|
+
mkdirSync(dirname(resolve(file)), { recursive: true });
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function compare(file, expected, label) {
|
|
186
|
+
let actual;
|
|
187
|
+
try {
|
|
188
|
+
actual = readFileSync(resolve(file), "utf8");
|
|
189
|
+
} catch {
|
|
190
|
+
throw usageError(`${label}: ${file} does not exist yet — run the command without --check`);
|
|
191
|
+
}
|
|
192
|
+
if (actual !== expected) {
|
|
193
|
+
const err = new Error(`${label}: ${file} is stale — regenerate it with this command`);
|
|
194
|
+
err.code = 1;
|
|
195
|
+
throw err;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export async function runTrustCardCli(argv = process.argv.slice(2), io = {}) {
|
|
200
|
+
const log = io.log ?? ((s) => process.stdout.write(String(s) + "\n"));
|
|
201
|
+
const err = io.err ?? ((s) => process.stderr.write(String(s) + "\n"));
|
|
202
|
+
let opts;
|
|
203
|
+
try {
|
|
204
|
+
opts = parseArgs(argv);
|
|
205
|
+
} catch (error) {
|
|
206
|
+
err(`trust-card: ${error.message}`);
|
|
207
|
+
err(USAGE);
|
|
208
|
+
return { code: 2 };
|
|
209
|
+
}
|
|
210
|
+
if (opts.help) {
|
|
211
|
+
log(USAGE);
|
|
212
|
+
return { code: 0 };
|
|
213
|
+
}
|
|
214
|
+
if (!opts.serverJson) {
|
|
215
|
+
err("trust-card: --server-json <file> is required");
|
|
216
|
+
return { code: 2 };
|
|
217
|
+
}
|
|
218
|
+
if (Boolean(opts.toolsList) === Boolean(opts.stdio)) {
|
|
219
|
+
err("trust-card: pass exactly one of --tools-list <file> or --stdio \"<command>\" — a card without a scanned tool surface is not issued");
|
|
220
|
+
return { code: 2 };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
try {
|
|
224
|
+
const { value: manifest } = readJson(opts.serverJson, "server.json");
|
|
225
|
+
let tools;
|
|
226
|
+
let toolsShape;
|
|
227
|
+
let toolsLabel;
|
|
228
|
+
if (opts.toolsList) {
|
|
229
|
+
const { value } = readJson(opts.toolsList, "tools/list");
|
|
230
|
+
tools = parseToolsList(value);
|
|
231
|
+
toolsShape = toolsListShape(value);
|
|
232
|
+
toolsLabel = opts.toolsList;
|
|
233
|
+
} else {
|
|
234
|
+
tools = await captureToolsList(opts.stdio, { timeoutMs: opts.timeout });
|
|
235
|
+
toolsShape = "json-rpc";
|
|
236
|
+
toolsLabel = `stdio: ${opts.stdio}`;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const card = buildTrustCard({
|
|
240
|
+
manifest,
|
|
241
|
+
tools,
|
|
242
|
+
name: opts.name,
|
|
243
|
+
date: opts.date,
|
|
244
|
+
url: opts.url,
|
|
245
|
+
toolsShape,
|
|
246
|
+
sources: { manifest: opts.serverJson, tools: toolsLabel },
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
const jsonText = JSON.stringify(card.json, null, 2) + "\n";
|
|
250
|
+
if (opts.check) {
|
|
251
|
+
if (opts.out === "-") throw usageError("--check needs --out <file>");
|
|
252
|
+
compare(opts.out, card.markdown, "trust card");
|
|
253
|
+
if (opts.jsonOut) compare(opts.jsonOut, jsonText, "trust card JSON");
|
|
254
|
+
log(`trust-card: up to date (${card.verdict}, ${card.json.tools.count} tools, ${card.cardDigest.slice(0, 23)}…)`);
|
|
255
|
+
return { code: exitCodeFor(card.verdict, opts.failOn), result: card };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
if (opts.out === "-") {
|
|
259
|
+
log(card.markdown.replace(/\n$/, ""));
|
|
260
|
+
} else {
|
|
261
|
+
ensureDir(opts.out);
|
|
262
|
+
writeFileSync(resolve(opts.out), card.markdown);
|
|
263
|
+
log(`trust-card: wrote ${opts.out} (${card.verdict}, ${card.json.tools.count} tools, ${card.cardDigest})`);
|
|
264
|
+
}
|
|
265
|
+
if (opts.jsonOut) {
|
|
266
|
+
ensureDir(opts.jsonOut);
|
|
267
|
+
writeFileSync(resolve(opts.jsonOut), jsonText);
|
|
268
|
+
if (opts.out !== "-") log(`trust-card: wrote ${opts.jsonOut}`);
|
|
269
|
+
}
|
|
270
|
+
if (opts.toolsOut) {
|
|
271
|
+
ensureDir(opts.toolsOut);
|
|
272
|
+
writeFileSync(resolve(opts.toolsOut), JSON.stringify(tools, null, 2) + "\n");
|
|
273
|
+
log(`trust-card: wrote ${opts.toolsOut} (${tools.length} tools)`);
|
|
274
|
+
}
|
|
275
|
+
const code = exitCodeFor(card.verdict, opts.failOn);
|
|
276
|
+
if (code !== 0) err(`trust-card: gate --fail-on ${opts.failOn} tripped by verdict ${card.verdict}`);
|
|
277
|
+
return { code, result: card };
|
|
278
|
+
} catch (error) {
|
|
279
|
+
err(`trust-card: ${error.message}`);
|
|
280
|
+
return { code: error.code === 1 ? 1 : 2 };
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const invokedDirectly = process.argv[1] && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url));
|
|
285
|
+
if (invokedDirectly) {
|
|
286
|
+
runTrustCardCli().then(({ code }) => {
|
|
287
|
+
process.exitCode = code;
|
|
288
|
+
});
|
|
289
|
+
}
|
package/trust-card.mjs
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CoreGuard trust cards (CG-TC/1) — turn a server record and a tools/list into
|
|
3
|
+
* one publishable page.
|
|
4
|
+
*
|
|
5
|
+
* This module is the product surface behind `coreguard_audit_server_manifest`
|
|
6
|
+
* and `coreguard_scan_tool_descriptions`: a deterministic composition of both
|
|
7
|
+
* checks plus the inventory, digests and the honesty boundary a listing needs.
|
|
8
|
+
*
|
|
9
|
+
* It performs no I/O, reads no wall clock and calls no network. The CLI wraps
|
|
10
|
+
* it; the MCP tools stay available for agents that want the raw structures.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { auditServerManifest, scanToolDescriptions, digestOf } from "./wave3.mjs";
|
|
14
|
+
|
|
15
|
+
export const TRUST_CARD_SPEC = "CG-TC/1";
|
|
16
|
+
|
|
17
|
+
const str = (v) => (typeof v === "string" && v.trim() ? v.trim() : null);
|
|
18
|
+
|
|
19
|
+
/** Accept an array, {tools}, a JSON-RPC tools/list response, or {result:{tools}}. */
|
|
20
|
+
export function parseToolsList(text) {
|
|
21
|
+
let parsed;
|
|
22
|
+
try {
|
|
23
|
+
parsed = typeof text === "string" ? JSON.parse(text) : text;
|
|
24
|
+
} catch (err) {
|
|
25
|
+
throw new Error(`tools/list is not valid JSON: ${err?.message ?? err}`);
|
|
26
|
+
}
|
|
27
|
+
const tools = Array.isArray(parsed)
|
|
28
|
+
? parsed
|
|
29
|
+
: Array.isArray(parsed?.tools)
|
|
30
|
+
? parsed.tools
|
|
31
|
+
: Array.isArray(parsed?.result?.tools)
|
|
32
|
+
? parsed.result.tools
|
|
33
|
+
: null;
|
|
34
|
+
if (!tools) throw new Error("tools/list must be an array, {tools:[...]} or a JSON-RPC tools/list response");
|
|
35
|
+
if (tools.some((t) => !t || typeof t !== "object" || !str(t.name))) {
|
|
36
|
+
throw new Error("every tool needs a non-empty name");
|
|
37
|
+
}
|
|
38
|
+
return tools;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Detect the JSON-RPC envelope so the card can state what the bytes were. */
|
|
42
|
+
export function toolsListShape(text) {
|
|
43
|
+
let parsed;
|
|
44
|
+
try {
|
|
45
|
+
parsed = typeof text === "string" ? JSON.parse(text) : text;
|
|
46
|
+
} catch {
|
|
47
|
+
return "unknown";
|
|
48
|
+
}
|
|
49
|
+
if (Array.isArray(parsed)) return "array";
|
|
50
|
+
if (Array.isArray(parsed?.tools)) return "object";
|
|
51
|
+
if (Array.isArray(parsed?.result?.tools)) return "json-rpc";
|
|
52
|
+
return "unknown";
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Structural verdict. Deliberately conservative:
|
|
57
|
+
* BLOCKED — a HIGH manifest finding or a DANGEROUS description scan.
|
|
58
|
+
* REVIEW — anything medium/suspicious, plus any manifest-only card.
|
|
59
|
+
* PASS — no structural finding at all. PASS is not SAFE.
|
|
60
|
+
*/
|
|
61
|
+
export function verdictFor(manifestAudit, scan, coverage) {
|
|
62
|
+
const reasons = [];
|
|
63
|
+
if (!coverage.tools) reasons.push("TOOLS_LIST_MISSING: descriptions were not scanned, so the surface is not covered");
|
|
64
|
+
if (manifestAudit.risk === "high") reasons.push("MANIFEST_HIGH: at least one HIGH-severity manifest finding");
|
|
65
|
+
if (scan.verdict === "DANGEROUS") reasons.push("TOOLS_DANGEROUS: at least one HIGH-severity description finding");
|
|
66
|
+
if (reasons.length > 0) return { verdict: "BLOCKED", reasons };
|
|
67
|
+
if (manifestAudit.risk === "medium" || scan.verdict === "SUSPICIOUS" || !coverage.manifest) reasons.push("REVIEW_REQUIRED: medium-severity findings or missing manifest");
|
|
68
|
+
if (manifestAudit.findings.length > 0) reasons.push(`${manifestAudit.findings.length} informational/low manifest finding(s)`);
|
|
69
|
+
return { verdict: reasons.length > 0 ? "REVIEW" : "PASS", reasons };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const esc = (s) => String(s ?? "").replace(/\|/g, "\\|").replace(/\n/g, " ");
|
|
73
|
+
const short = (s, n = 96) => {
|
|
74
|
+
const v = String(s ?? "");
|
|
75
|
+
return v.length <= n ? v : v.slice(0, n - 1) + "…";
|
|
76
|
+
};
|
|
77
|
+
const code = (v) => "`" + String(v).replace(/`/g, "'") + "`";
|
|
78
|
+
|
|
79
|
+
function findingsTable(findings) {
|
|
80
|
+
if (findings.length === 0) return "_No manifest findings._";
|
|
81
|
+
const rows = findings.map(
|
|
82
|
+
(f) => `| ${code(f.id)} | ${f.severity} | ${esc(f.detail)}${f.evidence === undefined || f.evidence === null ? "" : ` — ${code(short(JSON.stringify(f.evidence), 120))}`} |`,
|
|
83
|
+
);
|
|
84
|
+
return ["| Finding | Severity | Detail |", "|---|---|---|", ...rows].join("\n");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Build the card.
|
|
89
|
+
*
|
|
90
|
+
* @param {object} input
|
|
91
|
+
* @param {object} input.manifest server.json record
|
|
92
|
+
* @param {Array} [input.tools] tools/list entries
|
|
93
|
+
* @param {object} [input.sources] { manifest: label, tools: label }
|
|
94
|
+
* @param {string} [input.date] YYYY-MM-DD, caller-supplied (no wall clock here)
|
|
95
|
+
* @param {string} [input.url] published URL, if any
|
|
96
|
+
* @param {string} [input.toolsShape] array | object | json-rpc
|
|
97
|
+
*/
|
|
98
|
+
export function buildTrustCard(input = {}) {
|
|
99
|
+
const manifest = input.manifest;
|
|
100
|
+
if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) {
|
|
101
|
+
throw new Error("server.json must be a JSON object");
|
|
102
|
+
}
|
|
103
|
+
const tools = Array.isArray(input.tools) ? input.tools : null;
|
|
104
|
+
if (!tools) throw new Error("tools/list is required: a card that has not scanned the tool surface is not a trust card");
|
|
105
|
+
if (input.date !== undefined && input.date !== null && !/^\d{4}-\d{2}-\d{2}$/.test(String(input.date))) {
|
|
106
|
+
throw new Error("--date must be YYYY-MM-DD");
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const coverage = { manifest: true, tools: true };
|
|
110
|
+
const manifestAudit = auditServerManifest({ manifest });
|
|
111
|
+
const scan = scanToolDescriptions({ tools });
|
|
112
|
+
const { verdict, reasons } = verdictFor(manifestAudit, scan, coverage);
|
|
113
|
+
|
|
114
|
+
const serverName = str(input.name) ?? manifestAudit.serverName ?? str(manifest.name) ?? "unnamed server";
|
|
115
|
+
const version = manifest.version ?? "unpinned";
|
|
116
|
+
const toolsDigest = digestOf(tools);
|
|
117
|
+
const sources = { manifest: input.sources?.manifest ?? "server.json", tools: input.sources?.tools ?? "tools/list" };
|
|
118
|
+
const cardDigest = digestOf({
|
|
119
|
+
spec: TRUST_CARD_SPEC,
|
|
120
|
+
server: serverName,
|
|
121
|
+
version,
|
|
122
|
+
verdict,
|
|
123
|
+
manifestDigest: manifestAudit.manifestDigest,
|
|
124
|
+
toolsDigest,
|
|
125
|
+
toolsCount: tools.length,
|
|
126
|
+
date: input.date ?? null,
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
const byTool = new Map();
|
|
130
|
+
for (const f of scan.findings) {
|
|
131
|
+
const list = byTool.get(f.tool) ?? [];
|
|
132
|
+
list.push(f);
|
|
133
|
+
byTool.set(f.tool, list);
|
|
134
|
+
}
|
|
135
|
+
const inventory = tools
|
|
136
|
+
.map((t, i) => {
|
|
137
|
+
const hits = byTool.get(String(t.name)) ?? [];
|
|
138
|
+
const status = hits.length === 0 ? "clean" : hits.some((h) => h.severity === "HIGH") ? "**FLAGGED**" : "review";
|
|
139
|
+
return `| ${i + 1} | ${code(short(t.name, 48))} | ${short(t.description, 80) || "—"} | ${status} |`;
|
|
140
|
+
})
|
|
141
|
+
.join("\n");
|
|
142
|
+
|
|
143
|
+
const flagged = scan.findings.length === 0
|
|
144
|
+
? "_No hidden characters, HTML comments or imperative phrases were found in any tool description._"
|
|
145
|
+
: scan.findings
|
|
146
|
+
.map((f) => `- ${code(f.tool)} — ${f.kind}${f.codepoint ? ` ${f.codepoint}` : f.phrase ? ` "${esc(f.phrase)}"` : ""} at offset ${f.index} (${f.severity})`)
|
|
147
|
+
.join("\n");
|
|
148
|
+
|
|
149
|
+
const lines = [
|
|
150
|
+
`# Trust card — ${serverName} ${version}`,
|
|
151
|
+
"",
|
|
152
|
+
`> **Verdict: ${verdict}** · manifest risk \`${manifestAudit.risk}\` · tool descriptions \`${scan.verdict}\` · ${tools.length} tools`,
|
|
153
|
+
">",
|
|
154
|
+
"> Generated by CoreGuard (`CG-TC/1`) from the published server record and a live `tools/list`. Structural audit only: it executes nothing and contacts no network. **PASS ≠ SAFE; absence of findings is not proof of safety.**",
|
|
155
|
+
"",
|
|
156
|
+
"| Field | Value |",
|
|
157
|
+
"|---|---|",
|
|
158
|
+
`| Server | ${esc(serverName)} |`,
|
|
159
|
+
`| Version | ${code(version)} |`,
|
|
160
|
+
`| Transport | ${manifestAudit.transport} |`,
|
|
161
|
+
`| Tools | ${tools.length} — ${code(toolsDigest)} |`,
|
|
162
|
+
`| Manifest digest | ${code(manifestAudit.manifestDigest)} |`,
|
|
163
|
+
`| Card digest | ${code(cardDigest)} |`,
|
|
164
|
+
`| Sources | record: ${code(sources.manifest)} · tools: ${code(sources.tools)} |`,
|
|
165
|
+
...(input.date ? [`| Card date | ${code(input.date)} |`] : []),
|
|
166
|
+
"",
|
|
167
|
+
"## Why this verdict",
|
|
168
|
+
"",
|
|
169
|
+
...(reasons.length === 0 ? ["_No structural finding was raised. That is all this card can say._"] : reasons.map((r) => `- ${r}`)),
|
|
170
|
+
"",
|
|
171
|
+
"## Server-record findings",
|
|
172
|
+
"",
|
|
173
|
+
findingsTable(manifestAudit.findings),
|
|
174
|
+
"",
|
|
175
|
+
"## Tool-description scan",
|
|
176
|
+
"",
|
|
177
|
+
`Scanned ${tools.length} descriptions. Findings: ${scan.counts.findings} (${scan.counts.high} high, ${scan.counts.medium} medium).`,
|
|
178
|
+
"",
|
|
179
|
+
flagged,
|
|
180
|
+
"",
|
|
181
|
+
"## Tool inventory",
|
|
182
|
+
"",
|
|
183
|
+
"| # | Tool | Description (truncated) | Scan |",
|
|
184
|
+
"|---|---|---|---|",
|
|
185
|
+
inventory,
|
|
186
|
+
"",
|
|
187
|
+
"## What was checked",
|
|
188
|
+
"",
|
|
189
|
+
"- Server record: pinned version and package, declared distribution, transport, repository provenance, secret-shaped environment variables.",
|
|
190
|
+
"- Tool descriptions: bidi overrides, Unicode tag/smuggling characters, zero-width and soft-hyphen characters, HTML comments, and a fixed imperative-phrase list.",
|
|
191
|
+
"- Binding: both digests are embedded above, so a changed record or a single changed description changes the card digest.",
|
|
192
|
+
"",
|
|
193
|
+
"## What this does not prove",
|
|
194
|
+
"",
|
|
195
|
+
"- It does not execute the server, its package, or its remote endpoint.",
|
|
196
|
+
"- It does not review source code, permissions, data handling, licensing, or the payment behaviour of any tool.",
|
|
197
|
+
"- It does not detect every poisoning technique; the phrase list is fixed and the scanner is intentionally narrow.",
|
|
198
|
+
"- A clean card is a starting point for review, not an approval.",
|
|
199
|
+
"",
|
|
200
|
+
"## Reproduce",
|
|
201
|
+
"",
|
|
202
|
+
"```bash",
|
|
203
|
+
`coreguard-trust-card \\`,
|
|
204
|
+
` --server-json ${sources.manifest === "server.json" ? "server.json" : sources.manifest} \\`,
|
|
205
|
+
` --tools-list ${sources.tools === "tools/list" ? "tools.json" : sources.tools} \\`,
|
|
206
|
+
` --out trust-card.md`,
|
|
207
|
+
"```",
|
|
208
|
+
"",
|
|
209
|
+
"Same inputs and same `--date` produce the same card digest. Verify it by re-running and comparing the digest line.",
|
|
210
|
+
"",
|
|
211
|
+
"<!-- paste-ready summary for a listing page -->",
|
|
212
|
+
"",
|
|
213
|
+
`> **Trust card:** ${verdict} · manifest risk \`${manifestAudit.risk}\` · tool descriptions \`${scan.verdict}\` · ${tools.length} tools · card \`${cardDigest}\``,
|
|
214
|
+
`> Structural audit by CoreGuard (CG-TC/1) from the server record and a live \`tools/list\`. PASS ≠ SAFE.${input.url ? ` Full card: ${input.url}` : ""}`,
|
|
215
|
+
"",
|
|
216
|
+
];
|
|
217
|
+
|
|
218
|
+
const json = {
|
|
219
|
+
spec: TRUST_CARD_SPEC,
|
|
220
|
+
server: { name: serverName, version, transport: manifestAudit.transport },
|
|
221
|
+
verdict,
|
|
222
|
+
reasons,
|
|
223
|
+
coverage,
|
|
224
|
+
manifest: {
|
|
225
|
+
digest: manifestAudit.manifestDigest,
|
|
226
|
+
risk: manifestAudit.risk,
|
|
227
|
+
findings: manifestAudit.findings,
|
|
228
|
+
counts: manifestAudit.counts,
|
|
229
|
+
},
|
|
230
|
+
tools: {
|
|
231
|
+
count: tools.length,
|
|
232
|
+
digest: toolsDigest,
|
|
233
|
+
shape: input.toolsShape ?? "unknown",
|
|
234
|
+
scan: { verdict: scan.verdict, counts: scan.counts, findings: scan.findings },
|
|
235
|
+
},
|
|
236
|
+
sources,
|
|
237
|
+
cardDigest,
|
|
238
|
+
...(input.date ? { date: input.date } : {}),
|
|
239
|
+
...(input.url ? { url: input.url } : {}),
|
|
240
|
+
boundary: "structural audit only; executes nothing; PASS ≠ SAFE",
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
return { markdown: lines.join("\n"), json, verdict, cardDigest, manifestAudit, scan };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Exit status for the gate: 0 below the threshold, 1 at/above it. */
|
|
247
|
+
export function exitCodeFor(verdict, failOn = "high") {
|
|
248
|
+
const rank = { PASS: 0, REVIEW: 1, BLOCKED: 2 };
|
|
249
|
+
const threshold = { none: 99, high: 2, medium: 1 }[failOn];
|
|
250
|
+
if (threshold === undefined) throw new Error("--fail-on must be none, medium or high");
|
|
251
|
+
return rank[verdict] >= threshold ? 1 : 0;
|
|
252
|
+
}
|
package/wave3.mjs
CHANGED
|
@@ -80,10 +80,12 @@ export function compilePolicy(args = {}) {
|
|
|
80
80
|
rules.push({ ruleId: "RECIPIENT_001", type: "RECIPIENT_ALLOWLIST", params: { addresses: spec.allowRecipients.map(String) }, severity: "CRITICAL" });
|
|
81
81
|
}
|
|
82
82
|
if (Array.isArray(spec.allowSelectors) && spec.allowSelectors.length) {
|
|
83
|
-
|
|
83
|
+
// Selectors are bytes, not prose: normalise at compile time so a spec written
|
|
84
|
+
// as "0xA9059CBB" and an intent written as "0xa9059cbb" are the same rule.
|
|
85
|
+
rules.push({ ruleId: "SELECTOR_001", type: "SELECTOR_ALLOWLIST", params: { selectors: spec.allowSelectors.map((s) => String(s).toLowerCase()) }, severity: "CRITICAL" });
|
|
84
86
|
}
|
|
85
87
|
if (spec.currency) {
|
|
86
|
-
rules.push({ ruleId: "CURRENCY_001", type: "CURRENCY_ALLOWLIST", params: { currencies: [String(spec.currency)] }, severity: "HIGH" });
|
|
88
|
+
rules.push({ ruleId: "CURRENCY_001", type: "CURRENCY_ALLOWLIST", params: { currencies: [String(spec.currency).toUpperCase()] }, severity: "HIGH" });
|
|
87
89
|
}
|
|
88
90
|
const policy = {
|
|
89
91
|
version: "CGEP/1",
|
|
@@ -358,11 +360,12 @@ export function scanToolDescriptions(args = {}) {
|
|
|
358
360
|
const name = String(tool?.name ?? `tool-${toolIndex}`);
|
|
359
361
|
const description = String(tool?.description ?? "");
|
|
360
362
|
for (let i = 0; i < description.length; i++) {
|
|
363
|
+
const start = i; // astral code points consume two UTF-16 units; report where the character STARTS
|
|
361
364
|
const cp = description.codePointAt(i);
|
|
362
|
-
if (cp > 0xffff) i++; //
|
|
365
|
+
if (cp > 0xffff) i++; // consume the low surrogate
|
|
363
366
|
const kind = HIDDEN_CHAR_KINDS.find(([lo, hi]) => cp >= lo && cp <= hi)?.[2];
|
|
364
367
|
if (kind) {
|
|
365
|
-
findings.push({ tool: name, toolIndex, index:
|
|
368
|
+
findings.push({ tool: name, toolIndex, index: start, codepoint: "U+" + cp.toString(16).toUpperCase().padStart(4, "0"), kind, severity: kind === "unicode_tag" || kind === "bidi_override" ? "HIGH" : "MEDIUM" });
|
|
366
369
|
}
|
|
367
370
|
}
|
|
368
371
|
const lower = description.toLowerCase();
|
|
@@ -397,13 +400,80 @@ const CONFUSABLES = Object.freeze({
|
|
|
397
400
|
"5": "s", "3": "e", "8": "b", "|": "l", "!": "i",
|
|
398
401
|
});
|
|
399
402
|
|
|
403
|
+
/**
|
|
404
|
+
* Minimal RFC 3492 decoder for a single `xn--` label.
|
|
405
|
+
*
|
|
406
|
+
* Without this, an attacker writes the homoglyph in punycode and the string
|
|
407
|
+
* comparison sees two unrelated ASCII names — the exact trick the check exists
|
|
408
|
+
* to catch. Returns null when the label is not decodable (the caller then keeps
|
|
409
|
+
* the raw label and the `punycode` signal still fires).
|
|
410
|
+
*/
|
|
411
|
+
function decodePunycodeLabel(label) {
|
|
412
|
+
const prefix = "xn--";
|
|
413
|
+
if (!label.startsWith(prefix)) return label;
|
|
414
|
+
const input = label.slice(prefix.length);
|
|
415
|
+
const base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128;
|
|
416
|
+
const adapt = (delta, numPoints, firstTime) => {
|
|
417
|
+
let d = firstTime ? Math.floor(delta / damp) : delta >> 1;
|
|
418
|
+
d += Math.floor(d / numPoints);
|
|
419
|
+
let k = 0;
|
|
420
|
+
while (d > ((base - tMin) * tMax) >> 1) {
|
|
421
|
+
d = Math.floor(d / (base - tMin));
|
|
422
|
+
k += base;
|
|
423
|
+
}
|
|
424
|
+
return Math.floor(k + ((base - tMin + 1) * d) / (d + skew));
|
|
425
|
+
};
|
|
426
|
+
const digitOf = (code) => {
|
|
427
|
+
if (code >= 0x30 && code <= 0x39) return code - 22;
|
|
428
|
+
if (code >= 0x41 && code <= 0x5a) return code - 0x41;
|
|
429
|
+
if (code >= 0x61 && code <= 0x7a) return code - 0x61;
|
|
430
|
+
return -1;
|
|
431
|
+
};
|
|
432
|
+
const output = [];
|
|
433
|
+
let n = initialN, i = 0, bias = initialBias;
|
|
434
|
+
const basic = input.lastIndexOf("-");
|
|
435
|
+
if (basic > 0) {
|
|
436
|
+
for (let j = 0; j < basic; j++) {
|
|
437
|
+
const code = input.charCodeAt(j);
|
|
438
|
+
if (code >= 0x80) return null;
|
|
439
|
+
output.push(String.fromCharCode(code));
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
let idx = basic > 0 ? basic + 1 : 0;
|
|
443
|
+
while (idx < input.length) {
|
|
444
|
+
const oldi = i;
|
|
445
|
+
let w = 1;
|
|
446
|
+
for (let k = base; ; k += base) {
|
|
447
|
+
if (idx >= input.length) return null;
|
|
448
|
+
const digit = digitOf(input.charCodeAt(idx++));
|
|
449
|
+
if (digit < 0) return null;
|
|
450
|
+
i += digit * w;
|
|
451
|
+
const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
|
|
452
|
+
if (digit < t) break;
|
|
453
|
+
w *= base - t;
|
|
454
|
+
}
|
|
455
|
+
const total = output.length + 1;
|
|
456
|
+
bias = adapt(i - oldi, total, oldi === 0);
|
|
457
|
+
n += Math.floor(i / total);
|
|
458
|
+
i %= total;
|
|
459
|
+
if (n > 0x10ffff || (n >= 0xd800 && n <= 0xdfff)) return null;
|
|
460
|
+
output.splice(i, 0, String.fromCodePoint(n));
|
|
461
|
+
i++;
|
|
462
|
+
}
|
|
463
|
+
return output.join("");
|
|
464
|
+
}
|
|
465
|
+
|
|
400
466
|
function skeleton(domain) {
|
|
401
|
-
|
|
467
|
+
const labels = String(domain ?? "")
|
|
402
468
|
.toLowerCase()
|
|
403
469
|
.trim()
|
|
404
470
|
.replace(/^https?:\/\//, "")
|
|
405
471
|
.replace(/\/.*$/, "")
|
|
406
472
|
.replace(/\.$/, "")
|
|
473
|
+
.split(".")
|
|
474
|
+
.map((label) => decodePunycodeLabel(label) ?? label);
|
|
475
|
+
return labels
|
|
476
|
+
.join(".")
|
|
407
477
|
.replace(/[^a-z0-9.\-\u0080-\uffff]/g, "")
|
|
408
478
|
.split("")
|
|
409
479
|
.map((ch) => CONFUSABLES[ch] ?? ch)
|
|
@@ -664,9 +734,16 @@ export function freezeAgent(args = {}) {
|
|
|
664
734
|
const pinned = args.nowSeconds === undefined ? null : Number(args.nowSeconds);
|
|
665
735
|
const cp = createControlPlane({ storePath, create: true, ...(pinned === null ? {} : { now: () => new Date(pinned * 1000) }) });
|
|
666
736
|
const state = cp.getState();
|
|
667
|
-
const
|
|
737
|
+
const wasRevoked = state.agents?.[agentId]?.status === "revoked";
|
|
738
|
+
const pending = Object.values(state.approvals ?? {}).filter((a) => a.agentId === agentId && a.status === "pending");
|
|
739
|
+
// The ledger only transitions pending → approved/rejected. An approval that was
|
|
740
|
+
// already approved cannot be re-decided, so the freeze must not pretend it did:
|
|
741
|
+
// revocation already makes it fail closed at evaluate() time. Report it as
|
|
742
|
+
// superseded instead of counting a silent "rejection" that never happened.
|
|
743
|
+
// A second freeze must not re-report approvals the first one already superseded.
|
|
744
|
+
const approved = wasRevoked ? [] : Object.values(state.approvals ?? {}).filter((a) => a.agentId === agentId && a.status === "approved");
|
|
668
745
|
const revoked = cp.revokeAgent(agentId, reason);
|
|
669
|
-
const rejected =
|
|
746
|
+
const rejected = pending.map((a) => {
|
|
670
747
|
try {
|
|
671
748
|
return cp.decideApproval(a.id, { decision: "rejected", decidedBy: decidedBy ?? "freeze", reason: `agent frozen: ${reason}` });
|
|
672
749
|
} catch (err) {
|
|
@@ -674,14 +751,23 @@ export function freezeAgent(args = {}) {
|
|
|
674
751
|
}
|
|
675
752
|
});
|
|
676
753
|
const report = cp.auditReport({ limit: 1 });
|
|
754
|
+
const rejectedOk = rejected.filter((r) => !r.error);
|
|
677
755
|
return {
|
|
678
756
|
type: "agent_freeze",
|
|
679
757
|
spec: "CG-FZ/1",
|
|
680
758
|
agentId,
|
|
681
759
|
reason,
|
|
682
760
|
revoked,
|
|
683
|
-
approvals: {
|
|
684
|
-
|
|
761
|
+
approvals: {
|
|
762
|
+
open: pending.length + approved.length,
|
|
763
|
+
rejected: rejectedOk.length,
|
|
764
|
+
failures: rejected.filter((r) => r.error).length,
|
|
765
|
+
approvedSuperseded: approved.length,
|
|
766
|
+
},
|
|
767
|
+
openApprovalIds: [...pending, ...approved].map((a) => a.id),
|
|
768
|
+
rejectedApprovalIds: rejectedOk.map((r) => r.id),
|
|
769
|
+
approvedSupersededIds: approved.map((a) => a.id),
|
|
770
|
+
note: "pending approvals are rejected in this operation; approved-but-unexecuted approvals cannot be re-decided by the ledger and are superseded by the agent revocation (evaluate() denies them)",
|
|
685
771
|
chain: { ok: report.chain?.ok ?? null, length: report.chain?.length ?? null, headHash: report.chain?.headHash ?? null },
|
|
686
772
|
boundary: "revocation and rejection are recorded in the local hash-chained ledger; they do not reach a chain, a merchant or a payment network. " + WAVE3_BOUNDARY,
|
|
687
773
|
};
|
|
@@ -984,9 +1070,9 @@ export const WAVE3_TOOLS = Object.freeze([
|
|
|
984
1070
|
},
|
|
985
1071
|
{
|
|
986
1072
|
name: "coreguard_freeze_agent",
|
|
987
|
-
description: "Kill switch over a CGCP/1 control plane: revoke the agent
|
|
1073
|
+
description: "Kill switch over a CGCP/1 control plane: revoke the agent, reject every pending approval it holds in one audited operation, and report approved-but-unexecuted approvals as superseded by the revocation. Returns the chain head and every affected id.",
|
|
988
1074
|
inputSchema: schema({ storePath: { type: "string" }, agentId: { type: "string" }, reason: { type: "string" }, decidedBy: { type: "string" }, nowSeconds: { type: "string", pattern: "^[0-9]+$", description: "optional pinned epoch seconds; omit to let the local ledger stamp call time" } }, ["storePath", "agentId"], "Control-plane path and the agent to freeze."),
|
|
989
|
-
outputSchema: out("Revocation record, rejected
|
|
1075
|
+
outputSchema: out("Revocation record, rejected and superseded approval ids, failure count and chain status."),
|
|
990
1076
|
},
|
|
991
1077
|
{
|
|
992
1078
|
name: "coreguard_budget_runway",
|