@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/decision.mjs ADDED
@@ -0,0 +1,152 @@
1
+ /**
2
+ * CoreGuard Payment Decision (CG-DECIDE/1) — the gap between an outcome and an
3
+ * authorisation, written down so nobody has to guess it at 3am.
4
+ *
5
+ * A verifier produces outcomes. A payment system produces authorisations. The
6
+ * mapping between them is a POLICY, and most integrations get it wrong in one of
7
+ * two directions:
8
+ *
9
+ * false decline treating `ABSENT` or `NOT_CHECKED` as a failure. The merchant
10
+ * that never adopted receipts suddenly loses every sale, which
11
+ * is how an opt-in layer acquires an enemy.
12
+ * false trust treating `ABSENT` or `NOT_CHECKED` as a pass, because the
13
+ * authorisation flow only understands allow/deny. The missing
14
+ * evidence disappears into a green result and nobody can tell
15
+ * afterwards that nothing was checked.
16
+ *
17
+ * So there are four decisions, not two, and each one carries what it is based on:
18
+ *
19
+ * ALLOW evidence was presented and passed
20
+ * ALLOW_UNVERIFIED the sale may proceed, and the record says `unverified:
21
+ * true` so a risk engine, an auditor or a disputes team can
22
+ * see that no evidence was checked
23
+ * HOLD do not ship, do not capture; retry resolution or escalate
24
+ * DECLINE evidence was presented and failed
25
+ *
26
+ * The rule that makes the table safe is one line: only `VERIFICATION_FAILED` can
27
+ * DECLINE. Everything else that is not a pass is either a hold with a named
28
+ * reason or an allow that is loudly unmarked-green.
29
+ *
30
+ * BOUNDARY (standing, load-bearing):
31
+ * - This module decides nothing about fraud, credit or delivery. It maps an
32
+ * evidence outcome to an authorisation posture, and it refuses to invent
33
+ * evidence that was not presented.
34
+ * - `ALLOW` never means "safe". It means the receipt's own checks passed.
35
+ * - No clock, no network, no keys: the caller supplies the outcome and the
36
+ * policy, and the table is deterministic so it can be replayed in a dispute.
37
+ */
38
+
39
+ export const DECISION_VERSION = "CG-DECIDE/1";
40
+ export const DECISION_SCHEMA = "coreguard.decision/1";
41
+
42
+ export const DECISIONS = Object.freeze(["ALLOW", "ALLOW_UNVERIFIED", "HOLD", "DECLINE"]);
43
+ export const POLICIES = Object.freeze(["strict", "balanced", "availability"]);
44
+
45
+ /** Outcome → policy → decision. The only table in this module, on purpose. */
46
+ const TABLE = Object.freeze({
47
+ VERIFIED: Object.freeze({ strict: "ALLOW", balanced: "ALLOW", availability: "ALLOW" }),
48
+ VERIFICATION_FAILED: Object.freeze({ strict: "DECLINE", balanced: "DECLINE", availability: "DECLINE" }),
49
+ UNRESOLVABLE_RECORD: Object.freeze({ strict: "HOLD", balanced: "HOLD", availability: "ALLOW_UNVERIFIED" }),
50
+ ABSENT: Object.freeze({ strict: "ALLOW_UNVERIFIED", balanced: "ALLOW_UNVERIFIED", availability: "ALLOW_UNVERIFIED" }),
51
+ NOT_CHECKED: Object.freeze({ strict: "ALLOW_UNVERIFIED", balanced: "ALLOW_UNVERIFIED", availability: "ALLOW_UNVERIFIED" }),
52
+ });
53
+
54
+ const CODES = Object.freeze({
55
+ DECLINE: "EVIDENCE_FAILED",
56
+ HOLD: "RESOLUTION_INCOMPLETE",
57
+ ALLOW_UNVERIFIED: "NO_EVIDENCE_CHECKED",
58
+ });
59
+
60
+ const REASONS = Object.freeze({
61
+ VERIFIED: "every presented check passed",
62
+ VERIFICATION_FAILED: "a presented record failed a named check",
63
+ UNRESOLVABLE_RECORD: "a record was presented and could not be resolved",
64
+ ABSENT: "no record was presented",
65
+ NOT_CHECKED: "a record was presented and this verifier has no opinion",
66
+ });
67
+
68
+ /**
69
+ * decidePayment({ outcome, policy })
70
+ *
71
+ * outcome one of CG-OUT/1's five. Anything else is a caller defect and
72
+ * throws, because silently mapping an unknown word to ALLOW is the
73
+ * false-trust failure this file exists to prevent.
74
+ * policy "strict" | "balanced" | "availability" (default "balanced")
75
+ */
76
+ export function decidePayment({ outcome, policy = "balanced" } = {}) {
77
+ const row = TABLE[outcome];
78
+ if (!row) throw new TypeError(`unknown outcome: ${String(outcome)} — CG-DECIDE/1 has no decision for it`);
79
+ if (!POLICIES.includes(policy)) throw new TypeError(`unknown policy: ${String(policy)}`);
80
+ const decision = row[policy];
81
+ const unverified = decision === "ALLOW_UNVERIFIED";
82
+ const blocks = decision === "DECLINE" || decision === "HOLD";
83
+ return Object.freeze({
84
+ decisionVersion: DECISION_VERSION,
85
+ schema: DECISION_SCHEMA,
86
+ decision,
87
+ outcome,
88
+ policy,
89
+ code: CODES[decision] ?? null,
90
+ reason: REASONS[outcome] ?? null,
91
+ unverified,
92
+ verified: decision === "ALLOW",
93
+ blocks,
94
+ captureAllowed: decision === "ALLOW" || decision === "ALLOW_UNVERIFIED",
95
+ retry: decision === "HOLD",
96
+ explain: explainDecision({ decision, outcome, policy }),
97
+ });
98
+ }
99
+
100
+ /** One sentence a support agent can paste into a ticket without translating a code. */
101
+ export function explainDecision({ decision, outcome, policy }) {
102
+ const base = {
103
+ ALLOW: "Approved: the presented receipt passed its checks.",
104
+ ALLOW_UNVERIFIED: "Approved without verification: no evidence was checked, and the record says so.",
105
+ HOLD: "Held: evidence was presented but could not be resolved; retry or escalate before capture.",
106
+ DECLINE: "Declined: a presented receipt failed a named check.",
107
+ }[decision];
108
+ return `${base} (outcome ${outcome}, policy ${policy})`;
109
+ }
110
+
111
+ /**
112
+ * The negative controls, exported so an integrator can test against them rather
113
+ * than against prose: every cell, plus the invariants that make the table safe.
114
+ */
115
+ export function decisionMatrix() {
116
+ const rows = [];
117
+ for (const outcome of Object.keys(TABLE)) {
118
+ for (const policy of POLICIES) rows.push(decidePayment({ outcome, policy }));
119
+ }
120
+ return Object.freeze(rows);
121
+ }
122
+
123
+ /** Invariants a conforming mapper must satisfy. Used by the tests and by partners. */
124
+ export function assertDecisionInvariants() {
125
+ const rows = decisionMatrix();
126
+ const violations = [];
127
+ for (const r of rows) {
128
+ if (r.decision === "DECLINE" && r.outcome !== "VERIFICATION_FAILED") {
129
+ violations.push(`DECLINE from ${r.outcome}/${r.policy} — only a failed check may decline`);
130
+ }
131
+ if (r.decision === "ALLOW_UNVERIFIED" && r.unverified !== true) {
132
+ violations.push(`${r.outcome}/${r.policy} allows unverified without the flag`);
133
+ }
134
+ if (r.decision === "DECLINE" && !r.code) violations.push(`DECLINE from ${r.outcome} carries no code`);
135
+ if (r.decision === "ALLOW" && r.outcome !== "VERIFIED") {
136
+ violations.push(`ALLOW from ${r.outcome} — a pass must come from a pass`);
137
+ }
138
+ }
139
+ return Object.freeze({ ok: violations.length === 0, violations: Object.freeze(violations), rows: rows.length });
140
+ }
141
+
142
+ export function selfCheck() {
143
+ const checks = [];
144
+ const inv = assertDecisionInvariants();
145
+ checks.push({ name: "the table has no false decline", pass: !inv.violations.some((v) => v.startsWith("DECLINE from")) });
146
+ checks.push({ name: "the table has no false trust", pass: !inv.violations.some((v) => v.startsWith("ALLOW from")) });
147
+ checks.push({ name: "every unverified allow is flagged", pass: !inv.violations.some((v) => v.includes("without the flag")) });
148
+ checks.push({ name: "15 cells, all decided", pass: inv.rows === 15 });
149
+ checks.push({ name: "absent never declines, even under strict", pass: decidePayment({ outcome: "ABSENT", policy: "strict" }).decision !== "DECLINE" });
150
+ checks.push({ name: "unknown outcome throws instead of allowing", pass: (() => { try { decidePayment({ outcome: "PROBABLY_FINE" }); return false; } catch { return true; } })() });
151
+ return Object.freeze({ ok: checks.every((c) => c.pass), checks });
152
+ }
package/firewall.mjs CHANGED
@@ -185,7 +185,7 @@ export async function authorizeRequest({ consent = null, intent = null, policy =
185
185
 
186
186
  // Single-use replay state at request time — consulted, never consumed.
187
187
  const ledger = consent.intent.singleUse ? (consumedSet ?? null) : null;
188
- if (ledger && consent.receiptId && ledger.has(consent.receiptId)) {
188
+ if (ledger && consent.receiptId && (await ledger.has(consent.receiptId))) {
189
189
  reasons.push(reject("SINGLE_USE_CONSUMED", { field: "consent.receiptId", detail: "this single-use authorization was already consumed by a verified execution" }));
190
190
  }
191
191
  }
package/identity.mjs ADDED
@@ -0,0 +1,205 @@
1
+ /**
2
+ * CoreGuard Identity Split (CG-ID/1) — a record's name, kept apart from its bytes.
3
+ *
4
+ * The defect this closes: when identity is a function of the content digest,
5
+ * the digest is the only handle a consumer has on a record. Two consequences
6
+ * follow, both bad.
7
+ *
8
+ * 1. An anchor cannot be carried. An anchor points at a PLACE ("this receipt
9
+ * is at ledger 4123, tx 0x…"), and a place is not a property of bytes. A
10
+ * content-addressed name has nowhere to put it, so every consumer has to
11
+ * re-derive which copy it holds from content alone — and content cannot say
12
+ * where it was anchored.
13
+ * 2. Drift stops being visible. If the bytes change, the name changes, and a
14
+ * verifier comparing names sees two unrelated records instead of one
15
+ * record whose content moved.
16
+ *
17
+ * So identity is split into three fields that answer three different questions:
18
+ *
19
+ * recordId who this record IS — sha256 over {issuer, scope, subject}
20
+ * contentDigest what these bytes ARE — sha256 over the committed bytes,
21
+ * supplied by the caller and never derived here
22
+ * anchorRef where a copy of it IS — { kind, locator }, or null
23
+ *
24
+ * recordId is deliberately NOT derived from contentDigest. Same record, new
25
+ * bytes: same recordId, different digest — drift, named. Same bytes, two
26
+ * anchors: same recordId, same digest, two anchorRefs — a mirrored record.
27
+ *
28
+ * BOUNDARY (standing, load-bearing):
29
+ * - This module computes nothing about truth. A split identity says which
30
+ * record you hold and where a copy of it sits; it never says the record is
31
+ * correct, current or safe.
32
+ * - It performs no network I/O and reads no clock. An anchor is resolved by
33
+ * the caller, and the caller passes back what happened; this module only
34
+ * describes the reference.
35
+ * - An identity with no anchor is not broken: unfinished anchoring is the
36
+ * normal state of a young record, and `anchorFacts` reports it as absent
37
+ * rather than as a failure.
38
+ */
39
+
40
+ import { createHash } from "node:crypto";
41
+
42
+ export const IDENTITY_VERSION = "CG-ID/1";
43
+ export const IDENTITY_SCHEMA = "coreguard.identity/1";
44
+
45
+ /** Anchor kinds this layer can name. Adding one is a schema change. */
46
+ export const ANCHOR_KINDS = Object.freeze(["chain", "transparency-log", "notary", "mirror"]);
47
+
48
+ const HEX64 = /^[0-9a-f]{64}$/;
49
+ const MAX_TEXT = 512;
50
+
51
+ /** Canonical JSON: sorted keys, no whitespace, recursive. Byte-deterministic. */
52
+ function canonicalJson(value) {
53
+ if (value === null || typeof value !== "object") return JSON.stringify(value ?? null);
54
+ if (Array.isArray(value)) return "[" + value.map((v) => canonicalJson(v)).join(",") + "]";
55
+ const keys = Object.keys(value).sort();
56
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalJson(value[k])).join(",") + "}";
57
+ }
58
+
59
+ function requireText(value, field) {
60
+ if (typeof value !== "string" || value.length === 0) {
61
+ throw new TypeError(`${field} must be a non-empty string`);
62
+ }
63
+ if (value.length > MAX_TEXT) {
64
+ throw new TypeError(`${field} must be at most ${MAX_TEXT} characters`);
65
+ }
66
+ return value;
67
+ }
68
+
69
+ /**
70
+ * The record's name, and nothing else. Purpose-built so a reader can say out
71
+ * loud what a recordId means: "the same issuer, in the same scope, about the
72
+ * same subject" — never "the same bytes".
73
+ */
74
+ export function recordIdFor({ issuer, scope, subject }) {
75
+ const name = {
76
+ issuer: requireText(issuer, "issuer"),
77
+ scope: requireText(scope, "scope"),
78
+ subject: requireText(subject, "subject"),
79
+ };
80
+ return createHash("sha256").update(Buffer.from(canonicalJson(name), "utf8")).digest("hex");
81
+ }
82
+
83
+ /**
84
+ * splitIdentity({ issuer, scope, subject, contentDigest, anchor })
85
+ *
86
+ * anchor: { kind, locator } | null
87
+ *
88
+ * Returns a frozen identity. Throws TypeError on a caller defect (a wrong type
89
+ * is a bug in the caller, never something to coerce), and Error with a named
90
+ * code on a value this layer refuses.
91
+ */
92
+ export function splitIdentity({ issuer, scope, subject, contentDigest, anchor = null } = {}) {
93
+ const recordId = recordIdFor({ issuer, scope, subject });
94
+ const digest = requireText(contentDigest, "contentDigest");
95
+ if (!HEX64.test(digest)) throw new TypeError("contentDigest must be 32 bytes of lowercase hex");
96
+ const anchorRef = anchor === null || anchor === undefined ? null : normalizeAnchor(anchor);
97
+ return Object.freeze({
98
+ identityVersion: IDENTITY_VERSION,
99
+ schema: IDENTITY_SCHEMA,
100
+ recordId,
101
+ contentDigest: digest,
102
+ anchorRef,
103
+ });
104
+ }
105
+
106
+ /** Normalize one anchor reference. Unknown kinds are refused, never passed through. */
107
+ export function normalizeAnchor(anchor) {
108
+ if (typeof anchor !== "object" || anchor === null || Array.isArray(anchor)) {
109
+ throw new TypeError("anchor must be an object { kind, locator }");
110
+ }
111
+ const { kind } = anchor;
112
+ if (!ANCHOR_KINDS.includes(kind)) {
113
+ throw new Error(`unknown anchor kind: ${JSON.stringify(kind)} (use one of ${ANCHOR_KINDS.join(", ")})`);
114
+ }
115
+ const extra = Object.keys(anchor).filter((k) => k !== "kind" && k !== "locator");
116
+ if (extra.length) throw new Error(`unknown anchor fields: ${extra.join(", ")}`);
117
+ return Object.freeze({ kind, locator: requireText(anchor.locator, "anchor.locator") });
118
+ }
119
+
120
+ /**
121
+ * The two things a split identity makes checkable, as facts — not verdicts.
122
+ *
123
+ * { identity, heldDigest } -> { sameRecord, sameBytes }
124
+ * { identity, resolved } -> { present, evaluated, outcome }
125
+ *
126
+ * `sameRecord` is true when the two identities name the same record (drift is
127
+ * possible); `sameBytes` is true when they also hold the same content. A record
128
+ * that drifted is sameRecord && !sameBytes, which a content-addressed identity
129
+ * cannot express at all.
130
+ */
131
+ export function compareIdentities(a, b) {
132
+ if (!a || !b) throw new TypeError("compareIdentities requires two identities");
133
+ for (const [label, value] of [
134
+ ["a", a],
135
+ ["b", b],
136
+ ]) {
137
+ if (typeof value.recordId !== "string" || !HEX64.test(value.recordId)) {
138
+ throw new TypeError(`identities.${label}.recordId must be 32 bytes of lowercase hex`);
139
+ }
140
+ if (typeof value.contentDigest !== "string" || !HEX64.test(value.contentDigest)) {
141
+ throw new TypeError(`identities.${label}.contentDigest must be 32 bytes of lowercase hex`);
142
+ }
143
+ }
144
+ const sameRecord = a.recordId === b.recordId;
145
+ const sameBytes = a.contentDigest === b.contentDigest;
146
+ return Object.freeze({
147
+ sameRecord,
148
+ sameBytes,
149
+ drifted: sameRecord && !sameBytes,
150
+ verdictHint: sameRecord
151
+ ? sameBytes
152
+ ? "same record, same bytes"
153
+ : "same record, different bytes — drift, not a different record"
154
+ : "different records",
155
+ });
156
+ }
157
+
158
+ /**
159
+ * Anchor-layer facts for the outcome layer (CG-OUT/1), in its own vocabulary.
160
+ *
161
+ * resolved true -> the anchor resolved and its target matched
162
+ * false -> the anchor was looked for and could not be resolved
163
+ * undefined/null -> the anchor was never resolved (deliberately
164
+ * skipped, or nothing tried)
165
+ *
166
+ * No anchorRef at all is `absent`: an unanchored record has an absent anchor
167
+ * layer, which is not a failed verification of anything.
168
+ */
169
+ export function anchorFacts(identity, { resolved } = {}) {
170
+ const ref = identity?.anchorRef ?? null;
171
+ if (!ref) return Object.freeze({ present: false, evaluated: false, outcome: "absent" });
172
+ if (resolved === undefined || resolved === null) {
173
+ return Object.freeze({ present: true, evaluated: false, outcome: "not_checked" });
174
+ }
175
+ if (resolved === false) {
176
+ return Object.freeze({ present: true, evaluated: true, outcome: "unresolvable" });
177
+ }
178
+ return Object.freeze({ present: true, evaluated: true, outcome: "verified" });
179
+ }
180
+
181
+ /** Self-check: the split's own invariants, for callers that cannot run tests. */
182
+ export function selfCheck() {
183
+ const bytes = "a".repeat(64);
184
+ const other = "b".repeat(64);
185
+ const base = { issuer: "coreguard", scope: "execution-receipt", subject: "order-42" };
186
+ const plain = splitIdentity({ ...base, contentDigest: bytes });
187
+ const mirrored = splitIdentity({
188
+ ...base,
189
+ contentDigest: bytes,
190
+ anchor: { kind: "chain", locator: "core:4123:0xabc" },
191
+ });
192
+ const drifted = splitIdentity({ ...base, contentDigest: other });
193
+ const checks = [
194
+ { name: "a record keeps its name when bytes change", pass: plain.recordId === drifted.recordId },
195
+ { name: "a record's bytes are still distinguishable", pass: plain.contentDigest !== drifted.contentDigest },
196
+ { name: "an anchor does not rename the record", pass: plain.recordId === mirrored.recordId },
197
+ { name: "an unanchored identity reports an absent anchor", pass: anchorFacts(plain).outcome === "absent" },
198
+ {
199
+ name: "an unresolved anchor is unresolvable, never a failure of the record",
200
+ pass: anchorFacts(mirrored, { resolved: false }).outcome === "unresolvable",
201
+ },
202
+ { name: "drift is visible as drift", pass: compareIdentities(plain, drifted).drifted === true },
203
+ ];
204
+ return Object.freeze({ identityVersion: IDENTITY_VERSION, checks, ok: checks.every((c) => c.pass) });
205
+ }