@coreguard/agent-commerce 0.1.2 → 0.1.3

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/reference.mjs ADDED
@@ -0,0 +1,350 @@
1
+ /**
2
+ * CoreGuard Reference Resolution (CG-REF/1) — from a `receipt_id` to bytes.
3
+ *
4
+ * A field that names evidence is not a field that finds it. This module is the
5
+ * procedure behind the name, and its first rule is that a name alone proves
6
+ * nothing: `receipt_id` is resolved only to a RECORD, and the record is what
7
+ * gets judged. Resolution therefore has to survive four different answers
8
+ * without collapsing them into one:
9
+ *
10
+ * resolved bytes were produced, and their digest matches something the
11
+ * caller could check (the id itself, a registry entry, or an
12
+ * expectation the caller supplied)
13
+ * absent every source said "nothing here" — silence, never a failure
14
+ * unresolvable a source was reachable in principle but could not answer, or
15
+ * the id carried no checkable expectation at all
16
+ * tampered bytes arrived and did not hash to what the id/index claimed
17
+ *
18
+ * Three id forms are recognised, in descending order of what the id itself
19
+ * proves:
20
+ *
21
+ * urn:sha256:<64 hex> content-addressed. Fetch anything you like; it is
22
+ * resolved only if it hashes to the id. No registry, no
23
+ * trust in the locator, no trust in us.
24
+ * https://… a locator. It proves WHERE, never WHAT: the bytes are
25
+ * checked against an expectation (registry entry or the
26
+ * caller's own digest), and with no expectation the
27
+ * result is `unresolvable`, not `resolved`.
28
+ * opaque an identifier with no expectation (AER-1's shape).
29
+ * Locator hints may still be tried, but the outcome
30
+ * cannot be better than `unresolvable` unless the caller
31
+ * brings the expectation with it.
32
+ *
33
+ * BOUNDARY (standing, load-bearing):
34
+ * - The network exists only through an injected `fetchImpl`. There is no
35
+ * ambient fetch, no retry storm, no redirect following beyond what the
36
+ * injected function does, and a hard byte cap: a resolver that lets a peer
37
+ * decide how much memory it uses is a denial-of-service with extra steps.
38
+ * - Plain http is refused unless the host is loopback AND the caller opted in
39
+ * (`allowInsecureLoopback`), so a test can use a real socket without the
40
+ * library ever shipping an http-anywhere default.
41
+ * - Resolution says nothing about correctness. `resolved` means "these are
42
+ * the bytes behind that name", never "these bytes are good".
43
+ */
44
+
45
+ import { createHash } from "node:crypto";
46
+
47
+ export const REFERENCE_VERSION = "CG-REF/1";
48
+ export const REFERENCE_SCHEMA = "coreguard.reference/1";
49
+
50
+ const HEX64 = /^[0-9a-f]{64}$/;
51
+ const URN = /^urn:sha256:([0-9a-f]{64})$/;
52
+ const DEFAULT_MAX_BYTES = 1 << 20;
53
+ const DEFAULT_TIMEOUT_MS = 5000;
54
+
55
+ export const ID_FORMS = Object.freeze(["urn-sha256", "url", "opaque"]);
56
+
57
+ /** sha256 over raw bytes, as the prefixed form the rest of the repo uses. */
58
+ export function digestOf(bytes) {
59
+ const buf = typeof bytes === "string" ? Buffer.from(bytes, "utf8") : Buffer.from(bytes);
60
+ return "sha256:" + createHash("sha256").update(buf).digest("hex");
61
+ }
62
+
63
+ /** What the id itself claims, before any network exists. */
64
+ export function classifyReceiptId(receiptId) {
65
+ if (typeof receiptId !== "string" || receiptId.length === 0 || receiptId.length > 2048) {
66
+ throw new TypeError("receiptId must be a non-empty string of at most 2048 characters");
67
+ }
68
+ const urn = URN.exec(receiptId);
69
+ if (urn) return Object.freeze({ form: "urn-sha256", receiptId, digest: "sha256:" + urn[1], contentAddressed: true });
70
+ let url = null;
71
+ try {
72
+ url = new URL(receiptId);
73
+ } catch {
74
+ url = null;
75
+ }
76
+ if (url && (url.protocol === "https:" || url.protocol === "http:")) {
77
+ return Object.freeze({ form: "url", receiptId, digest: null, contentAddressed: false });
78
+ }
79
+ return Object.freeze({ form: "opaque", receiptId, digest: null, contentAddressed: false });
80
+ }
81
+
82
+ /**
83
+ * The locator hints a profile may derive from an id. This is the "well-known"
84
+ * half of discovery: a content-addressed id already contains everything a
85
+ * mirror needs, so a merchant, an agent platform and an auditor can all probe
86
+ * the same path shape and compare bytes instead of trusting whoever answers.
87
+ */
88
+ export function deriveLocatorCandidates({ receiptId, issuerOrigin, path = "/.well-known/var1/receipts/" } = {}) {
89
+ const id = classifyReceiptId(receiptId);
90
+ const out = [];
91
+ if (id.form === "url") out.push(id.receiptId);
92
+ if (id.contentAddressed && typeof issuerOrigin === "string" && issuerOrigin) {
93
+ const origin = issuerOrigin.replace(/\/+$/, "");
94
+ out.push(`${origin}${path}${id.digest.slice("sha256:".length)}`);
95
+ }
96
+ return Object.freeze(out);
97
+ }
98
+
99
+ /**
100
+ * What a resolution plan can PROVE, step by step, so a reviewer can see that
101
+ * the tiers are not interchangeable before any bytes are fetched.
102
+ */
103
+ export function planResolution({ receiptId, issuerOrigin } = {}) {
104
+ const id = classifyReceiptId(receiptId);
105
+ const steps = [];
106
+ steps.push({
107
+ tier: "inline",
108
+ proves: id.contentAddressed ? "bytes hash to the id" : "bytes hash to the caller's expectation, if any",
109
+ possible: true,
110
+ });
111
+ steps.push({
112
+ tier: "registry",
113
+ proves: "the registry's published digest matches the bytes",
114
+ possible: true,
115
+ });
116
+ const candidates = deriveLocatorCandidates({ receiptId, issuerOrigin });
117
+ steps.push({
118
+ tier: "locator",
119
+ proves: id.contentAddressed ? "bytes hash to the id, so the locator is irrelevant" : "bytes hash to an expectation; the locator is not trusted",
120
+ possible: candidates.length > 0,
121
+ candidates,
122
+ });
123
+ return Object.freeze({
124
+ refVersion: REFERENCE_VERSION,
125
+ idForm: id.form,
126
+ contentAddressed: id.contentAddressed,
127
+ idDigest: id.digest,
128
+ steps: Object.freeze(steps),
129
+ strongestPossible: id.contentAddressed ? "resolved-by-content" : "resolved-by-expectation",
130
+ });
131
+ }
132
+
133
+ function normalizeExpectation(value) {
134
+ if (value == null) return null;
135
+ if (typeof value !== "string" || !/^sha256:[0-9a-f]{64}$/.test(value)) {
136
+ throw new TypeError("expectedDigest must be sha256:<64 hex>");
137
+ }
138
+ return value;
139
+ }
140
+
141
+ function checkUrlAllowed(url, allowInsecureLoopback) {
142
+ const u = new URL(url);
143
+ if (u.protocol === "https:") return true;
144
+ if (u.protocol !== "http:") return false;
145
+ if (!allowInsecureLoopback) return false;
146
+ return u.hostname === "127.0.0.1" || u.hostname === "localhost" || u.hostname === "::1" || u.hostname === "[::1]";
147
+ }
148
+
149
+ /**
150
+ * resolveReceipt({ reference, inline, registry, expectedDigest, fetchImpl, … })
151
+ *
152
+ * reference { receiptId, profile? } — the two fields ACP carries
153
+ * inline { bytes } — the record handed over with the message
154
+ * registry function(id) -> { bytes, digest } | null, or a Map of id -> same
155
+ * expectedDigest what the caller already believes the bytes must hash to
156
+ * fetchImpl async (url) -> { url, status, bytes } — injected, never ambient
157
+ *
158
+ * Precedence is deliberate: inline, then registry, then locator. The first
159
+ * source that produces bytes decides; bytes that fail their expectation are
160
+ * `tampered` immediately, never silently retried against a laxer source.
161
+ */
162
+ export async function resolveReceipt({
163
+ reference,
164
+ inline = null,
165
+ registry = null,
166
+ expectedDigest = null,
167
+ fetchImpl = null,
168
+ maxBytes = DEFAULT_MAX_BYTES,
169
+ timeoutMs = DEFAULT_TIMEOUT_MS,
170
+ allowInsecureLoopback = false,
171
+ } = {}) {
172
+ if (!reference || typeof reference !== "object") throw new TypeError("reference must be an object with receiptId");
173
+ const id = classifyReceiptId(reference.receiptId);
174
+ const expected = normalizeExpectation(expectedDigest) ?? id.digest ?? null;
175
+ const tried = [];
176
+ const checks = [];
177
+
178
+ const judge = (bytes, source, claimedDigest) => {
179
+ const buf = typeof bytes === "string" ? Buffer.from(bytes, "utf8") : Buffer.from(bytes ?? []);
180
+ const digest = digestOf(buf);
181
+ checks.push({ name: "bytes are non-empty", ok: buf.length > 0 });
182
+ checks.push({ name: "bytes are within the cap", ok: buf.length <= maxBytes });
183
+ const target = expected ?? normalizeExpectation(claimedDigest) ?? null;
184
+ if (target) checks.push({ name: `bytes hash to ${target.slice(0, 14)}…`, ok: digest === target });
185
+ return Object.freeze({
186
+ refVersion: REFERENCE_VERSION,
187
+ schema: REFERENCE_SCHEMA,
188
+ receiptId: id.receiptId,
189
+ idForm: id.form,
190
+ source,
191
+ state: target ? (digest === target ? "resolved" : "tampered") : "resolved-unchecked",
192
+ digest,
193
+ expectedDigest: target,
194
+ bytes: buf.toString("utf8"),
195
+ size: buf.length,
196
+ checks: Object.freeze(checks),
197
+ tried: Object.freeze(tried.slice()),
198
+ reason: target ? null : "no_expectation",
199
+ });
200
+ };
201
+
202
+ // 1. inline
203
+ if (inline && (typeof inline.bytes === "string" || Buffer.isBuffer(inline.bytes))) {
204
+ tried.push({ tier: "inline", ok: true });
205
+ return judge(inline.bytes, "inline", inline.digest);
206
+ }
207
+ tried.push({ tier: "inline", ok: false });
208
+
209
+ // 2. registry
210
+ if (registry) {
211
+ let entry = null;
212
+ try {
213
+ entry = typeof registry === "function" ? registry(id.receiptId) : registry.get?.(id.receiptId) ?? null;
214
+ } catch (err) {
215
+ tried.push({ tier: "registry", ok: false, reason: `registry threw: ${err?.message ?? err}` });
216
+ }
217
+ if (entry && (typeof entry.bytes === "string" || Buffer.isBuffer(entry.bytes))) {
218
+ tried.push({ tier: "registry", ok: true });
219
+ const claim = normalizeExpectation(entry.digest);
220
+ if (expected && claim && expected !== claim) {
221
+ return Object.freeze({
222
+ refVersion: REFERENCE_VERSION,
223
+ schema: REFERENCE_SCHEMA,
224
+ receiptId: id.receiptId,
225
+ idForm: id.form,
226
+ source: "registry",
227
+ state: "tampered",
228
+ digest: null,
229
+ expectedDigest: expected,
230
+ bytes: null,
231
+ size: 0,
232
+ checks: Object.freeze([{ name: "registry digest agrees with the id/expectation", ok: false }]),
233
+ tried: Object.freeze(tried.slice()),
234
+ reason: "registry_disagrees_with_expectation",
235
+ });
236
+ }
237
+ return judge(entry.bytes, "registry", claim);
238
+ }
239
+ if (!entry) tried.push({ tier: "registry", ok: false, reason: "no entry" });
240
+ }
241
+
242
+ // 3. locator
243
+ const candidates = deriveLocatorCandidates({ receiptId: id.receiptId, issuerOrigin: reference.issuerOrigin });
244
+ if (candidates.length === 0) {
245
+ return Object.freeze({
246
+ refVersion: REFERENCE_VERSION,
247
+ schema: REFERENCE_SCHEMA,
248
+ receiptId: id.receiptId,
249
+ idForm: id.form,
250
+ source: null,
251
+ state: "unresolvable",
252
+ digest: null,
253
+ expectedDigest: expected,
254
+ bytes: null,
255
+ size: 0,
256
+ checks: Object.freeze([{ name: "a locator can be derived", ok: false }]),
257
+ tried: Object.freeze(tried.slice()),
258
+ reason: expected ? "no_source_answered" : "no_expectation_and_no_locator",
259
+ });
260
+ }
261
+ if (typeof fetchImpl !== "function") {
262
+ return Object.freeze({
263
+ refVersion: REFERENCE_VERSION,
264
+ schema: REFERENCE_SCHEMA,
265
+ receiptId: id.receiptId,
266
+ idForm: id.form,
267
+ source: null,
268
+ state: "unresolvable",
269
+ digest: null,
270
+ expectedDigest: expected,
271
+ bytes: null,
272
+ size: 0,
273
+ checks: Object.freeze([{ name: "a fetch implementation is available", ok: false }]),
274
+ tried: Object.freeze(tried.slice()),
275
+ reason: "no_fetch_impl",
276
+ });
277
+ }
278
+ for (const url of candidates) {
279
+ if (!checkUrlAllowed(url, allowInsecureLoopback)) {
280
+ tried.push({ tier: "locator", url, ok: false, reason: "url refused by policy" });
281
+ continue;
282
+ }
283
+ const ctrl = new AbortController();
284
+ const timer = setTimeout(() => ctrl.abort(), Math.max(50, timeoutMs));
285
+ try {
286
+ const res = await fetchImpl(url, { signal: ctrl.signal, maxBytes });
287
+ const bytes = res?.bytes ?? res?.body;
288
+ if (!bytes || (typeof bytes === "string" && bytes.length === 0)) {
289
+ tried.push({ tier: "locator", url, ok: false, status: res?.status ?? null, reason: "empty answer" });
290
+ continue;
291
+ }
292
+ tried.push({ tier: "locator", url, ok: true, status: res?.status ?? null });
293
+ return judge(bytes, "locator", res?.digest);
294
+ } catch (err) {
295
+ tried.push({ tier: "locator", url, ok: false, reason: `fetch failed: ${err?.message ?? err}` });
296
+ } finally {
297
+ clearTimeout(timer);
298
+ }
299
+ }
300
+ return Object.freeze({
301
+ refVersion: REFERENCE_VERSION,
302
+ schema: REFERENCE_SCHEMA,
303
+ receiptId: id.receiptId,
304
+ idForm: id.form,
305
+ source: null,
306
+ state: expected ? "unresolvable" : "absent",
307
+ digest: null,
308
+ expectedDigest: expected,
309
+ bytes: null,
310
+ size: 0,
311
+ checks: Object.freeze([{ name: "at least one source answered", ok: false }]),
312
+ tried: Object.freeze(tried.slice()),
313
+ reason: expected ? "no_source_answered" : "nothing_presented",
314
+ });
315
+ }
316
+
317
+ /** The resolution as CG-OUT/1 reads it: absent and unresolvable stay distinct. */
318
+ export function resolutionOutcome(resolution) {
319
+ const state = resolution?.state;
320
+ const map = {
321
+ resolved: { outcome: "VERIFIED", blocks: false },
322
+ "resolved-unchecked": { outcome: "NOT_CHECKED", blocks: false },
323
+ absent: { outcome: "ABSENT", blocks: false },
324
+ unresolvable: { outcome: "UNRESOLVABLE_RECORD", blocks: true },
325
+ tampered: { outcome: "VERIFICATION_FAILED", blocks: true },
326
+ };
327
+ const hit = map[state] ?? { outcome: "NOT_CHECKED", blocks: false };
328
+ return Object.freeze({
329
+ ...hit,
330
+ state: state ?? "unknown",
331
+ reason: resolution?.reason ?? null,
332
+ source: resolution?.source ?? null,
333
+ digest: resolution?.digest ?? null,
334
+ });
335
+ }
336
+
337
+ export function selfCheck() {
338
+ const checks = [];
339
+ const urn = classifyReceiptId("urn:sha256:" + "a".repeat(64));
340
+ checks.push({ name: "urn form is content-addressed", pass: urn.form === "urn-sha256" && urn.contentAddressed });
341
+ checks.push({ name: "https form is a locator, not content-addressed", pass: classifyReceiptId("https://m.example/r/1").form === "url" });
342
+ checks.push({ name: "opaque form proves nothing by itself", pass: classifyReceiptId("r-123").digest === null });
343
+ const body = JSON.stringify({ ok: true });
344
+ const good = digestOf(body);
345
+ checks.push({ name: "digest is prefixed sha256", pass: /^sha256:[0-9a-f]{64}$/.test(good) });
346
+ const plan = planResolution({ receiptId: "r-123" });
347
+ checks.push({ name: "plan states what the name cannot prove", pass: plan.strongestPossible === "resolved-by-expectation" });
348
+ checks.push({ name: "outcome keeps absent and unresolvable apart", pass: resolutionOutcome({ state: "absent" }).outcome === "ABSENT" && resolutionOutcome({ state: "unresolvable" }).outcome === "UNRESOLVABLE_RECORD" });
349
+ return Object.freeze({ ok: checks.every((c) => c.pass), checks });
350
+ }
package/risk-cli.mjs CHANGED
@@ -11,8 +11,14 @@
11
11
  * node packages/agent-commerce/risk-cli.mjs --input <file> [--out <file>] [--ledger <file>]
12
12
  *
13
13
  * Input JSON shape:
14
- * { "intent": {...}, "policy": {...}, "trace": {...}, "consumed": false }
15
- * (policy and consumed are optional; classes are frozen per AGR/1)
14
+ * { "intent": {...}, "policy": {...}, "trace": {...}, "consumed": false,
15
+ * "receiptOutcome": "ABSENT" }
16
+ * (policy, consumed and receiptOutcome are optional; classes are frozen per AGR/1)
17
+ *
18
+ * receiptOutcome is a CG-OUT/1 outcome (or a CG-OUT/1 result object). When it
19
+ * says ABSENT or NOT_CHECKED the CLI still exits 0 and still prints a report,
20
+ * whose classification is NO_DECISION: there is nothing to assess, and printing
21
+ * CLEAN would assert an authorization that was never presented.
16
22
  *
17
23
  * Persistence:
18
24
  * --out <file> write the assessment report as JSON (overwritten/created)
@@ -94,6 +100,7 @@ export function runRiskCli(argv = process.argv.slice(2), io = {}) {
94
100
  policy: input.policy,
95
101
  trace: input.trace,
96
102
  consumed: input.consumed === true,
103
+ receiptOutcome: input.receiptOutcome ?? null,
97
104
  });
98
105
  } catch (e) {
99
106
  err("risk-cli: assessment refused: " + (e && e.message ? e.message : e));
@@ -118,6 +125,7 @@ export function runRiskCli(argv = process.argv.slice(2), io = {}) {
118
125
  const record = {
119
126
  spec: AGR_VERSION,
120
127
  classification: report.classification,
128
+ ...(report.authorization ? { authorization: report.authorization } : {}),
121
129
  violations: report.violations.map((v) => v.code),
122
130
  report,
123
131
  };
package/risk.mjs CHANGED
@@ -18,6 +18,7 @@
18
18
 
19
19
  import { evaluatePolicy } from "@coreguard/policy";
20
20
  import { tracePolicyContext } from "./policy-context.mjs";
21
+ import { authorizationDecision } from "./outcomes-bridge.mjs";
21
22
 
22
23
  export const AGR_VERSION = "AGR/1";
23
24
 
@@ -111,9 +112,35 @@ function amountBig(value) {
111
112
  * Assess one executed order against one approved authorization.
112
113
  * Returns a deterministic report; `boundary` travels inside every report so a
113
114
  * reader of the committed file can see the taxonomy's ceiling, not just its verdict.
115
+ *
116
+ * receiptOutcome (optional) is a CG-OUT/1 outcome describing the receipt that
117
+ * authorizes this execution. It changes nothing about the drift taxonomy —
118
+ * drift is drift — and everything about what the report may be read as:
119
+ *
120
+ * ABSENT / NOT_CHECKED -> classification NO_DECISION, no violations listed
121
+ * as a judgement. There is no authorization to drift
122
+ * from. CLEAN would be a claim nobody made.
123
+ * VERIFICATION_FAILED / UNRESOLVABLE_RECORD -> classification BLOCKED: the
124
+ * receipt did not clear its own checks, so drift
125
+ * findings are recorded but never read as the verdict.
126
+ * VERIFIED -> unchanged: CLEAN or VIOLATIONS, as before.
114
127
  */
115
- export function assessRisk({ intent, policy, trace, consumed = false }) {
128
+ export function assessRisk({ intent, policy, trace, consumed = false, receiptOutcome = null }) {
116
129
  const violations = [];
130
+ const authorization = receiptOutcome ? toAuthorization(receiptOutcome) : null;
131
+
132
+ if (authorization && authorization.decision === "NONE") {
133
+ return {
134
+ spec: AGR_VERSION,
135
+ classification: "NO_DECISION",
136
+ decision: "NONE",
137
+ reason: authorization.reason,
138
+ authorization,
139
+ violations: [],
140
+ boundary:
141
+ "deterministic authorization-drift taxonomy (AGR/1) — never a probabilistic fraud score; VERIFIED ≠ SAFE",
142
+ };
143
+ }
117
144
 
118
145
  const push = (code, extra) => {
119
146
  const cls = RISK_CLASSES[code];
@@ -245,11 +272,31 @@ export function assessRisk({ intent, policy, trace, consumed = false }) {
245
272
 
246
273
  violations.sort((a, b) => (a.code < b.code ? -1 : a.code > b.code ? 1 : 0));
247
274
 
275
+ const classification =
276
+ authorization && authorization.decision === "BLOCK"
277
+ ? "BLOCKED"
278
+ : violations.length === 0
279
+ ? "CLEAN"
280
+ : "VIOLATIONS";
281
+
248
282
  return {
249
283
  spec: AGR_VERSION,
250
- classification: violations.length === 0 ? "CLEAN" : "VIOLATIONS",
284
+ classification,
285
+ ...(authorization ? { decision: authorization.decision, authorization } : {}),
251
286
  violations,
252
287
  boundary:
253
288
  "deterministic authorization-drift taxonomy (AGR/1) — never a probabilistic fraud score; VERIFIED ≠ SAFE",
254
289
  };
255
290
  }
291
+
292
+ /**
293
+ * Accept either a CG-OUT/1 result object or its bare name, and never guess a
294
+ * decision for a string this layer does not know. An unknown outcome name is
295
+ * BLOCK, because the only safe reading of "something we do not recognise" is
296
+ * "do not proceed" — and it is named as a verifier error, not as a drift class.
297
+ */
298
+ function toAuthorization(receiptOutcome) {
299
+ const name = typeof receiptOutcome === "string" ? receiptOutcome : receiptOutcome?.outcome ?? null;
300
+ const decision = authorizationDecision(name);
301
+ return Object.freeze({ outcome: name, decision: decision.decision, reason: decision.reason });
302
+ }