@333eco/origin-verify 0.5.0 → 0.6.0

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.
Files changed (3) hide show
  1. package/README.md +10 -0
  2. package/agreement.mjs +342 -0
  3. package/package.json +3 -1
package/README.md CHANGED
@@ -50,6 +50,16 @@ both dates of the revocation that reaches it, or `covered: null` when the log wa
50
50
  unlocks the key. `findRevocations(get, size, trust)` reads the log's `revoke` entries; a holder's revocation reveals through
51
51
  `checkReveal` like a record. None of it says who held the phone.
52
52
 
53
+ ## Checking an agreement
54
+
55
+ `@333eco/origin-verify/agreement` implements b-poh-statements §3.4 (the `b-agreement/v1` text) and §9.6 (checking one).
56
+ `parseAgreement(text)` reads an agreement, an end or a notice, or throws the reason. `partyDigest(text, i)` is party `i`'s press (§3.4.2);
57
+ `matchCode(text)` is the 12-digit code both parties see, `matchShown(code, lang)` its grouped form. `checkAgreement({ statement, proofs, ends, notices, earlier }, { trust, get, size, waiting, lookup })`
58
+ returns a report of codes: `finding` (`both-pressed`, `offer-only`, `withdrawn-before-second`, `lapsed`, `not-confirmed`, `one-signer`, `no-press`,
59
+ `unavailable`, `unreadable`), per-party detail, facts beside the agreement in `also` (`both-ended`, `end-one-party`, `notice`, `withdrawal-after-both`,
60
+ `amendment-chain`), and `notChecked`.
61
+ It never says *valid*, *binding*, *verified*, *kept* or *broken*, and a log, waiting list or registry it cannot reach is `unavailable`, never read as fine.
62
+
53
63
  ## Finding a file after its metadata is gone
54
64
 
55
65
  | field | what it is | survives |
package/agreement.mjs ADDED
@@ -0,0 +1,342 @@
1
+ // @333eco/origin-verify/agreement. CC0. Checks a `b-agreement/v1` statement against the public log, by b-poh-statements v1.12 §3.4 (the text)
2
+ // and §9.6 (the steps and the report). No runtime dependencies; browser or Node: only primitives.mjs and index.mjs are imported.
3
+ // ⛔ It reports facts, each scoped, as CODES for a page to put words on. It never says "valid", "binding", "verified", "kept" or "broken" (§9.6).
4
+ // "A reading" in a comment marks a place where the public text is silent or ambiguous and the most conservative reading was taken.
5
+ import { concat, hex, sha256, text, u32, utf8 } from "./primitives.mjs";
6
+ import { canonical, checkReveal, checkWitnessSignature, readEntries } from "./index.mjs";
7
+
8
+ export const KINDS = ["b-agreement/v1", "b-agreement-end/v1", "b-agreement-notice/v1"];
9
+ const DOMAIN = utf8("b-agreement/v1/party\0");
10
+ const MATCH = utf8("b-agreement/v1/match\0");
11
+
12
+ // ── §3.4.2: the per-party press ─────────────────────────────────────────────────────────────────────────────────────────
13
+ /** The 57 bytes party i (1 or 2) presses over, for every statement of the family (an agreement, an end, a notice). */
14
+ export function partyPreimage(statement, i) {
15
+ if (i !== 1 && i !== 2) throw new Error("party is 1 or 2");
16
+ return concat(DOMAIN, u32(i), sha256(utf8(statement)));
17
+ }
18
+ /** d_i, in hex. */
19
+ export const partyDigest = (statement, i) => hex(sha256(partyPreimage(statement, i)));
20
+ /** The claim every press of the family carries: fixed in every field but the fingerprint. */
21
+ export const partyClaim = (d) => ({ v: 2, sha256: d, mime: "application/octet-stream", bytes: 57, source: "digitalCreation", tool: "agreement.333.eco", declared: true });
22
+
23
+ // ── the match code ───────────────────────────────────────────────────────────────────────────────────────────────────────
24
+ /** Twelve decimal digits: the first 8 bytes of sha256("b-agreement/v1/match\0" || sha256(statement)), big-endian, mod 10^12. It catches a mix-up, never a determined drafter. */
25
+ export function matchCode(statement) {
26
+ const m = sha256(MATCH, sha256(utf8(statement)));
27
+ return String(new DataView(m.buffer, m.byteOffset, 8).getBigUint64(0, false) % 1000000000000n).padStart(12, "0");
28
+ }
29
+ /** Four groups of three, single spaces; for lang "km" in Khmer numerals (U+17E0 to U+17E9): the same number. */
30
+ export function matchShown(code, lang) {
31
+ if (!/^\d{12}$/.test(String(code))) throw new Error("a match code is 12 digits");
32
+ const g = String(code).match(/\d{3}/g).join(" ");
33
+ return lang === "km" ? g.replace(/\d/g, (x) => String.fromCharCode(0x17e0 + Number(x))) : g;
34
+ }
35
+
36
+ // ── §3.4: the text ───────────────────────────────────────────────────────────────────────────────────────────────────────
37
+ // Characters: NFC, no control character but LF, no tab, no space but U+0020, no soft hyphen, no direction control, no byte-order mark, no line or
38
+ // paragraph separator, no line ending in whitespace or a zero-width character. Khmer's U+200B to U+200D stay allowed inside a line.
39
+ const FORBIDDEN = /[\u0000-\u0009\u000B-\u001F\u007F-\u009F\u00A0\u00AD\u061C\u1680\u2000-\u200A\u200E\u200F\u2028\u2029\u202A-\u202F\u205F\u2066-\u2069\u3000\uFEFF]/u;
40
+ const TRAILING = /[\s\u200B-\u200D]$/u;
41
+ // A reading: the spec says "folded name or tag: lowercase letters and digits only" and sets no length; 64 is what the two existing ports use.
42
+ const NAME = "@[a-z0-9]{1,64}";
43
+ const ADDRESS = "B:[0-9A-HJKMNP-TV-Z]{4}-[0-9A-HJKMNP-TV-Z]{4}-[0-9A-HJKMNP-TV-Z]{4}";
44
+ const TAG = "#[a-z0-9]{1,64}";
45
+ const HEX64 = /^[0-9a-f]{64}$/, SALT = /^[0-9a-f]{32}$/, MINUTE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})Z$/;
46
+ // A reading: "<language tag>" is not defined further; the two existing ports accept a lowercase 2-3 letter primary tag and subtags of 2-8 letters or digits.
47
+ const LANG = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
48
+ const oneLine = (v, max, what) => {
49
+ if (!v || v.length > max || /^\s|\s$/u.test(v) || /\s{2}/u.test(v)) throw new Error(`${what}: one line, no leading, trailing or doubled spaces, at most ${max} characters`);
50
+ return v;
51
+ };
52
+
53
+ const daysIn = (y, m) => (m === 2 ? (y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0) ? 29 : 28) : [4, 6, 9, 11].includes(m) ? 30 : 31);
54
+ /** A UTC time in ms from `YYYY-MM-DDTHH:MM[:SS[.fff]]Z`, or NaN. Explicit range checks, so engines cannot disagree over 02-30 or 24:00. Compare the numbers, never the text. */
55
+ export function timeOf(s) {
56
+ const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?Z$/.exec(typeof s === "string" ? s : "");
57
+ if (!m) return NaN;
58
+ const [y, mo, d, h, mi, sec] = [m[1], m[2], m[3], m[4], m[5], m[6] ?? "0"].map(Number);
59
+ if (mo < 1 || mo > 12 || d < 1 || d > daysIn(y, mo) || h > 23 || mi > 59 || sec > 59) return NaN;
60
+ return Date.UTC(y, mo - 1, d, h, mi, sec) + (m[7] ? Math.round(Number(m[7]) * 1000) : 0);
61
+ }
62
+
63
+ function linesOf(statement) {
64
+ if (typeof statement !== "string" || !statement.endsWith("\n") || statement.endsWith("\n\n")) throw new Error("ends with exactly one newline");
65
+ if (statement.normalize("NFC") !== statement) throw new Error("not NFC");
66
+ if (FORBIDDEN.test(statement)) throw new Error("a forbidden character");
67
+ // A reading: a lone surrogate cannot come from UTF-8 and would be hashed as U+FFFD, so the words shown would not be the bytes pressed.
68
+ if (new TextDecoder("utf-8", { ignoreBOM: true }).decode(utf8(statement)) !== statement) throw new Error("not well-formed text");
69
+ const ls = statement.slice(0, -1).split("\n");
70
+ ls.forEach((l, n) => { if (TRAILING.test(l)) throw new Error(`line ${n + 1} ends in whitespace`); });
71
+ return ls;
72
+ }
73
+ // Blocks: `<head> (<n> line|lines):`, then exactly n lines as they are. The count, not the content, ends a block.
74
+ function blocksOf(ls, at) {
75
+ const out = [];
76
+ while (at < ls.length) {
77
+ if (ls[at] !== "") throw new Error(`line ${at + 1}: an empty line before each block`);
78
+ const m = /^(.+) \((\d+) (line|lines)\):$/.exec(ls[at + 1] ?? "");
79
+ if (!m) throw new Error(`line ${at + 2}: a block head`);
80
+ const n = Number(m[2]);
81
+ if ((n === 1) !== (m[3] === "line") || String(n) !== m[2]) throw new Error(`line ${at + 2}: "1 line", else "<n> lines"`);
82
+ const body = ls.slice(at + 2, at + 2 + n);
83
+ if (body.length !== n) throw new Error(`line ${at + 2}: the block is shorter than it says`);
84
+ out.push({ head: m[1], body });
85
+ at += 2 + n;
86
+ }
87
+ return out;
88
+ }
89
+
90
+ /** §3.4 and §3.4.1. Returns the parts, or throws an Error whose message is the reason. */
91
+ export function parseAgreement(statement) {
92
+ const ls = linesOf(statement), kind = ls[0];
93
+ if (!KINDS.includes(kind)) throw new Error("unknown kind");
94
+ let at = 1;
95
+ const take = (key, re) => {
96
+ const m = new RegExp(`^${key}: (.*)$`).exec(ls[at] ?? "");
97
+ if (!m) return null;
98
+ if (re && !re.test(m[1])) throw new Error(`${key}: malformed`);
99
+ at++; return m[1];
100
+ };
101
+ const need = (key, re) => { const v = take(key, re); if (v === null) throw new Error(`line ${at + 1}: ${key}: expected`); return v; };
102
+
103
+ if (kind === "b-agreement/v1") {
104
+ const title = oneLine(need("title"), 200, "title"), parties = [];
105
+ for (let i = 1; i <= 2; i++) {
106
+ const m = new RegExp(`^(${NAME}|${ADDRESS}|${TAG}) (.+)$`).exec(need("party"));
107
+ if (!m) throw new Error(`party ${i}: an @name, a B:address or a #tag, then a legal name`);
108
+ const p = { i, id: m[1], legalName: oneLine(m[2], 200, "legal name") };
109
+ if (p.id.startsWith("#")) {
110
+ const s = new RegExp(`^(${NAME}) (.+)$`).exec(need("signer"));
111
+ if (!s) throw new Error(`party ${i}: signer: an @name, then a legal name`);
112
+ p.signer = s[1]; p.signerLegalName = oneLine(s[2], 200, "signer's legal name");
113
+ p.role = oneLine(need("role"), 100, "role");
114
+ } else if (/^(signer|role): /.test(ls[at] ?? "")) throw new Error(`party ${i}: only a #tag has a signer`);
115
+ parties.push(p);
116
+ }
117
+ if (parties[0].id === parties[1].id) throw new Error("two parties, never the same one twice");
118
+ const openUntil = need("open-until", MINUTE);
119
+ // A reading: "a time" means a real one (the ports lean on Date.parse, which some engines let roll 02-30 into March).
120
+ if (Number.isNaN(timeOf(openUntil))) throw new Error("open-until: not a time");
121
+ const languages = [need("language", LANG)], second = take("language", LANG);
122
+ if (second !== null) languages.push(second);
123
+ if (languages[0] === languages[1]) throw new Error("two different languages");
124
+ const governs = take("governs", LANG);
125
+ if ((languages.length === 2) !== (governs !== null) || (governs && !languages.includes(governs))) throw new Error("governs: exactly when there are two languages, naming one of them");
126
+ const amends = take("amends", HEX64), salt = need("salt", SALT), attachments = [];
127
+ for (let a; (a = take("attachment")) !== null;) {
128
+ const m = /^([0-9a-f]{64}) (.+)$/.exec(a);
129
+ if (!m) throw new Error("attachment: a sha256, then a file name");
130
+ attachments.push({ sha256: m[1], name: oneLine(m[2], 200, "file name") });
131
+ }
132
+ const blocks = blocksOf(ls, at);
133
+ const want = languages.flatMap((l) => [`party 1 gives, ${l}`, `party 2 gives, ${l}`, `terms, ${l}`]);
134
+ if (blocks.length !== want.length || blocks.some((b, n) => b.head !== want[n])) throw new Error(`the blocks, in order: ${want.join(" · ")}`);
135
+ for (const b of blocks) if (b.head.includes("gives") && !b.body.some((l) => l.trim() !== "")) throw new Error(`${b.head}: empty (a side that gives nothing is a gift: use Thank)`);
136
+ return { kind, title, parties, openUntil, languages, governs, amends, salt, attachments, blocks };
137
+ }
138
+ const agreement = need("agreement", HEX64);
139
+ let from = null, disowns = null;
140
+ if (kind === "b-agreement-notice/v1") {
141
+ from = Number(need("from", /^party [12]$/).slice(6));
142
+ // A reading: "a record number" is a decimal integer without leading zeros; 16 digits is what the two existing ports allow.
143
+ const d = take("disowns", /^(0|[1-9]\d{0,15})$/); if (d !== null) disowns = Number(d);
144
+ }
145
+ const salt = need("salt", SALT), blocks = blocksOf(ls, at), head = kind === "b-agreement-end/v1" ? "reason" : "notice";
146
+ if (blocks.length !== 1 || blocks[0].head !== head) throw new Error(`one block: ${head}`);
147
+ if (kind === "b-agreement-notice/v1" && disowns === null && !blocks[0].body.some((l) => l.trim() !== "")) throw new Error("a notice says something, or disowns a record");
148
+ return { kind, agreement, from, disowns, salt, blocks };
149
+ }
150
+
151
+ // ── §9.6: checking an agreement ──────────────────────────────────────────────────────────────────────────────────────────
152
+ // The report is CODES, never prose. `finding` is the first of `findings`, in this order (a reading: the rows co-occur, and the table gives no order;
153
+ // this one puts what makes the text unsafe to lean on first, and a missing press before a late one):
154
+ // unreadable · unavailable · one-signer · offer-only · withdrawn-before-second · lapsed · not-confirmed · both-pressed
155
+ // Facts that stand beside the agreement are in `also`: both-ended, end-one-party, notice, withdrawal-after-both, amendment-chain.
156
+ // ⛔ Nothing here is read as fine when a read failed: a log, waiting list or registry that cannot be reached gives `unavailable`.
157
+ const sameClaim = (claim, d) => { try { return canonical(claim) === canonical(partyClaim(d)); } catch { return false; } };
158
+ const nameOf = (p) => p.signer ?? p.id; // who presses: a person's own @name or address; for a #tag, the signer's @name
159
+ const unavailable = (why) => Object.assign(new Error("unavailable"), { unavailable: why });
160
+
161
+ async function loadLog(deps, notChecked) {
162
+ const out = [];
163
+ try {
164
+ const raw = await readEntries(deps.get, deps.size);
165
+ raw.forEach((b, pos) => out.push({ e: JSON.parse(text(b)), pos }));
166
+ } catch { throw unavailable("log"); }
167
+ if (typeof deps.waiting === "function") {
168
+ let w;
169
+ try { w = await deps.waiting(); if (!Array.isArray(w)) throw 0; } catch { throw unavailable("waiting"); }
170
+ const have = new Set(out.map(({ e }) => e?.index));
171
+ // A waiting record still carries the record key's signature, so it needs no trust in the list; the log wins where both hold an index.
172
+ for (const e of w) if (e && !have.has(e.index)) out.push({ e, pos: Number.isInteger(e.index) ? e.index : Infinity });
173
+ } else notChecked.push({ item: "waiting-list", why: "no reader given" });
174
+ const seq = (x) => (Number.isInteger(x.e?.index) ? x.e.index : x.pos);
175
+ const checked = [];
176
+ for (const x of out) {
177
+ const e = x.e;
178
+ if (e?.t !== "record" && e?.t !== "withdraw") continue;
179
+ if (await checkWitnessSignature(e, deps.trust)) checked.push({ e, at: seq(x) });
180
+ }
181
+ return checked.sort((a, b) => a.at - b.at); // by log index, never by minute
182
+ }
183
+
184
+ /** Records of the family's press `d` (a record whose claim is exactly §3.4.2's), with a good witness signature. Any other tool or field is ignored. */
185
+ const pressesOf = (log, d) => log.filter(({ e }) => e.t === "record" && sameClaim(e.claim, d));
186
+
187
+ /** Is `key` listed for the name in this registry answer as of the press (§9.6 step 5)? Compared as times. */
188
+ function listedAt(answer, party, key, pressMs) {
189
+ if (party.id.startsWith("B:") && answer?.name !== party.id) return { ok: false, why: "name-differs" }; // §9.4: an address redirected to an @name says nothing of the address
190
+ const mine = (Array.isArray(answer?.keys) ? answer.keys : []).filter((k) => k?.key === key);
191
+ if (!mine.length) return { ok: false, why: "key-not-listed" };
192
+ let why = "bad-time";
193
+ for (const k of mine) {
194
+ const since = timeOf(k.since), until = k.until === null ? Infinity : timeOf(k.until);
195
+ if (Number.isNaN(since) || Number.isNaN(until)) continue;
196
+ if (pressMs >= since && pressMs < until) return { ok: true };
197
+ why = pressMs < since ? "before-listing" : "removed-before";
198
+ }
199
+ return { ok: false, why };
200
+ }
201
+
202
+ async function evaluate(statement, input, ctx, seen, inChain = false) {
203
+ const sha = hex(sha256(utf8(statement)));
204
+ const base = { sha256: sha };
205
+ let a;
206
+ try { a = parseAgreement(statement); } catch (e) { return { ...base, finding: "unreadable", findings: ["unreadable"], why: e.message, parties: [], also: [], notChecked: [] }; }
207
+ if (a.kind !== "b-agreement/v1") return { ...base, finding: "unreadable", findings: ["unreadable"], why: "not an agreement", parties: [], also: [], notChecked: [] };
208
+ const notChecked = ctx.notChecked, also = [];
209
+ const log = await ctx.log();
210
+ const proofs = new Map();
211
+ for (const p of input.proofs ?? []) if (p?.kind === "b-origin-proof" && p.version === 1 && Number.isInteger(p.index) && !proofs.has(p.index)) proofs.set(p.index, p);
212
+
213
+ // Steps 2 and 3: find each party's press, open it.
214
+ const parties = [];
215
+ for (const p of a.parties) {
216
+ const d = partyDigest(statement, p.i), cands = pressesOf(log, d);
217
+ // A reading: anyone who holds the text can press d_i, so several records of one d_i can exist. The record a proof names decides; with no proof
218
+ // the earliest. The others are counted, never used.
219
+ const named = cands.find((c) => proofs.has(c.e.index));
220
+ const pick = named ?? cands[0] ?? null;
221
+ const row = { i: p.i, name: nameOf(p), record: pick ? pick.at : null, witnessedAt: pick?.e.witnessedAt ?? null, otherRecords: Math.max(0, cands.length - 1), key: null, confirmed: pick ? false : null, why: pick ? "no-proof" : "no-press", _at: pick?.at, _entry: pick?.e };
222
+ if (pick && named) {
223
+ let r; try { r = await checkReveal(pick.e, proofs.get(pick.e.index).opening, ctx.trust); } catch { r = { ok: false }; }
224
+ if (r.ok) { row.key = r.passkeyPublicKey; row.why = null; } else row.why = "opening-failed";
225
+ }
226
+ parties.push(row);
227
+ }
228
+ // An amendment chain, within reason: the earlier texts are inputs (the log holds only fingerprints), each checked as above, earliest first.
229
+ if (a.amends && !inChain) {
230
+ const pool = new Map((input.earlier ?? []).map((t) => [hex(sha256(utf8(t))), t]));
231
+ const chain = [];
232
+ let want = a.amends, ok = true;
233
+ while (want && !seen.has(want)) {
234
+ seen.add(want);
235
+ const t = pool.get(want);
236
+ if (!t) { notChecked.push({ item: "amendment", amends: want, why: "that earlier text was not given" }); ok = false; break; }
237
+ let prev; try { prev = parseAgreement(t); } catch { prev = null; }
238
+ const r = await evaluate(t, { proofs: input.proofs }, { ...ctx, notChecked: [] }, seen, true);
239
+ const sameParties = !!prev && prev.kind === "b-agreement/v1" && prev.parties.every((p, n) => p.id === a.parties[n].id);
240
+ chain.unshift({ sha256: r.sha256, finding: r.finding, findings: r.findings, sameParties });
241
+ want = prev?.amends ?? null;
242
+ }
243
+ if (chain.length) also.push({ finding: "amendment-chain", chain, complete: ok && !want });
244
+ }
245
+ const [p1, p2] = parties, pressed = parties.filter((p) => p.record !== null);
246
+ const flat = () => parties.map(({ _at, _entry, ...r }) => r);
247
+ const report = (findings, more = {}) => ({ ...base, finding: findings[0], findings, parties: flat(), also, notChecked, ...more });
248
+ if (!pressed.length) { return report(["no-press"]); } // a reading: the table has no row for no press at all; this is its own code
249
+
250
+ // Step 4 and 5: two signers; names as of the press. Only the registry knows the names, so any throw is `unavailable`.
251
+ const answers = new Map();
252
+ const answer = async (n) => {
253
+ if (!answers.has(n)) { try { answers.set(n, await ctx.lookup(n)); } catch { throw unavailable("registry"); } }
254
+ return answers.get(n);
255
+ };
256
+ const both = pressed.length === 2;
257
+ let oneSigner = false;
258
+ if (both) {
259
+ // A reading: one name on both sides is compared on the pressing names (a #tag's signer), as well as the keys, because `@ben` and `#cafe` signed for by `@ben` parse.
260
+ if (p1.name === p2.name) oneSigner = true;
261
+ if (p1.key && p1.key === p2.key) oneSigner = true;
262
+ }
263
+ for (const [n, row] of parties.entries()) {
264
+ const party = a.parties[n], other = a.parties[1 - n];
265
+ if (row.record === null) continue;
266
+ if (party.signer) notChecked.push({ item: "signer-list", party: party.i, tag: party.id, signer: party.signer, why: "until that list is defined" });
267
+ if (!row.key) continue;
268
+ const pressMs = timeOf(row.witnessedAt);
269
+ if (Number.isNaN(pressMs)) { row.why = "bad-time"; continue; }
270
+ const own = listedAt(await answer(row.name), party, row.key, pressMs);
271
+ row.confirmed = own.ok; row.why = own.ok ? null : own.why;
272
+ // A reading: "neither is listed (step 5) for the other party" takes step 5's meaning of listed: as of this press, as times.
273
+ if (both && other && !oneSigner && listedAt(await answer(nameOf(other)), other, row.key, pressMs).ok) oneSigner = true;
274
+ }
275
+
276
+ // Step 7 inputs, step 6: order by log index.
277
+ const first = both ? (p1._at < p2._at ? p1 : p2) : pressed[0], second = both ? (first === p1 ? p2 : p1) : null;
278
+ const withdrawals = log.filter(({ e }) => e.t === "withdraw");
279
+ const wBefore = withdrawals.find(({ e, at }) => e.target === first._at && at > first._at && (!second || at < second._at));
280
+ const findings = [];
281
+ if (oneSigner) findings.push("one-signer");
282
+ // A reading for an offer alone that was withdrawn: the row says "before <the other> pressed", which holds when no other press came; reported as that row, with no acceptance.
283
+ if (!both && !wBefore) findings.push("offer-only");
284
+ if (wBefore) findings.push("withdrawn-before-second");
285
+ let inTime = null;
286
+ if (second) {
287
+ const t = timeOf(second.witnessedAt), close = timeOf(a.openUntil);
288
+ if (Number.isNaN(t)) return report(["unreadable"], { why: "record-time" });
289
+ inTime = t <= close; // as times, at or before the last minute
290
+ if (!inTime) findings.push("lapsed");
291
+ }
292
+ if (pressed.some((p) => p.confirmed !== true)) findings.push("not-confirmed");
293
+ if (!findings.length) findings.push("both-pressed");
294
+ const details = { offer: { party: first.i, record: first._at }, acceptance: second ? { party: second.i, record: second._at, inTime } : null, withdrawal: wBefore ? { record: wBefore.at, target: wBefore.e.target } : null };
295
+
296
+ // Step 7: afterwards. Counted only when both pressed, and only a press (or withdrawal) after the second press.
297
+ if (second) {
298
+ const after = (c) => c.at > second._at;
299
+ for (const { e, at } of withdrawals) if (at > second._at && (e.target === first._at || e.target === second._at)) also.push({ finding: "withdrawal-after-both", record: at, target: e.target, recordStands: true });
300
+ const ignored = [];
301
+ const mine = (text2) => { try { const s = parseAgreement(text2); return s.agreement === sha ? s : null; } catch { return null; } };
302
+ for (const t of input.ends ?? []) {
303
+ const s = mine(t);
304
+ if (!s || s.kind !== "b-agreement-end/v1") { ignored.push({ item: "end", why: "not an end of this agreement" }); continue; }
305
+ const rs = [1, 2].map((i) => pressesOf(log, partyDigest(t, i)).find(after));
306
+ if (rs[0] && rs[1]) also.push({ finding: "both-ended", records: [rs[0].at, rs[1].at] });
307
+ else if (rs[0] || rs[1]) also.push({ finding: "end-one-party", party: rs[0] ? 1 : 2, record: (rs[0] ?? rs[1]).at });
308
+ else ignored.push({ item: "end", why: "no press after the second press" });
309
+ notChecked.push({ item: "end-press-keys", why: "the end statements' presses are not opened" });
310
+ }
311
+ for (const t of input.notices ?? []) {
312
+ const s = mine(t);
313
+ if (!s || s.kind !== "b-agreement-notice/v1") { ignored.push({ item: "notice", why: "not a notice of this agreement" }); continue; }
314
+ const r = pressesOf(log, partyDigest(t, s.from)).find(after);
315
+ if (r) also.push({ finding: "notice", from: s.from, record: r.at, disowns: s.disowns });
316
+ else ignored.push({ item: "notice", why: "no press after the second press" });
317
+ }
318
+ if (ignored.length) details.ignored = ignored;
319
+ }
320
+
321
+ return report(findings, details);
322
+ }
323
+
324
+ /**
325
+ * §9.6. `{ statement, proofs, ends?, notices?, earlier? }`: the text, the parties' proofs (§6), and optionally the end and notice texts and the earlier
326
+ * texts of an amendment chain (a reading: the log holds fingerprints only, so a checker can look for a text only if it is given one).
327
+ * `deps`: { trust, get, size } reads the log as `readEntries` does (its size from a checkpoint the caller has checked); `waiting?()` returns the waiting
328
+ * list's records; `lookup(name)` returns the registry's answer for a name (§7.3: `{ name, keys: [{ key, record, since, until }] }`) or throws when it
329
+ * cannot be reached. The name is as written in the statement (`@name`, `B:address`), or the signer's `@name` for a `#tag`.
330
+ */
331
+ export async function checkAgreement({ statement, proofs, ends, notices, earlier }, deps) {
332
+ const notChecked = [], ctx = { trust: deps.trust, lookup: deps.lookup, notChecked };
333
+ let cache;
334
+ ctx.log = async () => (cache ??= loadLog({ ...deps }, notChecked));
335
+ try {
336
+ const r = await evaluate(statement, { proofs, ends, notices, earlier }, ctx, new Set());
337
+ return r;
338
+ } catch (e) {
339
+ if (e?.unavailable) return { sha256: typeof statement === "string" ? hex(sha256(utf8(statement))) : null, finding: "unavailable", findings: ["unavailable"], why: e.unavailable, parties: [], also: [], notChecked };
340
+ throw e;
341
+ }
342
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@333eco/origin-verify",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Checks a B-Origin record with no help from its operator: signatures, its place in the public log, witness cosignatures, RFC 3161 tokens, OpenTimestamps proofs against Bitcoin, and a signer's reveal. Browser or Node, no runtime dependencies.",
5
5
  "license": "CC0-1.0 OR Apache-2.0",
6
6
  "author": "Thon Ly",
@@ -25,6 +25,7 @@
25
25
  ".": "./index.mjs",
26
26
  "./media": "./media.mjs",
27
27
  "./trust": "./trust.mjs",
28
+ "./agreement": "./agreement.mjs",
28
29
  "./package.json": "./package.json"
29
30
  },
30
31
  "files": [
@@ -34,6 +35,7 @@
34
35
  "media.mjs",
35
36
  "embed.mjs",
36
37
  "trust.mjs",
38
+ "agreement.mjs",
37
39
  "cli.mjs",
38
40
  "README.md", "LICENSE", "LICENSE-CC0", "LICENSE-APACHE"],
39
41
  "bin": {