@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/index.mjs
CHANGED
|
@@ -37,6 +37,56 @@ import { assessRisk, AGR_VERSION } from "./risk.mjs";
|
|
|
37
37
|
|
|
38
38
|
export { assessRisk, AGR_VERSION };
|
|
39
39
|
|
|
40
|
+
// CG-OUT/1 — the outcome layer above the reject codes: five outcomes over
|
|
41
|
+
// three layers, with ABSENT and NOT_CHECKED structurally unable to travel as a
|
|
42
|
+
// block. The bridges map what the existing surfaces already print onto it, and
|
|
43
|
+
// `authorizationDecision` is the one function that turns a vocabulary into
|
|
44
|
+
// behaviour (absent and not-checked yield NONE, never PASS and never BLOCK).
|
|
45
|
+
export {
|
|
46
|
+
OUTCOME_VERSION,
|
|
47
|
+
OUTCOMES,
|
|
48
|
+
OUTCOME_CODES,
|
|
49
|
+
NON_BLOCKING_OUTCOMES,
|
|
50
|
+
BLOCKING_OUTCOMES,
|
|
51
|
+
decideOutcome,
|
|
52
|
+
assertNotRenderedAsBlock,
|
|
53
|
+
selfCheck as outcomeSelfCheck,
|
|
54
|
+
} from "./outcomes.mjs";
|
|
55
|
+
|
|
56
|
+
// CG-ID/1 — identity split: recordId (who the record is) kept apart from
|
|
57
|
+
// contentDigest (what these bytes are) so an anchorRef can ride alongside.
|
|
58
|
+
export {
|
|
59
|
+
IDENTITY_VERSION,
|
|
60
|
+
IDENTITY_SCHEMA,
|
|
61
|
+
ANCHOR_KINDS,
|
|
62
|
+
recordIdFor,
|
|
63
|
+
splitIdentity,
|
|
64
|
+
normalizeAnchor,
|
|
65
|
+
compareIdentities,
|
|
66
|
+
anchorFacts,
|
|
67
|
+
selfCheck as identitySelfCheck,
|
|
68
|
+
} from "./identity.mjs";
|
|
69
|
+
|
|
70
|
+
// CG-OUT/1 profile reference — the three fields a protocol would carry
|
|
71
|
+
// (receipt_id, profile, profile_version), with the version checked on arrival.
|
|
72
|
+
export {
|
|
73
|
+
PROFILE_ID,
|
|
74
|
+
PROFILE_VERSION,
|
|
75
|
+
PROFILE_REFERENCE_SCHEMA,
|
|
76
|
+
REFERENCE_FIELDS,
|
|
77
|
+
makeProfileReference,
|
|
78
|
+
parseProfileReference,
|
|
79
|
+
selfCheck as profileSelfCheck,
|
|
80
|
+
} from "./profile-ref.mjs";
|
|
81
|
+
|
|
82
|
+
export {
|
|
83
|
+
BRIDGE_VERSION,
|
|
84
|
+
outcomeForVerificationReport,
|
|
85
|
+
outcomeForPsarResult,
|
|
86
|
+
authorizationDecision,
|
|
87
|
+
profileReferenceFor,
|
|
88
|
+
} from "./outcomes-bridge.mjs";
|
|
89
|
+
|
|
40
90
|
// AC-CS/1 — durable single-use consumption store adapter (file-backed,
|
|
41
91
|
// Set-compatible; cross-process on host). NOT a distributed ledger, NOT an
|
|
42
92
|
// on-chain marker (on-chain anchoring OWNER-GATED / NOT_BUILT).
|
|
@@ -213,7 +263,10 @@ export async function verifyConsent(consent) {
|
|
|
213
263
|
export async function verifyExecution(consent, trace, { consumedSet } = {}) {
|
|
214
264
|
requireConsent(consent);
|
|
215
265
|
const ledger = consumedSet ?? processConsumed;
|
|
216
|
-
|
|
266
|
+
// Ledger reads/writes are awaited so an asynchronous adapter (a shared or
|
|
267
|
+
// remote consumption store) is a first-class injection. A plain Set still
|
|
268
|
+
// works unchanged: awaiting a non-promise is the value itself.
|
|
269
|
+
const alreadyConsumed = (await ledger.has(consent.receiptId)) === true;
|
|
217
270
|
|
|
218
271
|
const verification = await verifyReceipt(consent.receipt, null, consent.intent, consent.policy, trace);
|
|
219
272
|
const risk = assessRisk({ intent: consent.intent, policy: consent.policy, trace, consumed: alreadyConsumed });
|
|
@@ -222,7 +275,7 @@ export async function verifyExecution(consent, trace, { consumedSet } = {}) {
|
|
|
222
275
|
const drift = nameDrift(consent.intent, trace);
|
|
223
276
|
const verified = verification.result === "VERIFIED" && !hardFail && risk.classification === "CLEAN";
|
|
224
277
|
|
|
225
|
-
if (verified && consent.intent.singleUse) ledger.add(consent.receiptId);
|
|
278
|
+
if (verified && consent.intent.singleUse) await ledger.add(consent.receiptId);
|
|
226
279
|
|
|
227
280
|
return {
|
|
228
281
|
spec: AGENT_COMMERCE_VERSION,
|
|
@@ -232,8 +285,192 @@ export async function verifyExecution(consent, trace, { consumedSet } = {}) {
|
|
|
232
285
|
risk,
|
|
233
286
|
driftNamed: drift,
|
|
234
287
|
consumed: alreadyConsumed || verified,
|
|
235
|
-
consumedLedger:
|
|
288
|
+
consumedLedger: consumedSet
|
|
289
|
+
? "caller-supplied ledger — process-local Set, AC-CS/1 file store (cross-process on this host), or an asynchronous shared store; a global register and on-chain anchoring are NOT_BUILT"
|
|
290
|
+
: "process-local — pass an AC-CS/1 store for cross-process anchoring on this host; cross-host reconciliation is CG-SPEND/1; a global register and on-chain anchoring are NOT_BUILT",
|
|
236
291
|
boundary:
|
|
237
292
|
"execution verification never decides delivery conformity (DDE/1); VERIFIED ≠ SAFE; the actor is declared, never detected",
|
|
238
293
|
};
|
|
239
294
|
}
|
|
295
|
+
|
|
296
|
+
// CG-AER1/1 — a parser for AER-1 (draft-zambo-aer1-26) receipts. The committed
|
|
297
|
+
// payload and the receipt id are kept apart, because the format keeps them
|
|
298
|
+
// apart: the digest is recomputed, the id is bound only against something
|
|
299
|
+
// external (an expected id, or a resolved record that must agree on the digest).
|
|
300
|
+
export {
|
|
301
|
+
AER1_PARSER_VERSION,
|
|
302
|
+
SUPPORTED_RECEIPT_SCHEMAS,
|
|
303
|
+
parseAer1Record,
|
|
304
|
+
aer1Outcome,
|
|
305
|
+
selfCheck as aer1SelfCheck,
|
|
306
|
+
} from "./aer1.mjs";
|
|
307
|
+
|
|
308
|
+
// CG-OBS/1 — the observation ledger: a verification is an event, not a property
|
|
309
|
+
// of the run. One immutable record per (observer, read), carrying who looked,
|
|
310
|
+
// what access they held, which bytes they recomputed, when they read, and why a
|
|
311
|
+
// check did not happen. A later read adds evidence; it never rewrites the
|
|
312
|
+
// earlier one, and it never replays the action.
|
|
313
|
+
export {
|
|
314
|
+
OBSERVATION_VERSION,
|
|
315
|
+
CHECK_OUTCOMES,
|
|
316
|
+
NOT_CHECKED_REASONS,
|
|
317
|
+
OBSERVATION_CODES,
|
|
318
|
+
parseInstant,
|
|
319
|
+
observationId,
|
|
320
|
+
recordObservation,
|
|
321
|
+
createLedger,
|
|
322
|
+
appendObservation,
|
|
323
|
+
buildLedger,
|
|
324
|
+
accrue as accrueObservations,
|
|
325
|
+
describeAccrual,
|
|
326
|
+
selfCheck as observationsSelfCheck,
|
|
327
|
+
} from "./observations.mjs";
|
|
328
|
+
|
|
329
|
+
// CG-ANCHOR/1 — the anchor service we run ourselves: Ed25519 attestations that
|
|
330
|
+
// verify offline, an append-only hash-chained log, one Merkle root over it, and
|
|
331
|
+
// a chain adapter that prepares a 32-byte memo and refuses mainnet by name.
|
|
332
|
+
// No broadcast path exists in the module.
|
|
333
|
+
export {
|
|
334
|
+
ANCHOR_VERSION,
|
|
335
|
+
ANCHOR_SCHEMA,
|
|
336
|
+
normalizeSubject,
|
|
337
|
+
generateIssuerKey,
|
|
338
|
+
keyIdFor,
|
|
339
|
+
signAttestation,
|
|
340
|
+
verifyAttestation as verifyAnchorAttestation,
|
|
341
|
+
leafHash,
|
|
342
|
+
merkleRoot,
|
|
343
|
+
createLog,
|
|
344
|
+
appendAnchor,
|
|
345
|
+
verifyLog,
|
|
346
|
+
resolveAnchor,
|
|
347
|
+
prepareChainAnchor,
|
|
348
|
+
selfCheck as anchorSelfCheck,
|
|
349
|
+
} from "./anchor.mjs";
|
|
350
|
+
|
|
351
|
+
// CG-COMPOSE/1 — one composition rule, two defensible answers. "composed"
|
|
352
|
+
// lets an unresolvable anchor block the headline (best for a commerce consumer
|
|
353
|
+
// that needs one answer now); "layered" keeps the record verdict fixed and
|
|
354
|
+
// reports the rejection on the anchor layer (best for a record that outlives
|
|
355
|
+
// any single anchor). The difference is a mode, not an argument.
|
|
356
|
+
export {
|
|
357
|
+
COMPOSITION_VERSION,
|
|
358
|
+
COMPOSITION_MODES,
|
|
359
|
+
composeOutcome,
|
|
360
|
+
compareModes,
|
|
361
|
+
selfCheck as compositionSelfCheck,
|
|
362
|
+
} from "./composition.mjs";
|
|
363
|
+
|
|
364
|
+
// CG-REF/1 — the procedure behind a receipt_id. A name proves nothing on its
|
|
365
|
+
// own: resolution produces bytes, the bytes are hashed against an expectation,
|
|
366
|
+
// and "no expectation" is unresolvable rather than resolved.
|
|
367
|
+
export {
|
|
368
|
+
REFERENCE_VERSION,
|
|
369
|
+
REFERENCE_SCHEMA,
|
|
370
|
+
ID_FORMS,
|
|
371
|
+
digestOf,
|
|
372
|
+
classifyReceiptId,
|
|
373
|
+
deriveLocatorCandidates,
|
|
374
|
+
planResolution,
|
|
375
|
+
resolveReceipt,
|
|
376
|
+
resolutionOutcome,
|
|
377
|
+
selfCheck as referenceSelfCheck,
|
|
378
|
+
} from "./reference.mjs";
|
|
379
|
+
|
|
380
|
+
// CG-KEYS/1 — pinned trust, signed rotation chains and time-aware revocation.
|
|
381
|
+
// An unknown key is NOT_CHECKED, never forged; retroactive revocation is a
|
|
382
|
+
// distinct statement from a routine retirement.
|
|
383
|
+
export {
|
|
384
|
+
KEYS_VERSION,
|
|
385
|
+
KEYS_SCHEMA,
|
|
386
|
+
KEY_STATUSES,
|
|
387
|
+
createKeyring,
|
|
388
|
+
pinKey,
|
|
389
|
+
rotateKey,
|
|
390
|
+
revokeKey,
|
|
391
|
+
checkKey,
|
|
392
|
+
verifyWithTrust,
|
|
393
|
+
selfCheck as keysSelfCheck,
|
|
394
|
+
} from "./trust.mjs";
|
|
395
|
+
|
|
396
|
+
// CG-SPEND/1 — single use as an append-only, signed, lock-guarded log rather
|
|
397
|
+
// than a process-local boolean. Two systems that spent the same approval under
|
|
398
|
+
// different nonces produce a `conflict`, which is the only honest way to say
|
|
399
|
+
// "both of us thought we were first".
|
|
400
|
+
export {
|
|
401
|
+
SPEND_VERSION,
|
|
402
|
+
SPEND_SCHEMA,
|
|
403
|
+
SPEND_STATES,
|
|
404
|
+
spendKeyFor,
|
|
405
|
+
createSpendLog,
|
|
406
|
+
makeSpendEntry,
|
|
407
|
+
verifySpendEntry,
|
|
408
|
+
checkSpent,
|
|
409
|
+
readSpendLog,
|
|
410
|
+
claimSpend,
|
|
411
|
+
mergeLogs,
|
|
412
|
+
selfCheck as spendSelfCheck,
|
|
413
|
+
} from "./spend.mjs";
|
|
414
|
+
|
|
415
|
+
// CG-DECIDE/1 — outcome to authorisation. Four decisions, not two, so missing
|
|
416
|
+
// evidence can neither decline a sale nor masquerade as a pass.
|
|
417
|
+
export {
|
|
418
|
+
DECISION_VERSION,
|
|
419
|
+
DECISION_SCHEMA,
|
|
420
|
+
DECISIONS,
|
|
421
|
+
POLICIES,
|
|
422
|
+
decidePayment,
|
|
423
|
+
explainDecision,
|
|
424
|
+
decisionMatrix,
|
|
425
|
+
assertDecisionInvariants,
|
|
426
|
+
selfCheck as decisionSelfCheck,
|
|
427
|
+
} from "./decision.mjs";
|
|
428
|
+
|
|
429
|
+
// CGCP/1 — self-hosted Policy & Evidence Control Plane: versioned policies,
|
|
430
|
+
// approvals, spend windows, execution/verification ledgers, revocation, a
|
|
431
|
+
// hash-chained audit trail, an authenticated HTTP API and a CLI. Single host,
|
|
432
|
+
// single API key; multi-tenant RBAC/SSO, distributed HA and KMS are NOT_BUILT.
|
|
433
|
+
export {
|
|
434
|
+
CONTROL_PLANE_VERSION,
|
|
435
|
+
CONTROL_PLANE_SCHEMA,
|
|
436
|
+
CONTROL_PLANE_BOUNDARY,
|
|
437
|
+
CONTROL_PLANE_DECISION_REASONS,
|
|
438
|
+
createControlPlane,
|
|
439
|
+
verifyAuditChain,
|
|
440
|
+
} from "./control-plane.mjs";
|
|
441
|
+
|
|
442
|
+
export {
|
|
443
|
+
createControlPlaneHandler,
|
|
444
|
+
createControlPlaneServer,
|
|
445
|
+
startControlPlaneServer,
|
|
446
|
+
} from "./control-plane-http.mjs";
|
|
447
|
+
|
|
448
|
+
// CG-ME/1 - Machine Economy Wave 1: deterministic offline x402/machine/delegation
|
|
449
|
+
// verification and evidence records. No custody, no broadcast, no network calls;
|
|
450
|
+
// physical-world truth/signature trust roots NOT proven here. VERIFIED != SAFE.
|
|
451
|
+
export {
|
|
452
|
+
MACHINE_ECONOMY_VERSION,
|
|
453
|
+
MACHINE_ECONOMY_BOUNDARY,
|
|
454
|
+
parseX402Challenge,
|
|
455
|
+
authorizeX402Payment,
|
|
456
|
+
verifyX402Settlement,
|
|
457
|
+
reconcilePayment,
|
|
458
|
+
meterAgentUsage,
|
|
459
|
+
registerMachine,
|
|
460
|
+
createMachineTask,
|
|
461
|
+
verifyTelemetry,
|
|
462
|
+
verifyTaskCompletion,
|
|
463
|
+
verifyDelegationChain,
|
|
464
|
+
machineEconomySelfCheck,
|
|
465
|
+
} from "./machine-economy.mjs";
|
|
466
|
+
|
|
467
|
+
// CGCP/1 MCP Wave 2 mapping tools (file-backed single-host control plane).
|
|
468
|
+
export {
|
|
469
|
+
CGCP_MCP_BOUNDARY,
|
|
470
|
+
createIntent,
|
|
471
|
+
issueReceipt,
|
|
472
|
+
verifyReceipt as verifyCgcpReceipt,
|
|
473
|
+
checkLimits,
|
|
474
|
+
revokeConsent,
|
|
475
|
+
auditTransaction,
|
|
476
|
+
} from "./cgcp-mcp-tools.mjs";
|
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CoreGuard Machine Economy (Wave 1) - deterministic, offline, fail-closed.
|
|
3
|
+
*
|
|
4
|
+
* BOUNDARIES: no payment network contact, no custody, no broadcast, no signing
|
|
5
|
+
* on behalf of users. x402 settlement is verified only from caller-supplied
|
|
6
|
+
* evidence. Telemetry/machine identity/task completion are verified only against
|
|
7
|
+
* provided evidence; physical-world truth is NOT proven. VERIFIED != SAFE.
|
|
8
|
+
*/
|
|
9
|
+
import crypto from "node:crypto";
|
|
10
|
+
import { createPublicKey, verify as cryptoVerify } from "node:crypto";
|
|
11
|
+
|
|
12
|
+
export const MACHINE_ECONOMY_VERSION = "CG-ME/1";
|
|
13
|
+
export const MACHINE_ECONOMY_BOUNDARY =
|
|
14
|
+
"deterministic offline verification/planning surface; no payment custody, no broadcast, no network calls; " +
|
|
15
|
+
"x402 settlement/telemetry/physical completion verified only from caller-supplied evidence; VERIFIED != SAFE.";
|
|
16
|
+
|
|
17
|
+
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
18
|
+
const sha256 = (s) => crypto.createHash("sha256").update(s).digest("hex");
|
|
19
|
+
const canon = (v) => JSON.stringify(v, Object.keys(v instanceof Object ? v : {}).sort?.() ? undefined : undefined);
|
|
20
|
+
function stable(v) {
|
|
21
|
+
if (Array.isArray(v)) return `[${v.map(stable).join(",")}]`;
|
|
22
|
+
if (isObj(v)) return `{${Object.keys(v).sort().map(k => JSON.stringify(k)+":"+stable(v[k])).join(",")}}`;
|
|
23
|
+
return JSON.stringify(v);
|
|
24
|
+
}
|
|
25
|
+
function digest(obj) { return sha256(stable(obj)); }
|
|
26
|
+
function nowPin(nowSeconds) {
|
|
27
|
+
if (nowSeconds === undefined || nowSeconds === null) return null;
|
|
28
|
+
const n = typeof nowSeconds === "string" ? Number(nowSeconds) : nowSeconds;
|
|
29
|
+
if (!Number.isInteger(n) || n < 0) throw new Error("nowSeconds must be a non-negative integer or digit string");
|
|
30
|
+
return n;
|
|
31
|
+
}
|
|
32
|
+
function req(obj, key, type = "string") {
|
|
33
|
+
if (!isObj(obj) || obj[key] === undefined) throw new Error(`${key} is required`);
|
|
34
|
+
const v = obj[key];
|
|
35
|
+
if (type === "object") { if (!isObj(v)) throw new Error(`${key} must be an object`); return v; }
|
|
36
|
+
if (type === "array") { if (!Array.isArray(v)) throw new Error(`${key} must be an array`); return v; }
|
|
37
|
+
if (type === "string") { if (typeof v !== "string" || v.length === 0) throw new Error(`${key} must be a non-empty string`); return v; }
|
|
38
|
+
if (type === "boolean") { if (typeof v !== "boolean") throw new Error(`${key} must be a boolean`); return v; }
|
|
39
|
+
return v;
|
|
40
|
+
}
|
|
41
|
+
function optStr(obj, key) { const v = obj?.[key]; if (v === undefined) return undefined; if (typeof v !== "string") throw new Error(`${key} must be a string`); return v; }
|
|
42
|
+
|
|
43
|
+
export function parseX402Challenge(input = {}) {
|
|
44
|
+
const challenge = req(input, "challenge", "object");
|
|
45
|
+
const accepts = Array.isArray(challenge.accepts) ? challenge.accepts : [];
|
|
46
|
+
const normalizedAccepts = accepts.map((a, i) => {
|
|
47
|
+
if (!isObj(a)) throw new Error(`challenge.accepts[${i}] must be an object`);
|
|
48
|
+
return {
|
|
49
|
+
scheme: optStr(a, "scheme") ?? "exact",
|
|
50
|
+
network: optStr(a, "network") ?? null,
|
|
51
|
+
asset: optStr(a, "asset") ?? null,
|
|
52
|
+
amount: optStr(a, "amount") ?? optStr(a, "maxAmountRequired") ?? null,
|
|
53
|
+
payTo: optStr(a, "payTo") ?? null,
|
|
54
|
+
resource: optStr(a, "resource") ?? optStr(challenge, "resource") ?? null,
|
|
55
|
+
extra: isObj(a.extra) ? a.extra : undefined,
|
|
56
|
+
};
|
|
57
|
+
});
|
|
58
|
+
const issues = [];
|
|
59
|
+
if (normalizedAccepts.length === 0) issues.push("NO_ACCEPTS");
|
|
60
|
+
for (const [i,a] of normalizedAccepts.entries()) {
|
|
61
|
+
if (!a.network) issues.push(`ACCEPT_${i}_MISSING_NETWORK`);
|
|
62
|
+
if (!a.asset) issues.push(`ACCEPT_${i}_MISSING_ASSET`);
|
|
63
|
+
if (!a.amount) issues.push(`ACCEPT_${i}_MISSING_AMOUNT`);
|
|
64
|
+
if (!a.payTo) issues.push(`ACCEPT_${i}_MISSING_PAY_TO`);
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
spec: MACHINE_ECONOMY_VERSION, type: "x402_challenge",
|
|
68
|
+
verdict: issues.length === 0 ? "PARSED" : "INVALID",
|
|
69
|
+
issues, accepts: normalizedAccepts,
|
|
70
|
+
challengeDigest: digest(challenge),
|
|
71
|
+
boundary: MACHINE_ECONOMY_BOUNDARY,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function authorizeX402Payment(input = {}) {
|
|
76
|
+
const challenge = req(input, "challenge", "object");
|
|
77
|
+
const policy = req(input, "policy", "object");
|
|
78
|
+
const parsed = parseX402Challenge({ challenge });
|
|
79
|
+
const selectedIndex = input.selectedIndex ?? 0;
|
|
80
|
+
if (!Number.isInteger(selectedIndex) || selectedIndex < 0 || selectedIndex >= parsed.accepts.length) {
|
|
81
|
+
return { spec: MACHINE_ECONOMY_VERSION, type: "x402_authorization", verdict: "DENIED", reason: "INVALID_SELECTED_INDEX", parsed, boundary: MACHINE_ECONOMY_BOUNDARY };
|
|
82
|
+
}
|
|
83
|
+
const selected = parsed.accepts[selectedIndex];
|
|
84
|
+
const issues = [...parsed.issues];
|
|
85
|
+
const maxAmount = optStr(policy, "maxAmount");
|
|
86
|
+
if (maxAmount && selected.amount && BigInt(selected.amount) > BigInt(maxAmount)) issues.push("AMOUNT_EXCEEDS_POLICY");
|
|
87
|
+
const allowedNetworks = Array.isArray(policy.allowedNetworks) ? policy.allowedNetworks : null;
|
|
88
|
+
if (allowedNetworks && selected.network && !allowedNetworks.includes(selected.network)) issues.push("NETWORK_NOT_ALLOWED");
|
|
89
|
+
const allowedAssets = Array.isArray(policy.allowedAssets) ? policy.allowedAssets : null;
|
|
90
|
+
if (allowedAssets && selected.asset && !allowedAssets.includes(selected.asset)) issues.push("ASSET_NOT_ALLOWED");
|
|
91
|
+
const allowedPayTo = Array.isArray(policy.allowedPayTo) ? policy.allowedPayTo : null;
|
|
92
|
+
if (allowedPayTo && selected.payTo && !allowedPayTo.includes(selected.payTo)) issues.push("PAY_TO_NOT_ALLOWED");
|
|
93
|
+
const verdict = issues.length === 0 ? "AUTHORIZED" : "DENIED";
|
|
94
|
+
return {
|
|
95
|
+
spec: MACHINE_ECONOMY_VERSION, type: "x402_authorization", verdict, issues, selectedIndex, selected,
|
|
96
|
+
challengeDigest: parsed.challengeDigest, policyDigest: digest(policy),
|
|
97
|
+
authorizationId: digest({ challengeDigest: parsed.challengeDigest, policyDigest: digest(policy), selectedIndex, verdict }),
|
|
98
|
+
boundary: MACHINE_ECONOMY_BOUNDARY + " No payment executed; authorization is a policy decision only.",
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function verifyX402Settlement(input = {}) {
|
|
103
|
+
const challenge = req(input, "challenge", "object");
|
|
104
|
+
const settlement = req(input, "settlement", "object");
|
|
105
|
+
const parsed = parseX402Challenge({ challenge });
|
|
106
|
+
const issues = [];
|
|
107
|
+
if (parsed.verdict !== "PARSED") issues.push("INVALID_CHALLENGE");
|
|
108
|
+
const network = optStr(settlement, "network");
|
|
109
|
+
const asset = optStr(settlement, "asset");
|
|
110
|
+
const amount = optStr(settlement, "amount");
|
|
111
|
+
const payTo = optStr(settlement, "payTo");
|
|
112
|
+
const txRef = optStr(settlement, "txRef") ?? optStr(settlement, "transaction") ?? optStr(settlement, "proofRef");
|
|
113
|
+
const status = optStr(settlement, "status") ?? "unknown";
|
|
114
|
+
if (!txRef) issues.push("MISSING_SETTLEMENT_PROOF_REF");
|
|
115
|
+
const match = parsed.accepts.some(a => (!network || a.network===network) && (!asset || a.asset===asset) && (!amount || a.amount===amount) && (!payTo || a.payTo===payTo));
|
|
116
|
+
if (!match) issues.push("SETTLEMENT_DOES_NOT_MATCH_ACCEPTS");
|
|
117
|
+
if (!["settled","confirmed","success","finalized"].includes(status.toLowerCase())) issues.push("SETTLEMENT_STATUS_NOT_CONFIRMED");
|
|
118
|
+
return {
|
|
119
|
+
spec: MACHINE_ECONOMY_VERSION, type: "x402_settlement_verification",
|
|
120
|
+
verdict: issues.length === 0 ? "VERIFIED" : "UNVERIFIED",
|
|
121
|
+
issues, challengeDigest: parsed.challengeDigest, settlementDigest: digest(settlement),
|
|
122
|
+
boundary: MACHINE_ECONOMY_BOUNDARY + " Settlement verified only from caller-supplied evidence; no network confirmation performed.",
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function reconcilePayment(input = {}) {
|
|
127
|
+
const authorization = req(input, "authorization", "object");
|
|
128
|
+
const settlement = isObj(input.settlement) ? input.settlement : null;
|
|
129
|
+
const receipt = isObj(input.receipt) ? input.receipt : null;
|
|
130
|
+
const issues = [];
|
|
131
|
+
if (authorization.verdict !== "AUTHORIZED") issues.push("AUTHORIZATION_NOT_AUTHORIZED");
|
|
132
|
+
if (!settlement) issues.push("MISSING_SETTLEMENT");
|
|
133
|
+
if (!receipt) issues.push("MISSING_RECEIPT");
|
|
134
|
+
if (settlement) {
|
|
135
|
+
const sv = verifyX402Settlement({ challenge: input.challenge ?? { accepts: [authorization.selected].filter(Boolean) }, settlement });
|
|
136
|
+
if (sv.verdict !== "VERIFIED") issues.push(...sv.issues.map(i => `SETTLEMENT_${i}`));
|
|
137
|
+
}
|
|
138
|
+
if (receipt && authorization.authorizationId && receipt.authorizationId && receipt.authorizationId !== authorization.authorizationId) issues.push("RECEIPT_AUTHORIZATION_MISMATCH");
|
|
139
|
+
return {
|
|
140
|
+
spec: MACHINE_ECONOMY_VERSION, type: "payment_reconciliation",
|
|
141
|
+
verdict: issues.length === 0 ? "RECONCILED" : "NOT_RECONCILED",
|
|
142
|
+
issues,
|
|
143
|
+
authorizationId: authorization.authorizationId ?? null,
|
|
144
|
+
boundary: MACHINE_ECONOMY_BOUNDARY,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function meterAgentUsage(input = {}) {
|
|
149
|
+
const agentId = req(input, "agentId");
|
|
150
|
+
const events = req(input, "events", "array");
|
|
151
|
+
let total = 0n;
|
|
152
|
+
const normalized = events.map((e, i) => {
|
|
153
|
+
if (!isObj(e)) throw new Error(`events[${i}] must be an object`);
|
|
154
|
+
const amount = String(e.amount ?? "0");
|
|
155
|
+
let a; try { a = BigInt(amount); } catch { throw new Error(`events[${i}].amount must be integer string`); }
|
|
156
|
+
if (a < 0n) throw new Error(`events[${i}].amount must be non-negative`);
|
|
157
|
+
total += a;
|
|
158
|
+
return { eventId: optStr(e, "eventId") ?? `event-${i+1}`, amount: a.toString(), unit: optStr(e, "unit") ?? "minor", resource: optStr(e, "resource") ?? null };
|
|
159
|
+
});
|
|
160
|
+
return {
|
|
161
|
+
spec: MACHINE_ECONOMY_VERSION, type: "agent_usage_meter",
|
|
162
|
+
agentId, eventCount: normalized.length, totalAmount: total.toString(),
|
|
163
|
+
currency: optStr(input, "currency") ?? null,
|
|
164
|
+
eventsDigest: digest(normalized),
|
|
165
|
+
boundary: MACHINE_ECONOMY_BOUNDARY,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function registerMachine(input = {}) {
|
|
170
|
+
const machineId = req(input, "machineId");
|
|
171
|
+
const manifest = req(input, "manifest", "object");
|
|
172
|
+
const owner = optStr(input, "owner") ?? null;
|
|
173
|
+
const capabilities = Array.isArray(manifest.capabilities) ? manifest.capabilities.filter(x => typeof x === "string") : [];
|
|
174
|
+
return {
|
|
175
|
+
spec: MACHINE_ECONOMY_VERSION, type: "machine_registration",
|
|
176
|
+
verdict: "REGISTERED_LOCAL",
|
|
177
|
+
machineId, owner, capabilities,
|
|
178
|
+
manifestDigest: digest(manifest),
|
|
179
|
+
registrationId: digest({ machineId, owner, manifestDigest: digest(manifest) }),
|
|
180
|
+
boundary: MACHINE_ECONOMY_BOUNDARY + " Local registration record only; no external identity attestation performed.",
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function createMachineTask(input = {}) {
|
|
185
|
+
const taskId = req(input, "taskId");
|
|
186
|
+
const machineId = req(input, "machineId");
|
|
187
|
+
const terms = req(input, "terms", "object");
|
|
188
|
+
const price = optStr(terms, "price") ?? req(terms, "price");
|
|
189
|
+
const currency = optStr(terms, "currency") ?? "UNKNOWN";
|
|
190
|
+
return {
|
|
191
|
+
spec: MACHINE_ECONOMY_VERSION, type: "machine_task",
|
|
192
|
+
verdict: "CREATED",
|
|
193
|
+
taskId, machineId, termsDigest: digest(terms),
|
|
194
|
+
price: String(price), currency,
|
|
195
|
+
taskDigest: digest({ taskId, machineId, terms }),
|
|
196
|
+
boundary: MACHINE_ECONOMY_BOUNDARY,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function canonicalJson(value) {
|
|
201
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
202
|
+
if (Array.isArray(value)) return "[" + value.map(canonicalJson).join(",") + "]";
|
|
203
|
+
const keys = Object.keys(value).sort();
|
|
204
|
+
return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalJson(value[k])).join(",") + "}";
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function resolvePublicKey(trust, keyId, publicKeyPem) {
|
|
208
|
+
if (typeof publicKeyPem === "string" && publicKeyPem.includes("PUBLIC KEY")) return publicKeyPem;
|
|
209
|
+
if (!trust || typeof trust !== "object") return null;
|
|
210
|
+
if (typeof trust.publicKeyPem === "string" && trust.publicKeyPem.includes("PUBLIC KEY")) return trust.publicKeyPem;
|
|
211
|
+
const keys = trust.publicKeys;
|
|
212
|
+
if (Array.isArray(keys)) {
|
|
213
|
+
const found = keys.find((k) => k && typeof k === "object" && (k.keyId === keyId || (!keyId && keys.length === 1)) && typeof k.publicKeyPem === "string");
|
|
214
|
+
if (found) return found.publicKeyPem;
|
|
215
|
+
} else if (keys && typeof keys === "object") {
|
|
216
|
+
if (keyId && typeof keys[keyId] === "string") return keys[keyId];
|
|
217
|
+
const vals = Object.values(keys);
|
|
218
|
+
if (!keyId && vals.length === 1 && typeof vals[0] === "string") return vals[0];
|
|
219
|
+
}
|
|
220
|
+
if (trust.keyring && Array.isArray(trust.keyring.pinned)) {
|
|
221
|
+
const found = trust.keyring.pinned.find((k) => k && k.keyId === keyId);
|
|
222
|
+
if (found?.publicKeyPem) return found.publicKeyPem;
|
|
223
|
+
}
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function verifyEd25519Signature({ payload, signature, publicKeyPem }) {
|
|
228
|
+
try {
|
|
229
|
+
const ok = cryptoVerify(null, Buffer.from(canonicalJson(payload), "utf8"), createPublicKey(publicKeyPem), Buffer.from(signature, "base64"));
|
|
230
|
+
return { ok: ok === true, error: null };
|
|
231
|
+
} catch (e) {
|
|
232
|
+
return { ok: false, error: e instanceof Error ? e.message : String(e) };
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export function verifyTelemetry(input = {}) {
|
|
237
|
+
const taskId = req(input, "taskId");
|
|
238
|
+
const telemetry = req(input, "telemetry", "object");
|
|
239
|
+
const trust = isObj(input.trust) ? input.trust : null;
|
|
240
|
+
const issues = [];
|
|
241
|
+
const machineId = optStr(telemetry, "machineId");
|
|
242
|
+
const timestamp = telemetry.timestamp;
|
|
243
|
+
const readings = Array.isArray(telemetry.readings) ? telemetry.readings : null;
|
|
244
|
+
if (!machineId) issues.push("MISSING_MACHINE_ID");
|
|
245
|
+
if (timestamp === undefined) issues.push("MISSING_TIMESTAMP");
|
|
246
|
+
if (!readings) issues.push("MISSING_READINGS_ARRAY");
|
|
247
|
+
const signature = optStr(telemetry, "signature");
|
|
248
|
+
const contentDigest = optStr(telemetry, "contentDigest");
|
|
249
|
+
const keyId = optStr(telemetry, "keyId") ?? optStr(telemetry, "signerKeyId") ?? null;
|
|
250
|
+
const signedPayload = isObj(telemetry.signedPayload) ? telemetry.signedPayload : { ...telemetry, signature: undefined };
|
|
251
|
+
const signedPayloadDigest = digest(signedPayload);
|
|
252
|
+
const observedPayload = { machineId, timestamp, readings };
|
|
253
|
+
const observedDigest = digest(observedPayload);
|
|
254
|
+
if (isObj(telemetry.signedPayload) && signedPayloadDigest !== observedDigest) issues.push("SIGNED_PAYLOAD_DOES_NOT_MATCH_OBSERVED_FIELDS");
|
|
255
|
+
const computedDigest = digest({ ...telemetry, signature: undefined });
|
|
256
|
+
if (contentDigest && contentDigest !== computedDigest) issues.push("CONTENT_DIGEST_MISMATCH");
|
|
257
|
+
if (!signature) issues.push("MISSING_SIGNATURE_EVIDENCE");
|
|
258
|
+
|
|
259
|
+
let signatureVerified = false;
|
|
260
|
+
let trustStatus = "NO_TRUST_ROOT";
|
|
261
|
+
const publicKeyPem = resolvePublicKey(trust, keyId, optStr(telemetry, "publicKeyPem"));
|
|
262
|
+
if (signature && publicKeyPem) {
|
|
263
|
+
const v = verifyEd25519Signature({ payload: signedPayload, signature, publicKeyPem });
|
|
264
|
+
signatureVerified = v.ok;
|
|
265
|
+
trustStatus = v.ok ? "SIGNATURE_VERIFIED_WITH_SUPPLIED_KEY" : "SIGNATURE_INVALID";
|
|
266
|
+
if (!v.ok) issues.push("SIGNATURE_VERIFICATION_FAILED");
|
|
267
|
+
} else if (signature && !publicKeyPem) {
|
|
268
|
+
trustStatus = "SIGNATURE_UNVERIFIED_NO_TRUST_ROOT";
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
let verdict;
|
|
272
|
+
if (issues.includes("MISSING_MACHINE_ID") || issues.includes("MISSING_TIMESTAMP") || issues.includes("MISSING_READINGS_ARRAY") || issues.includes("CONTENT_DIGEST_MISMATCH") || issues.includes("SIGNED_PAYLOAD_DOES_NOT_MATCH_OBSERVED_FIELDS")) {
|
|
273
|
+
verdict = "INVALID";
|
|
274
|
+
} else if (!signature) {
|
|
275
|
+
verdict = "INVALID";
|
|
276
|
+
} else if (signatureVerified) {
|
|
277
|
+
verdict = "SIGNATURE_VERIFIED";
|
|
278
|
+
} else {
|
|
279
|
+
verdict = "EVIDENCE_PRESENT_UNVERIFIED_TRUST";
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
return {
|
|
283
|
+
spec: MACHINE_ECONOMY_VERSION, type: "telemetry_verification",
|
|
284
|
+
verdict, issues, taskId, machineId: machineId ?? null,
|
|
285
|
+
keyId, signatureVerified, trustStatus,
|
|
286
|
+
telemetryDigest: digest(telemetry), computedDigest,
|
|
287
|
+
boundary: MACHINE_ECONOMY_BOUNDARY + " Cryptographic signature verification is performed only when a trust root/public key is supplied; supplied-key verification does NOT prove device identity, key custody, or physical-world truth.",
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export function verifyTaskCompletion(input = {}) {
|
|
292
|
+
const task = req(input, "task", "object");
|
|
293
|
+
const completion = req(input, "completion", "object");
|
|
294
|
+
const issues = [];
|
|
295
|
+
if (task.taskId && completion.taskId && task.taskId !== completion.taskId) issues.push("TASK_ID_MISMATCH");
|
|
296
|
+
if (task.machineId && completion.machineId && task.machineId !== completion.machineId) issues.push("MACHINE_ID_MISMATCH");
|
|
297
|
+
const evidence = Array.isArray(completion.evidence) ? completion.evidence : [];
|
|
298
|
+
if (evidence.length === 0) issues.push("MISSING_COMPLETION_EVIDENCE");
|
|
299
|
+
const status = optStr(completion, "status") ?? "unknown";
|
|
300
|
+
if (!["completed","success","done"].includes(status.toLowerCase())) issues.push("STATUS_NOT_COMPLETED");
|
|
301
|
+
const telemetryResult = isObj(input.telemetryVerification) ? input.telemetryVerification : null;
|
|
302
|
+
if (telemetryResult && telemetryResult.verdict !== "EVIDENCE_PRESENT_UNVERIFIED_TRUST" && telemetryResult.verdict !== "VERIFIED") issues.push("TELEMETRY_NOT_ACCEPTED");
|
|
303
|
+
return {
|
|
304
|
+
spec: MACHINE_ECONOMY_VERSION, type: "task_completion_verification",
|
|
305
|
+
verdict: issues.length === 0 ? "EVIDENCE_ACCEPTED" : "NOT_ACCEPTED",
|
|
306
|
+
issues,
|
|
307
|
+
taskDigest: task.taskDigest ?? digest(task),
|
|
308
|
+
completionDigest: digest(completion),
|
|
309
|
+
boundary: MACHINE_ECONOMY_BOUNDARY + " Evidence acceptance is not physical-world proof. Independent verification/oracle required for high-stakes actions.",
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
export function verifyDelegationChain(input = {}) {
|
|
314
|
+
const chain = req(input, "chain", "array");
|
|
315
|
+
const trust = isObj(input.trust) ? input.trust : null;
|
|
316
|
+
const issues = [];
|
|
317
|
+
if (chain.length === 0) issues.push("EMPTY_CHAIN");
|
|
318
|
+
const normalized = chain.map((d, i) => {
|
|
319
|
+
if (!isObj(d)) { issues.push(`DELEGATION_${i}_INVALID`); return null; }
|
|
320
|
+
const delegator = optStr(d, "delegator");
|
|
321
|
+
const delegate = optStr(d, "delegate");
|
|
322
|
+
const scope = Array.isArray(d.scope) ? d.scope.filter(x=>typeof x==="string") : [];
|
|
323
|
+
const expiresAt = d.expiresAt;
|
|
324
|
+
const keyId = optStr(d, "keyId") ?? optStr(d, "delegatorKeyId") ?? null;
|
|
325
|
+
const sig = optStr(d, "signature") ?? null;
|
|
326
|
+
const signedPayload = isObj(d.signedPayload) ? d.signedPayload : { delegator, delegate, scope, expiresAt: expiresAt ?? null, ...(optStr(d,"intentId")?{intentId:optStr(d,"intentId")}:{}), ...(optStr(d,"taskId")?{taskId:optStr(d,"taskId")}:{}) };
|
|
327
|
+
if (!delegator) issues.push(`DELEGATION_${i}_MISSING_DELEGATOR`);
|
|
328
|
+
if (!delegate) issues.push(`DELEGATION_${i}_MISSING_DELEGATE`);
|
|
329
|
+
if (scope.length === 0) issues.push(`DELEGATION_${i}_MISSING_SCOPE`);
|
|
330
|
+
return { delegator, delegate, scope, expiresAt: expiresAt ?? null, keyId, sig, signedPayload, publicKeyPem: optStr(d, "publicKeyPem") ?? null };
|
|
331
|
+
}).filter(Boolean);
|
|
332
|
+
for (let i=1; i<normalized.length; i++) {
|
|
333
|
+
if (normalized[i].delegator && normalized[i-1].delegate && normalized[i].delegator !== normalized[i-1].delegate) {
|
|
334
|
+
issues.push(`CHAIN_BREAK_AT_${i}`);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
let allSigsVerified = normalized.length > 0;
|
|
338
|
+
for (const [i,d] of normalized.entries()) {
|
|
339
|
+
if (!d.sig) { issues.push(`DELEGATION_${i}_MISSING_SIGNATURE`); allSigsVerified = false; continue; }
|
|
340
|
+
const publicKeyPem = resolvePublicKey(trust, d.keyId, d.publicKeyPem);
|
|
341
|
+
if (!publicKeyPem) { allSigsVerified = false; continue; }
|
|
342
|
+
const v = verifyEd25519Signature({ payload: d.signedPayload, signature: d.sig, publicKeyPem });
|
|
343
|
+
if (!v.ok) { issues.push(`DELEGATION_${i}_SIGNATURE_INVALID`); allSigsVerified = false; }
|
|
344
|
+
}
|
|
345
|
+
const hasTrust = !!trust;
|
|
346
|
+
let verdict;
|
|
347
|
+
if (issues.length > 0) verdict = "INVALID";
|
|
348
|
+
else if (allSigsVerified && hasTrust) verdict = "VERIFIED";
|
|
349
|
+
else verdict = "CHAIN_STRUCTURALLY_VALID_UNVERIFIED_SIGNATURES";
|
|
350
|
+
return {
|
|
351
|
+
spec: MACHINE_ECONOMY_VERSION, type: "delegation_chain_verification",
|
|
352
|
+
verdict, issues, depth: normalized.length,
|
|
353
|
+
signaturesVerified: allSigsVerified && hasTrust,
|
|
354
|
+
chainDigest: digest(chain),
|
|
355
|
+
boundary: MACHINE_ECONOMY_BOUNDARY + " Cryptographic signature verification is performed only when trust roots/public keys are supplied; verification proves signature over the supplied payload, not delegator identity beyond the supplied key material.",
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
export function machineEconomySelfCheck() {
|
|
360
|
+
return [
|
|
361
|
+
["version", MACHINE_ECONOMY_VERSION === "CG-ME/1"],
|
|
362
|
+
["boundary", MACHINE_ECONOMY_BOUNDARY.includes("VERIFIED != SAFE")],
|
|
363
|
+
["parse rejects empty", parseX402Challenge({ challenge: { accepts: [] } }).verdict === "INVALID"],
|
|
364
|
+
["delegation empty invalid", verifyDelegationChain({ chain: [] }).verdict === "INVALID"],
|
|
365
|
+
];
|
|
366
|
+
}
|