signed-md 0.0.0-stage → 1.1.1

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/README.md CHANGED
@@ -1,3 +1,105 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="https://github.com/varops/signed-md"><img src="https://raw.githubusercontent.com/varops/signed-md/main/brand/signedmd-light.svg" alt="Signed.md" height="56"></a>
3
+ </p>
2
4
 
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.
5
+ <h3 align="center">Check a signed agreement yourself</h3>
6
+
7
+ <p align="center">
8
+ The offline verifier for <a href="https://github.com/varops/signed-md">Signed.md</a> evidence packages.<br>No account, no server, no internet connection.
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="https://www.npmjs.com/package/signed-md"><img src="https://img.shields.io/npm/v/signed-md?color=1c1917&label=npm" alt="npm version"></a>
13
+ <a href="https://github.com/varops/signed-md/blob/main/LICENSE"><img src="https://img.shields.io/badge/licence-AGPL--3.0-1c1917" alt="Licence: AGPL-3.0"></a>
14
+ <img src="https://img.shields.io/badge/dependencies-0-f6da1c" alt="No dependencies">
15
+ <img src="https://img.shields.io/badge/works-offline-1c1917" alt="Works offline">
16
+ </p>
17
+
18
+ ---
19
+
20
+ When everyone has signed, [Signed.md](https://github.com/varops/signed-md) gives each party an evidence package: a ZIP with the signed Markdown, the sealed PDF, a hash-chained evidence log and a signed manifest.
21
+
22
+ You shouldn't have to trust the company that sent it. Run one command and see for yourself that nothing was changed after signing:
23
+
24
+ ```bash
25
+ npx signed-md verify agreement.zip
26
+ ```
27
+
28
+ ```text
29
+ Mutual NDA (doc_3ytrryxfn5b4qjhkxw18)
30
+ Revision rev_b74005c16ce436bf916218d24c7e4b0a · key smdk_b8ab402827010b3c
31
+
32
+ ✓ manifest signature valid
33
+ ✓ file agreement.md
34
+ ✓ PDF signature valid – CN=Acme (Signed.md), O=Acme
35
+ ✓ PDF not changed after signing
36
+ ✓ PDF signature timestamp – 2026-11-20T12:06:14.000Z by C=US, O=DigiCert\, Inc., …
37
+ ✓ evidence chain – 16 events
38
+ ✓ agreement.md matches the sent document
39
+ ✓ signer a signed – Jane Doe <jane@example.com>
40
+
41
+ VALID: the package is intact. Pass --keys to also check who signed it.
42
+ ```
43
+
44
+ The output above is shortened. A real run lists every file and check.
45
+
46
+ ## Also check who sent it
47
+
48
+ A package carries its own public key. That proves nothing inside it was changed, but anyone could make a package with their own key. To check it came from the sender's installation, compare it with the sender's published keys:
49
+
50
+ 1. Download the keys once from the sender's server, and keep the file:
51
+
52
+ ```bash
53
+ curl -o signed-md-keys.json https://sign.example.com/.well-known/signed-md-keys.json
54
+ ```
55
+
56
+ 2. Verify against them:
57
+
58
+ ```bash
59
+ npx signed-md verify agreement.zip --keys signed-md-keys.json
60
+ ```
61
+
62
+ ```text
63
+ VALID: the package is intact and signed by a key you trust.
64
+ ```
65
+
66
+ Keep the keys file you downloaded first. If a later package only matches keys fetched later, ask the sender why their key changed.
67
+
68
+ ## What it checks
69
+
70
+ | Check | What it proves |
71
+ |---|---|
72
+ | Manifest and its signature | Every file in the ZIP is the one the server sealed. Nothing was added, removed or edited. |
73
+ | PDF seal (PAdES) | The PDF wasn't changed after signing. PDF readers like Adobe Acrobat check the same seal. |
74
+ | Timestamps (RFC 3161) | A trusted time authority saw the sealed PDF at that time, when the package has a timestamp. |
75
+ | Evidence chain | Each event (sent, viewed, consented, signed) links to the one before it by hash. None was removed or reordered. |
76
+ | Agreement text | Every signer signed the exact text in `agreement.md`, word for word. |
77
+ | Keys (with `--keys`) | The package was sealed by the installation whose keys you trust. |
78
+
79
+ ## Options
80
+
81
+ ```text
82
+ signed-md verify <agreement.zip> [--keys <keys.json>] [--json]
83
+ ```
84
+
85
+ | Option | Description |
86
+ |---|---|
87
+ | `--keys <file>` | A keys file you trust, from the sender's `/.well-known/signed-md-keys.json`. |
88
+ | `--json` | Print the full report as JSON, for scripts and CI. |
89
+ | `--help` | Show the usage. |
90
+
91
+ | Exit code | Meaning |
92
+ |---|---|
93
+ | `0` | Valid |
94
+ | `1` | Invalid: the package was changed, is incomplete, or isn't a Signed.md package |
95
+ | `2` | Wrong usage, or a file couldn't be read |
96
+
97
+ You need Node.js 20 or later. The command is one bundled file with no dependencies. It reads only the files you give it and never connects to the internet.
98
+
99
+ ## About Signed.md
100
+
101
+ [Signed.md](https://github.com/varops/signed-md) is open-source document signing you host yourself. AI agents draft agreements from approved Markdown templates, over MCP or a REST API. People review, approve and send them, and signers sign in the browser. Every completed agreement becomes a sealed, timestamped PDF/A plus the evidence package this tool checks.
102
+
103
+ ## Licence
104
+
105
+ AGPL-3.0-only. This tool checks that a package is intact. It doesn't tell you whether an agreement is legally binding where you are, and it isn't legal advice. See [how Signed.md fits ESIGN, UETA, eIDAS and UK law](https://github.com/varops/signed-md/blob/main/docs/legal.md).
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ // Published packages run the bundled build. In this repository, Node runs the TypeScript sources directly.
3
+ import { existsSync } from "node:fs";
4
+ const bundled = new URL("../dist/cli.js", import.meta.url);
5
+ const { run } = existsSync(bundled) ? await import(bundled.href) : await import("../src/cli.ts");
6
+ process.exitCode = run(process.argv.slice(2));
package/dist/cli.js ADDED
@@ -0,0 +1,916 @@
1
+ // src/cli.ts
2
+ import { readFileSync } from "node:fs";
3
+
4
+ // ../core/src/evidence.ts
5
+ import { createHash as createHash3, createPublicKey as createPublicKey2, verify as edVerify, X509Certificate as X509Certificate2 } from "node:crypto";
6
+
7
+ // ../core/src/cms.ts
8
+ import { createHash, createPublicKey, verify as cryptoVerify, X509Certificate } from "node:crypto";
9
+
10
+ // ../core/src/der.ts
11
+ function derDecode(buf, offset = 0) {
12
+ const tag = buf[offset];
13
+ if ((tag & 31) === 31) throw new Error("High tag numbers are not supported");
14
+ let pos = offset + 1;
15
+ let len = buf[pos++];
16
+ if (len & 128) {
17
+ const n = len & 127;
18
+ if (n === 0 || n > 4) throw new Error("Unsupported DER length");
19
+ len = 0;
20
+ for (let i2 = 0; i2 < n; i2++) len = len * 256 + buf[pos++];
21
+ }
22
+ const contentStart = pos;
23
+ const end = contentStart + len;
24
+ if (end > buf.length) throw new Error("DER element runs past the end of the buffer");
25
+ const constructed = (tag & 32) !== 0;
26
+ const node = {
27
+ tag,
28
+ constructed,
29
+ start: offset,
30
+ contentStart,
31
+ end,
32
+ raw: buf.subarray(offset, end),
33
+ value: buf.subarray(contentStart, end),
34
+ children: []
35
+ };
36
+ if (constructed) {
37
+ let p = contentStart;
38
+ while (p < end) {
39
+ const child = derDecode(buf, p);
40
+ node.children.push(child);
41
+ p = child.end;
42
+ }
43
+ }
44
+ return node;
45
+ }
46
+ function oidToString(value) {
47
+ const parts = [];
48
+ let v = 0;
49
+ for (let i2 = 0; i2 < value.length; i2++) {
50
+ v = v * 128 + (value[i2] & 127);
51
+ if (!(value[i2] & 128)) {
52
+ if (parts.length === 0) {
53
+ const first = v < 80 ? Math.floor(v / 40) : 2;
54
+ parts.push(first, v - first * 40);
55
+ } else parts.push(v);
56
+ v = 0;
57
+ }
58
+ }
59
+ return parts.join(".");
60
+ }
61
+ function derTime(node) {
62
+ const s = new TextDecoder().decode(node.value);
63
+ if (node.tag === 23) {
64
+ const y = Number(s.slice(0, 2));
65
+ return new Date(Date.UTC(y < 50 ? 2e3 + y : 1900 + y, Number(s.slice(2, 4)) - 1, Number(s.slice(4, 6)), Number(s.slice(6, 8)), Number(s.slice(8, 10)), Number(s.slice(10, 12))));
66
+ }
67
+ const m = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(?:\.(\d+))?Z$/.exec(s);
68
+ if (!m) throw new Error(`Unsupported time '${s}'`);
69
+ const ms = m[7] ? Math.round(Number(`0.${m[7]}`) * 1e3) : 0;
70
+ return new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6]), ms));
71
+ }
72
+
73
+ // ../core/src/cms.ts
74
+ var OID = {
75
+ data: "1.2.840.113549.1.7.1",
76
+ signedData: "1.2.840.113549.1.7.2",
77
+ tstInfo: "1.2.840.113549.1.9.16.1.4",
78
+ contentType: "1.2.840.113549.1.9.3",
79
+ messageDigest: "1.2.840.113549.1.9.4",
80
+ signingCertificateV2: "1.2.840.113549.1.9.16.2.47",
81
+ signatureTimeStampToken: "1.2.840.113549.1.9.16.2.14",
82
+ sha256: "2.16.840.1.101.3.4.2.1",
83
+ rsaEncryption: "1.2.840.113549.1.1.1",
84
+ sha256WithRSA: "1.2.840.113549.1.1.11",
85
+ ecdsaWithSHA256: "1.2.840.10045.4.3.2"
86
+ };
87
+ function sha256(b) {
88
+ return createHash("sha256").update(b).digest();
89
+ }
90
+ function equal(a, b) {
91
+ return a.length === b.length && a.every((x2, i2) => x2 === b[i2]);
92
+ }
93
+ function parseSignedData(contentInfo) {
94
+ const ci = derDecode(contentInfo);
95
+ if (oidToString(ci.children[0].value) !== OID.signedData) throw new Error("Not a CMS SignedData structure");
96
+ const sd = ci.children[1].children[0];
97
+ const parts = sd.children;
98
+ const encap = parts[2];
99
+ const eContentType = oidToString(encap.children[0].value);
100
+ const content = encap.children[1] ? encap.children[1].children[0].value : null;
101
+ const certificates = [];
102
+ let i2 = 3;
103
+ if (parts[i2] && parts[i2].tag === 160) {
104
+ for (const c of parts[i2].children) certificates.push(new X509Certificate(Buffer.from(c.raw)));
105
+ i2++;
106
+ }
107
+ if (parts[i2] && parts[i2].tag === 161) i2++;
108
+ const signerInfos = parts[i2];
109
+ const si = signerInfos.children[0];
110
+ const sid = si.children[1];
111
+ const signedAttrs = si.children[3];
112
+ if (signedAttrs.tag !== 160) throw new Error("Signed attributes are required");
113
+ const sigAlg = oidToString(si.children[4].children[0].value);
114
+ const signatureValue = si.children[5].value;
115
+ const unsigned = si.children[6] && si.children[6].tag === 161 ? si.children[6] : null;
116
+ const serialHex = Buffer.from(sid.children[1].value).toString("hex").replace(/^(00)+/, "").toUpperCase();
117
+ const certificate = certificates.find((c) => c.serialNumber.replace(/^(00)+/, "").toUpperCase() === serialHex) ?? certificates[0];
118
+ if (!certificate) throw new Error("No signer certificate in the signature");
119
+ const attrs = /* @__PURE__ */ new Map();
120
+ for (const a of signedAttrs.children) attrs.set(oidToString(a.children[0].value), a.children[1].children[0]);
121
+ const md = attrs.get(OID.messageDigest);
122
+ if (!md) throw new Error("messageDigest attribute missing");
123
+ const toVerify = Buffer.from(signedAttrs.raw);
124
+ toVerify[0] = 49;
125
+ const key = createPublicKey(certificate.publicKey.export({ format: "pem", type: "spki" }));
126
+ const algorithm = sigAlg === OID.rsaEncryption || sigAlg === OID.sha256WithRSA || sigAlg === OID.ecdsaWithSHA256 ? "sha256" : "sha256";
127
+ let signatureValid = false;
128
+ try {
129
+ signatureValid = cryptoVerify(algorithm, toVerify, key, Buffer.from(signatureValue));
130
+ } catch {
131
+ signatureValid = false;
132
+ }
133
+ let signingCertificateBound = false;
134
+ const scv2 = attrs.get(OID.signingCertificateV2);
135
+ if (scv2) {
136
+ const first = scv2.children[0].children[0];
137
+ const hashNode = first.children.find((c) => c.tag === 4);
138
+ signingCertificateBound = equal(hashNode.value, sha256(certificate.raw));
139
+ }
140
+ let timestampToken = null;
141
+ if (unsigned) {
142
+ for (const a of unsigned.children) {
143
+ if (oidToString(a.children[0].value) === OID.signatureTimeStampToken) timestampToken = a.children[1].children[0].raw;
144
+ }
145
+ }
146
+ return { certificate, certificates, messageDigest: md.value, eContentType, content, signatureValue, signatureValid, signingCertificateBound, timestampToken };
147
+ }
148
+ function parseTimestampToken(token) {
149
+ const sd = parseSignedData(token);
150
+ if (sd.eContentType !== OID.tstInfo || !sd.content) throw new Error("Not a timestamp token");
151
+ const tst = derDecode(sd.content);
152
+ const imprint = tst.children[2].children[1].value;
153
+ const genTime = derTime(tst.children[4]);
154
+ const contentOk = equal(sd.messageDigest, sha256(sd.content));
155
+ return { genTime, imprint, authority: sd.certificate.subject.replace(/\n/g, ", "), signatureValid: sd.signatureValid && contentOk };
156
+ }
157
+
158
+ // ../core/src/canonical.ts
159
+ import { createHash as createHash2 } from "node:crypto";
160
+ function canonicalJson(value) {
161
+ if (value === null) return "null";
162
+ switch (typeof value) {
163
+ case "boolean":
164
+ return value ? "true" : "false";
165
+ case "number":
166
+ if (!Number.isFinite(value)) throw new TypeError("Cannot canonicalize non-finite number");
167
+ return JSON.stringify(value);
168
+ case "string":
169
+ return JSON.stringify(value);
170
+ case "object": {
171
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
172
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
173
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
174
+ }
175
+ default:
176
+ throw new TypeError(`Cannot canonicalize ${typeof value}`);
177
+ }
178
+ }
179
+ function sha256Hex(data) {
180
+ return createHash2("sha256").update(data).digest("hex");
181
+ }
182
+
183
+ // ../core/src/evidence.ts
184
+ var MANIFEST_FORMAT = "signed-md/manifest@1";
185
+ var EVIDENCE_FORMAT = "signed-md/evidence@1";
186
+ function eventHashInput(e) {
187
+ return canonicalJson({
188
+ document_id: e.document_id,
189
+ seq: e.seq,
190
+ type: e.type,
191
+ actor: e.actor,
192
+ actor_label: e.actor_label,
193
+ created_at: e.created_at,
194
+ data: e.data,
195
+ prev_hash: e.prev_hash
196
+ });
197
+ }
198
+ var sha = (b) => createHash3("sha256").update(b).digest();
199
+ function verifyPdfSignature(pdf, expectedCertPem) {
200
+ const text = Buffer.from(pdf).toString("latin1");
201
+ const ranges = [...text.matchAll(/\/ByteRange\s*\[\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*\]/g)];
202
+ const last = ranges.at(-1);
203
+ if (!last) return null;
204
+ const [a, b, c, d] = last.slice(1, 5).map(Number);
205
+ const checks = [];
206
+ const hex = text.slice(b, c).replace(/^</, "").replace(/>$/, "").trim();
207
+ const cms = Buffer.from(hex, "hex");
208
+ const digest = sha(Buffer.concat([pdf.subarray(a, a + b), pdf.subarray(c, c + d)]));
209
+ let info;
210
+ try {
211
+ info = parseSignedData(cms);
212
+ } catch (e) {
213
+ return { checks: [{ name: "PDF signature readable", ok: false, detail: e.message }], signer: "", timestamp: null };
214
+ }
215
+ const signer = info.certificate.subject.replace(/\n/g, ", ");
216
+ checks.push({ name: "PDF signature valid", ok: info.signatureValid && Buffer.from(info.messageDigest).equals(digest), detail: signer });
217
+ checks.push({ name: "PDF not changed after signing", ok: a === 0 && c + d === pdf.length });
218
+ checks.push({ name: "PDF signature is PAdES (signing certificate bound)", ok: info.signingCertificateBound });
219
+ if (expectedCertPem) {
220
+ const same = Buffer.from(new X509Certificate2(expectedCertPem).raw).equals(Buffer.from(info.certificate.raw));
221
+ checks.push({ name: "PDF signed by this installation's certificate", ok: same });
222
+ }
223
+ let timestamp = null;
224
+ if (info.timestampToken) {
225
+ try {
226
+ const ts = parseTimestampToken(info.timestampToken);
227
+ const ok = ts.signatureValid && Buffer.from(ts.imprint).equals(sha(info.signatureValue));
228
+ checks.push({ name: "PDF signature timestamp", ok, detail: `${ts.genTime.toISOString()} by ${ts.authority}` });
229
+ timestamp = { time: ts.genTime.toISOString(), authority: ts.authority };
230
+ } catch (e) {
231
+ checks.push({ name: "PDF signature timestamp", ok: false, detail: e.message });
232
+ }
233
+ }
234
+ return { checks, signer, timestamp };
235
+ }
236
+ function verifyPackageFiles(files, opts = {}) {
237
+ const checks = [];
238
+ const check = (name, ok, detail) => {
239
+ checks.push(detail === void 0 ? { name, ok } : { name, ok, detail });
240
+ return ok;
241
+ };
242
+ const text = (p) => files[p] ? Buffer.from(files[p]).toString("utf8") : null;
243
+ const json = (p) => {
244
+ const t = text(p);
245
+ if (t === null) return null;
246
+ try {
247
+ return JSON.parse(t);
248
+ } catch {
249
+ return null;
250
+ }
251
+ };
252
+ const report = { ok: false, document_id: null, title: null, revision: null, key_id: null, trusted_key: false, signers: [], timestamp: null, pdf_signature: null, checks };
253
+ const manifest = json("manifest.json");
254
+ const sig = text("manifest.sig")?.trim() ?? null;
255
+ const pub = json("public-key.json");
256
+ if (!check("manifest present", manifest !== null && manifest.format === MANIFEST_FORMAT)) return report;
257
+ if (!check("signature present", sig !== null && sig.length > 0)) return report;
258
+ if (!check("public key present", pub !== null && pub.alg === "Ed25519")) return report;
259
+ report.document_id = manifest.document_id;
260
+ report.revision = manifest.revision;
261
+ report.key_id = manifest.key_id;
262
+ let sigOk = false;
263
+ try {
264
+ const key = createPublicKey2({ key: Buffer.from(pub.public_key, "base64"), format: "der", type: "spki" });
265
+ sigOk = edVerify(null, Buffer.from(canonicalJson(manifest)), key, Buffer.from(sig, "base64"));
266
+ } catch {
267
+ sigOk = false;
268
+ }
269
+ check("manifest signature valid", sigOk);
270
+ check("key id matches", pub.kid === manifest.key_id, `${pub.kid} / ${manifest.key_id}`);
271
+ if (opts.trustedKeys && opts.trustedKeys.length > 0) {
272
+ report.trusted_key = opts.trustedKeys.includes(pub.public_key);
273
+ check("signing key is trusted", report.trusted_key, report.trusted_key ? pub.kid : "The package was signed with a key you did not list as trusted");
274
+ }
275
+ const listed = new Set(manifest.files.map((f) => f.path));
276
+ for (const f of manifest.files) {
277
+ const data = files[f.path];
278
+ check(`file ${f.path}`, data !== void 0 && sha256Hex(data) === f.sha256 && data.length === f.size, data === void 0 ? "missing" : void 0);
279
+ }
280
+ const extra = Object.keys(files).filter((p) => !listed.has(p) && !["manifest.json", "manifest.sig", "manifest.tsr"].includes(p));
281
+ check("no unlisted files", extra.length === 0, extra.length ? extra.join(", ") : void 0);
282
+ if (files["manifest.tsr"]) {
283
+ try {
284
+ const ts = parseTimestampToken(files["manifest.tsr"]);
285
+ const ok = ts.signatureValid && Buffer.from(ts.imprint).equals(sha(Buffer.from(canonicalJson(manifest))));
286
+ check("package timestamp", ok, `${ts.genTime.toISOString()} by ${ts.authority}`);
287
+ if (ok) report.timestamp = { time: ts.genTime.toISOString(), authority: ts.authority };
288
+ } catch (e) {
289
+ check("package timestamp", false, e.message);
290
+ }
291
+ }
292
+ if (files["signed.pdf"]) {
293
+ const pdfSig = verifyPdfSignature(files["signed.pdf"], pub.pdf_signing_certificate);
294
+ if (pdfSig) {
295
+ for (const c of pdfSig.checks) check(c.name, c.ok, c.detail);
296
+ report.pdf_signature = { signer: pdfSig.signer, signed_at_timestamp: pdfSig.timestamp?.time ?? null, timestamp_authority: pdfSig.timestamp?.authority ?? null };
297
+ }
298
+ }
299
+ const evidence = json("evidence.json");
300
+ let chainOk = evidence !== null && evidence.format === EVIDENCE_FORMAT && evidence.events.length > 0;
301
+ let prev = null;
302
+ for (const [i2, e] of (evidence?.events ?? []).entries()) {
303
+ const { hash, ...rest } = e;
304
+ if (e.seq !== i2 + 1 || e.prev_hash !== prev || sha256Hex(eventHashInput(rest)) !== hash || e.document_id !== manifest.document_id) {
305
+ chainOk = false;
306
+ check("evidence chain", false, `event ${e.seq} (${e.type}) does not match the chain`);
307
+ break;
308
+ }
309
+ prev = hash;
310
+ }
311
+ if (chainOk) check("evidence chain", true, `${evidence.events.length} events`);
312
+ const agreement = json("agreement.json");
313
+ const md = files["agreement.md"];
314
+ if (agreement) {
315
+ report.title = agreement.title;
316
+ report.signers = agreement.signers.map((s) => ({ key: s.key, name: s.name, email: s.email, signed_at: s.signed_at }));
317
+ check("revision matches manifest", agreement.revision === manifest.revision);
318
+ } else {
319
+ check("agreement.json readable", false);
320
+ }
321
+ const events = evidence?.events ?? [];
322
+ const sent = events.find((e) => e.type === "document.sent");
323
+ const mdHash = md ? sha256Hex(md) : null;
324
+ check("agreement.md matches the sent document", sent !== void 0 && mdHash !== null && sent.data.content_sha256 === mdHash);
325
+ const sigs = json("signatures.json");
326
+ for (const s of agreement?.signers ?? []) {
327
+ const ev = events.find((e) => e.type === "signer.signed" && e.data.signer === s.key);
328
+ const consent = events.find((e) => e.type === "signer.consented" && e.data.signer === s.key);
329
+ let ok = ev !== void 0 && consent !== void 0 && ev.data.content_sha256 === mdHash;
330
+ const evFields = ev?.data.fields ?? [];
331
+ for (const f of evFields) {
332
+ const stored = sigs?.fields.find((x2) => x2.key === f.key);
333
+ if (!stored || sha256Hex(JSON.stringify(stored.value)) !== f.value_sha256) ok = false;
334
+ }
335
+ check(`signer ${s.key} signed`, ok, `${s.name} <${s.email}>`);
336
+ }
337
+ report.ok = checks.every((c) => c.ok);
338
+ return report;
339
+ }
340
+
341
+ // ../../node_modules/.pnpm/fflate@0.8.3/node_modules/fflate/esm/index.mjs
342
+ import { createRequire } from "module";
343
+ var require2 = createRequire("/");
344
+ var _a;
345
+ var Worker;
346
+ var isMarkedAsUntransferable;
347
+ try {
348
+ _a = require2("worker_threads"), Worker = _a.Worker, isMarkedAsUntransferable = _a.isMarkedAsUntransferable;
349
+ } catch (e) {
350
+ }
351
+ var u8 = Uint8Array;
352
+ var u16 = Uint16Array;
353
+ var i32 = Int32Array;
354
+ var fleb = new u8([
355
+ 0,
356
+ 0,
357
+ 0,
358
+ 0,
359
+ 0,
360
+ 0,
361
+ 0,
362
+ 0,
363
+ 1,
364
+ 1,
365
+ 1,
366
+ 1,
367
+ 2,
368
+ 2,
369
+ 2,
370
+ 2,
371
+ 3,
372
+ 3,
373
+ 3,
374
+ 3,
375
+ 4,
376
+ 4,
377
+ 4,
378
+ 4,
379
+ 5,
380
+ 5,
381
+ 5,
382
+ 5,
383
+ 0,
384
+ /* unused */
385
+ 0,
386
+ 0,
387
+ /* impossible */
388
+ 0
389
+ ]);
390
+ var fdeb = new u8([
391
+ 0,
392
+ 0,
393
+ 0,
394
+ 0,
395
+ 1,
396
+ 1,
397
+ 2,
398
+ 2,
399
+ 3,
400
+ 3,
401
+ 4,
402
+ 4,
403
+ 5,
404
+ 5,
405
+ 6,
406
+ 6,
407
+ 7,
408
+ 7,
409
+ 8,
410
+ 8,
411
+ 9,
412
+ 9,
413
+ 10,
414
+ 10,
415
+ 11,
416
+ 11,
417
+ 12,
418
+ 12,
419
+ 13,
420
+ 13,
421
+ /* unused */
422
+ 0,
423
+ 0
424
+ ]);
425
+ var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
426
+ var freb = function(eb, start) {
427
+ var b = new u16(31);
428
+ for (var i2 = 0; i2 < 31; ++i2) {
429
+ b[i2] = start += 1 << eb[i2 - 1];
430
+ }
431
+ var r = new i32(b[30]);
432
+ for (var i2 = 1; i2 < 30; ++i2) {
433
+ for (var j = b[i2]; j < b[i2 + 1]; ++j) {
434
+ r[j] = j - b[i2] << 5 | i2;
435
+ }
436
+ }
437
+ return { b, r };
438
+ };
439
+ var _a = freb(fleb, 2);
440
+ var fl = _a.b;
441
+ var revfl = _a.r;
442
+ fl[28] = 258, revfl[258] = 28;
443
+ var _b = freb(fdeb, 0);
444
+ var fd = _b.b;
445
+ var revfd = _b.r;
446
+ var rev = new u16(32768);
447
+ for (i = 0; i < 32768; ++i) {
448
+ x = (i & 43690) >> 1 | (i & 21845) << 1;
449
+ x = (x & 52428) >> 2 | (x & 13107) << 2;
450
+ x = (x & 61680) >> 4 | (x & 3855) << 4;
451
+ rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1;
452
+ }
453
+ var x;
454
+ var i;
455
+ var hMap = (function(cd, mb, r) {
456
+ var s = cd.length;
457
+ var i2 = 0;
458
+ var l = new u16(mb);
459
+ for (; i2 < s; ++i2) {
460
+ if (cd[i2])
461
+ ++l[cd[i2] - 1];
462
+ }
463
+ var le = new u16(mb);
464
+ for (i2 = 1; i2 < mb; ++i2) {
465
+ le[i2] = le[i2 - 1] + l[i2 - 1] << 1;
466
+ }
467
+ var co;
468
+ if (r) {
469
+ co = new u16(1 << mb);
470
+ var rvb = 15 - mb;
471
+ for (i2 = 0; i2 < s; ++i2) {
472
+ if (cd[i2]) {
473
+ var sv = i2 << 4 | cd[i2];
474
+ var r_1 = mb - cd[i2];
475
+ var v = le[cd[i2] - 1]++ << r_1;
476
+ for (var m = v | (1 << r_1) - 1; v <= m; ++v) {
477
+ co[rev[v] >> rvb] = sv;
478
+ }
479
+ }
480
+ }
481
+ } else {
482
+ co = new u16(s);
483
+ for (i2 = 0; i2 < s; ++i2) {
484
+ if (cd[i2]) {
485
+ co[i2] = rev[le[cd[i2] - 1]++] >> 15 - cd[i2];
486
+ }
487
+ }
488
+ }
489
+ return co;
490
+ });
491
+ var flt = new u8(288);
492
+ for (i = 0; i < 144; ++i)
493
+ flt[i] = 8;
494
+ var i;
495
+ for (i = 144; i < 256; ++i)
496
+ flt[i] = 9;
497
+ var i;
498
+ for (i = 256; i < 280; ++i)
499
+ flt[i] = 7;
500
+ var i;
501
+ for (i = 280; i < 288; ++i)
502
+ flt[i] = 8;
503
+ var i;
504
+ var fdt = new u8(32);
505
+ for (i = 0; i < 32; ++i)
506
+ fdt[i] = 5;
507
+ var i;
508
+ var flrm = /* @__PURE__ */ hMap(flt, 9, 1);
509
+ var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
510
+ var max = function(a) {
511
+ var m = a[0];
512
+ for (var i2 = 1; i2 < a.length; ++i2) {
513
+ if (a[i2] > m)
514
+ m = a[i2];
515
+ }
516
+ return m;
517
+ };
518
+ var bits = function(d, p, m) {
519
+ var o = p / 8 | 0;
520
+ return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
521
+ };
522
+ var bits16 = function(d, p) {
523
+ var o = p / 8 | 0;
524
+ return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
525
+ };
526
+ var shft = function(p) {
527
+ return (p + 7) / 8 | 0;
528
+ };
529
+ var slc = function(v, s, e) {
530
+ if (s == null || s < 0)
531
+ s = 0;
532
+ if (e == null || e > v.length)
533
+ e = v.length;
534
+ return new u8(v.subarray(s, e));
535
+ };
536
+ var ec = [
537
+ "unexpected EOF",
538
+ "invalid block type",
539
+ "invalid length/literal",
540
+ "invalid distance",
541
+ "stream finished",
542
+ "no stream handler",
543
+ ,
544
+ // determined by compression function
545
+ "no callback",
546
+ "invalid UTF-8 data",
547
+ "extra field too long",
548
+ "date not in range 1980-2099",
549
+ "filename too long",
550
+ "stream finishing",
551
+ "invalid zip data"
552
+ // determined by unknown compression method
553
+ ];
554
+ var err = function(ind, msg, nt) {
555
+ var e = new Error(msg || ec[ind]);
556
+ e.code = ind;
557
+ if (Error.captureStackTrace)
558
+ Error.captureStackTrace(e, err);
559
+ if (!nt)
560
+ throw e;
561
+ return e;
562
+ };
563
+ var inflt = function(dat, st, buf, dict) {
564
+ var sl = dat.length, dl = dict ? dict.length : 0;
565
+ if (!sl || st.f && !st.l)
566
+ return buf || new u8(0);
567
+ var noBuf = !buf;
568
+ var resize = noBuf || st.i != 2;
569
+ var noSt = st.i;
570
+ if (noBuf)
571
+ buf = new u8(sl * 3);
572
+ var cbuf = function(l2) {
573
+ var bl = buf.length;
574
+ if (l2 > bl) {
575
+ var nbuf = new u8(Math.max(bl * 2, l2));
576
+ nbuf.set(buf);
577
+ buf = nbuf;
578
+ }
579
+ };
580
+ var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
581
+ var tbts = sl * 8;
582
+ do {
583
+ if (!lm) {
584
+ final = bits(dat, pos, 1);
585
+ var type = bits(dat, pos + 1, 3);
586
+ pos += 3;
587
+ if (!type) {
588
+ var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l;
589
+ if (t > sl) {
590
+ if (noSt)
591
+ err(0);
592
+ break;
593
+ }
594
+ if (resize)
595
+ cbuf(bt + l);
596
+ buf.set(dat.subarray(s, t), bt);
597
+ st.b = bt += l, st.p = pos = t * 8, st.f = final;
598
+ continue;
599
+ } else if (type == 1)
600
+ lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
601
+ else if (type == 2) {
602
+ var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
603
+ var tl = hLit + bits(dat, pos + 5, 31) + 1;
604
+ pos += 14;
605
+ var ldt = new u8(tl);
606
+ var clt = new u8(19);
607
+ for (var i2 = 0; i2 < hcLen; ++i2) {
608
+ clt[clim[i2]] = bits(dat, pos + i2 * 3, 7);
609
+ }
610
+ pos += hcLen * 3;
611
+ var clb = max(clt), clbmsk = (1 << clb) - 1;
612
+ var clm = hMap(clt, clb, 1);
613
+ for (var i2 = 0; i2 < tl; ) {
614
+ var r = clm[bits(dat, pos, clbmsk)];
615
+ pos += r & 15;
616
+ var s = r >> 4;
617
+ if (s < 16) {
618
+ ldt[i2++] = s;
619
+ } else {
620
+ var c = 0, n = 0;
621
+ if (s == 16)
622
+ n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i2 - 1];
623
+ else if (s == 17)
624
+ n = 3 + bits(dat, pos, 7), pos += 3;
625
+ else if (s == 18)
626
+ n = 11 + bits(dat, pos, 127), pos += 7;
627
+ while (n--)
628
+ ldt[i2++] = c;
629
+ }
630
+ }
631
+ var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
632
+ lbt = max(lt);
633
+ dbt = max(dt);
634
+ lm = hMap(lt, lbt, 1);
635
+ dm = hMap(dt, dbt, 1);
636
+ } else
637
+ err(1);
638
+ if (pos > tbts) {
639
+ if (noSt)
640
+ err(0);
641
+ break;
642
+ }
643
+ }
644
+ if (resize)
645
+ cbuf(bt + 131072);
646
+ var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
647
+ var lpos = pos;
648
+ for (; ; lpos = pos) {
649
+ var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
650
+ pos += c & 15;
651
+ if (pos > tbts) {
652
+ if (noSt)
653
+ err(0);
654
+ break;
655
+ }
656
+ if (!c)
657
+ err(2);
658
+ if (sym < 256)
659
+ buf[bt++] = sym;
660
+ else if (sym == 256) {
661
+ lpos = pos, lm = null;
662
+ break;
663
+ } else {
664
+ var add = sym - 254;
665
+ if (sym > 264) {
666
+ var i2 = sym - 257, b = fleb[i2];
667
+ add = bits(dat, pos, (1 << b) - 1) + fl[i2];
668
+ pos += b;
669
+ }
670
+ var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
671
+ if (!d)
672
+ err(3);
673
+ pos += d & 15;
674
+ var dt = fd[dsym];
675
+ if (dsym > 3) {
676
+ var b = fdeb[dsym];
677
+ dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
678
+ }
679
+ if (pos > tbts) {
680
+ if (noSt)
681
+ err(0);
682
+ break;
683
+ }
684
+ if (resize)
685
+ cbuf(bt + 131072);
686
+ var end = bt + add;
687
+ if (bt < dt) {
688
+ var shift = dl - dt, dend = Math.min(dt, end);
689
+ if (shift + bt < 0)
690
+ err(3);
691
+ for (; bt < dend; ++bt)
692
+ buf[bt] = dict[shift + bt];
693
+ }
694
+ for (; bt < end; ++bt)
695
+ buf[bt] = buf[bt - dt];
696
+ }
697
+ }
698
+ st.l = lm, st.p = lpos, st.b = bt, st.f = final;
699
+ if (lm)
700
+ final = 1, st.m = lbt, st.d = dm, st.n = dbt;
701
+ } while (!final);
702
+ return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
703
+ };
704
+ var et = /* @__PURE__ */ new u8(0);
705
+ var b2 = function(d, b) {
706
+ return d[b] | d[b + 1] << 8;
707
+ };
708
+ var b4 = function(d, b) {
709
+ return (d[b] | d[b + 1] << 8 | d[b + 2] << 16 | d[b + 3] << 24) >>> 0;
710
+ };
711
+ var b8 = function(d, b) {
712
+ return b4(d, b) + b4(d, b + 4) * 4294967296;
713
+ };
714
+ function inflateSync(data, opts) {
715
+ return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
716
+ }
717
+ var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder();
718
+ var tds = 0;
719
+ try {
720
+ td.decode(et, { stream: true });
721
+ tds = 1;
722
+ } catch (e) {
723
+ }
724
+ var dutf8 = function(d) {
725
+ for (var r = "", i2 = 0; ; ) {
726
+ var c = d[i2++];
727
+ var eb = (c > 127) + (c > 223) + (c > 239);
728
+ if (i2 + eb > d.length)
729
+ return { s: r, r: slc(d, i2 - 1) };
730
+ if (!eb)
731
+ r += String.fromCharCode(c);
732
+ else if (eb == 3) {
733
+ c = ((c & 15) << 18 | (d[i2++] & 63) << 12 | (d[i2++] & 63) << 6 | d[i2++] & 63) - 65536, r += String.fromCharCode(55296 | c >> 10, 56320 | c & 1023);
734
+ } else if (eb & 1)
735
+ r += String.fromCharCode((c & 31) << 6 | d[i2++] & 63);
736
+ else
737
+ r += String.fromCharCode((c & 15) << 12 | (d[i2++] & 63) << 6 | d[i2++] & 63);
738
+ }
739
+ };
740
+ function strFromU8(dat, latin1) {
741
+ if (latin1) {
742
+ var r = "";
743
+ for (var i2 = 0; i2 < dat.length; i2 += 16384)
744
+ r += String.fromCharCode.apply(null, dat.subarray(i2, i2 + 16384));
745
+ return r;
746
+ } else if (td) {
747
+ return td.decode(dat);
748
+ } else {
749
+ var _a2 = dutf8(dat), s = _a2.s, r = _a2.r;
750
+ if (r.length)
751
+ err(8);
752
+ return s;
753
+ }
754
+ }
755
+ var slzh = function(d, b) {
756
+ return b + 30 + b2(d, b + 26) + b2(d, b + 28);
757
+ };
758
+ var zh = function(d, b, z) {
759
+ var fnl = b2(d, b + 28), efl = b2(d, b + 30), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl;
760
+ var _a2 = z64hs(d, es, efl, z, b4(d, b + 20), b4(d, b + 24), b4(d, b + 42)), sc = _a2[0], su = _a2[1], off = _a2[2];
761
+ return [b2(d, b + 10), sc, su, fn, es + efl + b2(d, b + 32), off];
762
+ };
763
+ var z64hs = function(d, b, l, z, sc, su, off) {
764
+ var nsc = sc == 4294967295, nsu = su == 4294967295, noff = off == 4294967295, e = b + l;
765
+ var nf = nsc + nsu + noff;
766
+ if (z && nf) {
767
+ for (; b + 4 < e; b += 4 + b2(d, b + 2)) {
768
+ if (b2(d, b) == 1) {
769
+ return [
770
+ nsc ? b8(d, b + 4 + 8 * nsu) : sc,
771
+ nsu ? b8(d, b + 4) : su,
772
+ noff ? b8(d, b + 4 + 8 * (nsu + nsc)) : off,
773
+ 1
774
+ ];
775
+ }
776
+ }
777
+ if (z < 2)
778
+ err(13);
779
+ }
780
+ return [sc, su, off, 0];
781
+ };
782
+ function unzipSync(data, opts) {
783
+ var files = {};
784
+ var e = data.length - 22;
785
+ for (; b4(data, e) != 101010256; --e) {
786
+ if (!e || data.length - e > 65558)
787
+ err(13);
788
+ }
789
+ ;
790
+ var c = b2(data, e + 8);
791
+ if (!c)
792
+ return {};
793
+ var o = b4(data, e + 16);
794
+ var z = b4(data, e - 20) == 117853008;
795
+ if (z) {
796
+ var ze = b4(data, e - 12);
797
+ z = b4(data, ze) == 101075792;
798
+ if (z) {
799
+ c = b4(data, ze + 32);
800
+ o = b4(data, ze + 48);
801
+ }
802
+ }
803
+ var fltr = opts && opts.filter;
804
+ for (var i2 = 0; i2 < c; ++i2) {
805
+ var _a2 = zh(data, o, z), c_2 = _a2[0], sc = _a2[1], su = _a2[2], fn = _a2[3], no = _a2[4], off = _a2[5], b = slzh(data, off);
806
+ o = no;
807
+ if (!fltr || fltr({
808
+ name: fn,
809
+ size: sc,
810
+ originalSize: su,
811
+ compression: c_2
812
+ })) {
813
+ if (!c_2)
814
+ files[fn] = slc(data, b, b + sc);
815
+ else if (c_2 == 8)
816
+ files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });
817
+ else
818
+ err(14, "unknown compression type " + c_2);
819
+ }
820
+ }
821
+ return files;
822
+ }
823
+
824
+ // src/index.ts
825
+ function verifyPackage(zip, opts = {}) {
826
+ let files;
827
+ try {
828
+ files = unzipSync(zip);
829
+ } catch {
830
+ return { ok: false, document_id: null, title: null, revision: null, key_id: null, trusted_key: false, signers: [], timestamp: null, pdf_signature: null, checks: [{ name: "readable ZIP", ok: false }] };
831
+ }
832
+ return verifyPackageFiles(files, opts);
833
+ }
834
+ function trustedKeysFrom(json) {
835
+ const data = JSON.parse(json);
836
+ if (Array.isArray(data.keys)) return data.keys.map((k) => k.public_key);
837
+ if (typeof data.public_key === "string") return [data.public_key];
838
+ throw new Error("Keys file has no public keys");
839
+ }
840
+
841
+ // src/cli.ts
842
+ var HELP = `signed-md verify <agreement.zip> [--keys <keys.json>] [--json]
843
+
844
+ Verifies a Signed.md completion package offline:
845
+ - every file matches the signed manifest
846
+ - the manifest signature is valid
847
+ - the evidence log hash chain is intact
848
+ - every signer signed the exact agreement content
849
+
850
+ --keys A keys file you trust (download /.well-known/signed-md-keys.json from the
851
+ sender's server once and keep it). Without it, the package is checked against
852
+ the public key it carries, which proves integrity but not who signed it.
853
+ --json Print the full report as JSON.`;
854
+ function run(argv) {
855
+ const [cmd, ...rest] = argv;
856
+ if (cmd !== "verify" || rest.includes("-h") || rest.includes("--help")) {
857
+ console.log(HELP);
858
+ return cmd === "verify" || cmd === "-h" || cmd === "--help" || cmd === void 0 ? 0 : 2;
859
+ }
860
+ const file = rest.find((a, i2) => !a.startsWith("--") && rest[i2 - 1] !== "--keys");
861
+ if (!file) {
862
+ console.error("Missing package file.\n\n" + HELP);
863
+ return 2;
864
+ }
865
+ const keysIdx = rest.indexOf("--keys");
866
+ const keysFile = keysIdx >= 0 ? rest[keysIdx + 1] : void 0;
867
+ if (keysIdx >= 0 && (!keysFile || keysFile.startsWith("--"))) {
868
+ console.error("--keys needs a keys file.\n\n" + HELP);
869
+ return 2;
870
+ }
871
+ let trustedKeys;
872
+ let bytes;
873
+ try {
874
+ trustedKeys = keysFile ? trustedKeysFrom(readFileSync(keysFile, "utf8")) : void 0;
875
+ } catch (e) {
876
+ console.error(`Could not read the keys file ${keysFile}: ${reason(e)}`);
877
+ return 2;
878
+ }
879
+ try {
880
+ bytes = new Uint8Array(readFileSync(file));
881
+ } catch (e) {
882
+ console.error(`Could not read ${file}: ${reason(e)}`);
883
+ return 2;
884
+ }
885
+ let report;
886
+ try {
887
+ report = verifyPackage(bytes, trustedKeys ? { trustedKeys } : {});
888
+ } catch (e) {
889
+ console.error(`INVALID: ${file} is not a Signed.md package (${reason(e)}).`);
890
+ return 1;
891
+ }
892
+ if (rest.includes("--json")) {
893
+ console.log(JSON.stringify(report, null, 2));
894
+ return report.ok ? 0 : 1;
895
+ }
896
+ const mark = (ok) => ok ? "\u2713" : "\u2717";
897
+ console.log(`${report.title ?? "Unknown document"} (${report.document_id ?? "?"})`);
898
+ console.log(`Revision ${report.revision ?? "?"} \xB7 key ${report.key_id ?? "?"}
899
+ `);
900
+ for (const c of report.checks) console.log(` ${mark(c.ok)} ${c.name}${c.detail ? ` \u2013 ${c.detail}` : ""}`);
901
+ console.log("");
902
+ if (report.ok) {
903
+ console.log(trustedKeys ? "VALID: the package is intact and signed by a key you trust." : "VALID: the package is intact. Pass --keys to also check who signed it.");
904
+ } else {
905
+ console.log("INVALID: the package was changed or is incomplete.");
906
+ }
907
+ return report.ok ? 0 : 1;
908
+ }
909
+ function reason(e) {
910
+ if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") return "no such file";
911
+ if (e && typeof e === "object" && "code" in e && e.code === "EISDIR") return "it is a folder";
912
+ return e instanceof Error ? e.message : String(e);
913
+ }
914
+ export {
915
+ run
916
+ };
package/package.json CHANGED
@@ -1,6 +1,19 @@
1
1
  {
2
2
  "name": "signed-md",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.1",
4
+ "description": "Verify Signed.md completion packages offline.",
5
+ "type": "module",
6
+ "bin": {
7
+ "signed-md": "bin/signed-md.js"
8
+ },
9
+ "license": "AGPL-3.0-only",
10
+ "homepage": "https://github.com/varops/signed-md/tree/main/packages/verify#readme",
11
+ "files": [
12
+ "bin",
13
+ "dist"
14
+ ],
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/varops/signed-md.git"
18
+ }
19
+ }