@coreguard/agent-commerce 0.1.1 → 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.
@@ -0,0 +1,169 @@
1
+ /**
2
+ * CG-OUT/1 bridges — the outcome layer as the surfaces actually print it.
3
+ *
4
+ * An outcome vocabulary that only exists in a library is a vocabulary nobody
5
+ * reads. This file is the seam between the layer (`outcomes.mjs`) and the three
6
+ * places a human or a machine meets it: the `verify-run` CLI, the PSAR/1
7
+ * pre-sign verifier, and the AGR/1 risk taxonomy.
8
+ *
9
+ * The seam exists because those three surfaces already have their own words,
10
+ * and the words are not wrong — they answer narrower questions:
11
+ *
12
+ * verify-run VERIFIED / INVALID / UNVERIFIED / INCONCLUSIVE + exit code
13
+ * PSAR/1 PASS / BLOCK + a named reject code
14
+ * AGR/1 CLEAN / VIOLATIONS over authorization drift
15
+ *
16
+ * What none of them can say is "nobody handed us a record". The mapping below
17
+ * adds exactly that, without changing any existing field, exit code or verdict:
18
+ * every surface keeps the words its consumers already parse and gains one
19
+ * `outcome` field that says what a reader is allowed to conclude.
20
+ *
21
+ * The mapping rules, deliberately few:
22
+ *
23
+ * no record at all -> ABSENT
24
+ * evaluated and passed -> VERIFIED
25
+ * evaluated and a check failed -> VERIFICATION_FAILED (code kept)
26
+ * presented, never evaluated -> NOT_CHECKED (reason named)
27
+ * present, anchor unresolvable -> UNRESOLVABLE_RECORD
28
+ * a verdict this build does not know -> VERIFICATION_FAILED / VERIFIER_ERROR
29
+ *
30
+ * That last line is the fail-closed edge: an unrecognised verdict string from
31
+ * somebody's report is never allowed to become a pass.
32
+ *
33
+ * One deliberate asymmetry, stated here so nobody discovers it in production:
34
+ * `verify-run` reports UNVERIFIED when required evidence is missing and
35
+ * INCONCLUSIVE when a level has no runtime pathway. Both are real exit codes
36
+ * and both stay exactly as they are. As outcomes, both are NOT_CHECKED — the
37
+ * run did not reach a judgement, and rendering a missing binding as a failed
38
+ * verification is the defect this layer exists to prevent. A consumer that
39
+ * should refuse either way still refuses: refusal is its policy, and `blocks`
40
+ * is not a permission slip.
41
+ */
42
+
43
+ import { decideOutcome, OUTCOME_CODES } from "./outcomes.mjs";
44
+ import { PROFILE_ID, makeProfileReference } from "./profile-ref.mjs";
45
+
46
+ export const BRIDGE_VERSION = "CG-OUT-BRIDGE/1";
47
+
48
+ const VERDICTS_KNOWN = Object.freeze(["VERIFIED", "INVALID", "UNVERIFIED", "INCONCLUSIVE"]);
49
+
50
+ /**
51
+ * Outcome for a `runVerification` report (the verify-run surface).
52
+ * Returns the CG-OUT/1 result object, or an ABSENT result when no report was
53
+ * produced at all.
54
+ */
55
+ export function outcomeForVerificationReport(report) {
56
+ if (!report || typeof report !== "object" || !report.verdict || typeof report.verdict !== "object") {
57
+ return decideOutcome({ presented: false });
58
+ }
59
+ const { verdict, code, reason, requiredMissing } = report.verdict;
60
+ const presented = report.observed?.present ?? {};
61
+ const anyPresent = ["evidence", "intent", "policy", "trace"].some((k) => presented[k] === true);
62
+ if (!anyPresent && !report.observed?.receiptId) {
63
+ return decideOutcome({ presented: false });
64
+ }
65
+
66
+ if (!VERDICTS_KNOWN.includes(verdict)) {
67
+ return decideOutcome({
68
+ presented: true,
69
+ record: { evaluated: true, ok: false, code: "VERIFIER_ERROR", reason: `unknown verdict: ${JSON.stringify(verdict)}` },
70
+ });
71
+ }
72
+
73
+ if (verdict === "VERIFIED") {
74
+ return decideOutcome({ presented: true, record: { evaluated: true, ok: true } });
75
+ }
76
+
77
+ if (verdict === "INVALID") {
78
+ return decideOutcome({
79
+ presented: true,
80
+ record: { evaluated: true, ok: false, code: code ?? "VERIFIER_ERROR", reason: reason ?? null },
81
+ });
82
+ }
83
+
84
+ // UNVERIFIED and INCONCLUSIVE: presented and deliberately not judged.
85
+ const why = Array.isArray(requiredMissing) && requiredMissing.length
86
+ ? `required bindings not present: ${requiredMissing.join(", ")}`
87
+ : reason ?? "the verifier did not reach a judgement for this record";
88
+ return decideOutcome({ presented: true, record: { evaluated: false, reason: why } });
89
+ }
90
+
91
+ /**
92
+ * Outcome for a PSAR/1 `verifyAuthorizationReceipt` result.
93
+ *
94
+ * result the verifier's own { decision, code, ... }
95
+ * receipt optional, only to read the version a receipt claims
96
+ *
97
+ * A receipt claiming a version this build does not implement is NOT_CHECKED
98
+ * with the version named, even though PSAR/1's own `decision` stays BLOCK: the
99
+ * decision is what this build does under its fail-closed policy, the outcome is
100
+ * what a reader may conclude. They differ here, and the difference is the point.
101
+ */
102
+ export function outcomeForPsarResult(result, { receipt } = {}) {
103
+ if (!result || typeof result !== "object") return decideOutcome({ presented: false });
104
+ const claimed = receipt && typeof receipt === "object" && typeof receipt.v === "string" ? receipt.v : null;
105
+ if (claimed && claimed !== "PSAR/1") {
106
+ return decideOutcome({ presented: true, record: { evaluated: false, version: claimed } });
107
+ }
108
+ if (result.decision === "PASS") {
109
+ return decideOutcome({ presented: true, record: { evaluated: true, ok: true } });
110
+ }
111
+ if (result.decision === "BLOCK") {
112
+ const code = typeof result.code === "string" ? result.code : "VERIFIER_ERROR";
113
+ return decideOutcome({
114
+ presented: true,
115
+ record: { evaluated: true, ok: false, code, reason: Array.isArray(result.reasons) ? result.reasons[0] ?? null : null },
116
+ });
117
+ }
118
+ return decideOutcome({
119
+ presented: true,
120
+ record: {
121
+ evaluated: true,
122
+ ok: false,
123
+ code: "VERIFIER_ERROR",
124
+ reason: `unknown decision: ${JSON.stringify(result.decision)}`,
125
+ },
126
+ });
127
+ }
128
+
129
+ /**
130
+ * What an authorization-dependent system may DO with an outcome.
131
+ *
132
+ * This is the function that turns a vocabulary into behaviour, and the two
133
+ * lines that matter are the first two: an absent record and a record nobody
134
+ * evaluated both yield `NONE`, never `PASS` and never `BLOCK`. A risk engine
135
+ * that treats "no receipt" as "no objection" is the failure this prevents, and
136
+ * so is one that treats it as an objection: both are decisions the facts do not
137
+ * support.
138
+ *
139
+ * VERIFIED -> PASS
140
+ * VERIFICATION_FAILED / UNRESOLVABLE_RECORD -> BLOCK
141
+ * ABSENT / NOT_CHECKED -> NONE (no decision, ever)
142
+ */
143
+ export function authorizationDecision(outcome) {
144
+ const name = outcome && typeof outcome === "object" ? outcome.outcome : outcome;
145
+ if (name === "VERIFIED") return Object.freeze({ decision: "PASS", reason: null });
146
+ if (name === "VERIFICATION_FAILED") {
147
+ return Object.freeze({ decision: "BLOCK", reason: outcome?.code ?? "VERIFICATION_FAILED" });
148
+ }
149
+ if (name === "UNRESOLVABLE_RECORD") {
150
+ return Object.freeze({ decision: "BLOCK", reason: OUTCOME_CODES.UNRESOLVABLE_RECORD });
151
+ }
152
+ if (name === "ABSENT") {
153
+ return Object.freeze({ decision: "NONE", reason: "no record was presented — nothing to decide on" });
154
+ }
155
+ if (name === "NOT_CHECKED") {
156
+ return Object.freeze({ decision: "NONE", reason: "the record was presented and evaluated by nobody" });
157
+ }
158
+ return Object.freeze({ decision: "BLOCK", reason: "VERIFIER_ERROR: unknown outcome" });
159
+ }
160
+
161
+ /**
162
+ * The pointer a protocol would carry alongside a receipt: which receipt, which
163
+ * profile, which version. Nothing about the verdict travels with it.
164
+ */
165
+ export function profileReferenceFor(receiptId) {
166
+ return makeProfileReference({ receiptId });
167
+ }
168
+
169
+ export { PROFILE_ID };
package/outcomes.mjs ADDED
@@ -0,0 +1,220 @@
1
+ /**
2
+ * CoreGuard Outcome Layer (CG-OUT/1) — the words above the reject codes.
3
+ *
4
+ * A reject code describes a record that was PRESENTED and CHECKED. It has no
5
+ * way to say "nobody handed us one", and rendering that silence as a failure
6
+ * is how an opt-in layer dies: every party that never adopted is scored as
7
+ * having failed a verification it never took part in.
8
+ *
9
+ * So this layer sits above the codes and answers a different question — what is
10
+ * a consumer allowed to conclude — with five outcomes and no sixth:
11
+ *
12
+ * VERIFIED the record was evaluated and its checks passed
13
+ * VERIFICATION_FAILED the record was evaluated and a check failed, named
14
+ * ABSENT no record was presented; never a failure of a record
15
+ * NOT_CHECKED a layer was presented and not evaluated; claims nothing
16
+ * UNRESOLVABLE_RECORD a present, well-formed record whose anchor cannot be
17
+ * resolved; not a failure of the record, not an absence
18
+ *
19
+ * Three layers, three answers. A run can be VERIFIED at the record layer,
20
+ * `matched` at the identity layer and `absent` at the anchor layer at once, and
21
+ * the composite outcome names the weakest layer instead of a single PASS/BLOCK
22
+ * hiding the only interesting fact in the run.
23
+ *
24
+ * BOUNDARY (standing, load-bearing):
25
+ * - ABSENT and NOT_CHECKED NEVER travel as BLOCK. A caller that maps them to
26
+ * a refusal is reporting a decision it did not make.
27
+ * - This layer decides nothing about quality, safety or delivery: VERIFIED
28
+ * means the receipt's own checks passed, never that the result was right.
29
+ * - It is deterministic and pure: no clock, no network, no keys. The caller
30
+ * supplies measured facts, not opinions, and nothing here trusts a string
31
+ * it did not check against a frozen set.
32
+ */
33
+
34
+ export const OUTCOME_VERSION = "CG-OUT/1";
35
+
36
+ /** The five outcomes. Adding one is a schema change; none may be renamed. */
37
+ export const OUTCOMES = Object.freeze([
38
+ "VERIFIED",
39
+ "VERIFICATION_FAILED",
40
+ "ABSENT",
41
+ "NOT_CHECKED",
42
+ "UNRESOLVABLE_RECORD",
43
+ ]);
44
+
45
+ /**
46
+ * The codes this layer owns. They appear ONLY beside their own outcome and are
47
+ * never used as a BLOCK reason: collapsing them into the reject vocabulary is
48
+ * the defect this file exists to prevent.
49
+ */
50
+ export const OUTCOME_CODES = Object.freeze({
51
+ ABSENT: "ABSENT",
52
+ NOT_CHECKED: "NOT_CHECKED",
53
+ UNRESOLVABLE_RECORD: "UNRESOLVABLE_RECORD",
54
+ });
55
+
56
+ /**
57
+ * Outcomes that must never be rendered as a refusal, by anybody, anywhere.
58
+ * VERIFIED is on the list for the same reason ABSENT is: a pass is not a
59
+ * refusal either, and a caller that renders it as one is reporting a decision
60
+ * nobody made. Only VERIFICATION_FAILED and UNRESOLVABLE_RECORD may block.
61
+ */
62
+ export const NON_BLOCKING_OUTCOMES = Object.freeze(["VERIFIED", "ABSENT", "NOT_CHECKED"]);
63
+
64
+ /** The only two outcomes that may be presented as a refusal. */
65
+ export const BLOCKING_OUTCOMES = Object.freeze(["VERIFICATION_FAILED", "UNRESOLVABLE_RECORD"]);
66
+
67
+ /** Facts a caller may supply. Anything else is ignored, never inferred. */
68
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
69
+
70
+ const layerVerdict = (layer) => {
71
+ if (!isObject(layer)) return { evaluated: false, stated: false };
72
+ return {
73
+ evaluated: layer.evaluated === true,
74
+ stated: true,
75
+ ok: layer.ok === true,
76
+ code: typeof layer.code === "string" ? layer.code : null,
77
+ reason: typeof layer.reason === "string" ? layer.reason : null,
78
+ outcome: typeof layer.outcome === "string" ? layer.outcome : null,
79
+ present: layer.present === true,
80
+ version: typeof layer.version === "string" ? layer.version : null,
81
+ };
82
+ };
83
+
84
+ const result = (outcome, code, reason, layers, detail) => {
85
+ if (!OUTCOMES.includes(outcome)) throw new Error(`unknown outcome: ${outcome}`);
86
+ return Object.freeze({
87
+ outcome,
88
+ code: code ?? null,
89
+ reason,
90
+ layers,
91
+ blocks: BLOCKING_OUTCOMES.includes(outcome),
92
+ outcomeVersion: OUTCOME_VERSION,
93
+ detail: detail ?? null,
94
+ });
95
+ };
96
+
97
+ /**
98
+ * decideOutcome({ presented, record, anchor })
99
+ *
100
+ * presented true only if a record was actually handed to the verifier
101
+ * record { evaluated, ok, code?, reason?, version? }
102
+ * anchor { present, evaluated, outcome? } where outcome is one of
103
+ * "verified" | "absent" | "not_checked" | "unresolvable"
104
+ *
105
+ * Precedence is deliberate and documented, because the order IS the policy:
106
+ * 1. absent — nothing was presented
107
+ * 2. not checked — the record layer never evaluated it
108
+ * 3. failed — the record layer evaluated it and a check failed
109
+ * 4. not checked — the record is fine but the anchor layer never ran
110
+ * 5. unresolvable — the anchor layer ran and could not resolve
111
+ * 6. verified
112
+ */
113
+ export function decideOutcome({ presented, record, anchor } = {}) {
114
+ const recordLayer = layerVerdict(record);
115
+ const anchorLayer = layerVerdict(anchor);
116
+ const layers = Object.freeze({
117
+ record: recordLayer.stated
118
+ ? { evaluated: recordLayer.evaluated, ok: recordLayer.evaluated && recordLayer.ok, code: recordLayer.code }
119
+ : { evaluated: false, ok: null, code: null },
120
+ anchor: {
121
+ present: anchorLayer.present,
122
+ evaluated: anchorLayer.evaluated,
123
+ outcome: anchorLayer.outcome,
124
+ },
125
+ });
126
+
127
+ if (presented !== true) {
128
+ return result(
129
+ "ABSENT",
130
+ OUTCOME_CODES.ABSENT,
131
+ "no record was presented — silence is not a failed verification",
132
+ layers,
133
+ );
134
+ }
135
+
136
+ if (!recordLayer.evaluated) {
137
+ // A caller that knows WHY a layer was skipped says so; otherwise the layer
138
+ // names the version it did not implement, and only then falls back to the
139
+ // generic sentence. The reason is never dropped on the floor: "not checked"
140
+ // without a why is the vague answer this layer exists to replace.
141
+ const why = recordLayer.version
142
+ ? `the record layer did not evaluate version ${recordLayer.version}`
143
+ : recordLayer.reason
144
+ ? recordLayer.reason
145
+ : "the record layer was not evaluated";
146
+ return result("NOT_CHECKED", OUTCOME_CODES.NOT_CHECKED, why, layers, {
147
+ version: recordLayer.version,
148
+ });
149
+ }
150
+
151
+ if (!recordLayer.ok) {
152
+ return result(
153
+ "VERIFICATION_FAILED",
154
+ recordLayer.code ?? "VERIFIER_ERROR",
155
+ recordLayer.reason ?? "a record-layer check failed",
156
+ layers,
157
+ );
158
+ }
159
+
160
+ if (anchorLayer.present && !anchorLayer.evaluated) {
161
+ return result(
162
+ "NOT_CHECKED",
163
+ OUTCOME_CODES.NOT_CHECKED,
164
+ "the anchor layer was present and deliberately not evaluated",
165
+ layers,
166
+ );
167
+ }
168
+
169
+ if (anchorLayer.evaluated && anchorLayer.outcome === "unresolvable") {
170
+ return result(
171
+ "UNRESOLVABLE_RECORD",
172
+ OUTCOME_CODES.UNRESOLVABLE_RECORD,
173
+ "the record is well formed and its anchor cannot be resolved",
174
+ layers,
175
+ );
176
+ }
177
+
178
+ return result("VERIFIED", null, "the record layer evaluated the record and it passed", layers);
179
+ }
180
+
181
+ /**
182
+ * A caller-side guard for the one mistake that would quietly break opt-in:
183
+ * turning an absence into a refusal. Returns the outcome unchanged when it is
184
+ * safe to render, and throws when a non-blocking outcome is about to be
185
+ * presented as a block.
186
+ */
187
+ export function assertNotRenderedAsBlock(outcome) {
188
+ if (!OUTCOMES.includes(outcome)) throw new Error(`unknown outcome: ${outcome}`);
189
+ if (NON_BLOCKING_OUTCOMES.includes(outcome)) {
190
+ throw new Error(`${outcome} must never travel as BLOCK — it is not a decision`);
191
+ }
192
+ return outcome;
193
+ }
194
+
195
+ /** Self-check: the layer's own invariants, for callers that cannot run tests. */
196
+ export function selfCheck() {
197
+ const absent = decideOutcome({ presented: false });
198
+ const unchecked = decideOutcome({ presented: true, record: { evaluated: false } });
199
+ const failed = decideOutcome({
200
+ presented: true,
201
+ record: { evaluated: true, ok: false, code: "BAD_DIGEST" },
202
+ });
203
+ const verified = decideOutcome({ presented: true, record: { evaluated: true, ok: true } });
204
+ const checks = [
205
+ { name: "absent is ABSENT", pass: absent.outcome === "ABSENT" },
206
+ { name: "absent never blocks", pass: absent.blocks === false },
207
+ { name: "unevaluated is NOT_CHECKED", pass: unchecked.outcome === "NOT_CHECKED" },
208
+ { name: "unevaluated never blocks", pass: unchecked.blocks === false },
209
+ { name: "failed keeps its code", pass: failed.outcome === "VERIFICATION_FAILED" && failed.code === "BAD_DIGEST" },
210
+ { name: "failed blocks", pass: failed.blocks === true },
211
+ { name: "verified is VERIFIED", pass: verified.outcome === "VERIFIED" },
212
+ { name: "every outcome reachable", pass: new Set([absent, unchecked, failed, verified].map((r) => r.outcome)).size >= 4 },
213
+ ];
214
+ return Object.freeze({
215
+ outcomeVersion: OUTCOME_VERSION,
216
+ outcomes: OUTCOMES,
217
+ checks,
218
+ ok: checks.every((c) => c.pass),
219
+ });
220
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@coreguard/agent-commerce",
3
- "version": "0.1.1",
4
- "description": "CoreGuard Agent Commerce: consent receipts (CGCR/1) and fail-closed execution verification (AGR/1) for agentic purchases — SDK, REST surface, and a stdio MCP server (JSON-RPC 2.0, offline, zero keys)",
3
+ "version": "0.1.3",
4
+ "description": "CoreGuard Agent Commerce: consent receipts (CGCR/1) and fail-closed execution verification (AGR/1) for agentic purchases \u2014 SDK, REST surface, and a stdio MCP server (JSON-RPC 2.0, offline, zero keys)",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
7
7
  "exports": {
@@ -12,25 +12,53 @@
12
12
  "./firewall.mjs": "./firewall.mjs",
13
13
  "./risk.mjs": "./risk.mjs",
14
14
  "./risk-cli.mjs": "./risk-cli.mjs",
15
- "./attest.mjs": "./attest.mjs"
15
+ "./outcomes.mjs": "./outcomes.mjs",
16
+ "./outcomes-bridge.mjs": "./outcomes-bridge.mjs",
17
+ "./identity.mjs": "./identity.mjs",
18
+ "./profile-ref.mjs": "./profile-ref.mjs",
19
+ "./attest.mjs": "./attest.mjs",
20
+ "./aer1.mjs": "./aer1.mjs",
21
+ "./anchor.mjs": "./anchor.mjs",
22
+ "./composition.mjs": "./composition.mjs",
23
+ "./reference.mjs": "./reference.mjs",
24
+ "./trust.mjs": "./trust.mjs",
25
+ "./spend.mjs": "./spend.mjs",
26
+ "./decision.mjs": "./decision.mjs",
27
+ "./control-plane.mjs": "./control-plane.mjs",
28
+ "./control-plane-http.mjs": "./control-plane-http.mjs",
29
+ "./control-plane-cli.mjs": "./control-plane-cli.mjs"
16
30
  },
17
31
  "bin": {
18
32
  "coreguard-agent-commerce-mcp": "./bin/mcp.mjs"
19
33
  },
20
34
  "files": [
21
- "index.mjs",
22
- "index.d.ts",
23
- "mcp.mjs",
24
- "http.mjs",
35
+ "README.md",
36
+ "aer1.mjs",
37
+ "anchor.mjs",
38
+ "attest.mjs",
39
+ "bin/mcp.mjs",
25
40
  "client.mjs",
41
+ "composition.mjs",
42
+ "consumption-store.mjs",
43
+ "control-plane.mjs",
44
+ "control-plane-http.mjs",
45
+ "control-plane-cli.mjs",
46
+ "decision.mjs",
26
47
  "firewall.mjs",
27
- "risk.mjs",
28
- "risk-cli.mjs",
29
- "attest.mjs",
48
+ "http.mjs",
49
+ "identity.mjs",
50
+ "index.d.ts",
51
+ "index.mjs",
52
+ "mcp.mjs",
53
+ "outcomes-bridge.mjs",
54
+ "outcomes.mjs",
30
55
  "policy-context.mjs",
31
- "consumption-store.mjs",
32
- "bin/mcp.mjs",
33
- "README.md"
56
+ "profile-ref.mjs",
57
+ "reference.mjs",
58
+ "risk-cli.mjs",
59
+ "risk.mjs",
60
+ "spend.mjs",
61
+ "trust.mjs"
34
62
  ],
35
63
  "engines": {
36
64
  "node": ">=18"
@@ -41,7 +69,7 @@
41
69
  "@coreguard/policy": "^0.1.0",
42
70
  "@coreguard/verifier": "^0.1.0"
43
71
  },
44
- "mcpName": "io.github.eslam-x/coreguard-agent-commerce",
72
+ "mcpName": "io.github.EslaM-X/coreguard-agent-commerce",
45
73
  "repository": {
46
74
  "type": "git",
47
75
  "url": "git+https://github.com/coreguard-global/CoreGuard.git"
@@ -0,0 +1,130 @@
1
+ /**
2
+ * CG-OUT/1 profile reference — the two fields a protocol would carry.
3
+ *
4
+ * A wire protocol should not embed our vocabulary. If ACP, AER-1 or anything
5
+ * else ever wants to point at an outcome computed here, what it needs is a
6
+ * pointer, not a copy of our rules: which receipt, and under which profile
7
+ * those words were produced. Everything else — the five outcomes, the layer
8
+ * precedence, the tests — stays ours to version.
9
+ *
10
+ * {
11
+ * "receipt_id": "…",
12
+ * "profile": "CG-OUT/1",
13
+ * "profile_version": 1
14
+ * }
15
+ *
16
+ * Three fields, not two, and the third is the important one: `profile` is a
17
+ * name, `profile_version` is what a reader can actually check. A pointer that
18
+ * names a profile without a version asks a consumer to guess which rules were
19
+ * in force, which is the same defect as a receipt that cannot say what it is
20
+ * certified under.
21
+ *
22
+ * BOUNDARY (standing):
23
+ * - A reference is not a verdict. Holding one tells you where an outcome
24
+ * lives and under which rules it was computed; it says nothing about what
25
+ * that outcome is. A consumer that renders a reference as a pass has
26
+ * invented a decision.
27
+ * - Unknown profile or unsupported version is refused by name, never coerced
28
+ * into the nearest version. Version confusion is the failure mode this
29
+ * file exists to prevent, so it fails closed on it.
30
+ */
31
+
32
+ export const PROFILE_ID = "CG-OUT/1";
33
+ export const PROFILE_VERSION = 1;
34
+ export const PROFILE_REFERENCE_SCHEMA = "coreguard.profile-ref/1";
35
+
36
+ /** The exact field set. Unknown fields are a defect, not decoration. */
37
+ export const REFERENCE_FIELDS = Object.freeze(["receipt_id", "profile", "profile_version"]);
38
+
39
+ const MAX_ID = 512;
40
+
41
+ function requireReceiptId(value) {
42
+ if (typeof value !== "string" || value.length === 0) {
43
+ throw new TypeError("receipt_id must be a non-empty string");
44
+ }
45
+ if (value.length > MAX_ID) throw new TypeError(`receipt_id must be at most ${MAX_ID} characters`);
46
+ if (/\s/.test(value)) throw new TypeError("receipt_id must not contain whitespace");
47
+ return value;
48
+ }
49
+
50
+ /**
51
+ * Build a profile reference for a receipt. `outcome` is accepted only to keep
52
+ * the reference tied to the run that produced it in logs; it is NOT part of the
53
+ * wire shape and is deliberately not emitted.
54
+ */
55
+ export function makeProfileReference({ receiptId } = {}) {
56
+ return Object.freeze({
57
+ receipt_id: requireReceiptId(receiptId),
58
+ profile: PROFILE_ID,
59
+ profile_version: PROFILE_VERSION,
60
+ });
61
+ }
62
+
63
+ /**
64
+ * Parse and validate a reference received from someone else. Returns
65
+ * { ok, reference, error }. Never throws on hostile input: a foreign document
66
+ * arriving here is untrusted data, and a parser that throws on it is a parser
67
+ * that can be crashed by a stranger.
68
+ */
69
+ export function parseProfileReference(input) {
70
+ const fail = (error) => ({ ok: false, reference: null, error });
71
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
72
+ return fail("reference must be an object");
73
+ }
74
+ let keys;
75
+ try {
76
+ keys = Object.keys(input).sort();
77
+ } catch {
78
+ return fail("reference is not a readable object");
79
+ }
80
+ const unknown = keys.filter((k) => !REFERENCE_FIELDS.includes(k));
81
+ if (unknown.length) return fail(`unknown reference fields: ${unknown.join(", ")}`);
82
+ const missing = REFERENCE_FIELDS.filter((f) => !keys.includes(f));
83
+ if (missing.length) return fail(`missing reference fields: ${missing.join(", ")}`);
84
+
85
+ let receiptId;
86
+ let profile;
87
+ let version;
88
+ try {
89
+ receiptId = input.receipt_id;
90
+ profile = input.profile;
91
+ version = input.profile_version;
92
+ } catch {
93
+ return fail("reference fields are not readable");
94
+ }
95
+
96
+ if (typeof receiptId !== "string" || receiptId.length === 0 || /\s/.test(receiptId)) {
97
+ return fail("receipt_id must be a non-empty string without whitespace");
98
+ }
99
+ if (profile !== PROFILE_ID) {
100
+ return fail(`unknown profile: ${JSON.stringify(profile)} (this build speaks ${PROFILE_ID})`);
101
+ }
102
+ if (!Number.isSafeInteger(version) || version < 1) {
103
+ return fail("profile_version must be a positive integer");
104
+ }
105
+ if (version !== PROFILE_VERSION) {
106
+ // Named, not rounded: a version we do not implement is not a version we
107
+ // may interpret as if we did.
108
+ return fail(`unsupported profile_version: ${version} (this build implements ${PROFILE_VERSION})`);
109
+ }
110
+ return { ok: true, reference: makeProfileReference({ receiptId }), error: null };
111
+ }
112
+
113
+ /** Self-check: shape, refusal and round-trip, for callers that cannot run tests. */
114
+ export function selfCheck() {
115
+ const ref = makeProfileReference({ receiptId: "a".repeat(64) });
116
+ const roundTrip = parseProfileReference(ref);
117
+ const extra = parseProfileReference({ ...ref, outcome: "VERIFIED" });
118
+ const wrongProfile = parseProfileReference({ ...ref, profile: "CG-OUT/2" });
119
+ const future = parseProfileReference({ ...ref, profile_version: 2 });
120
+ const noVersion = parseProfileReference({ receipt_id: "a".repeat(64), profile: PROFILE_ID });
121
+ const checks = [
122
+ { name: "a reference round-trips", pass: roundTrip.ok && roundTrip.reference.receipt_id === ref.receipt_id },
123
+ { name: "the wire shape is exactly three fields", pass: Object.keys(ref).length === REFERENCE_FIELDS.length },
124
+ { name: "an outcome smuggled into the shape is refused", pass: extra.ok === false },
125
+ { name: "an unknown profile is refused", pass: wrongProfile.ok === false },
126
+ { name: "a future version is refused, not rounded", pass: future.ok === false && /unsupported profile_version/.test(future.error) },
127
+ { name: "a reference without a version is refused", pass: noVersion.ok === false },
128
+ ];
129
+ return Object.freeze({ profile: PROFILE_ID, checks, ok: checks.every((c) => c.pass) });
130
+ }