@coreguard/agent-commerce 0.1.2 → 0.1.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/README.md +307 -11
- package/aer1.mjs +954 -0
- package/anchor.mjs +278 -0
- package/bin/mcp.mjs +0 -0
- package/cgcp-mcp-tools.mjs +142 -0
- package/composition.mjs +150 -0
- package/consumption-store.mjs +114 -38
- package/control-plane-cli.mjs +272 -0
- package/control-plane-http.mjs +348 -0
- package/control-plane.mjs +1177 -0
- package/decision.mjs +152 -0
- package/firewall.mjs +1 -1
- package/identity.mjs +205 -0
- package/index.d.ts +991 -1
- package/index.mjs +240 -3
- package/machine-economy.mjs +366 -0
- package/mcp.mjs +657 -28
- package/observations.mjs +524 -0
- package/outcomes-bridge.mjs +169 -0
- package/outcomes.mjs +220 -0
- package/package.json +64 -14
- package/prod/kms-anchor.mjs +51 -0
- package/prod/migrate.mjs +73 -0
- package/prod/observability.mjs +35 -0
- package/prod/rbac.mjs +46 -0
- package/prod/schema.mjs +188 -0
- package/prod/sqlite-storage.mjs +135 -0
- package/profile-ref.mjs +130 -0
- package/reference.mjs +350 -0
- package/risk-cli.mjs +10 -2
- package/risk.mjs +49 -2
- package/spend.mjs +291 -0
- package/trust.mjs +322 -0
package/anchor.mjs
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CoreGuard Anchor Service (CG-ANCHOR/1) — our own append-only witness.
|
|
3
|
+
*
|
|
4
|
+
* A verification layer that cannot say WHERE it saw a record is a layer that
|
|
5
|
+
* asks to be trusted. This service is the smallest thing we can run ourselves
|
|
6
|
+
* and that a stranger can check without asking us:
|
|
7
|
+
*
|
|
8
|
+
* attestation a signed statement: "at T, I saw this digest" — Ed25519 over
|
|
9
|
+
* canonical JSON, carrying the signing public key, so it verifies
|
|
10
|
+
* offline and outlives the file it arrived in
|
|
11
|
+
* log append-only, hash-chained: entry n names the digest of entry
|
|
12
|
+
* n-1, so a silent rewrite anywhere is visible at the tail
|
|
13
|
+
* root one Merkle root over the log; that 32-byte value is the only
|
|
14
|
+
* thing that ever needs to reach a chain, a notary or a mirror
|
|
15
|
+
*
|
|
16
|
+
* That last line is the design decision worth stating: the log does not need a
|
|
17
|
+
* chain to be useful, and a chain does not make the log honest. Anchoring the
|
|
18
|
+
* root elsewhere is an upgrade, never a precondition.
|
|
19
|
+
*
|
|
20
|
+
* BOUNDARY (standing, load-bearing):
|
|
21
|
+
* - No clock, no network, no keys inside this repository. The caller passes
|
|
22
|
+
* `now` and a key; the CLI generates a key locally and prints the path.
|
|
23
|
+
* - Nothing here broadcasts. `prepareChainAnchor` returns the exact 32-byte
|
|
24
|
+
* memo a chain anchor would carry and refuses `mainnet` outright — the
|
|
25
|
+
* decision to write to a live network is not a library call.
|
|
26
|
+
* - An anchor says a digest existed at a time, in a place. It never says the
|
|
27
|
+
* record was correct, authorized or safe, and it cannot resurrect bytes.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify } from "node:crypto";
|
|
31
|
+
|
|
32
|
+
export const ANCHOR_VERSION = "CG-ANCHOR/1";
|
|
33
|
+
export const ANCHOR_SCHEMA = "coreguard.anchor/1";
|
|
34
|
+
|
|
35
|
+
const HEX64 = /^[0-9a-f]{64}$/;
|
|
36
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
37
|
+
const sha256hex = (buf) => createHash("sha256").update(buf).digest("hex");
|
|
38
|
+
|
|
39
|
+
/** Canonical JSON: sorted keys, no whitespace, recursive. Byte-deterministic. */
|
|
40
|
+
function canonicalJson(value) {
|
|
41
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value ?? null);
|
|
42
|
+
if (Array.isArray(value)) return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
|
|
43
|
+
const keys = Object.keys(value).sort();
|
|
44
|
+
return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalJson(value[k])).join(",") + "}";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Normalize a subject digest to `sha256:<64 lowercase hex>`. */
|
|
48
|
+
export function normalizeSubject({ kind, digest } = {}) {
|
|
49
|
+
if (typeof kind !== "string" || kind.length === 0) throw new TypeError("subject.kind must be a non-empty string");
|
|
50
|
+
const raw = typeof digest === "string" ? digest.trim() : "";
|
|
51
|
+
const hex = raw.startsWith("sha256:") ? raw.slice(7) : raw;
|
|
52
|
+
if (!HEX64.test(hex)) throw new TypeError("subject.digest must be 32 bytes of lowercase hex (sha256:<hex>)");
|
|
53
|
+
return Object.freeze({ kind, digest: `sha256:${hex}` });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** A fresh Ed25519 key pair. The private key is the caller's to keep. */
|
|
57
|
+
export function generateIssuerKey() {
|
|
58
|
+
const { publicKey, privateKey } = generateKeyPairSync("ed25519");
|
|
59
|
+
return Object.freeze({
|
|
60
|
+
publicKeyPem: publicKey.export({ type: "spki", format: "pem" }).toString(),
|
|
61
|
+
privateKeyPem: privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** keyId = sha256 over the DER of the public key. Stable, and not a fingerprint. */
|
|
66
|
+
export function keyIdFor(publicKeyPem) {
|
|
67
|
+
const der = createPublicKey(publicKeyPem).export({ type: "spki", format: "der" });
|
|
68
|
+
return sha256hex(der);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Build and sign one attestation. `now` is an ISO-8601 string supplied by the caller. */
|
|
72
|
+
export function signAttestation({ subject, issuedAt, privateKeyPem, sequence = 0, previous = null } = {}) {
|
|
73
|
+
const normalized = normalizeSubject(subject);
|
|
74
|
+
if (typeof issuedAt !== "string" || Number.isNaN(Date.parse(issuedAt))) {
|
|
75
|
+
throw new TypeError("issuedAt must be an ISO-8601 timestamp");
|
|
76
|
+
}
|
|
77
|
+
if (typeof privateKeyPem !== "string" || !privateKeyPem.includes("PRIVATE KEY")) {
|
|
78
|
+
throw new TypeError("privateKeyPem must be a PKCS#8 PEM string");
|
|
79
|
+
}
|
|
80
|
+
const publicKeyPem = createPublicKeyFromPrivate(privateKeyPem);
|
|
81
|
+
const body = {
|
|
82
|
+
anchorVersion: ANCHOR_VERSION,
|
|
83
|
+
schema: ANCHOR_SCHEMA,
|
|
84
|
+
subject: normalized,
|
|
85
|
+
sequence,
|
|
86
|
+
previous: previous ?? null,
|
|
87
|
+
issuedAt,
|
|
88
|
+
issuer: { keyId: keyIdFor(publicKeyPem), publicKeyPem },
|
|
89
|
+
};
|
|
90
|
+
const signature = sign(null, Buffer.from(canonicalJson(body), "utf8"), privateKeyPem).toString("base64");
|
|
91
|
+
return Object.freeze({ ...body, signature });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function createPublicKeyFromPrivate(privateKeyPem) {
|
|
95
|
+
const priv = createPrivateKey(privateKeyPem);
|
|
96
|
+
return createPublicKey(priv).export({ type: "spki", format: "pem" }).toString();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Leaf hash of one attestation: sha256 over its canonical JSON, signature included. */
|
|
100
|
+
export function leafHash(attestation) {
|
|
101
|
+
return sha256hex(Buffer.from(canonicalJson(attestation), "utf8"));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Merkle root over leaf hashes, duplicated-last, empty tree = 64 zeros. */
|
|
105
|
+
export function merkleRoot(leaves) {
|
|
106
|
+
if (!Array.isArray(leaves)) throw new TypeError("merkleRoot requires an array of leaf hashes");
|
|
107
|
+
if (leaves.length === 0) return "0".repeat(64);
|
|
108
|
+
let level = leaves.map((l) => {
|
|
109
|
+
const hex = String(l).startsWith("sha256:") ? String(l).slice(7) : String(l);
|
|
110
|
+
if (!HEX64.test(hex)) throw new TypeError("every leaf must be 32 bytes of lowercase hex");
|
|
111
|
+
return hex;
|
|
112
|
+
});
|
|
113
|
+
while (level.length > 1) {
|
|
114
|
+
const next = [];
|
|
115
|
+
for (let i = 0; i < level.length; i += 2) {
|
|
116
|
+
const a = level[i];
|
|
117
|
+
const b = level[i + 1] ?? a;
|
|
118
|
+
next.push(sha256hex(Buffer.from(a + b, "hex")));
|
|
119
|
+
}
|
|
120
|
+
level = next;
|
|
121
|
+
}
|
|
122
|
+
return level[0];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** A new, empty log. Logs are immutable by convention: append returns a copy. */
|
|
126
|
+
export function createLog() {
|
|
127
|
+
return Object.freeze({ anchorVersion: ANCHOR_VERSION, schema: ANCHOR_SCHEMA, entries: Object.freeze([]) });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Append one anchor. Returns a NEW log; the input is never mutated.
|
|
132
|
+
*
|
|
133
|
+
* The chain is over attestations, so `previous` is the leaf hash of the last
|
|
134
|
+
* entry — not its sequence number. Renumbering entries therefore breaks the
|
|
135
|
+
* chain, which is the point.
|
|
136
|
+
*/
|
|
137
|
+
export function appendAnchor(log, { subject, issuedAt, privateKeyPem } = {}) {
|
|
138
|
+
if (!isObject(log) || !Array.isArray(log.entries)) throw new TypeError("appendAnchor requires a log");
|
|
139
|
+
const previous = log.entries.length === 0 ? null : leafHash(log.entries[log.entries.length - 1]);
|
|
140
|
+
const attestation = signAttestation({
|
|
141
|
+
subject,
|
|
142
|
+
issuedAt,
|
|
143
|
+
privateKeyPem,
|
|
144
|
+
sequence: log.entries.length,
|
|
145
|
+
previous,
|
|
146
|
+
});
|
|
147
|
+
const entries = Object.freeze([...log.entries, attestation]);
|
|
148
|
+
return Object.freeze({ ...log, entries, root: merkleRoot(entries.map(leafHash)) });
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Verify one attestation, offline and self-contained. */
|
|
152
|
+
export function verifyAttestation(attestation) {
|
|
153
|
+
const checks = [];
|
|
154
|
+
if (!isObject(attestation)) return Object.freeze({ ok: false, checks: [{ name: "attestation is an object", ok: false }] });
|
|
155
|
+
const { signature, ...body } = attestation;
|
|
156
|
+
checks.push({ name: "anchor version is CG-ANCHOR/1", ok: body.anchorVersion === ANCHOR_VERSION });
|
|
157
|
+
try {
|
|
158
|
+
normalizeSubject(body.subject);
|
|
159
|
+
checks.push({ name: "subject digest is sha256:<64 hex>", ok: true });
|
|
160
|
+
} catch {
|
|
161
|
+
checks.push({ name: "subject digest is sha256:<64 hex>", ok: false });
|
|
162
|
+
}
|
|
163
|
+
const keyOk = isObject(body.issuer) && typeof body.issuer.publicKeyPem === "string";
|
|
164
|
+
checks.push({ name: "issuer carries a public key", ok: keyOk });
|
|
165
|
+
if (keyOk) checks.push({ name: "keyId matches the public key", ok: body.issuer.keyId === keyIdFor(body.issuer.publicKeyPem) });
|
|
166
|
+
let sigOk = false;
|
|
167
|
+
if (keyOk && typeof signature === "string") {
|
|
168
|
+
try {
|
|
169
|
+
sigOk = verify(null, Buffer.from(canonicalJson(body), "utf8"), body.issuer.publicKeyPem, Buffer.from(signature, "base64"));
|
|
170
|
+
} catch {
|
|
171
|
+
sigOk = false;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
checks.push({ name: "Ed25519 signature verifies over canonical JSON", ok: sigOk });
|
|
175
|
+
return Object.freeze({ ok: checks.every((c) => c.ok), checks });
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Verify a whole log: every signature, the previous-link chain, and the root. */
|
|
179
|
+
export function verifyLog(log) {
|
|
180
|
+
if (!isObject(log) || !Array.isArray(log.entries)) throw new TypeError("verifyLog requires a log");
|
|
181
|
+
const checks = [];
|
|
182
|
+
let prevLeaf = null;
|
|
183
|
+
for (let i = 0; i < log.entries.length; i++) {
|
|
184
|
+
const entry = log.entries[i];
|
|
185
|
+
const single = verifyAttestation(entry);
|
|
186
|
+
checks.push({ name: `entry ${i} verifies`, ok: single.ok });
|
|
187
|
+
checks.push({ name: `entry ${i} sequence is ${i}`, ok: entry.sequence === i });
|
|
188
|
+
checks.push({ name: `entry ${i} links to the previous entry`, ok: entry.previous === prevLeaf });
|
|
189
|
+
prevLeaf = leafHash(entry);
|
|
190
|
+
}
|
|
191
|
+
const root = merkleRoot(log.entries.map(leafHash));
|
|
192
|
+
checks.push({ name: "declared root matches the computed root", ok: log.root === undefined || log.root === root });
|
|
193
|
+
return Object.freeze({ ok: checks.every((c) => c.ok), checks, root });
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Resolve a digest against a log, in CG-OUT/1's anchor vocabulary.
|
|
198
|
+
*
|
|
199
|
+
* { present, evaluated, outcome } outcome: verified | absent | unresolvable
|
|
200
|
+
*
|
|
201
|
+
* A digest with matching entries is `verified`. A digest addressed by a broken
|
|
202
|
+
* entry is `unresolvable` — we can see it was written, and we cannot stand
|
|
203
|
+
* behind it. A digest with no entry at all is `absent`: no one claimed it.
|
|
204
|
+
*/
|
|
205
|
+
export function resolveAnchor(log, digest) {
|
|
206
|
+
let subject;
|
|
207
|
+
try {
|
|
208
|
+
subject = normalizeSubject({ kind: "unknown", digest });
|
|
209
|
+
} catch {
|
|
210
|
+
return Object.freeze({ present: false, evaluated: false, outcome: "absent", reason: "digest is not sha256:<64 hex>" });
|
|
211
|
+
}
|
|
212
|
+
if (!isObject(log) || !Array.isArray(log.entries)) {
|
|
213
|
+
return Object.freeze({ present: false, evaluated: false, outcome: "absent", reason: "no log was supplied" });
|
|
214
|
+
}
|
|
215
|
+
const matches = log.entries.filter((e) => e?.subject?.digest === subject.digest);
|
|
216
|
+
if (matches.length === 0) {
|
|
217
|
+
return Object.freeze({ present: false, evaluated: true, outcome: "absent", matches: 0 });
|
|
218
|
+
}
|
|
219
|
+
const allValid = matches.every((e) => verifyAttestation(e).ok);
|
|
220
|
+
return Object.freeze({
|
|
221
|
+
present: true,
|
|
222
|
+
evaluated: true,
|
|
223
|
+
outcome: allValid ? "verified" : "unresolvable",
|
|
224
|
+
matches: matches.length,
|
|
225
|
+
reason: allValid ? undefined : "an entry for this digest failed its own signature check",
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* The only thing that would need to reach a chain: the 32-byte root.
|
|
231
|
+
*
|
|
232
|
+
* `broadcast` is hard-coded false and `mainnet` is refused by name. Preparing a
|
|
233
|
+
* memo is not authorization to write it, and this repository has no path from
|
|
234
|
+
* here to a signed transaction.
|
|
235
|
+
*/
|
|
236
|
+
export function prepareChainAnchor(log, { network = "testnet" } = {}) {
|
|
237
|
+
const verified = verifyLog(log);
|
|
238
|
+
if (!verified.ok) return Object.freeze({ ok: false, reason: "the log does not verify", checks: verified.checks });
|
|
239
|
+
if (network === "mainnet" || network === "public") {
|
|
240
|
+
return Object.freeze({
|
|
241
|
+
ok: false,
|
|
242
|
+
reason: "mainnet is refused here by name: anchoring the root to a live network is a deliberate, separate decision",
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
return Object.freeze({
|
|
246
|
+
ok: true,
|
|
247
|
+
adapter: "stellar",
|
|
248
|
+
network,
|
|
249
|
+
memoHashHex: verified.root,
|
|
250
|
+
memoType: "hash",
|
|
251
|
+
broadcast: false,
|
|
252
|
+
root: verified.root,
|
|
253
|
+
entries: log.entries.length,
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Self-check: the service's own invariants, for callers that cannot run tests. */
|
|
258
|
+
export function selfCheck() {
|
|
259
|
+
const keys = generateIssuerKey();
|
|
260
|
+
const digest = sha256hex(Buffer.from("self-check"));
|
|
261
|
+
const t0 = "2026-01-01T00:00:00.000Z";
|
|
262
|
+
const log1 = appendAnchor(createLog(), { subject: { kind: "receipt", digest }, issuedAt: t0, privateKeyPem: keys.privateKeyPem });
|
|
263
|
+
const log2 = appendAnchor(log1, { subject: { kind: "receipt", digest }, issuedAt: t0, privateKeyPem: keys.privateKeyPem });
|
|
264
|
+
const tampered = Object.freeze({
|
|
265
|
+
...log1,
|
|
266
|
+
entries: Object.freeze([{ ...log1.entries[0], issuedAt: "2026-01-02T00:00:00.000Z" }]),
|
|
267
|
+
});
|
|
268
|
+
const checks = [
|
|
269
|
+
{ name: "a fresh log verifies", pass: verifyLog(log1).ok },
|
|
270
|
+
{ name: "a two-entry log verifies", pass: verifyLog(log2).ok },
|
|
271
|
+
{ name: "a re-signed-looking edit breaks the log", pass: verifyLog(tampered).ok === false },
|
|
272
|
+
{ name: "a known digest resolves to verified", pass: resolveAnchor(log2, `sha256:${digest}`).outcome === "verified" },
|
|
273
|
+
{ name: "an unknown digest is absent, not unresolvable", pass: resolveAnchor(log2, `sha256:${"a".repeat(64)}`).outcome === "absent" },
|
|
274
|
+
{ name: "mainnet preparation is refused", pass: prepareChainAnchor(log1, { network: "mainnet" }).ok === false },
|
|
275
|
+
{ name: "the chain memo is the Merkle root", pass: prepareChainAnchor(log1).memoHashHex === verifyLog(log1).root },
|
|
276
|
+
];
|
|
277
|
+
return Object.freeze({ ok: checks.every((c) => c.pass), checks });
|
|
278
|
+
}
|
package/bin/mcp.mjs
CHANGED
|
File without changes
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CGCP/1 MCP Wave 2 mapping tools - deterministic, file-backed control plane operations.
|
|
3
|
+
* BOUNDARIES: self-hosted single-host file-backed control plane; no distributed HA,
|
|
4
|
+
* no external IdP/KMS/witness, no payment custody/broadcast. VERIFIED != SAFE.
|
|
5
|
+
*/
|
|
6
|
+
import { createControlPlane, verifyAuditChain, CONTROL_PLANE_BOUNDARY } from "./control-plane.mjs";
|
|
7
|
+
|
|
8
|
+
export const CGCP_MCP_BOUNDARY = CONTROL_PLANE_BOUNDARY +
|
|
9
|
+
" MCP Wave 2 tools are CGCP/1 mappings; they do not create blockchain receipts, do not custody funds, and do not prove external settlement.";
|
|
10
|
+
|
|
11
|
+
function reqString(args, k) { const v = args?.[k]; if (typeof v !== "string" || !v) throw new Error(`${k} is required`); return v; }
|
|
12
|
+
function optString(args, k) { const v = args?.[k]; if (v === undefined || v === null) return undefined; if (typeof v !== "string") throw new Error(`${k} must be a string`); return v; }
|
|
13
|
+
|
|
14
|
+
function withCp(storePath) {
|
|
15
|
+
return createControlPlane({ storePath, create: true });
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function createIntent(args = {}) {
|
|
19
|
+
const storePath = reqString(args, "storePath");
|
|
20
|
+
const cp = withCp(storePath);
|
|
21
|
+
const approval = cp.requestApproval({
|
|
22
|
+
id: optString(args, "intentId"),
|
|
23
|
+
agentId: reqString(args, "agentId"),
|
|
24
|
+
policyId: optString(args, "policyId"),
|
|
25
|
+
merchant: optString(args, "merchant"),
|
|
26
|
+
address: optString(args, "address"),
|
|
27
|
+
amountMinor: optString(args, "amountMinor"),
|
|
28
|
+
currency: optString(args, "currency"),
|
|
29
|
+
requestedBy: optString(args, "requestedBy"),
|
|
30
|
+
expiresAt: optString(args, "expiresAt"),
|
|
31
|
+
});
|
|
32
|
+
return { type: "cgcp_intent", spec: "CGCP/1", intent: approval, mapping: "coreguard_create_intent -> CGCP requestApproval (intent/approval request)", boundary: CGCP_MCP_BOUNDARY };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function issueReceipt(args = {}) {
|
|
36
|
+
const storePath = reqString(args, "storePath");
|
|
37
|
+
const cp = withCp(storePath);
|
|
38
|
+
const execution = cp.recordExecution({
|
|
39
|
+
id: optString(args, "receiptId"),
|
|
40
|
+
agentId: reqString(args, "agentId"),
|
|
41
|
+
policyId: optString(args, "policyId"),
|
|
42
|
+
approvalId: optString(args, "approvalId"),
|
|
43
|
+
merchant: optString(args, "merchant"),
|
|
44
|
+
address: optString(args, "address"),
|
|
45
|
+
amountMinor: optString(args, "amountMinor"),
|
|
46
|
+
currency: optString(args, "currency"),
|
|
47
|
+
status: optString(args, "status") ?? "executed",
|
|
48
|
+
txRef: optString(args, "txRef"),
|
|
49
|
+
metadata: args.metadata && typeof args.metadata === "object" ? args.metadata : undefined,
|
|
50
|
+
});
|
|
51
|
+
return { type: "cgcp_receipt", spec: "CGCP/1", receipt: execution, mapping: "coreguard_issue_receipt -> CGCP recordExecution (execution receipt record)", boundary: CGCP_MCP_BOUNDARY };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function verifyReceipt(args = {}) {
|
|
55
|
+
const storePath = reqString(args, "storePath");
|
|
56
|
+
const cp = withCp(storePath);
|
|
57
|
+
const report = cp.auditReport({ limit: 10000 });
|
|
58
|
+
const chain = report.chain;
|
|
59
|
+
const receiptId = optString(args, "receiptId");
|
|
60
|
+
let receipt = null;
|
|
61
|
+
let receiptFound = false;
|
|
62
|
+
if (receiptId) {
|
|
63
|
+
receipt = (report.recentExecutions || []).find((e) => e.id === receiptId) ||
|
|
64
|
+
(report.recentVerifications || []).find((v) => v.id === receiptId || v.receiptId === receiptId) ||
|
|
65
|
+
null;
|
|
66
|
+
receiptFound = !!receipt;
|
|
67
|
+
}
|
|
68
|
+
const issues = [];
|
|
69
|
+
if (!chain?.ok) issues.push("AUDIT_CHAIN_INVALID");
|
|
70
|
+
if (receiptId && !receiptFound) issues.push("RECEIPT_NOT_FOUND");
|
|
71
|
+
return {
|
|
72
|
+
type: "cgcp_receipt_verification", spec: "CGCP/1",
|
|
73
|
+
verdict: issues.length === 0 ? "VERIFIED" : "INVALID",
|
|
74
|
+
issues,
|
|
75
|
+
receiptId: receiptId ?? null,
|
|
76
|
+
receiptFound,
|
|
77
|
+
receipt,
|
|
78
|
+
auditChain: chain,
|
|
79
|
+
mapping: "coreguard_verify_receipt -> CGCP audit chain verification + receipt lookup in audit report",
|
|
80
|
+
boundary: CGCP_MCP_BOUNDARY,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function checkLimits(args = {}) {
|
|
85
|
+
const storePath = reqString(args, "storePath");
|
|
86
|
+
const cp = withCp(storePath);
|
|
87
|
+
const decision = cp.evaluate({
|
|
88
|
+
agentId: reqString(args, "agentId"),
|
|
89
|
+
policyId: optString(args, "policyId"),
|
|
90
|
+
merchant: optString(args, "merchant"),
|
|
91
|
+
address: optString(args, "address"),
|
|
92
|
+
amountMinor: optString(args, "amountMinor"),
|
|
93
|
+
currency: optString(args, "currency"),
|
|
94
|
+
approvalId: optString(args, "approvalId"),
|
|
95
|
+
});
|
|
96
|
+
return { type: "cgcp_limit_check", spec: "CGCP/1", decision, mapping: "coreguard_check_limits -> CGCP evaluate (policy/limit decision)", boundary: CGCP_MCP_BOUNDARY };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function revokeConsent(args = {}) {
|
|
100
|
+
const storePath = reqString(args, "storePath");
|
|
101
|
+
const cp = withCp(storePath);
|
|
102
|
+
const targetType = reqString(args, "targetType"); // approval|agent|policy
|
|
103
|
+
const reason = optString(args, "reason") ?? "revoked via MCP";
|
|
104
|
+
let result;
|
|
105
|
+
if (targetType === "approval") {
|
|
106
|
+
result = cp.decideApproval(reqString(args, "targetId"), { decision: "rejected", decidedBy: optString(args, "decidedBy"), reason });
|
|
107
|
+
} else if (targetType === "agent") {
|
|
108
|
+
result = cp.revokeAgent(reqString(args, "targetId"), reason);
|
|
109
|
+
} else if (targetType === "policy") {
|
|
110
|
+
result = cp.revokePolicy(reqString(args, "targetId"), reason);
|
|
111
|
+
} else {
|
|
112
|
+
throw new Error("targetType must be approval, agent, or policy");
|
|
113
|
+
}
|
|
114
|
+
return { type: "cgcp_revocation", spec: "CGCP/1", targetType, targetId: args.targetId, result, mapping: "coreguard_revoke_consent -> CGCP revoke/decision mapping", boundary: CGCP_MCP_BOUNDARY };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function auditTransaction(args = {}) {
|
|
118
|
+
const storePath = reqString(args, "storePath");
|
|
119
|
+
const cp = withCp(storePath);
|
|
120
|
+
const limit = Number.isInteger(args.limit) ? args.limit : 200;
|
|
121
|
+
const report = cp.auditReport({ limit });
|
|
122
|
+
const txRef = optString(args, "txRef");
|
|
123
|
+
const approvalId = optString(args, "approvalId");
|
|
124
|
+
const agentId = optString(args, "agentId");
|
|
125
|
+
const filterFn = (e) => {
|
|
126
|
+
const d = e?.detail || {};
|
|
127
|
+
if (txRef && d.txRef !== txRef && d.receiptId !== txRef && d.executionId !== txRef) return false;
|
|
128
|
+
if (approvalId && d.approvalId !== approvalId) return false;
|
|
129
|
+
if (agentId && d.agentId !== agentId) return false;
|
|
130
|
+
return true;
|
|
131
|
+
};
|
|
132
|
+
if (txRef || approvalId || agentId) {
|
|
133
|
+
report.recentAudit = (report.recentAudit || []).filter(filterFn);
|
|
134
|
+
report.recentExecutions = (report.recentExecutions || []).filter((e) => {
|
|
135
|
+
if (txRef && e.txRef !== txRef && e.id !== txRef) return false;
|
|
136
|
+
if (approvalId && e.approvalId !== approvalId) return false;
|
|
137
|
+
if (agentId && e.agentId !== agentId) return false;
|
|
138
|
+
return true;
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
return { type: "cgcp_audit_report", spec: "CGCP/1", report, mapping: "coreguard_audit_transaction -> CGCP auditReport/filter", boundary: CGCP_MCP_BOUNDARY };
|
|
142
|
+
}
|
package/composition.mjs
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CoreGuard Composition Policy (CG-COMPOSE/1) — one rule, two defensible answers.
|
|
3
|
+
*
|
|
4
|
+
* The record layer and the anchor layer answer different questions, and a
|
|
5
|
+
* consumer sometimes needs them merged and sometimes needs them apart. AER-1
|
|
6
|
+
* keeps them apart; our default merges them. Neither is a disagreement about
|
|
7
|
+
* the receipt, and pretending one of them is wrong costs a review round every
|
|
8
|
+
* time the topic comes up. So the choice is a value, not an argument:
|
|
9
|
+
*
|
|
10
|
+
* mode: "composed" the anchor outcome participates in the headline. A
|
|
11
|
+
* well-formed record whose anchor cannot be resolved reads
|
|
12
|
+
* UNRESOLVABLE_RECORD and may be presented as a refusal.
|
|
13
|
+
* Best for a commerce consumer that needs ONE answer now.
|
|
14
|
+
*
|
|
15
|
+
* mode: "layered" the record outcome never moves. The anchor layer reports
|
|
16
|
+
* its own fact, including `rejected: "unresolvable record"`,
|
|
17
|
+
* and the headline describes the record alone. Best for a
|
|
18
|
+
* record that must outlive any single anchor.
|
|
19
|
+
*
|
|
20
|
+
* The property worth writing down, because it is the whole difference:
|
|
21
|
+
*
|
|
22
|
+
* In "layered" mode, a second anchor that resolves LATER changes the anchor
|
|
23
|
+
* block and never the record outcome. In "composed" mode, the same event
|
|
24
|
+
* legitimately flips the headline — the composed answer was about the pair,
|
|
25
|
+
* not about the bytes.
|
|
26
|
+
*
|
|
27
|
+
* BOUNDARY (standing, load-bearing):
|
|
28
|
+
* - Neither mode may turn ABSENT into a refusal. Silence is not a failure in
|
|
29
|
+
* both, and that invariant is asserted rather than described.
|
|
30
|
+
* - Composition never upgrades a record: a failed record layer stays failed
|
|
31
|
+
* in both modes. The anchor layer can only make the pair weaker, never the
|
|
32
|
+
* record stronger.
|
|
33
|
+
* - No clock, no network, no keys. Facts in, decision out.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import { decideOutcome, OUTCOMES } from "./outcomes.mjs";
|
|
37
|
+
|
|
38
|
+
export const COMPOSITION_VERSION = "CG-COMPOSE/1";
|
|
39
|
+
|
|
40
|
+
/** The two policies. Adding a third is a schema change, not a preference. */
|
|
41
|
+
export const COMPOSITION_MODES = Object.freeze(["composed", "layered"]);
|
|
42
|
+
|
|
43
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* composeOutcome({ presented, record, anchor, mode })
|
|
47
|
+
*
|
|
48
|
+
* presented true only if a record was actually handed over
|
|
49
|
+
* record { evaluated, ok, code?, reason?, version? }
|
|
50
|
+
* anchor { present, evaluated, outcome? } in CG-OUT/1's vocabulary
|
|
51
|
+
* mode "composed" (default) | "layered"
|
|
52
|
+
*/
|
|
53
|
+
export function composeOutcome({ presented, record, anchor, mode = "composed" } = {}) {
|
|
54
|
+
if (!COMPOSITION_MODES.includes(mode)) {
|
|
55
|
+
throw new Error(`unknown composition mode: ${JSON.stringify(mode)} (use one of ${COMPOSITION_MODES.join(", ")})`);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (mode === "composed") {
|
|
59
|
+
const composed = decideOutcome({ presented, record, anchor });
|
|
60
|
+
return Object.freeze({
|
|
61
|
+
compositionVersion: COMPOSITION_VERSION,
|
|
62
|
+
mode,
|
|
63
|
+
headline: composed.outcome,
|
|
64
|
+
record: Object.freeze({ outcome: recordHeadline({ presented, record }), moved: false }),
|
|
65
|
+
anchor: anchorBlock(anchor),
|
|
66
|
+
blocks: composed.blocks,
|
|
67
|
+
resolutionSensitive: anchorContributed(anchor, composed.outcome),
|
|
68
|
+
code: composed.code,
|
|
69
|
+
reason: composed.reason,
|
|
70
|
+
layers: composed.layers,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Layered: the headline is the record's own answer, computed without the
|
|
75
|
+
// anchor facts at all. That is what makes it stable under later resolution.
|
|
76
|
+
const recordOnly = decideOutcome({ presented, record });
|
|
77
|
+
const anchorFacts = anchorBlock(anchor);
|
|
78
|
+
return Object.freeze({
|
|
79
|
+
compositionVersion: COMPOSITION_VERSION,
|
|
80
|
+
mode,
|
|
81
|
+
headline: recordOnly.outcome,
|
|
82
|
+
record: Object.freeze({ outcome: recordOnly.outcome, moved: false }),
|
|
83
|
+
anchor: Object.freeze({ ...anchorFacts, rejected: anchorFacts.outcome === "unresolvable" ? "unresolvable record" : null }),
|
|
84
|
+
blocks: recordOnly.blocks,
|
|
85
|
+
resolutionSensitive: false,
|
|
86
|
+
code: recordOnly.code,
|
|
87
|
+
reason: recordOnly.reason,
|
|
88
|
+
layers: Object.freeze({
|
|
89
|
+
record: recordOnly.layers.record,
|
|
90
|
+
anchor: Object.freeze({ present: anchorFacts.present, evaluated: anchorFacts.evaluated, outcome: anchorFacts.outcome }),
|
|
91
|
+
}),
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function recordHeadline({ presented, record }) {
|
|
96
|
+
return decideOutcome({ presented, record }).outcome;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function anchorBlock(anchor) {
|
|
100
|
+
const stated = isObject(anchor);
|
|
101
|
+
const outcome = stated && typeof anchor.outcome === "string" ? anchor.outcome : "not_checked";
|
|
102
|
+
return Object.freeze({
|
|
103
|
+
present: stated ? anchor.present === true : false,
|
|
104
|
+
evaluated: stated ? anchor.evaluated === true : false,
|
|
105
|
+
outcome,
|
|
106
|
+
rejected: outcome === "unresolvable" ? "unresolvable record" : null,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function anchorContributed(anchor, headline) {
|
|
111
|
+
return isObject(anchor) && anchor.evaluated === true && anchor.outcome === "unresolvable" && headline === "UNRESOLVABLE_RECORD";
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** A picture of the two modes over the same facts — used by the CLI and docs. */
|
|
115
|
+
export function compareModes(input) {
|
|
116
|
+
const composed = composeOutcome({ ...input, mode: "composed" });
|
|
117
|
+
const layered = composeOutcome({ ...input, mode: "layered" });
|
|
118
|
+
return Object.freeze({
|
|
119
|
+
compositionVersion: COMPOSITION_VERSION,
|
|
120
|
+
composed,
|
|
121
|
+
layered,
|
|
122
|
+
diverges: composed.headline !== layered.headline,
|
|
123
|
+
recordStable: composed.record.outcome === layered.record.outcome,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Self-check: the policy's own invariants, for callers that cannot run tests. */
|
|
128
|
+
export function selfCheck() {
|
|
129
|
+
const ok = { evaluated: true, ok: true };
|
|
130
|
+
const facts = { presented: true, record: ok };
|
|
131
|
+
const unresolvable = { present: true, evaluated: true, outcome: "unresolvable" };
|
|
132
|
+
const resolved = { present: true, evaluated: true, outcome: "verified" };
|
|
133
|
+
|
|
134
|
+
const c1 = compareModes({ ...facts, anchor: unresolvable });
|
|
135
|
+
const c2 = compareModes({ ...facts, anchor: resolved });
|
|
136
|
+
const silence = compareModes({ presented: false, anchor: unresolvable });
|
|
137
|
+
const failedRecord = compareModes({ presented: true, record: { evaluated: true, ok: false }, anchor: resolved });
|
|
138
|
+
|
|
139
|
+
const checks = [
|
|
140
|
+
{ name: "the modes diverge only when the anchor is unresolvable", pass: c1.diverges === true && c2.diverges === false },
|
|
141
|
+
{ name: "the record outcome is identical in both modes", pass: c1.recordStable && c2.recordStable },
|
|
142
|
+
{ name: "composed mode blocks on an unresolvable anchor", pass: c1.composed.blocks === true },
|
|
143
|
+
{ name: "layered mode never blocks on an unresolvable anchor", pass: c1.layered.blocks === false },
|
|
144
|
+
{ name: "layered mode carries the rejection on the anchor layer", pass: c1.layered.anchor.rejected === "unresolvable record" },
|
|
145
|
+
{ name: "silence is not a refusal in either mode", pass: silence.composed.headline === "ABSENT" && silence.layered.headline === "ABSENT" && !silence.layered.blocks },
|
|
146
|
+
{ name: "a failed record stays failed in both modes", pass: failedRecord.composed.headline === "VERIFICATION_FAILED" && failedRecord.layered.headline === "VERIFICATION_FAILED" },
|
|
147
|
+
{ name: "every headline is one of the five outcomes", pass: OUTCOMES.includes(c1.composed.headline) && OUTCOMES.includes(c1.layered.headline) },
|
|
148
|
+
];
|
|
149
|
+
return Object.freeze({ ok: checks.every((c) => c.pass), checks });
|
|
150
|
+
}
|