@333eco/origin-verify 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,125 @@
1
+ Creative Commons Legal Code
2
+
3
+ CC0 1.0 Universal
4
+
5
+ The authoritative text of this licence is published at
6
+ https://creativecommons.org/publicdomain/zero/1.0/legalcode
7
+ and governs in the event of any discrepancy with the copy below.
8
+
9
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
10
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
11
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
12
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
13
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
14
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
15
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
16
+ HEREUNDER.
17
+
18
+ Statement of Purpose
19
+
20
+ The laws of most jurisdictions throughout the world automatically confer
21
+ exclusive Copyright and Related Rights (defined below) upon the creator
22
+ and subsequent owner(s) (each and all, an "owner") of an original work of
23
+ authorship and/or a database (each, a "Work").
24
+
25
+ Certain owners wish to permanently relinquish those rights to a Work for
26
+ the purpose of contributing to a commons of creative, cultural and
27
+ scientific works ("Commons") that the public can reliably and without fear
28
+ of later claims of infringement build upon, modify, incorporate in other
29
+ works, reuse and redistribute as freely as possible in any form whatsoever
30
+ and for any purposes, including without limitation commercial purposes.
31
+ These owners may contribute to the Commons to promote the ideal of a free
32
+ culture and the further production of creative, cultural and scientific
33
+ works, or to gain reputation or greater distribution for their Work in
34
+ part through the use and efforts of others.
35
+
36
+ For these and/or other purposes and motivations, and without any
37
+ expectation of additional consideration or compensation, the person
38
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
39
+ is an owner of Copyright and Related Rights in the Work, voluntarily
40
+ elects to apply CC0 to the Work and publicly distribute the Work under its
41
+ terms, with knowledge of his or her Copyright and Related Rights in the
42
+ Work and the meaning and intended legal effect of CC0 on those rights.
43
+
44
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
45
+ protected by copyright and related or neighboring rights ("Copyright and
46
+ Related Rights"). Copyright and Related Rights include, but are not
47
+ limited to, the following:
48
+
49
+ i. the right to reproduce, adapt, distribute, perform, display,
50
+ communicate, and translate a Work;
51
+ ii. moral rights retained by the original author(s) and/or performer(s);
52
+ iii. publicity and privacy rights pertaining to a person's image or
53
+ likeness depicted in a Work;
54
+ iv. rights protecting against unfair competition in regards to a Work,
55
+ subject to the limitations in paragraph 4(a), below;
56
+ v. rights protecting the extraction, dissemination, use and reuse of
57
+ data in a Work;
58
+ vi. database rights (such as those arising under Directive 96/9/EC of the
59
+ European Parliament and of the Council of 11 March 1996 on the legal
60
+ protection of databases, and under any national implementation
61
+ thereof, including any amended or successor version of such
62
+ directive); and
63
+ vii. other similar, equivalent or corresponding rights throughout the
64
+ world based on applicable law or treaty, and any national
65
+ implementations thereof.
66
+
67
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
68
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
69
+ irrevocably and unconditionally waives, abandons, and surrenders all of
70
+ Affirmer's Copyright and Related Rights and associated claims and causes
71
+ of action, whether now known or unknown (including existing as well as
72
+ future claims and causes of action), in the Work (i) in all territories
73
+ worldwide, (ii) for the maximum duration provided by applicable law or
74
+ treaty (including future time extensions), (iii) in any current or future
75
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
76
+ including without limitation commercial, advertising or promotional
77
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
78
+ member of the public at large and to the detriment of Affirmer's heirs and
79
+ successors, fully intending that such Waiver shall not be subject to
80
+ revocation, rescission, cancellation, termination, or any other legal or
81
+ equitable action to disrupt the quiet enjoyment of the Work by the public
82
+ as contemplated by Affirmer's express Statement of Purpose.
83
+
84
+ 3. Public License Fallback. Should any part of the Waiver for any reason
85
+ be judged legally invalid or ineffective under applicable law, then the
86
+ Waiver shall be preserved to the maximum extent permitted taking into
87
+ account Affirmer's express Statement of Purpose. In addition, to the
88
+ extent the Waiver is so judged Affirmer hereby grants to each affected
89
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
90
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
91
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
92
+ maximum duration provided by applicable law or treaty (including future
93
+ time extensions), (iii) in any current or future medium and for any number
94
+ of copies, and (iv) for any purpose whatsoever, including without
95
+ limitation commercial, advertising or promotional purposes (the
96
+ "License"). The License shall be deemed effective as of the date CC0 was
97
+ applied by Affirmer to the Work. Should any part of the License for any
98
+ reason be judged legally invalid or ineffective under applicable law, such
99
+ partial invalidity or ineffectiveness shall not invalidate the remainder
100
+ of the License, and in such case Affirmer hereby affirms that he or she
101
+ will not (i) exercise any of his or her remaining Copyright and Related
102
+ Rights in the Work or (ii) assert any associated claims and causes of
103
+ action with respect to the Work, in either case contrary to Affirmer's
104
+ express Statement of Purpose.
105
+
106
+ 4. Limitations and Disclaimers.
107
+
108
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
109
+ surrendered, licensed or otherwise affected by this document.
110
+ b. Affirmer offers the Work as-is and makes no representations or
111
+ warranties of any kind concerning the Work, express, implied,
112
+ statutory or otherwise, including without limitation warranties of
113
+ title, merchantability, fitness for a particular purpose, non
114
+ infringement, or the absence of latent or other defects, accuracy, or
115
+ the present or absence of errors, whether or not discoverable, all to
116
+ the greatest extent permissible under applicable law.
117
+ c. Affirmer disclaims responsibility for clearing rights of other persons
118
+ that may apply to the Work or any use thereof, including without
119
+ limitation any person's Copyright and Related Rights in the Work.
120
+ Further, Affirmer disclaims responsibility for obtaining any necessary
121
+ consents, permissions or other rights required for any use of the
122
+ Work.
123
+ d. Affirmer understands and acknowledges that Creative Commons is not a
124
+ party to this document and has no duty or obligation with respect to
125
+ this CC0 or use of the Work.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # @333eco/origin-verify
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Checks a **B-Origin℠** record with no help from anyone: not from **HeartBank®**, not from a lookup service, and, with a saved pack, not from the network. No runtime dependencies. Runs in a browser or in Node.
4
+
5
+ A record is an entry in a public, append-only log at `log.333.eco`, made when a person signs a file with their passkey on `sign.333.eco`.
6
+
7
+ ```sh
8
+ npx @333eco/origin-verify file picture.png # finds the file's records by what it still is, and checks each one
9
+ npx @333eco/origin-verify record 0 # one record: signature, place in the tree, witnesses, clocks, Bitcoin
10
+ npx @333eco/origin-verify pack 0 record.json # saves a pack
11
+ npx @333eco/origin-verify check record.json # checks it, reading no network
12
+ npx @333eco/origin-verify audit # the whole log, recomputed from its public tiles
13
+ ```
14
+
15
+ ```js
16
+ import { verifyPack, findRecords, hashFile } from "@333eco/origin-verify";
17
+ import trust from "@333eco/origin-verify/trust";
18
+
19
+ const result = await verifyPack(pack, trust);
20
+ ```
21
+
22
+ ## What a result means
23
+
24
+ Four states. Each stands alone and none implies another.
25
+
26
+ | state | it says | it rests on |
27
+ |---|---|---|
28
+ | `included` | this record is in the tree this checkpoint signs, and the log cannot later remove it unnoticed | the operator's keys and the Merkle proof |
29
+ | `witnessed` | enough outside witnesses cosigned the checkpoint | their signatures. ⚠️ False today: no witness has admitted this log yet, and the result says so |
30
+ | `timestamped` | a checkpoint holding this record existed by this time | each authority's word, one per token |
31
+ | `bitcoin` | a checkpoint holding this record existed by this block | Bitcoin's proof of work |
32
+
33
+ **What a record does not say:** who imagined the work, or that one person holds one account. Without a signer's reveal it says *the operator witnessed this claim at this time and cannot later remove it*. With the reveal, *a passkey whose public key is given here signed exactly this claim*.
34
+
35
+ ## Finding a file after its metadata is gone
36
+
37
+ | field | what it is | survives |
38
+ |---|---|---|
39
+ | `sha256` | the exact bytes | nothing changing the file |
40
+ | `pixels` | SHA-256 of the decoded picture as RGB, alpha dropped; PNG only, decoded here byte for byte | stripping metadata, re-compressing a PNG |
41
+ | `phash` | 64 bits: over white, luma, an exact box filter to 8×8, each cell above the mean or not | JPEG, scaling. A hint that two pictures look alike, nothing more |
42
+
43
+ `findRecords` reads the public log directly, so nobody learns what you checked. JPEG and other decoders differ, so those files never get `pixels`.
44
+
45
+ ⚠️ The DCT hash most people reach for fails on pixel art: half the coefficients of a mirror-symmetric sprite are near zero, so their bits are noise. Measured on 150 pictures × 5 re-encodings, 40 of them symmetric sprites: this hash finds 99.7% of the same picture within distance 8, with 0.8% of different pictures within 8.
46
+
47
+ ## Honest limits
48
+
49
+ - `trust.mjs` pins the log's keys and the timestamp authorities' roots. If you got this package from somewhere you don't trust, nothing here helps. npm provenance links each version to this repository's source.
50
+ - A timestamp token's certificate is judged at the token's own time. Revocation isn't checked: that would need the network and the authority's cooperation.
51
+ - A Bitcoin header proves its own work, but its height is the word of whoever supplied it. The CLI asks blockstream.info; check against your own node if it matters.
52
+ - It verifies. It never grades a person or a work, and it has no opinion on whether something is genuine.
53
+
54
+ CC0.
package/cli.mjs ADDED
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env node
2
+ // origin-verify file <path> [url] finds a file's records by what it still is, and checks each one
3
+ // origin-verify record <index> [url] one record: signature, place in the tree, witnesses, clocks, Bitcoin
4
+ // origin-verify pack <index> <out> [url] saves a pack that checks offline, with no help from anyone
5
+ // origin-verify check <pack> checks a saved pack. Reads no network
6
+ // origin-verify proof <file> [url] a signer's saved proof file, with its reveal
7
+ // origin-verify audit [url] the whole log, recomputed from its public tiles
8
+ import { readFileSync, writeFileSync } from "node:fs";
9
+ import trust from "./trust.mjs";
10
+ import { auditLog, checkCheckpoint, findRecords, hashFile, packRecord, readEntries, verifyPack } from "./index.mjs";
11
+
12
+ const [cmd, a, b, c] = process.argv.slice(2);
13
+ const baseOf = (u) => (u ?? "https://log.333.eco/origin/").replace(/\/?$/, "/");
14
+ const getter = (base) => async (path) => { const r = await fetch(base + path); if (r.status === 404) return null; if (!r.ok) throw new Error(`${path}: ${r.status}`); return new Uint8Array(await r.arrayBuffer()); };
15
+ const say = (o) => { console.log(JSON.stringify(o, null, 2)); process.exit(o.ok === false ? 1 : 0); };
16
+ /** One public source for block headers. Each header proves its own work, but the height is this source's word: compare with your own node if it matters. */
17
+ const header = async (height) => {
18
+ const hash = await (await fetch(`https://blockstream.info/api/block-height/${height}`)).text();
19
+ const hx = await (await fetch(`https://blockstream.info/api/block/${hash}/header`)).text();
20
+ return Uint8Array.from(hx.match(/../g), (x) => parseInt(x, 16));
21
+ };
22
+ const latest = async (get) => new TextDecoder().decode(await get("checkpoint"));
23
+
24
+ if (cmd === "audit") { const get = getter(baseOf(a)); say(await auditLog(get, await latest(get), trust)); }
25
+ else if (cmd === "record") { const get = getter(baseOf(b)); say(await verifyPack(await packRecord(get, Number(a), trust, { header }), trust)); }
26
+ else if (cmd === "pack") { const get = getter(baseOf(c)); writeFileSync(b, JSON.stringify(await packRecord(get, Number(a), trust, { header }), null, 2)); console.log(`saved ${b}`); }
27
+ else if (cmd === "check") say(await verifyPack(JSON.parse(readFileSync(a, "utf8")), trust));
28
+ else if (cmd === "proof") { const get = getter(baseOf(b)), p = JSON.parse(readFileSync(a, "utf8")); say(await verifyPack(await packRecord(get, p.index, trust, { opening: p.opening, header }), trust)); }
29
+ else if (cmd === "file") {
30
+ const get = getter(baseOf(b)), cp = await checkCheckpoint(await latest(get), trust);
31
+ if (!cp.ok) say(cp);
32
+ const hashes = await hashFile(readFileSync(a));
33
+ const found = await findRecords(get, cp.size, hashes);
34
+ const records = [];
35
+ for (const m of found) records.push({ how: m.how, ...(m.distance !== undefined ? { distance: m.distance } : {}), ...(m.withdrawnAt ? { withdrawnAt: m.withdrawnAt } : {}), claim: m.entry.claim, ...(await verifyPack(await packRecord(get, m.index, trust, { header }), trust)) });
36
+ say({ ok: true, hashes, logSize: cp.size, records });
37
+ } else { console.error("usage: origin-verify file|record|pack|check|proof|audit …"); process.exit(2); }
package/clocks.mjs ADDED
@@ -0,0 +1,178 @@
1
+ // The outside clocks, checked with no help: RFC 3161 tokens against pinned roots, and OpenTimestamps proofs against Bitcoin headers.
2
+ // ⛔ Neither says who did anything. A token says this hash existed by this time, on the authority's word; a block says it existed by that block.
3
+ import { concat, der, derSigToRaw, eq, hex, kids, oid, sha256, text } from "./primitives.mjs";
4
+
5
+ const HASHES = { "2.16.840.1.101.3.4.2.1": "SHA-256", "2.16.840.1.101.3.4.2.2": "SHA-384", "2.16.840.1.101.3.4.2.3": "SHA-512", "1.3.14.3.2.26": "SHA-1" };
6
+ const SIG_HASH = { "1.2.840.113549.1.1.11": "SHA-256", "1.2.840.113549.1.1.12": "SHA-384", "1.2.840.113549.1.1.13": "SHA-512", "1.2.840.10045.4.3.2": "SHA-256", "1.2.840.10045.4.3.3": "SHA-384", "1.2.840.10045.4.3.4": "SHA-512" };
7
+ const OID_RSA = "1.2.840.113549.1.1.1", OID_PSS = "1.2.840.113549.1.1.10", OID_EC = "1.2.840.10045.2.1";
8
+ const CURVES = { "1.2.840.10045.3.1.7": ["P-256", 32], "1.3.132.0.34": ["P-384", 48], "1.3.132.0.35": ["P-521", 66] };
9
+ const digest = async (name, data) => new Uint8Array(await crypto.subtle.digest(name, data));
10
+
11
+ function parseTime(n) {
12
+ const s = text(n.value), m = n.tag === 0x17 ? /^(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)Z$/.exec(s) : /^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(?:\.\d+)?Z$/.exec(s);
13
+ if (!m) throw new Error("a time this reader does not know");
14
+ const year = n.tag === 0x17 ? (Number(m[1]) >= 50 ? 1900 : 2000) + Number(m[1]) : Number(m[1]);
15
+ return Date.UTC(year, Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6]));
16
+ }
17
+ function parseCert(rawDer) {
18
+ const cert = der(rawDer), [tbs, sigAlg, sigBits] = kids(cert), t = kids(tbs);
19
+ let i = t[0].tag === 0xa0 ? 1 : 0;
20
+ const serial = t[i], issuer = t[i + 2], validity = kids(t[i + 3]), subject = t[i + 4], spki = t[i + 5];
21
+ const out = { raw: cert.raw, tbs: tbs.raw, sigAlg: kids(sigAlg), signature: sigBits.value.subarray(1), serial: serial.value, issuer: issuer.raw, subject: subject.raw, spki: spki.raw, notBefore: parseTime(validity[0]), notAfter: parseTime(validity[1]), ca: false, eku: [], ski: null };
22
+ const ext = t.find((n) => n.tag === 0xa3);
23
+ if (ext) for (const e of kids(kids(ext)[0])) {
24
+ const parts = kids(e), id = oid(parts[0]), value = der(parts[parts.length - 1].value);
25
+ if (id === "2.5.29.19") out.ca = kids(value).some((k) => k.tag === 0x01 && k.value[0] !== 0);
26
+ if (id === "2.5.29.37") out.eku = kids(value).map(oid);
27
+ if (id === "2.5.29.14") out.ski = value.value;
28
+ }
29
+ return out;
30
+ }
31
+ /** A signature under a certificate's public key, whichever of the algorithms a TSA uses. `hashName` comes from the signature algorithm or SignerInfo. */
32
+ async function checkSig(spkiDer, algKids, signature, data, signerDigest) {
33
+ const spki = kids(der(spkiDer)), keyAlg = kids(spki[0]), keyOid = oid(keyAlg[0]), sigOid = oid(algKids[0]);
34
+ if (keyOid === OID_EC) {
35
+ const [curve, size] = CURVES[oid(keyAlg[1])] ?? [];
36
+ if (!curve) throw new Error("an unknown curve");
37
+ const hash = SIG_HASH[sigOid] ?? signerDigest;
38
+ return crypto.subtle.verify({ name: "ECDSA", hash }, await crypto.subtle.importKey("spki", spkiDer, { name: "ECDSA", namedCurve: curve }, false, ["verify"]), derSigToRaw(signature, size), data);
39
+ }
40
+ if (keyOid !== OID_RSA && keyOid !== OID_PSS) throw new Error("an unknown key type");
41
+ if (sigOid === OID_PSS) {
42
+ const p = kids(algKids[1]), hashAlg = kids(kids(p[0])[0]), hash = HASHES[oid(hashAlg[0])], salt = p.find((n) => n.tag === 0xa2);
43
+ const saltLength = salt ? kids(salt)[0].value.reduce((a, b) => a * 256 + b, 0) : 20;
44
+ return crypto.subtle.verify({ name: "RSA-PSS", saltLength }, await crypto.subtle.importKey("spki", spkiDer, { name: "RSA-PSS", hash }, false, ["verify"]), signature, data);
45
+ }
46
+ const hash = SIG_HASH[sigOid] ?? (sigOid === OID_RSA ? signerDigest : null);
47
+ if (!hash) throw new Error(`a signature algorithm this reader refuses: ${sigOid}`);
48
+ return crypto.subtle.verify("RSASSA-PKCS1-v1_5", await crypto.subtle.importKey("spki", spkiDer, { name: "RSASSA-PKCS1-v1_5", hash }, false, ["verify"]), signature, data);
49
+ }
50
+
51
+ /**
52
+ * RFC 3161 and CMS by hand: the token's hash is this data's, the authority signed that token, and its certificate leads to a root the caller pinned.
53
+ * Certificates are judged at the token's own time, because an archive outlives them. ⚠️ Revocation is not checked: that would need the network and the CA's cooperation.
54
+ * ⚠️ A token has parts nobody signs (status text, the digest list, spare copies of certificates), so a changed byte there passes, and rightly: nothing here reads meaning from them.
55
+ */
56
+ export async function checkTimestamp(tsr, data, rootsDer) {
57
+ const fail = (why) => ({ ok: false, why });
58
+ try {
59
+ const top = der(tsr);
60
+ if (top.tag !== 0x30 || top.end !== tsr.length) return fail("not a time stamp response");
61
+ const resp = kids(top);
62
+ const status = kids(resp[0])[0].value.reduce((a, b) => a * 256 + b, 0);
63
+ if (status > 1) return fail(`the authority refused: status ${status}`);
64
+ if (!resp[1]) return fail("the response carries no token");
65
+ const content = kids(resp[1]);
66
+ if (oid(content[0]) !== "1.2.840.113549.1.7.2") return fail("the token is not signed data");
67
+ const signed = kids(kids(content[1])[0]);
68
+ const encap = kids(signed[2]);
69
+ if (oid(encap[0]) !== "1.2.840.113549.1.9.16.1.4") return fail("the token holds something other than a time stamp");
70
+ const inner = kids(encap[1])[0];
71
+ if (inner.tag !== 0x04) return fail("the token's contents are not an octet string");
72
+ const eContent = inner.value;
73
+ const info = kids(der(eContent)), imprint = kids(info[2]);
74
+ if (oid(kids(imprint[0])[0]) !== "2.16.840.1.101.3.4.2.1") return fail("the token's hash is not SHA-256");
75
+ if (!eq(imprint[1].value, sha256(data))) return fail("the token speaks of different data");
76
+ const genNode = info.find((n) => n.tag === 0x18);
77
+ if (!genNode) return fail("the token states no time");
78
+ const time = parseTime(genNode);
79
+
80
+ const certs = (signed.find((n) => n.tag === 0xa0) ? kids(signed.find((n) => n.tag === 0xa0)) : []).filter((n) => n.tag === 0x30).map((n) => parseCert(n.raw));
81
+ const signerInfo = kids(kids(signed[signed.length - 1])[0]);
82
+ const sid = signerInfo[1];
83
+ let leaf;
84
+ if (sid.tag === 0x80) leaf = certs.find((c) => c.ski && eq(c.ski, sid.value));
85
+ else { const [iss, ser] = kids(sid); leaf = certs.find((c) => eq(c.issuer, iss.raw) && eq(c.serial, ser.value)); }
86
+ if (!leaf) return fail("the token does not carry its signer's certificate");
87
+
88
+ const signedAttrs = signerInfo.find((n) => n.tag === 0xa0);
89
+ const hashName = HASHES[oid(kids(signerInfo[2])[0])];
90
+ if (!signedAttrs || !hashName || hashName === "SHA-1") return fail("the token's digest is not one this reader accepts");
91
+ const md = kids(signedAttrs).find((a) => oid(kids(a)[0]) === "1.2.840.113549.1.9.4");
92
+ if (!md || !eq(der(kids(kids(md)[1])[0].raw).value, await digest(hashName, eContent))) return fail("the signed digest does not match the token");
93
+ const asSet = concat(new Uint8Array([0x31]), signedAttrs.raw.subarray(1)); // the signature covers the attributes as a SET (RFC 5652 §5.4)
94
+ const after = signerInfo.indexOf(signedAttrs), sigAlg = kids(signerInfo[after + 1]), signature = signerInfo[after + 2].value;
95
+ if (!(await checkSig(leaf.spki, sigAlg, signature, asSet, hashName))) return fail("the authority's signature does not verify");
96
+ if (!leaf.eku.includes("1.3.6.1.5.5.7.3.8")) return fail("the signer's certificate is not for time stamping");
97
+
98
+ const roots = rootsDer.map(parseCert);
99
+ const pool = [...certs, ...roots];
100
+ let cur = leaf;
101
+ for (let depth = 0; depth < 8; depth++) {
102
+ if (time < cur.notBefore || time > cur.notAfter) return fail("a certificate was not valid at the token's time");
103
+ if (roots.some((r) => eq(r.raw, cur.raw))) return { ok: true, time: new Date(time).toISOString() };
104
+ const candidates = pool.filter((c) => eq(c.subject, cur.issuer) && !eq(c.raw, cur.raw));
105
+ let next = null;
106
+ for (const c of candidates) { try { if (c.ca && await checkSig(c.spki, cur.sigAlg, cur.signature, cur.tbs)) { next = c; break; } } catch { /* try the next one */ } }
107
+ if (!next) return fail("the certificate chain does not reach a pinned root");
108
+ cur = next;
109
+ }
110
+ return fail("the certificate chain is too long");
111
+ } catch (e) { return fail(`the token cannot be read: ${e.message}`); }
112
+ }
113
+
114
+ // ── OpenTimestamps ───────────────────────────────────────────────────────────────────────────────────────────────
115
+ const OTS_MAGIC = "004f70656e54696d657374616d7073000050726f6f6600bf89e2e884e89294";
116
+ const TAG_PENDING = "83dfe30d2ef90c8e", TAG_BITCOIN = "0588960d73d71901";
117
+ function reader(b) {
118
+ let i = 0;
119
+ const byte = () => { if (i >= b.length) throw new Error("truncated"); return b[i++]; };
120
+ const bytes = (n) => { if (i + n > b.length) throw new Error("truncated"); const v = b.subarray(i, i + n); i += n; return v; };
121
+ const varuint = () => { let v = 0, s = 0, c; do { c = byte(); v += (c & 0x7f) * 2 ** s; s += 7; if (s > 49) throw new Error("varuint too long"); } while (c & 0x80); return v; };
122
+ return { byte, bytes, varuint, varbytes: () => bytes(varuint()), at: () => i, done: () => i === b.length };
123
+ }
124
+ function walk(r, msg, out, depth = 0) {
125
+ if (depth > 256) throw new Error("too deep");
126
+ const one = (tag) => {
127
+ if (tag === 0x00) {
128
+ const t = hex(r.bytes(8)), payload = reader(r.varbytes());
129
+ if (t === TAG_BITCOIN) out.bitcoin.push({ height: payload.varuint(), msg });
130
+ else if (t === TAG_PENDING) out.pending.push(text(payload.varbytes()));
131
+ return;
132
+ }
133
+ let next;
134
+ if (tag === 0xf0) next = concat(msg, r.varbytes());
135
+ else if (tag === 0xf1) next = concat(r.varbytes(), msg);
136
+ else if (tag === 0x08) next = sha256(msg);
137
+ else throw new Error(`an operation this reader does not know: ${tag}`);
138
+ walk(r, next, out, depth + 1);
139
+ };
140
+ let tag = r.byte();
141
+ while (tag === 0xff) { one(r.byte()); tag = r.byte(); }
142
+ one(tag);
143
+ }
144
+ const sha256d = (b) => sha256(sha256(b));
145
+ /** A real header proves its own work; without this, anyone could supply a header holding whatever root they like. Height still comes from the header's source. */
146
+ function headerHasWork(h) {
147
+ if (h.length !== 80) return false;
148
+ const bits = (h[75] << 24) | (h[74] << 16) | (h[73] << 8) | h[72];
149
+ const exp = bits >>> 24, mant = BigInt(bits & 0x007fffff), target = exp <= 3 ? mant >> BigInt(8 * (3 - exp)) : mant << BigInt(8 * (exp - 3));
150
+ // Bitcoin's easiest target ever: nobody can claim work with an easier one.
151
+ if (target <= 0n || target > 0xffffn << 208n) return false;
152
+ const pow = sha256d(h); let v = 0n; for (let i = 31; i >= 0; i--) v = (v << 8n) + BigInt(pow[i]);
153
+ return v <= target;
154
+ }
155
+ /**
156
+ * `digest` is what the proof must speak of. Each Bitcoin line reads verified: true when the header (from `header(height)`) holds this branch's result, false when it does not, null when no header was given.
157
+ * A pending line is only a calendar's promise, listed and never counted.
158
+ */
159
+ export async function checkOts(proof, digest, { header } = {}) {
160
+ try {
161
+ const r = reader(proof);
162
+ if (hex(r.bytes(31)) !== OTS_MAGIC) return { ok: false, why: "not an OpenTimestamps proof" };
163
+ if (r.byte() !== 1 || r.byte() !== 0x08) return { ok: false, why: "not a version 1, SHA-256 proof" };
164
+ if (!eq(r.bytes(32), digest)) return { ok: false, why: "the proof speaks of different data" };
165
+ const seen = { bitcoin: [], pending: [] };
166
+ walk(r, digest, seen);
167
+ if (!r.done()) return { ok: false, why: "trailing bytes" };
168
+ const bitcoin = [];
169
+ for (const a of seen.bitcoin) {
170
+ const h = header ? await header(a.height) : null;
171
+ if (!h) { bitcoin.push({ height: a.height, verified: null }); continue; }
172
+ const good = headerHasWork(h) && eq(h.subarray(36, 68), a.msg);
173
+ const dv = new DataView(h.buffer, h.byteOffset, 80);
174
+ bitcoin.push({ height: a.height, verified: good, ...(good ? { time: new Date(dv.getUint32(68, true) * 1000).toISOString() } : {}) });
175
+ }
176
+ return { ok: true, bitcoin, pending: [...new Set(seen.pending)] };
177
+ } catch (e) { return { ok: false, why: `the proof cannot be read: ${e.message}` }; }
178
+ }
package/index.mjs ADDED
@@ -0,0 +1,376 @@
1
+ // @333eco/origin-verify. CC0. Checks a B-Origin record with no help from its operator: no runtime dependencies, in a browser or in Node.
2
+ // ⚠️ Written apart from the service on purpose: it shares no code with services/b, and it checks proofs with RFC 9162's
3
+ // iterative algorithms where the service builds them with RFC 6962's recursion. One author's blind spots still apply.
4
+ import { b64, b64u, concat, der, derSigToRaw, ed25519, eq, hmacSha256, sha256, text, toB64, toB64u, u32, u64, utf8 } from "./primitives.mjs";
5
+ import { checkOts, checkTimestamp } from "./clocks.mjs";
6
+ export { checkOts, checkTimestamp } from "./clocks.mjs";
7
+ export { hashFile, decodePng, phashOf, phashDistance } from "./media.mjs";
8
+
9
+ const NODE = new Uint8Array([1]), LEAF = new Uint8Array([0]);
10
+ const odd = (n) => n % 2 === 1;
11
+ const half = (n) => Math.floor(n / 2);
12
+
13
+ export const hashLeaf = (entry) => sha256(LEAF, entry);
14
+ const hashNode = (l, r) => sha256(NODE, l, r);
15
+
16
+ /** RFC 8785, for the only values entries hold. */
17
+ export function canonical(v) {
18
+ if (v === null || typeof v === "boolean" || typeof v === "string") return JSON.stringify(v);
19
+ if (typeof v === "number") { if (!Number.isSafeInteger(v)) throw new Error("non-integer number in an entry"); return String(v); }
20
+ if (Array.isArray(v)) return "[" + v.map(canonical).join(",") + "]";
21
+ return "{" + Object.keys(v).sort().map((k) => JSON.stringify(k) + ":" + canonical(v[k])).join(",") + "}";
22
+ }
23
+
24
+ /** RFC 9162 §2.1.3.2. */
25
+ export function checkInclusion(leaf, index, size, proof, root) {
26
+ if (index < 0 || index >= size) return false;
27
+ let fn = index, sn = size - 1, r = leaf;
28
+ for (const p of proof) {
29
+ if (sn === 0) return false;
30
+ if (odd(fn) || fn === sn) {
31
+ r = hashNode(p, r);
32
+ if (!odd(fn)) while (!odd(fn) && fn !== 0) { fn = half(fn); sn = half(sn); }
33
+ } else r = hashNode(r, p);
34
+ fn = half(fn); sn = half(sn);
35
+ }
36
+ return sn === 0 && eq(r, root);
37
+ }
38
+ /** RFC 9162 §2.1.4.2. */
39
+ export function checkConsistency(first, second, proof, firstRoot, secondRoot) {
40
+ if (first > second) return false;
41
+ if (first === second) return proof.length === 0 && eq(firstRoot, secondRoot);
42
+ if (first === 0) return proof.length === 0;
43
+ if (proof.length === 0) return false;
44
+ const path = Number.isInteger(Math.log2(first)) ? [firstRoot, ...proof] : proof;
45
+ let fn = first - 1, sn = second - 1;
46
+ while (odd(fn)) { fn = half(fn); sn = half(sn); }
47
+ let fr = path[0], sr = path[0];
48
+ for (const c of path.slice(1)) {
49
+ if (sn === 0) return false;
50
+ if (odd(fn) || fn === sn) {
51
+ fr = hashNode(c, fr); sr = hashNode(c, sr);
52
+ if (!odd(fn)) while (!odd(fn) && fn !== 0) { fn = half(fn); sn = half(sn); }
53
+ } else sr = hashNode(sr, c);
54
+ fn = half(fn); sn = half(sn);
55
+ }
56
+ return sn === 0 && eq(fr, firstRoot) && eq(sr, secondRoot);
57
+ }
58
+
59
+ // ── signed notes ─────────────────────────────────────────────────────────────────────────────────────────────────
60
+ function parseVkey(v) {
61
+ const m = /^([^+\s]+)\+([0-9a-f]{8})\+(\S+)$/.exec(v);
62
+ if (!m) throw new Error("bad vkey");
63
+ const all = b64(m[3]), type = all[0], raw = all.subarray(1), id = Uint8Array.from(m[2].match(/../g), (x) => parseInt(x, 16));
64
+ if (!eq(sha256(utf8(m[1] + "\n"), new Uint8Array([type]), raw).subarray(0, 4), id)) throw new Error("vkey hash mismatch");
65
+ return { name: m[1], id, type, raw };
66
+ }
67
+ /** Splits a note into its text and signature lines. */
68
+ function parseNote(note) {
69
+ const cut = note.indexOf("\n\n");
70
+ if (cut < 0) throw new Error("not a signed note");
71
+ const body = note.slice(0, cut + 1), sigs = [];
72
+ for (const l of note.slice(cut + 2).split("\n")) {
73
+ if (!l) continue;
74
+ const m = /^— (\S+) (\S+)$/.exec(l);
75
+ if (!m) throw new Error("bad signature line");
76
+ sigs.push({ name: m[1], bytes: b64(m[2]) });
77
+ }
78
+ return { body, sigs };
79
+ }
80
+ /** The part of a checkpoint every clock stamps: it does not change as cosignatures arrive. */
81
+ export const checkpointBody = (note) => note.slice(0, note.indexOf("\n\n") + 1);
82
+
83
+ /** Checks the log's own signature; counts distinct witnesses with a good cosignature. A bad line is simply not counted. */
84
+ export async function checkCheckpoint(note, trust) {
85
+ const { body, sigs } = parseNote(note);
86
+ const [origin, size, root] = body.split("\n");
87
+ if (origin !== trust.origin) return { ok: false, why: "another log's checkpoint" };
88
+ if (!/^(0|[1-9]\d*)$/.test(size)) return { ok: false, why: "bad size" };
89
+ const log = parseVkey(trust.logVkey), bodyBytes = utf8(body);
90
+ const mine = sigs.find((s) => s.name === log.name && eq(s.bytes.subarray(0, 4), log.id));
91
+ if (!mine || !(await ed25519(log.raw, bodyBytes, mine.bytes.subarray(4)))) return { ok: false, why: "the log's signature does not verify" };
92
+ const witnesses = new Set();
93
+ for (const v of trust.witnesses ?? []) {
94
+ const w = parseVkey(v);
95
+ if (w.type !== 0x04) continue;
96
+ for (const s of sigs) {
97
+ if (s.name !== w.name || s.bytes.length !== 76 || !eq(s.bytes.subarray(0, 4), w.id)) continue;
98
+ const time = new DataView(s.bytes.buffer, s.bytes.byteOffset + 4, 8).getBigUint64(0);
99
+ if (await ed25519(w.raw, utf8(`cosignature/v1\ntime ${time}\n${body}`), s.bytes.subarray(12))) witnesses.add(w.name);
100
+ }
101
+ }
102
+ return { ok: true, size: Number(size), root: b64(root), body, witnesses: [...witnesses] };
103
+ }
104
+
105
+ // ── entries ──────────────────────────────────────────────────────────────────────────────────────────────────────
106
+ const DOMAIN = (t, v) => utf8(`b-origin/${t}/v${v}\0`);
107
+ const importP256 = (spki) => crypto.subtle.importKey("spki", spki, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
108
+ /** The operator's witness signature over an entry. */
109
+ export async function checkWitnessSignature(entry, trust) {
110
+ const key = trust.recordKeys?.[entry.kid];
111
+ if (!key) return false;
112
+ const { witnessSig, ...rest } = entry;
113
+ if (typeof witnessSig !== "string") return false;
114
+ try {
115
+ return await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, await importP256(b64(key)), b64u(witnessSig), concat(DOMAIN(entry.t, entry.v), utf8(canonical(rest))));
116
+ } catch { return false; }
117
+ }
118
+
119
+ // Just enough CBOR to read a COSE public key: maps, integers and byte strings.
120
+ function cborMap(buf) {
121
+ let i = 0;
122
+ const head = () => { const b = buf[i++], maj = b >> 5, a = b & 31; let n = a;
123
+ if (a === 24) n = buf[i++]; else if (a === 25) { n = (buf[i] << 8) | buf[i + 1]; i += 2; } else if (a > 25) throw new Error("unsupported CBOR");
124
+ return [maj, n]; };
125
+ const item = () => { const [maj, n] = head();
126
+ if (maj === 0) return n; if (maj === 1) return -1 - n;
127
+ if (maj === 2) { const v = buf.subarray(i, i + n); i += n; return v; }
128
+ if (maj === 5) { const m = new Map(); for (let k = 0; k < n; k++) { const key = item(); m.set(key, item()); } return m; }
129
+ throw new Error("unsupported CBOR"); };
130
+ return item();
131
+ }
132
+ /** A passkey's signature over `signed`, under the key type its COSE key names. */
133
+ async function checkCose(coseBytes, signed, signature) {
134
+ const m = cborMap(coseBytes), alg = m.get(3);
135
+ if (alg === -8) return ed25519(m.get(-2), signed, signature);
136
+ if (alg === -7) {
137
+ const key = await crypto.subtle.importKey("jwk", { kty: "EC", crv: "P-256", x: toB64u(m.get(-2)), y: toB64u(m.get(-3)), ext: true }, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
138
+ return crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, key, derSigToRaw(signature, 32), signed);
139
+ }
140
+ if (alg === -257) {
141
+ const key = await crypto.subtle.importKey("jwk", { kty: "RSA", n: toB64u(m.get(-1)), e: toB64u(m.get(-2)), ext: true }, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]);
142
+ return crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, signature, signed);
143
+ }
144
+ throw new Error("unsupported key type");
145
+ }
146
+ const lp = (b) => concat(u32(b.length), b);
147
+
148
+ /**
149
+ * SPEC §6.3. With a signer's opening, the proof stops depending on the operator: a passkey whose public key is X signed exactly this claim.
150
+ * ⛔ It never says who imagined the work, or that a person holds one account.
151
+ */
152
+ export async function checkReveal(entry, opening, trust) {
153
+ const fail = (why) => ({ ok: false, why });
154
+ const raw = Object.fromEntries(["salt", "nonce", "authenticatorData", "clientDataJSON", "signature", "credentialPublicKey"].map((k) => [k, b64u(String(opening?.[k] ?? ""))]));
155
+ const commitment = sha256(utf8("b-origin/assertion/v1\0"), lp(raw.salt), lp(raw.authenticatorData), lp(raw.clientDataJSON), lp(raw.signature), lp(raw.credentialPublicKey));
156
+ if (toB64u(commitment) !== entry.assertionCommitment) return fail("the opening does not match the record's commitment");
157
+ const challenge = entry.t === "record"
158
+ ? sha256(utf8("b-origin/claim/v1\0"), raw.nonce, sha256(utf8(canonical(entry.claim))))
159
+ : entry.t === "withdraw" ? sha256(utf8("b-origin/withdraw/v1\0"), raw.nonce, u64(entry.target)) : null;
160
+ if (!challenge) return fail("nothing to reveal in this entry");
161
+ if (toB64u(challenge) !== entry.claimCommitment) return fail("the challenge does not bind this claim");
162
+ let cd;
163
+ try { cd = JSON.parse(text(raw.clientDataJSON)); } catch { return fail("bad client data"); }
164
+ if (cd.type !== "webauthn.get" || cd.origin !== trust.webOrigin || cd.challenge !== entry.claimCommitment) return fail("the assertion was made elsewhere or for something else");
165
+ const auth = raw.authenticatorData;
166
+ if (auth.length < 37 || !eq(auth.subarray(0, 32), sha256(utf8(trust.rpId)))) return fail("the assertion names another site");
167
+ if ((auth[32] & 0x05) !== 0x05) return fail("the passkey's owner was not present and verified");
168
+ let good;
169
+ try { good = await checkCose(raw.credentialPublicKey, concat(auth, sha256(raw.clientDataJSON)), raw.signature); } catch (e) { return fail(e.message); }
170
+ if (!good) return fail("the passkey's signature does not verify");
171
+ return { ok: true, passkeyPublicKey: opening.credentialPublicKey };
172
+ }
173
+ /** SPEC §6.4: which of these entries carry this person's tag. Anything here they did not make is a forgery to report. */
174
+ export function findMine(tagKey, entries) {
175
+ const key = b64u(tagKey), out = [];
176
+ for (const e of entries) {
177
+ if (e.ownerTag === undefined) continue;
178
+ if (toB64u(hmacSha256(key, utf8("b-origin/tag/v1\0"), u64(e.index))) === e.ownerTag) out.push(e.index);
179
+ }
180
+ return out;
181
+ }
182
+
183
+ // ── reading the log ──────────────────────────────────────────────────────────────────────────────────────────────
184
+ const tilePath = (kind, n, width) => {
185
+ let s = "", v = n, first = true;
186
+ do { const part = String(v % 1000).padStart(3, "0"); s = (first ? part : "x" + part + "/") + s; first = false; v = Math.floor(v / 1000); } while (v > 0);
187
+ return `tile/${kind}/${s}${width ? `.p/${width}` : ""}`;
188
+ };
189
+ function entriesOf(bundle) {
190
+ const out = [];
191
+ for (let i = 0; i < bundle.length;) { const n = (bundle[i] << 8) | bundle[i + 1]; out.push(bundle.subarray(i + 2, i + 2 + n)); i += 2 + n; }
192
+ return out;
193
+ }
194
+ const merkle = (hashes) => {
195
+ if (hashes.length === 1) return hashes[0];
196
+ let k = 1; while (k * 2 < hashes.length) k *= 2;
197
+ return hashNode(merkle(hashes.slice(0, k)), merkle(hashes.slice(k)));
198
+ };
199
+ export const treeRoot = (leaves) => (leaves.length ? merkle(leaves) : sha256(new Uint8Array(0)));
200
+ /** Reads every entry at this size from public tiles. `get(path)` returns bytes or null. */
201
+ export async function readEntries(get, size) {
202
+ const out = [];
203
+ for (let n = 0; n * 256 < size; n++) {
204
+ const width = n * 256 + 256 <= size ? undefined : size % 256;
205
+ const b = await get(tilePath("entries", n, width));
206
+ if (!b) throw new Error(`missing entry bundle ${n}`);
207
+ const es = entriesOf(new Uint8Array(b));
208
+ if (es.length !== (width ?? 256)) throw new Error(`entry bundle ${n} has the wrong length`);
209
+ out.push(...es);
210
+ }
211
+ return out;
212
+ }
213
+ /**
214
+ * The full audit: recompute the tree from every entry, and hold the published hash tiles to it.
215
+ * A tile or bundle changed anywhere fails here. It costs a read of the whole log; a single record needs only checkInclusion.
216
+ */
217
+ export async function auditLog(get, note, trust) {
218
+ const cp = await checkCheckpoint(note, trust);
219
+ if (!cp.ok) return { ok: false, why: cp.why };
220
+ let entries;
221
+ try { entries = await readEntries(get, cp.size); } catch (e) { return { ok: false, why: e.message }; }
222
+ const leaves = entries.map(hashLeaf);
223
+ if (!eq(treeRoot(leaves), cp.root)) return { ok: false, why: "the entries do not produce the checkpoint's root" };
224
+ for (let n = 0; n * 256 < cp.size; n++) {
225
+ const width = n * 256 + 256 <= cp.size ? undefined : cp.size % 256;
226
+ const t = await get(tilePath(0, n, width));
227
+ if (!t || !eq(new Uint8Array(t), concat(...leaves.slice(n * 256, n * 256 + (width ?? 256))))) return { ok: false, why: `hash tile ${n} does not match the entries` };
228
+ }
229
+ for (const [i, bytes] of entries.entries()) {
230
+ const s = text(bytes), e = JSON.parse(s);
231
+ if (e.index !== i) return { ok: false, why: `the entry at ${i} says it belongs at ${e.index}` };
232
+ if (canonical(e) !== s) return { ok: false, why: `the entry at ${i} is not canonical` };
233
+ if (e.t !== "void" && !(await checkWitnessSignature(e, trust))) return { ok: false, why: `the entry at ${i} has no valid witness signature` };
234
+ }
235
+ return { ok: true, size: cp.size, witnesses: cp.witnesses, entries: entries.length };
236
+ }
237
+ /** The inclusion proof for one entry, computed from the entries themselves. */
238
+ export function proofFor(leaves, index) {
239
+ const path = (m, lo, hi) => {
240
+ if (hi - lo === 1) return [];
241
+ let k = 1; while (k * 2 < hi - lo) k *= 2;
242
+ return m < k ? [...path(m, lo, lo + k), merkle(leaves.slice(lo + k, hi))] : [...path(m - k, lo + k, hi), merkle(leaves.slice(lo, lo + k))];
243
+ };
244
+ return path(index, 0, leaves.length);
245
+ }
246
+ /** RFC 6962 §2.1.2: that the first `first` leaves are a prefix of these. */
247
+ export function consistencyFor(leaves, first) {
248
+ const sub = (m, lo, hi, whole) => {
249
+ if (m === hi - lo) return whole ? [] : [merkle(leaves.slice(lo, hi))];
250
+ let k = 1; while (k * 2 < hi - lo) k *= 2;
251
+ return m <= k ? [...sub(m, lo, lo + k, whole), merkle(leaves.slice(lo + k, hi))] : [...sub(m - k, lo + k, hi, false), merkle(leaves.slice(lo, lo + k))];
252
+ };
253
+ return first === 0 || first === leaves.length ? [] : sub(first, 0, leaves.length, true);
254
+ }
255
+
256
+ /** Finds records of a file by what it still is. The whole log is public, so no lookup service learns what is being checked (SPEC §6.5). */
257
+ export async function findRecords(get, size, hashes, { maxDistance = 8 } = {}) {
258
+ const { phashDistance } = await import("./media.mjs");
259
+ const out = [], withdrawn = new Map();
260
+ for (const bytes of await readEntries(get, size)) {
261
+ const e = JSON.parse(text(bytes));
262
+ if (e.t === "withdraw") { withdrawn.set(e.target, e.witnessedAt); continue; }
263
+ if (e.t !== "record") continue;
264
+ const c = e.claim;
265
+ if (hashes.sha256 && c.sha256 === hashes.sha256) out.push({ index: e.index, how: "exact", entry: e });
266
+ else if (hashes.pixels && c.pixels === hashes.pixels) out.push({ index: e.index, how: "same pixels", entry: e });
267
+ else if (hashes.phash && c.phash) { const distance = phashDistance(hashes.phash, c.phash); if (distance <= maxDistance) out.push({ index: e.index, how: "similar", distance, entry: e }); }
268
+ }
269
+ return out.map((m) => (withdrawn.has(m.index) ? { ...m, withdrawnAt: withdrawn.get(m.index) } : m));
270
+ }
271
+
272
+ /**
273
+ * Checks one bundle: { entry, checkpoint, inclusion: [base64…], opening? }. It needs no network and no operator.
274
+ * Each state stands alone (§6.4). A failed check says so; it is never softened into a lesser state.
275
+ */
276
+ export async function verifyBundle(bundle, trust) {
277
+ const fail = (why) => ({ ok: false, why });
278
+ const { entry, checkpoint, inclusion, opening } = bundle;
279
+ if (!entry || !checkpoint || !Array.isArray(inclusion)) return fail("the bundle is incomplete");
280
+ if (entry.t !== "record" && entry.t !== "withdraw") return fail("this entry is not a record");
281
+ if (!(await checkWitnessSignature(entry, trust))) return fail("the witness signature does not verify");
282
+ const cp = await checkCheckpoint(checkpoint, trust);
283
+ if (!cp.ok) return fail(cp.why);
284
+ const leaf = hashLeaf(utf8(canonical(entry)));
285
+ if (!checkInclusion(leaf, entry.index, cp.size, inclusion.map((p) => b64(p)), cp.root)) return fail("the record is not in the tree this checkpoint signs");
286
+ const quorum = trust.witnessQuorum ?? Infinity;
287
+ const out = {
288
+ ok: true, index: entry.index, size: cp.size, included: true,
289
+ witnessed: cp.witnesses.length >= quorum, witnesses: cp.witnesses, quorum, witnessLabel: trust.witnessLabel,
290
+ witnessedAt: entry.witnessedAt,
291
+ conclusion: "The operator witnessed this claim at this time and cannot later remove it.",
292
+ };
293
+ if (opening) {
294
+ const r = await checkReveal(entry, opening, trust);
295
+ if (!r.ok) return fail(`reveal: ${r.why}`);
296
+ out.revealed = true;
297
+ out.conclusion = "A passkey whose public key is given here signed exactly this claim.";
298
+ out.passkeyPublicKey = r.passkeyPublicKey;
299
+ }
300
+ return out;
301
+ }
302
+
303
+ // ── a pack: one record and everything needed to check it, offline, with no help from anyone ────────────────────────
304
+ const stampedAfter = (sizes, index) => (sizes ?? []).filter((s) => s > index).sort((a, b) => a - b)[0];
305
+ /** Gathers a pack from the public log. `header(height)` supplies Bitcoin block headers (80 bytes), so the pack keeps them too. */
306
+ export async function packRecord(get, index, trust, { opening, header } = {}) {
307
+ const note = text(await get("checkpoint")), cp = await checkCheckpoint(note, trust);
308
+ if (!cp.ok) throw new Error(cp.why);
309
+ if (index >= cp.size) throw new Error("not yet in the tree: it joins at the next checkpoint");
310
+ const entries = await readEntries(get, cp.size), leaves = entries.map(hashLeaf);
311
+ const pack = { kind: "b-origin-pack", v: 1, entry: JSON.parse(text(entries[index])), checkpoint: note, inclusion: proofFor(leaves, index).map(toB64), ...(opening ? { opening } : {}), stamps: {} };
312
+ const raw = await get("stamps/index.json"), list = raw ? JSON.parse(text(raw)) : {};
313
+ const carry = async (kind, size) => {
314
+ if (size === undefined) return null;
315
+ const archived = text(await get(`checkpoints/${size}`));
316
+ return { kind, size, checkpoint: archived, consistency: consistencyFor(leaves, size).map(toB64) };
317
+ };
318
+ const tsaAt = stampedAfter(list.tsa, index), otsAt = stampedAfter(list.ots, index);
319
+ if (tsaAt !== undefined) {
320
+ const c = await carry("tsa", tsaAt);
321
+ pack.stamps.tsa = { size: c.size, checkpoint: c.checkpoint, consistency: c.consistency, tokens: {} };
322
+ for (const name of Object.keys(trust.tsaRoots ?? {})) { const t = await get(`stamps/${tsaAt}.${name}.tsr`); if (t) pack.stamps.tsa.tokens[name] = toB64(new Uint8Array(t)); }
323
+ }
324
+ if (otsAt !== undefined) {
325
+ const c = await carry("ots", otsAt), proof = await get(`stamps/${otsAt}.ots`);
326
+ if (proof) {
327
+ pack.stamps.ots = { size: c.size, checkpoint: c.checkpoint, consistency: c.consistency, proof: toB64(new Uint8Array(proof)), headers: {} };
328
+ if (header) {
329
+ const seen = await checkOts(new Uint8Array(proof), sha256(utf8(checkpointBody(c.checkpoint))));
330
+ for (const a of seen.bitcoin ?? []) { const h = await header(a.height); if (h) pack.stamps.ots.headers[a.height] = toB64(h); }
331
+ }
332
+ }
333
+ }
334
+ return pack;
335
+ }
336
+ /** Proves a stamped checkpoint held this record, by showing it is a prefix of the tree that does. */
337
+ async function stampedCheckpoint(s, index, cp, trust) {
338
+ const old = await checkCheckpoint(s.checkpoint, trust);
339
+ if (!old.ok) return { ok: false, why: `the stamped checkpoint: ${old.why}` };
340
+ if (old.size !== s.size || old.size <= index) return { ok: false, why: "the stamped checkpoint does not hold this record" };
341
+ if (!checkConsistency(old.size, cp.size, (s.consistency ?? []).map(b64), old.root, cp.root)) return { ok: false, why: "the stamped checkpoint is not a prefix of this log" };
342
+ return { ok: true, body: utf8(old.body) };
343
+ }
344
+ /**
345
+ * Checks a pack. Each of the four states stands alone and none implies another: included · witnessed · timestamped · Bitcoin-anchored.
346
+ * `now` never enters: an authority's token is judged at the time it states.
347
+ */
348
+ export async function verifyPack(pack, trust, { header } = {}) {
349
+ if (pack?.kind !== "b-origin-pack" || pack.v !== 1) return { ok: false, why: "not a B-Origin pack" };
350
+ const out = await verifyBundle(pack, trust);
351
+ if (!out.ok) return out;
352
+ const cp = await checkCheckpoint(pack.checkpoint, trust);
353
+ out.timestamped = []; out.timestampFailures = []; out.bitcoin = []; out.bitcoinPending = [];
354
+ if (pack.stamps?.tsa) {
355
+ const held = await stampedCheckpoint(pack.stamps.tsa, out.index, cp, trust);
356
+ if (!held.ok) return { ok: false, why: `timestamp: ${held.why}` };
357
+ for (const [name, token] of Object.entries(pack.stamps.tsa.tokens ?? {})) {
358
+ const r = await checkTimestamp(b64(token), held.body, (trust.tsaRoots?.[name] ?? []).map(b64));
359
+ if (r.ok) out.timestamped.push({ authority: name, noLaterThan: r.time }); else out.timestampFailures.push({ authority: name, why: r.why });
360
+ }
361
+ }
362
+ if (pack.stamps?.ots) {
363
+ const held = await stampedCheckpoint(pack.stamps.ots, out.index, cp, trust);
364
+ if (!held.ok) return { ok: false, why: `Bitcoin: ${held.why}` };
365
+ const r = await checkOts(b64(pack.stamps.ots.proof), sha256(held.body), {
366
+ header: async (h) => { const saved = pack.stamps.ots.headers?.[h]; if (saved) return b64(saved); return header ? header(h) : null; },
367
+ });
368
+ if (!r.ok) return { ok: false, why: `Bitcoin: ${r.why}` };
369
+ out.bitcoin = r.bitcoin.filter((a) => a.verified).map(({ height, time }) => ({ height, time }));
370
+ out.bitcoinUnchecked = r.bitcoin.filter((a) => a.verified === null).map((a) => a.height);
371
+ out.bitcoinPending = r.pending;
372
+ const bad = r.bitcoin.find((a) => a.verified === false);
373
+ if (bad) return { ok: false, why: `Bitcoin: block ${bad.height} does not commit to this proof` };
374
+ }
375
+ return out;
376
+ }
package/media.mjs ADDED
@@ -0,0 +1,153 @@
1
+ // What a file still is after its metadata is gone. ⭐ `pixels` is /media's `ma:pixels`: SHA-256 of the decoded raster as RGB bytes, alpha dropped, and it must match PIL's
2
+ // `im.convert("RGB").tobytes()` exactly (test: real files against PIL). So PNG is decoded here, byte for byte: a browser's canvas premultiplies alpha and rounds.
3
+ // ⚠️ JPEG, WebP and the rest differ a little from decoder to decoder, so they get no `pixels`; `phash` still finds them. ⛔ Permanent once in the log: a change is a new field.
4
+ import { concat, hex, sha256 } from "./primitives.mjs";
5
+
6
+ const SIG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
7
+ const MAX_PIXELS = 100_000_000;
8
+ export const isPng = (b) => SIG.every((x, i) => b[i] === x);
9
+
10
+ async function inflate(data) {
11
+ const stream = new Blob([data]).stream().pipeThrough(new DecompressionStream("deflate"));
12
+ return new Uint8Array(await new Response(stream).arrayBuffer());
13
+ }
14
+ const ADAM7 = [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]];
15
+
16
+ /** Returns { width, height, rgb, alpha } as 8-bit rasters. `rgb` is null for 16-bit gray, which PIL clips rather than reduces, so no hash could match it. */
17
+ export async function decodePng(b) {
18
+ if (!isPng(b)) throw new Error("not a PNG");
19
+ const dv = new DataView(b.buffer, b.byteOffset, b.length);
20
+ let i = 8, width, height, depth, color, interlace, palette = null, trns = null;
21
+ const idat = [];
22
+ while (i + 8 <= b.length) {
23
+ const len = dv.getUint32(i), type = String.fromCharCode(b[i + 4], b[i + 5], b[i + 6], b[i + 7]), data = b.subarray(i + 8, i + 8 + len);
24
+ if (i + 12 + len > b.length) throw new Error("a truncated PNG");
25
+ if (type === "IHDR") { width = dv.getUint32(i + 8); height = dv.getUint32(i + 12); depth = b[i + 16]; color = b[i + 17]; interlace = b[i + 20]; }
26
+ else if (type === "PLTE") palette = data;
27
+ else if (type === "tRNS") trns = data;
28
+ else if (type === "IDAT") idat.push(data);
29
+ else if (type === "IEND") break;
30
+ i += 12 + len;
31
+ }
32
+ if (!width || !height || !idat.length || width * height > MAX_PIXELS) throw new Error("a PNG this reader will not open");
33
+ const channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[color];
34
+ if (!channels || (color === 3 && !palette)) throw new Error("a PNG with an unknown color type");
35
+ const bitsPerPixel = channels * depth, bpp = Math.max(1, bitsPerPixel >> 3);
36
+ const raw = await inflate(concat(...idat));
37
+ const rgb = new Uint8Array(width * height * 3), alpha = new Uint8Array(width * height).fill(255);
38
+ let at = 0;
39
+ const pass = (w, h, put) => {
40
+ if (w === 0 || h === 0) return;
41
+ const stride = Math.ceil((w * bitsPerPixel) / 8);
42
+ let prev = new Uint8Array(stride);
43
+ for (let y = 0; y < h; y++) {
44
+ if (at + 1 + stride > raw.length) throw new Error("a truncated PNG");
45
+ const filter = raw[at++], line = raw.slice(at, at + stride); at += stride;
46
+ for (let x = 0; x < stride; x++) {
47
+ const a = x >= bpp ? line[x - bpp] : 0, u = prev[x], c = x >= bpp ? prev[x - bpp] : 0;
48
+ if (filter === 1) line[x] += a;
49
+ else if (filter === 2) line[x] += u;
50
+ else if (filter === 3) line[x] += (a + u) >> 1;
51
+ else if (filter === 4) { const p = a + u - c, pa = Math.abs(p - a), pb = Math.abs(p - u), pc = Math.abs(p - c); line[x] += pa <= pb && pa <= pc ? a : pb <= pc ? u : c; }
52
+ else if (filter !== 0) throw new Error("a PNG with an unknown filter");
53
+ }
54
+ for (let px = 0; px < w; px++) put(px, y, line);
55
+ prev = line;
56
+ }
57
+ };
58
+ const sample = (line, px, ch) => {
59
+ if (depth === 8) return line[px * channels + ch];
60
+ if (depth === 16) return line[(px * channels + ch) * 2]; // the high byte, as PIL keeps
61
+ const bit = px * depth, v = (line[bit >> 3] >> (8 - depth - (bit & 7))) & ((1 << depth) - 1);
62
+ return v;
63
+ };
64
+ const scale = depth < 8 && color === 0 ? 255 / ((1 << depth) - 1) : 1;
65
+ const write = (X, Y, line, px) => {
66
+ const o = Y * width, p = (o + X) * 3;
67
+ if (color === 3) {
68
+ const v = sample(line, px, 0);
69
+ rgb[p] = palette[v * 3]; rgb[p + 1] = palette[v * 3 + 1]; rgb[p + 2] = palette[v * 3 + 2];
70
+ if (trns && v < trns.length) alpha[o + X] = trns[v];
71
+ } else if (color === 0 || color === 4) {
72
+ const v = sample(line, px, 0) * scale;
73
+ rgb[p] = rgb[p + 1] = rgb[p + 2] = v;
74
+ if (color === 4) alpha[o + X] = sample(line, px, 1);
75
+ } else {
76
+ rgb[p] = sample(line, px, 0); rgb[p + 1] = sample(line, px, 1); rgb[p + 2] = sample(line, px, 2);
77
+ if (color === 6) alpha[o + X] = sample(line, px, 3);
78
+ }
79
+ };
80
+ if (interlace === 1) {
81
+ for (const [x0, y0, dx, dy] of ADAM7) {
82
+ const w = Math.ceil((width - x0) / dx), h = Math.ceil((height - y0) / dy);
83
+ pass(w, h, (px, y, line) => write(x0 + px * dx, y0 + y * dy, line, px));
84
+ }
85
+ } else pass(width, height, (px, y, line) => write(px, y, line, px));
86
+ return { width, height, rgb: depth === 16 && (color === 0 || color === 4) ? null : rgb, alpha };
87
+ }
88
+
89
+ // ── phash ─────────────────────────────────────────────────────────────────────────────────────────────────────────
90
+ // 64 bits, specified here because they enter a permanent log: over white → luma → an exact box filter to 8×8 → each cell above the mean of all 64 or not, row by row, high bit first.
91
+ // ⭐ Measured 2026-11-03, 150 pictures × 5 re-encodings, 40 of them mirror-symmetric sprites: this finds 99.7% of the same picture at distance ≤ 8 with 0.8% of different pictures near.
92
+ // ⛔ The DCT hash everyone reaches for fails exactly on pixel art: half the coefficients of a symmetric picture are near zero, so their bits are noise (median distance 14 from a JPEG of itself).
93
+ // It is a hint that two pictures look alike, nothing more: an unrelated flat picture can land near.
94
+ export function phashOf({ width, height, rgb, alpha }) {
95
+ // 1000 × luma over white. Whole numbers and divisions only, so every engine agrees to the bit.
96
+ const luma = (x, y) => {
97
+ const p = (y * width + x) * 3, a = alpha ? alpha[y * width + x] : 255, over = (c) => c * a + 255 * (255 - a);
98
+ return (299 * over(rgb[p]) + 587 * over(rgb[p + 1]) + 114 * over(rgb[p + 2])) / 255;
99
+ };
100
+ // Each cell covers W/8 × H/8 source pixels; overlaps are counted in eighths of a pixel, so the weights are whole numbers.
101
+ const spans = (size) => { const out = []; for (let i = 0; i < 8; i++) { const lo = i * size, hi = (i + 1) * size, s = []; for (let p = Math.floor(lo / 8); p * 8 < hi; p++) s.push([p, Math.min(hi, (p + 1) * 8) - Math.max(lo, p * 8)]); out.push(s); } return out; };
102
+ const xs = spans(width), ys = spans(height), cells = [];
103
+ for (let j = 0; j < 8; j++) for (let i = 0; i < 8; i++) {
104
+ let sum = 0;
105
+ for (const [y, oy] of ys[j]) for (const [x, ox] of xs[i]) sum += luma(x, y) * ox * oy;
106
+ cells.push(sum / (width * height));
107
+ }
108
+ const mean = cells.reduce((a, b) => a + b, 0) / 64, out = new Uint8Array(8);
109
+ cells.forEach((c, i) => { if (c > mean) out[i >> 3] |= 0x80 >> (i & 7); });
110
+ return hex(out);
111
+ }
112
+ export function phashDistance(a, b) {
113
+ let d = 0;
114
+ for (let i = 0; i < 16; i += 2) { let x = parseInt(a.slice(i, i + 2), 16) ^ parseInt(b.slice(i, i + 2), 16); while (x) { d += x & 1; x >>= 1; } }
115
+ return d;
116
+ }
117
+
118
+ /**
119
+ * A browser's own decoder, for the types this file does not decode. Good for `phash` and nothing stricter: Safari's private browsing adds noise to canvas reads on purpose,
120
+ * and JPEG decoders differ, which a 64-bit hash of the shape shrugs off and an exact hash would not.
121
+ */
122
+ export async function canvasDecoder(bytes, mime) {
123
+ const blob = new Blob([bytes], mime ? { type: mime } : {});
124
+ const bmp = await createImageBitmap(blob, { premultiplyAlpha: "none", colorSpaceConversion: "none" });
125
+ const canvas = typeof OffscreenCanvas !== "undefined" ? new OffscreenCanvas(bmp.width, bmp.height) : Object.assign(document.createElement("canvas"), { width: bmp.width, height: bmp.height });
126
+ const ctx = canvas.getContext("2d");
127
+ ctx.drawImage(bmp, 0, 0);
128
+ const { data, width, height } = ctx.getImageData(0, 0, bmp.width, bmp.height);
129
+ const rgb = new Uint8Array(width * height * 3), alpha = new Uint8Array(width * height);
130
+ for (let i = 0; i < width * height; i++) { rgb[i * 3] = data[i * 4]; rgb[i * 3 + 1] = data[i * 4 + 1]; rgb[i * 3 + 2] = data[i * 4 + 2]; alpha[i] = data[i * 4 + 3]; }
131
+ bmp.close?.();
132
+ return { width, height, rgb, alpha };
133
+ }
134
+
135
+ /**
136
+ * The hashes a claim carries. `decode(bytes)` is the caller's own decoder for other image types, returning { width, height, rgb, alpha }: it may give `phash`, never `pixels`.
137
+ * A file that is not a picture, or that nothing can decode, simply has neither: it can still be signed, and found only by its exact bytes.
138
+ */
139
+ export async function hashFile(bytes, { decode } = {}) {
140
+ const b = new Uint8Array(bytes);
141
+ const sha = new Uint8Array(await crypto.subtle.digest("SHA-256", b));
142
+ const out = { sha256: hex(sha), bytes: b.length };
143
+ try {
144
+ if (isPng(b)) {
145
+ const png = await decodePng(b);
146
+ if (png.rgb) { out.pixels = hex(new Uint8Array(await crypto.subtle.digest("SHA-256", png.rgb))); out.phash = phashOf(png); }
147
+ } else if (decode) {
148
+ const r = await decode(b);
149
+ if (r) out.phash = phashOf(r);
150
+ }
151
+ } catch { /* what cannot be decoded has no picture to speak of */ }
152
+ return out;
153
+ }
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@333eco/origin-verify",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
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
+ "license": "CC0-1.0",
6
+ "author": "Thon Ly",
7
+ "homepage": "https://github.com/333eco/origin-verify.333.eco#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/333eco/origin-verify.333.eco.git"
11
+ },
12
+ "keywords": [
13
+ "provenance",
14
+ "transparency-log",
15
+ "tlog",
16
+ "rfc3161",
17
+ "opentimestamps",
18
+ "passkey",
19
+ "webauthn",
20
+ "perceptual-hash",
21
+ "c2sp"
22
+ ],
23
+ "type": "module",
24
+ "exports": {
25
+ ".": "./index.mjs",
26
+ "./media": "./media.mjs",
27
+ "./trust": "./trust.mjs",
28
+ "./package.json": "./package.json"
29
+ },
30
+ "files": [
31
+ "index.mjs",
32
+ "primitives.mjs",
33
+ "clocks.mjs",
34
+ "media.mjs",
35
+ "trust.mjs",
36
+ "cli.mjs",
37
+ "README.md"
38
+ ],
39
+ "bin": {
40
+ "origin-verify": "./cli.mjs"
41
+ },
42
+ "sideEffects": false,
43
+ "engines": {
44
+ "node": ">=20"
45
+ },
46
+ "scripts": {
47
+ "test": "node --test test/*.test.mjs"
48
+ }
49
+ }
package/primitives.mjs ADDED
@@ -0,0 +1,130 @@
1
+ // The arithmetic everything else stands on. Browser and Node alike: WebCrypto and Uint8Array only, no Node modules and no Buffer.
2
+ // SHA-256 is written out because a Merkle tree needs it synchronously and thousands of times; signatures go through WebCrypto.
3
+
4
+ export const utf8 = (s) => new TextEncoder().encode(s);
5
+ export const text = (b) => new TextDecoder().decode(b);
6
+ export const concat = (...parts) => {
7
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
8
+ let i = 0;
9
+ for (const p of parts) { out.set(p, i); i += p.length; }
10
+ return out;
11
+ };
12
+ export const eq = (a, b) => { if (a.length !== b.length) return false; let d = 0; for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i]; return d === 0; };
13
+ export const hex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
14
+ export const unhex = (s) => { const o = new Uint8Array(s.length / 2); for (let i = 0; i < o.length; i++) o[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16); return o; };
15
+ export const b64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
16
+ export const b64u = (s) => b64(s.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(s.length / 4) * 4, "="));
17
+ export const toB64 = (b) => { let s = ""; for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode(...b.subarray(i, i + 0x8000)); return btoa(s); };
18
+ export const toB64u = (b) => toB64(b).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
19
+ export const u64 = (n) => { const b = new Uint8Array(8); new DataView(b.buffer).setBigUint64(0, BigInt(n)); return b; };
20
+ export const u32 = (n) => { const b = new Uint8Array(4); new DataView(b.buffer).setUint32(0, n); return b; };
21
+
22
+ const K = new Uint32Array([
23
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
24
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
25
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
26
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
27
+ ]);
28
+ export function sha256(...parts) {
29
+ const m = parts.length === 1 ? parts[0] : concat(...parts);
30
+ const h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
31
+ const full = Math.floor((m.length + 9 + 63) / 64) * 64, tail = new Uint8Array(full - Math.floor(m.length / 64) * 64);
32
+ tail.set(m.subarray(Math.floor(m.length / 64) * 64));
33
+ tail[m.length % 64] = 0x80;
34
+ const dv = new DataView(tail.buffer);
35
+ dv.setUint32(tail.length - 8, Math.floor(m.length / 2 ** 29));
36
+ dv.setUint32(tail.length - 4, (m.length << 3) >>> 0);
37
+ const w = new Uint32Array(64);
38
+ const block = (b, o) => {
39
+ for (let t = 0; t < 16; t++) w[t] = (b[o + t * 4] << 24) | (b[o + t * 4 + 1] << 16) | (b[o + t * 4 + 2] << 8) | b[o + t * 4 + 3];
40
+ for (let t = 16; t < 64; t++) {
41
+ const a = w[t - 15], c = w[t - 2];
42
+ w[t] = (((a >>> 7) | (a << 25)) ^ ((a >>> 18) | (a << 14)) ^ (a >>> 3)) + w[t - 7] + (((c >>> 17) | (c << 15)) ^ ((c >>> 19) | (c << 13)) ^ (c >>> 10)) + w[t - 16];
43
+ }
44
+ let [a, bb, c, d, e, f, g, hh] = h;
45
+ for (let t = 0; t < 64; t++) {
46
+ const t1 = (hh + (((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7))) + ((e & f) ^ (~e & g)) + K[t] + w[t]) | 0;
47
+ const t2 = ((((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10))) + ((a & bb) ^ (a & c) ^ (bb & c))) | 0;
48
+ hh = g; g = f; f = e; e = (d + t1) | 0; d = c; c = bb; bb = a; a = (t1 + t2) | 0;
49
+ }
50
+ h[0] += a; h[1] += bb; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
51
+ };
52
+ for (let o = 0; o + 64 <= m.length; o += 64) block(m, o);
53
+ for (let o = 0; o < tail.length; o += 64) block(tail, o);
54
+ const out = new Uint8Array(32), odv = new DataView(out.buffer);
55
+ for (let i = 0; i < 8; i++) odv.setUint32(i * 4, h[i]);
56
+ return out;
57
+ }
58
+ export function hmacSha256(key, ...parts) {
59
+ const k = new Uint8Array(64);
60
+ k.set(key.length > 64 ? sha256(key) : key);
61
+ return sha256(k.map((x) => x ^ 0x5c), sha256(k.map((x) => x ^ 0x36), ...parts));
62
+ }
63
+
64
+ // ── Ed25519 ──────────────────────────────────────────────────────────────────────────────────────────────────────
65
+ // RFC 8032 verification by hand, for browsers whose WebCrypto lacks it (Chrome before 137, and the Android floor is Chrome 113).
66
+ // It handles only public values, so a timing leak gives nothing away.
67
+ const P = 2n ** 255n - 19n, L = 2n ** 252n + 27742317777372353535851937790883648493n, D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n, I = 19681161376707505956807079304988542015446066515923890162744021073123829784752n;
68
+ const mod = (a, m = P) => { const r = a % m; return r < 0n ? r + m : r; };
69
+ const pow = (b, e, m = P) => { let r = 1n; b = mod(b, m); while (e > 0n) { if (e & 1n) r = (r * b) % m; b = (b * b) % m; e >>= 1n; } return r; };
70
+ const addPt = ([x1, y1, z1, t1], [x2, y2, z2, t2]) => {
71
+ const a = mod((y1 - x1) * (y2 - x2)), b = mod((y1 + x1) * (y2 + x2)), c = mod(2n * t1 * t2 * D), d = mod(2n * z1 * z2), e = b - a, f = d - c, g = d + c, h = b + a;
72
+ return [mod(e * f), mod(g * h), mod(f * g), mod(e * h)];
73
+ };
74
+ const mulPt = (s, pt) => { let q = [0n, 1n, 1n, 0n]; while (s > 0n) { if (s & 1n) q = addPt(q, pt); pt = addPt(pt, pt); s >>= 1n; } return q; };
75
+ const leInt = (b) => { let n = 0n; for (let i = b.length - 1; i >= 0; i--) n = (n << 8n) + BigInt(b[i]); return n; };
76
+ function decodePt(b) {
77
+ if (b.length !== 32) return null;
78
+ const y = leInt(b) & (2n ** 255n - 1n), sign = b[31] >> 7;
79
+ if (y >= P) return null;
80
+ const y2 = mod(y * y), u = mod(y2 - 1n), v = mod(D * y2 + 1n);
81
+ let x = pow(mod(u * pow(v, P - 2n)), (P + 3n) / 8n);
82
+ if (mod(v * x * x - u) !== 0n) { x = mod(x * I); if (mod(v * x * x - u) !== 0n) return null; }
83
+ if (x === 0n && sign) return null;
84
+ if (Number(x & 1n) !== sign) x = P - x;
85
+ return [x, y, 1n, mod(x * y)];
86
+ }
87
+ const BASE = decodePt(unhex("5866666666666666666666666666666666666666666666666666666666666666"));
88
+ const samePt = ([x1, y1, z1], [x2, y2, z2]) => mod(x1 * z2 - x2 * z1) === 0n && mod(y1 * z2 - y2 * z1) === 0n;
89
+ export async function ed25519ByHand(pub, msg, sig) {
90
+ if (sig.length !== 64) return false;
91
+ const A = decodePt(pub), R = decodePt(sig.subarray(0, 32)), S = leInt(sig.subarray(32));
92
+ if (!A || !R || S >= L) return false;
93
+ const k = mod(leInt(new Uint8Array(await crypto.subtle.digest("SHA-512", concat(sig.subarray(0, 32), pub, msg)))), L);
94
+ return samePt(mulPt(S, BASE), addPt(R, mulPt(k, A)));
95
+ }
96
+ let hasEd25519;
97
+ export async function ed25519(pub, msg, sig) {
98
+ if (hasEd25519 === undefined) {
99
+ try { await crypto.subtle.importKey("raw", new Uint8Array(32).fill(1), { name: "Ed25519" }, false, ["verify"]); hasEd25519 = true; } catch { hasEd25519 = false; }
100
+ }
101
+ if (!hasEd25519) return ed25519ByHand(pub, msg, sig);
102
+ try { return await crypto.subtle.verify({ name: "Ed25519" }, await crypto.subtle.importKey("raw", pub, { name: "Ed25519" }, false, ["verify"]), sig, msg); }
103
+ catch { return false; }
104
+ }
105
+
106
+ // ── DER: just the reading a signature check needs ────────────────────────────────────────────────────────────────
107
+ /** One node: its tag, its value, and the whole encoding (a signature covers the encoding, so it must never be rebuilt). */
108
+ export function der(b, at = 0) {
109
+ if (at + 2 > b.length) throw new Error("DER: truncated");
110
+ const tag = b[at];
111
+ let len = b[at + 1], head = 2;
112
+ if (len & 0x80) { const n = len & 0x7f; if (n === 0 || n > 4) throw new Error("DER: bad length"); len = 0; for (let i = 0; i < n; i++) len = len * 256 + b[at + 2 + i]; head += n; }
113
+ const end = at + head + len;
114
+ if (end > b.length) throw new Error("DER: truncated");
115
+ return { tag, value: b.subarray(at + head, end), raw: b.subarray(at, end), end };
116
+ }
117
+ export const kids = (node) => { const out = []; for (let i = 0; i < node.value.length;) { const k = der(node.value, i); out.push(k); i = k.end; } return out; };
118
+ export const oid = (node) => {
119
+ const v = node.value; let s = `${Math.min(Math.floor(v[0] / 40), 2)}.${v[0] < 80 ? v[0] % 40 : v[0] - 80}`, n = 0;
120
+ for (let i = 1; i < v.length; i++) { n = n * 128 + (v[i] & 0x7f); if (!(v[i] & 0x80)) { s += `.${n}`; n = 0; } }
121
+ return s;
122
+ };
123
+ /** ECDSA in DER → the fixed r‖s WebCrypto wants. */
124
+ export function derSigToRaw(sig, size) {
125
+ const seq = der(sig), parts = kids(seq);
126
+ if (seq.tag !== 0x30 || seq.end !== sig.length || parts.length !== 2 || parts.some((k) => k.tag !== 0x02)) throw new Error("not an ECDSA signature");
127
+ const [r, s] = parts.map((k) => k.value);
128
+ const part = (x) => { let i = 0; while (i < x.length - 1 && x[i] === 0) i++; const v = x.subarray(i); if (v.length > size) throw new Error("ECDSA value too long"); const o = new Uint8Array(size); o.set(v, size - v.length); return o; };
129
+ return concat(part(r), part(s));
130
+ }
package/trust.mjs ADDED
@@ -0,0 +1,31 @@
1
+ // What a verifier trusts, and everything else it checks. A JavaScript module rather than JSON because import attributes are missing on the browsers the estate promises (Android floor: Chrome 113).
2
+ export default {
3
+ "origin": "log.333.eco/origin",
4
+ "logVkey": "log.333.eco/origin+f3d66572+AXi0v2hiHpHIJ+jLtTsRr8Oy0xQsAOONP3DTlQIPd7QF",
5
+ "recordKeys": {
6
+ "k1-1": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEBJbkbZoh6NVkspuIZKGXnOs25DxF331TbbGqhK1j2rtsWIZI5x6Ze+jo4mc3kNcqnJFnpUGlOoVu0zexPo0WzQ=="
7
+ },
8
+ "rpId": "sign.333.eco",
9
+ "webOrigin": "https://sign.333.eco",
10
+ "witnessQuorum": 4,
11
+ "witnessLabel": "staging witnesses",
12
+ "witnesses": [
13
+ "witness.navigli.sunlight.geomys.org+a3e00fe2+BNy/co4C1Hn1p+INwJrfUlgz7W55dSZReusH/GhUhJ/G",
14
+ "krabbel.ct.ipng.ch+4b10dbd8+BO4sLOtnhktlqMCejDx9C5LDd+/xZxbmBb6BP9ZD2Def",
15
+ "witness.gdbsecurity.com+a1398f73+BAbIijGonVIk3ikDac+KKlSm1ELHOzcddhjjB6zB4BNf",
16
+ "markovianprotocol.com/witness+41b8827f+BJKLl8rBYM0oUxSaWh9rjTldTprEpYj/SWVIGgacA9XC",
17
+ "witness.stagemole.eu+67f7aea0+BEqSG3yu9YrmcM3BHvQYTxwFj3uSWakQepafafpUqklv",
18
+ "staging.witness.transparency.goog/ring-any-bells+2e1a8dc9+BG5JTpLc3FJtwzgh1Uv+Qelz9qeOH2bfWjS1s0s+y4rL"
19
+ ],
20
+ "tsaRoots": {
21
+ "accv-es": [
22
+ "MIIH0zCCBbugAwIBAgIIXsO3pkN/pOAwDQYJKoZIhvcNAQEFBQAwQjESMBAGA1UEAwwJQUNDVlJBSVoxMRAwDgYDVQQLDAdQS0lBQ0NWMQ0wCwYDVQQKDARBQ0NWMQswCQYDVQQGEwJFUzAeFw0xMTA1MDUwOTM3MzdaFw0zMDEyMzEwOTM3MzdaMEIxEjAQBgNVBAMMCUFDQ1ZSQUlaMTEQMA4GA1UECwwHUEtJQUNDVjENMAsGA1UECgwEQUNDVjELMAkGA1UEBhMCRVMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCbq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