@coreguard/agent-commerce 0.1.3 → 0.1.5
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 +33 -1
- package/aer1.mjs +698 -2
- package/cgcp-mcp-tools.mjs +142 -0
- package/control-plane-cli.mjs +187 -161
- package/control-plane-http.mjs +91 -18
- package/control-plane.mjs +297 -43
- package/index.d.ts +143 -0
- package/index.mjs +51 -0
- package/machine-economy.mjs +366 -0
- package/mcp.mjs +182 -8
- package/observations.mjs +524 -0
- package/package.json +30 -7
- 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/server.json +20 -0
package/index.d.ts
CHANGED
|
@@ -561,6 +561,125 @@ export declare function aer1SelfCheck(): Readonly<{
|
|
|
561
561
|
checks: ReadonlyArray<{ name: string; pass: boolean }>;
|
|
562
562
|
}>;
|
|
563
563
|
|
|
564
|
+
// ---------------------------------------------------------------------------
|
|
565
|
+
// CG-OBS/1 — the observation ledger. A verification is an event, not a property
|
|
566
|
+
// of the run: one immutable record per (observer, read), with the bytes that
|
|
567
|
+
// observer recomputed, the read time that observer held, and a named reason
|
|
568
|
+
// wherever a check did not happen.
|
|
569
|
+
// ---------------------------------------------------------------------------
|
|
570
|
+
|
|
571
|
+
export const OBSERVATION_VERSION: "CG-OBS/1";
|
|
572
|
+
export type CheckOutcome =
|
|
573
|
+
| "verified"
|
|
574
|
+
| "verification_failed"
|
|
575
|
+
| "not_checked"
|
|
576
|
+
| "absent"
|
|
577
|
+
| "unresolvable_record";
|
|
578
|
+
export const CHECK_OUTCOMES: readonly CheckOutcome[];
|
|
579
|
+
export const NOT_CHECKED_REASONS: readonly string[];
|
|
580
|
+
export const OBSERVATION_CODES: Readonly<Record<string, string>>;
|
|
581
|
+
|
|
582
|
+
export interface ObservationInput {
|
|
583
|
+
observer: string;
|
|
584
|
+
scope?: string | null;
|
|
585
|
+
action_id: string;
|
|
586
|
+
record_id?: string | null;
|
|
587
|
+
subject_digest: string;
|
|
588
|
+
observed_digest?: string | null;
|
|
589
|
+
outcome: CheckOutcome;
|
|
590
|
+
code?: string | null;
|
|
591
|
+
reason?: string | null;
|
|
592
|
+
checked_at: string;
|
|
593
|
+
action_at?: string | null;
|
|
594
|
+
evidence?: Record<string, unknown> | null;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
export interface ObservationEvent {
|
|
598
|
+
observation_version: "CG-OBS/1";
|
|
599
|
+
observation_id: string;
|
|
600
|
+
observer: string;
|
|
601
|
+
scope: string | null;
|
|
602
|
+
action_id: string;
|
|
603
|
+
record_id: string | null;
|
|
604
|
+
subject_digest: string;
|
|
605
|
+
observed_digest: string | null;
|
|
606
|
+
outcome: CheckOutcome;
|
|
607
|
+
code: string | null;
|
|
608
|
+
reason: string | null;
|
|
609
|
+
checked_at: string;
|
|
610
|
+
action_at: string | null;
|
|
611
|
+
evidence: Readonly<Record<string, unknown>> | null;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
export interface ObservationRecording {
|
|
615
|
+
ok: boolean;
|
|
616
|
+
code: string | null;
|
|
617
|
+
detail?: string | null;
|
|
618
|
+
event: ObservationEvent | null;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
export interface ObservationLedger {
|
|
622
|
+
observation_version: "CG-OBS/1";
|
|
623
|
+
events: readonly ObservationEvent[];
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
export interface ObservationAppend {
|
|
627
|
+
ok: boolean;
|
|
628
|
+
code: string | null;
|
|
629
|
+
detail: string | null;
|
|
630
|
+
ledger: ObservationLedger;
|
|
631
|
+
event: ObservationEvent | null;
|
|
632
|
+
duplicate?: boolean;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
export interface ObservedAccrual {
|
|
636
|
+
observation_version: "CG-OBS/1";
|
|
637
|
+
action_id: string | null;
|
|
638
|
+
events: number;
|
|
639
|
+
observers: ReadonlyArray<{
|
|
640
|
+
observer: string;
|
|
641
|
+
latest_outcome: CheckOutcome;
|
|
642
|
+
latest_code: string | null;
|
|
643
|
+
latest_reason: string | null;
|
|
644
|
+
latest_checked_at: string;
|
|
645
|
+
scopes: readonly string[];
|
|
646
|
+
reads: number;
|
|
647
|
+
observation_ids: readonly string[];
|
|
648
|
+
}>;
|
|
649
|
+
verified_by: readonly string[];
|
|
650
|
+
not_checked_by: ReadonlyArray<{ observer: string; reason: string | null; at: string }>;
|
|
651
|
+
failed_by?: readonly string[];
|
|
652
|
+
absent_by?: readonly string[];
|
|
653
|
+
first_read_at: string | null;
|
|
654
|
+
first_verified_at?: string | null;
|
|
655
|
+
last_read_at: string | null;
|
|
656
|
+
composite: CheckOutcome;
|
|
657
|
+
contested: boolean;
|
|
658
|
+
executions: 1;
|
|
659
|
+
detail: string | null;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
export declare function parseInstant(value: unknown): { ms: number; lexeme: string } | null;
|
|
663
|
+
export declare function observationId(event: ObservationEvent): string;
|
|
664
|
+
export declare function recordObservation(input: ObservationInput): ObservationRecording;
|
|
665
|
+
export declare function createLedger(): ObservationLedger;
|
|
666
|
+
export declare function appendObservation(ledger: ObservationLedger, input: ObservationInput): ObservationAppend;
|
|
667
|
+
export declare function buildLedger(
|
|
668
|
+
inputs?: ObservationInput[],
|
|
669
|
+
): Readonly<{ ok: boolean; code: string | null; detail: string | null; ledger: ObservationLedger }>;
|
|
670
|
+
export declare function accrueObservations(
|
|
671
|
+
ledger: ObservationLedger,
|
|
672
|
+
options?: { action_id?: string; subject_digest?: string },
|
|
673
|
+
): ObservedAccrual;
|
|
674
|
+
export declare function describeAccrual(accrual: ObservedAccrual): string;
|
|
675
|
+
export declare function observationsSelfCheck(): Readonly<{
|
|
676
|
+
ok: boolean;
|
|
677
|
+
observationVersion: string;
|
|
678
|
+
outcomes: readonly CheckOutcome[];
|
|
679
|
+
reasons: readonly string[];
|
|
680
|
+
checks: ReadonlyArray<{ name: string; pass: boolean }>;
|
|
681
|
+
}>;
|
|
682
|
+
|
|
564
683
|
// ---------------------------------------------------------------------------
|
|
565
684
|
// CG-ANCHOR/1 — the anchor service we run: offline-verifiable attestations, an
|
|
566
685
|
// append-only hash-chained log, one Merkle root, and a prepare-only chain
|
|
@@ -1103,6 +1222,21 @@ export interface ControlPlaneLedgerVerification {
|
|
|
1103
1222
|
boundary: string;
|
|
1104
1223
|
}
|
|
1105
1224
|
|
|
1225
|
+
// CG-ME/1 - Machine Economy Wave 1 (deterministic offline, no custody/broadcast/network)
|
|
1226
|
+
export declare const MACHINE_ECONOMY_VERSION: string;
|
|
1227
|
+
export declare const MACHINE_ECONOMY_BOUNDARY: string;
|
|
1228
|
+
export declare function parseX402Challenge(input?: any): any;
|
|
1229
|
+
export declare function authorizeX402Payment(input?: any): any;
|
|
1230
|
+
export declare function verifyX402Settlement(input?: any): any;
|
|
1231
|
+
export declare function reconcilePayment(input?: any): any;
|
|
1232
|
+
export declare function meterAgentUsage(input?: any): any;
|
|
1233
|
+
export declare function registerMachine(input?: any): any;
|
|
1234
|
+
export declare function createMachineTask(input?: any): any;
|
|
1235
|
+
export declare function verifyTelemetry(input?: any): any;
|
|
1236
|
+
export declare function verifyTaskCompletion(input?: any): any;
|
|
1237
|
+
export declare function verifyDelegationChain(input?: any): any;
|
|
1238
|
+
export declare function machineEconomySelfCheck(): Array<[string, boolean]>;
|
|
1239
|
+
|
|
1106
1240
|
export interface ControlPlane {
|
|
1107
1241
|
version: string;
|
|
1108
1242
|
schema: string;
|
|
@@ -1169,3 +1303,12 @@ export declare function startControlPlaneServer(input: {
|
|
|
1169
1303
|
port: number;
|
|
1170
1304
|
close(): Promise<void>;
|
|
1171
1305
|
}>;
|
|
1306
|
+
|
|
1307
|
+
// CGCP/1 MCP Wave 2 mapping tools
|
|
1308
|
+
export declare const CGCP_MCP_BOUNDARY: string;
|
|
1309
|
+
export declare function createIntent(input?: any): any;
|
|
1310
|
+
export declare function issueReceipt(input?: any): any;
|
|
1311
|
+
export declare function verifyCgcpReceipt(input?: any): any;
|
|
1312
|
+
export declare function checkLimits(input?: any): any;
|
|
1313
|
+
export declare function revokeConsent(input?: any): any;
|
|
1314
|
+
export declare function auditTransaction(input?: any): any;
|
package/index.mjs
CHANGED
|
@@ -305,6 +305,27 @@ export {
|
|
|
305
305
|
selfCheck as aer1SelfCheck,
|
|
306
306
|
} from "./aer1.mjs";
|
|
307
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
|
+
|
|
308
329
|
// CG-ANCHOR/1 — the anchor service we run ourselves: Ed25519 attestations that
|
|
309
330
|
// verify offline, an append-only hash-chained log, one Merkle root over it, and
|
|
310
331
|
// a chain adapter that prepares a 32-byte memo and refuses mainnet by name.
|
|
@@ -423,3 +444,33 @@ export {
|
|
|
423
444
|
createControlPlaneServer,
|
|
424
445
|
startControlPlaneServer,
|
|
425
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
|
+
}
|