xvcache-mcp 0.0.0-stage → 0.2.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/AGENTS.md +86 -0
- package/LICENSE +202 -0
- package/NOTICE +8 -0
- package/README.md +230 -2
- package/SECURITY.md +25 -0
- package/TRADEMARK.md +17 -0
- package/certs/freetsa-cacert.pem +45 -0
- package/dist/certify.js +378 -0
- package/dist/der.js +102 -0
- package/dist/journal.js +295 -0
- package/dist/merkle.js +66 -0
- package/dist/ots.js +311 -0
- package/dist/plans.js +114 -0
- package/dist/server.js +586 -0
- package/dist/tsa.js +217 -0
- package/dist/verify-journal.js +23 -0
- package/llms.txt +47 -0
- package/package.json +73 -4
- package/plans.json +217 -0
- package/server.json +87 -0
package/dist/certify.js
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
import { promises as fs } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { sha256Hex, verifyJournalFile, readCompleteJournalLines, parseEntry, lastNoteRecord, normalizeNotePath, } from "./journal.js";
|
|
4
|
+
import { leafHash, merkleRoot, merklePath, verifyMerklePath } from "./merkle.js";
|
|
5
|
+
import { requestTimestamp, parseTimeStampToken, verifyTokenSignature, certsDir, OID_SHA256, } from "./tsa.js";
|
|
6
|
+
import { stampDigest, serializeOts, parseOts, upgradeTimestamp, otsStatus, DEFAULT_CALENDARS } from "./ots.js";
|
|
7
|
+
export const PROOF_FORMAT = "xvcache-proof/1";
|
|
8
|
+
export function certifyConfigFromEnv(base, env = process.env) {
|
|
9
|
+
const dataDir = env.XVCACHE_DATA ? path.resolve(env.XVCACHE_DATA) : path.join(path.dirname(base.journalPath), ".xvcache");
|
|
10
|
+
const otsOff = (env.XVCACHE_OTS ?? "on").toLowerCase();
|
|
11
|
+
const calendars = env.XVCACHE_OTS_CALENDARS ? env.XVCACHE_OTS_CALENDARS.split(",").map((s) => s.trim()).filter(Boolean) : DEFAULT_CALENDARS;
|
|
12
|
+
return { ...base, dataDir, ots: { enabled: !(otsOff === "off" || otsOff === "0" || otsOff === "false"), calendars } };
|
|
13
|
+
}
|
|
14
|
+
const NOTICE = "This proof contains hashes only, never note content. Layer A: RFC 3161 token over the Merkle root (legal value only if the provider is qualified eIDAS). Layer B: OpenTimestamps anchor of the same root (public, Bitcoin, confirmation takes hours). One timestamp covers every note in the batch.";
|
|
15
|
+
const HEX64 = /^[0-9a-f]{64}$/;
|
|
16
|
+
function errMsg(e) {
|
|
17
|
+
return e instanceof Error ? e.message : String(e);
|
|
18
|
+
}
|
|
19
|
+
/** Resolve a vault-relative .md note with the same rules as verify_journal. */
|
|
20
|
+
export async function resolveNoteInVault(vaultRoot, rel) {
|
|
21
|
+
if (path.isAbsolute(rel))
|
|
22
|
+
return { error: "Refusé : chemin absolu interdit." };
|
|
23
|
+
const norm = rel.replace(/\\/g, "/");
|
|
24
|
+
if (norm.split("/").some((p) => p === ".."))
|
|
25
|
+
return { error: "Refusé : chemin hors du coffre." };
|
|
26
|
+
const relMd = normalizeNotePath(norm).replace(/^\.\//, "");
|
|
27
|
+
const target = path.resolve(vaultRoot, relMd);
|
|
28
|
+
if (!target.startsWith(vaultRoot + path.sep))
|
|
29
|
+
return { error: "Refusé : chemin hors du coffre." };
|
|
30
|
+
let real;
|
|
31
|
+
try {
|
|
32
|
+
real = await fs.realpath(target);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return { error: "Note introuvable." };
|
|
36
|
+
}
|
|
37
|
+
if (!real.startsWith(vaultRoot + path.sep))
|
|
38
|
+
return { error: "Refusé : lien symbolique hors du coffre." };
|
|
39
|
+
return { real, relMd: path.relative(vaultRoot, real).split(path.sep).join("/") };
|
|
40
|
+
}
|
|
41
|
+
async function readJson(file, fallback) {
|
|
42
|
+
try {
|
|
43
|
+
return JSON.parse(await fs.readFile(file, "utf8"));
|
|
44
|
+
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
if (e.code === "ENOENT")
|
|
47
|
+
return fallback;
|
|
48
|
+
throw e;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
async function writeJsonAtomic(file, value) {
|
|
52
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
53
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
54
|
+
await fs.writeFile(tmp, JSON.stringify(value, null, 2) + "\n", { encoding: "utf8", mode: 0o644 });
|
|
55
|
+
await fs.rename(tmp, file);
|
|
56
|
+
}
|
|
57
|
+
function batchIdFor(date, root) {
|
|
58
|
+
return date.toISOString().replace(/[-:]/g, "").replace(/\.(\d{3})Z$/, "$1Z") + "-" + root.slice(0, 8);
|
|
59
|
+
}
|
|
60
|
+
export class Certifier {
|
|
61
|
+
cfg;
|
|
62
|
+
lock = Promise.resolve();
|
|
63
|
+
constructor(cfg) { this.cfg = cfg; }
|
|
64
|
+
get pendingFile() { return path.join(this.cfg.dataDir, "pending.json"); }
|
|
65
|
+
proofsDir() { return path.join(this.cfg.dataDir, "proofs"); }
|
|
66
|
+
batchesDir() { return path.join(this.cfg.dataDir, "batches"); }
|
|
67
|
+
serialize(fn) {
|
|
68
|
+
const run = this.lock.then(fn, fn);
|
|
69
|
+
this.lock = run.catch(() => { });
|
|
70
|
+
return run;
|
|
71
|
+
}
|
|
72
|
+
async journalEntries() {
|
|
73
|
+
const chain = await verifyJournalFile(this.cfg.journalPath);
|
|
74
|
+
if (!chain.ok)
|
|
75
|
+
return { ok: false, entries: [] };
|
|
76
|
+
const entries = [];
|
|
77
|
+
for (const line of await readCompleteJournalLines(this.cfg.journalPath)) {
|
|
78
|
+
const p = parseEntry(line);
|
|
79
|
+
if (!("error" in p))
|
|
80
|
+
entries.push(p);
|
|
81
|
+
}
|
|
82
|
+
return { ok: true, entries, lastSeq: chain.lastSeq, lastHash: chain.lastHash };
|
|
83
|
+
}
|
|
84
|
+
async pending() {
|
|
85
|
+
return readJson(this.pendingFile, []);
|
|
86
|
+
}
|
|
87
|
+
/** Add the note's current fingerprint to the pending batch. */
|
|
88
|
+
async enqueue(rel) {
|
|
89
|
+
return this.serialize(async () => {
|
|
90
|
+
const r = await resolveNoteInVault(this.cfg.vaultRoot, rel);
|
|
91
|
+
if ("error" in r)
|
|
92
|
+
return r;
|
|
93
|
+
const sha = sha256Hex(await fs.readFile(r.real));
|
|
94
|
+
const j = await this.journalEntries();
|
|
95
|
+
let journal_status;
|
|
96
|
+
if (!j.ok)
|
|
97
|
+
journal_status = "journal altéré";
|
|
98
|
+
else {
|
|
99
|
+
const rec = lastNoteRecord(j.entries, r.relMd);
|
|
100
|
+
journal_status = !rec ? "non journalisée" : rec.note_sha256 === sha ? "V" : "X";
|
|
101
|
+
}
|
|
102
|
+
const item = { path: r.relMd, note_sha256: sha, queued_at: new Date().toISOString(), journal_status };
|
|
103
|
+
const list = (await this.pending()).filter((p) => p.path !== item.path);
|
|
104
|
+
list.push(item);
|
|
105
|
+
await writeJsonAtomic(this.pendingFile, list);
|
|
106
|
+
return item;
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
/** Stamp every pending note with one timestamp over the Merkle root. */
|
|
110
|
+
async runBatch() {
|
|
111
|
+
return this.serialize(async () => {
|
|
112
|
+
const list = (await this.pending()).slice().sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
113
|
+
if (list.length === 0)
|
|
114
|
+
return { error: "Aucune note en attente de certification." };
|
|
115
|
+
if (!this.cfg.tsa && !this.cfg.ots.enabled)
|
|
116
|
+
return { error: "Aucun témoin configuré (TSA désactivée et OpenTimestamps désactivé)." };
|
|
117
|
+
const leaves = list.map((p) => ({ k: "note", p: p.path, h: p.note_sha256 }));
|
|
118
|
+
const j = await this.journalEntries();
|
|
119
|
+
let journalHead = null;
|
|
120
|
+
if (j.ok && j.lastSeq && j.lastHash) {
|
|
121
|
+
const jl = { k: "journal", seq: j.lastSeq, h: j.lastHash };
|
|
122
|
+
leaves.push(jl);
|
|
123
|
+
journalHead = { seq: j.lastSeq, hash: j.lastHash, leaf_hash: leafHash(jl) };
|
|
124
|
+
}
|
|
125
|
+
const hashes = leaves.map(leafHash);
|
|
126
|
+
const root = merkleRoot(hashes);
|
|
127
|
+
let tsa = null;
|
|
128
|
+
let tokenDer = null;
|
|
129
|
+
if (this.cfg.tsa) {
|
|
130
|
+
try {
|
|
131
|
+
const res = await requestTimestamp(this.cfg.tsa, root, { fetchImpl: this.cfg.fetchImpl });
|
|
132
|
+
tokenDer = res.token;
|
|
133
|
+
tsa = {
|
|
134
|
+
provider: this.cfg.tsa.id,
|
|
135
|
+
label: this.cfg.tsa.label,
|
|
136
|
+
url: this.cfg.tsa.url,
|
|
137
|
+
qualified: this.cfg.tsa.qualified,
|
|
138
|
+
qualified_basis: this.cfg.tsa.qualifiedBasis,
|
|
139
|
+
hash_algorithm: "sha256",
|
|
140
|
+
message_imprint: res.info.messageImprint,
|
|
141
|
+
gen_time: res.info.genTime,
|
|
142
|
+
serial: res.info.serial,
|
|
143
|
+
policy: res.info.policy,
|
|
144
|
+
token_base64: res.token.toString("base64"),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
catch (e) {
|
|
148
|
+
return { error: `Horodatage TSA impossible, notes laissées en attente : ${errMsg(e)}` };
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
let ots = null;
|
|
152
|
+
let otsBuf = null;
|
|
153
|
+
let ots_error;
|
|
154
|
+
if (this.cfg.ots.enabled) {
|
|
155
|
+
try {
|
|
156
|
+
const s = await stampDigest(Buffer.from(root, "hex"), this.cfg.ots.calendars, this.cfg.fetchImpl);
|
|
157
|
+
otsBuf = serializeOts(s.ts);
|
|
158
|
+
ots = { status: "pending", calendars: s.calendars, ots_base64: otsBuf.toString("base64"), detail: "Soumis aux calendriers OpenTimestamps ; confirmation Bitcoin en quelques heures." };
|
|
159
|
+
}
|
|
160
|
+
catch (e) {
|
|
161
|
+
ots_error = errMsg(e);
|
|
162
|
+
if (!tsa)
|
|
163
|
+
return { error: `Aucun témoin n'a répondu, notes laissées en attente : ${ots_error}` };
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
const created = new Date();
|
|
167
|
+
const batchId = batchIdFor(created, root);
|
|
168
|
+
const bdir = path.join(this.batchesDir(), batchId);
|
|
169
|
+
await fs.mkdir(bdir, { recursive: true });
|
|
170
|
+
if (tokenDer)
|
|
171
|
+
await fs.writeFile(path.join(bdir, "root.tst"), tokenDer);
|
|
172
|
+
if (otsBuf)
|
|
173
|
+
await fs.writeFile(path.join(bdir, "root.ots"), otsBuf);
|
|
174
|
+
await writeJsonAtomic(path.join(bdir, "batch.json"), {
|
|
175
|
+
format: "xvcache-batch/1",
|
|
176
|
+
batch_id: batchId,
|
|
177
|
+
created_at: created.toISOString(),
|
|
178
|
+
root,
|
|
179
|
+
leaf_hashes: hashes,
|
|
180
|
+
notes: list.map((p) => ({ path: p.path, note_sha256: p.note_sha256 })),
|
|
181
|
+
journal_head: journalHead,
|
|
182
|
+
tsa: tsa ? { provider: tsa.provider, qualified: tsa.qualified, gen_time: tsa.gen_time, serial: tsa.serial } : null,
|
|
183
|
+
ots: ots ? { status: ots.status, calendars: ots.calendars } : ots_error ? { status: "error", error: ots_error } : null,
|
|
184
|
+
});
|
|
185
|
+
const proofs = [];
|
|
186
|
+
for (let i = 0; i < list.length; i++) {
|
|
187
|
+
const p = list[i];
|
|
188
|
+
const proof = {
|
|
189
|
+
format: PROOF_FORMAT,
|
|
190
|
+
path: p.path,
|
|
191
|
+
note_sha256: p.note_sha256,
|
|
192
|
+
leaf: leaves[i],
|
|
193
|
+
leaf_hash: hashes[i],
|
|
194
|
+
merkle: { scheme: "sha256, leaf=H(0x00||canonical_json(leaf)), node=H(0x01||L||R), odd node promoted", leaf_index: i, leaf_count: hashes.length, path: merklePath(hashes, i), root },
|
|
195
|
+
batch_id: batchId,
|
|
196
|
+
batch_created_at: created.toISOString(),
|
|
197
|
+
queued_at: p.queued_at,
|
|
198
|
+
journal_status_at_certification: p.journal_status,
|
|
199
|
+
journal_head: journalHead,
|
|
200
|
+
tsa,
|
|
201
|
+
ots,
|
|
202
|
+
billing: { paid_feature: true, price: "TBD", payment_live: false },
|
|
203
|
+
notice: NOTICE,
|
|
204
|
+
};
|
|
205
|
+
await writeJsonAtomic(this.proofFile(p.path, batchId), proof);
|
|
206
|
+
proofs.push(proof);
|
|
207
|
+
}
|
|
208
|
+
const remaining = (await this.pending()).filter((q) => !list.some((p) => p.path === q.path && p.note_sha256 === q.note_sha256));
|
|
209
|
+
await writeJsonAtomic(this.pendingFile, remaining);
|
|
210
|
+
return { batch_id: batchId, root, leaf_count: hashes.length, proofs, ots_error };
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
proofFile(rel, batchId) {
|
|
214
|
+
return path.join(this.proofsDir(), ...rel.split("/"), `${batchId}.json`);
|
|
215
|
+
}
|
|
216
|
+
async latestProofFile(rel) {
|
|
217
|
+
const dir = path.join(this.proofsDir(), ...rel.split("/"));
|
|
218
|
+
let names;
|
|
219
|
+
try {
|
|
220
|
+
names = await fs.readdir(dir);
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
return null;
|
|
224
|
+
}
|
|
225
|
+
const jsons = names.filter((n) => n.endsWith(".json")).sort();
|
|
226
|
+
return jsons.length ? path.join(dir, jsons[jsons.length - 1]) : null;
|
|
227
|
+
}
|
|
228
|
+
caFor(provider) {
|
|
229
|
+
if (this.cfg.tsa && this.cfg.tsa.id === provider)
|
|
230
|
+
return { ca: this.cfg.tsa.caFile, untrusted: this.cfg.tsa.untrustedFile };
|
|
231
|
+
if (provider === "freetsa")
|
|
232
|
+
return { ca: path.join(certsDir(), "freetsa-cacert.pem") };
|
|
233
|
+
return {};
|
|
234
|
+
}
|
|
235
|
+
/** Check a proof: note hash, Merkle path, TSA token, OpenTimestamps anchor. */
|
|
236
|
+
async verify(input) {
|
|
237
|
+
const checks = {};
|
|
238
|
+
const report = (glyphOk, p, extra = {}) => {
|
|
239
|
+
const qualified = !!p?.tsa?.qualified;
|
|
240
|
+
const qualified_confirmed = qualified && checks.tsa_signature?.ok === true;
|
|
241
|
+
const shown = p?.path ?? input.path ?? "?";
|
|
242
|
+
const when = p?.tsa?.gen_time ? ` le ${p.tsa.gen_time}` : "";
|
|
243
|
+
const level = p?.tsa ? (qualified_confirmed ? "horodatage qualifié eIDAS" : qualified ? "fournisseur qualifié, signature non vérifiée" : p.tsa.label.replace(" (", ", ").replace(/\)$/, "")) : "ancrage OpenTimestamps seul";
|
|
244
|
+
const failed = Object.entries(checks).filter(([, c]) => c.ok === false).map(([k, c]) => `${k} : ${c.detail.replace(/\.$/, "")}`);
|
|
245
|
+
return {
|
|
246
|
+
glyph: glyphOk ? "V" : "X",
|
|
247
|
+
message: glyphOk
|
|
248
|
+
? `V certifiée — Note ${shown} existait telle quelle${when} (${level}).`
|
|
249
|
+
: `X preuve invalide — Note ${shown} : ${failed.join(" ; ") || "preuve illisible"}.`,
|
|
250
|
+
path: p?.path ?? input.path ?? null,
|
|
251
|
+
batch_id: p?.batch_id ?? null,
|
|
252
|
+
root: p?.merkle?.root ?? null,
|
|
253
|
+
gen_time: p?.tsa?.gen_time ?? null,
|
|
254
|
+
provider: p?.tsa?.provider ?? null,
|
|
255
|
+
qualified,
|
|
256
|
+
qualified_confirmed,
|
|
257
|
+
checks,
|
|
258
|
+
ots: null,
|
|
259
|
+
...extra,
|
|
260
|
+
};
|
|
261
|
+
};
|
|
262
|
+
let proof;
|
|
263
|
+
let proofFile = null;
|
|
264
|
+
try {
|
|
265
|
+
if (input.proof !== undefined && input.proof !== null && input.proof !== "") {
|
|
266
|
+
proof = (typeof input.proof === "string" ? JSON.parse(input.proof) : input.proof);
|
|
267
|
+
}
|
|
268
|
+
else if (input.path) {
|
|
269
|
+
const r = await resolveNoteInVault(this.cfg.vaultRoot, input.path);
|
|
270
|
+
const rel = "error" in r ? normalizeNotePath(input.path.replace(/\\/g, "/")) : r.relMd;
|
|
271
|
+
proofFile = await this.latestProofFile(rel);
|
|
272
|
+
if (!proofFile) {
|
|
273
|
+
checks.proof = { ok: false, detail: "Aucune preuve enregistrée pour cette note (lancer certify_note)." };
|
|
274
|
+
return report(false, null);
|
|
275
|
+
}
|
|
276
|
+
proof = JSON.parse(await fs.readFile(proofFile, "utf8"));
|
|
277
|
+
}
|
|
278
|
+
else {
|
|
279
|
+
checks.proof = { ok: false, detail: "Donner path ou proof." };
|
|
280
|
+
return report(false, null);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
catch (e) {
|
|
284
|
+
checks.proof = { ok: false, detail: `Preuve illisible : ${errMsg(e)}` };
|
|
285
|
+
return report(false, null);
|
|
286
|
+
}
|
|
287
|
+
if (!proof || proof.format !== PROOF_FORMAT || typeof proof.path !== "string" || !HEX64.test(String(proof.note_sha256)) || !proof.merkle || !HEX64.test(String(proof.merkle.root))) {
|
|
288
|
+
checks.proof = { ok: false, detail: "Format de preuve non reconnu." };
|
|
289
|
+
return report(false, null);
|
|
290
|
+
}
|
|
291
|
+
checks.proof = { ok: true, detail: `Preuve ${proof.batch_id}.` };
|
|
292
|
+
if (input.path && input.proof) {
|
|
293
|
+
const want = normalizeNotePath(input.path.replace(/\\/g, "/"));
|
|
294
|
+
if (want !== proof.path)
|
|
295
|
+
checks.path = { ok: false, detail: `La preuve concerne ${proof.path}, pas ${want}.` };
|
|
296
|
+
}
|
|
297
|
+
// 1) note content now vs certified fingerprint
|
|
298
|
+
const r = await resolveNoteInVault(this.cfg.vaultRoot, proof.path);
|
|
299
|
+
if ("error" in r)
|
|
300
|
+
checks.note = { ok: false, detail: r.error };
|
|
301
|
+
else {
|
|
302
|
+
const cur = sha256Hex(await fs.readFile(r.real));
|
|
303
|
+
checks.note = cur === proof.note_sha256
|
|
304
|
+
? { ok: true, detail: "Empreinte actuelle identique à l'empreinte certifiée." }
|
|
305
|
+
: { ok: false, detail: "Note MODIFIÉE depuis la certification (empreinte différente)." };
|
|
306
|
+
}
|
|
307
|
+
// 2) leaf + Merkle path -> root
|
|
308
|
+
const leaf = { k: "note", p: proof.path, h: proof.note_sha256 };
|
|
309
|
+
const lh = leafHash(leaf);
|
|
310
|
+
if (lh !== proof.leaf_hash)
|
|
311
|
+
checks.merkle = { ok: false, detail: "Feuille recalculée différente." };
|
|
312
|
+
else
|
|
313
|
+
checks.merkle = verifyMerklePath(lh, proof.merkle.path ?? [], proof.merkle.root)
|
|
314
|
+
? { ok: true, detail: `Chemin Merkle valide (${proof.merkle.path.length} étape(s), ${proof.merkle.leaf_count} feuille(s) sous la même racine).` }
|
|
315
|
+
: { ok: false, detail: "Chemin Merkle ne mène pas à la racine." };
|
|
316
|
+
// 3) RFC 3161 token
|
|
317
|
+
if (proof.tsa) {
|
|
318
|
+
try {
|
|
319
|
+
const token = Buffer.from(proof.tsa.token_base64, "base64");
|
|
320
|
+
const info = parseTimeStampToken(token);
|
|
321
|
+
if (info.hashAlgorithm !== OID_SHA256 || info.messageImprint !== proof.merkle.root) {
|
|
322
|
+
checks.tsa_token = { ok: false, detail: "Le jeton TSA ne porte pas sur cette racine." };
|
|
323
|
+
}
|
|
324
|
+
else if (info.genTime !== proof.tsa.gen_time) {
|
|
325
|
+
checks.tsa_token = { ok: false, detail: "Date du jeton différente de la date annoncée." };
|
|
326
|
+
}
|
|
327
|
+
else {
|
|
328
|
+
checks.tsa_token = { ok: true, detail: `Jeton RFC 3161 sur la racine, genTime ${info.genTime}, série ${info.serial}.` };
|
|
329
|
+
}
|
|
330
|
+
const ca = this.caFor(proof.tsa.provider);
|
|
331
|
+
const sig = await verifyTokenSignature(token, proof.merkle.root, ca.ca, ca.untrusted);
|
|
332
|
+
checks.tsa_signature = { ok: sig.status === "verified" ? true : sig.status === "failed" ? false : null, detail: sig.detail };
|
|
333
|
+
}
|
|
334
|
+
catch (e) {
|
|
335
|
+
checks.tsa_token = { ok: false, detail: `Jeton TSA illisible : ${errMsg(e)}` };
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
else {
|
|
339
|
+
checks.tsa_token = { ok: null, detail: "Pas de jeton TSA dans cette preuve." };
|
|
340
|
+
}
|
|
341
|
+
// 4) OpenTimestamps
|
|
342
|
+
let ots = null;
|
|
343
|
+
if (proof.ots?.ots_base64) {
|
|
344
|
+
try {
|
|
345
|
+
const ts = parseOts(Buffer.from(proof.ots.ots_base64, "base64"));
|
|
346
|
+
if (ts.msg.toString("hex") !== proof.merkle.root) {
|
|
347
|
+
checks.ots = { ok: false, detail: "Le fichier .ots ne porte pas sur cette racine." };
|
|
348
|
+
}
|
|
349
|
+
else {
|
|
350
|
+
const online = input.online !== false;
|
|
351
|
+
if (online && (await upgradeTimestamp(ts, this.cfg.fetchImpl))) {
|
|
352
|
+
const buf = serializeOts(ts);
|
|
353
|
+
proof.ots.ots_base64 = buf.toString("base64");
|
|
354
|
+
const bdir = path.join(this.batchesDir(), proof.batch_id);
|
|
355
|
+
await fs.writeFile(path.join(bdir, "root.ots"), buf).catch(() => { });
|
|
356
|
+
}
|
|
357
|
+
ots = await otsStatus(ts, { online, f: this.cfg.fetchImpl });
|
|
358
|
+
proof.ots.status = ots.status;
|
|
359
|
+
proof.ots.detail = ots.detail;
|
|
360
|
+
if (proofFile)
|
|
361
|
+
await writeJsonAtomic(proofFile, proof).catch(() => { });
|
|
362
|
+
checks.ots = { ok: ots.status === "failed" ? false : ots.status === "confirmed" ? true : null, detail: ots.detail };
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
catch (e) {
|
|
366
|
+
checks.ots = { ok: false, detail: `Fichier .ots illisible : ${errMsg(e)}` };
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
else {
|
|
370
|
+
checks.ots = { ok: null, detail: "Pas d'ancrage OpenTimestamps dans cette preuve." };
|
|
371
|
+
}
|
|
372
|
+
const anyWitness = checks.tsa_token.ok === true || (checks.ots.ok !== false && !!proof.ots?.ots_base64);
|
|
373
|
+
if (!anyWitness)
|
|
374
|
+
checks.witness = { ok: false, detail: "Aucun témoin valide (ni jeton TSA, ni ancrage OTS)." };
|
|
375
|
+
const allOk = Object.values(checks).every((c) => c.ok !== false);
|
|
376
|
+
return report(allOk, proof, { ots });
|
|
377
|
+
}
|
|
378
|
+
}
|
package/dist/der.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/** Minimal DER reader/writer, just enough for RFC 3161 requests and tokens. */
|
|
2
|
+
export function parseDer(buf, start = 0, end = buf.length, depth = 0) {
|
|
3
|
+
if (depth > 40)
|
|
4
|
+
throw new Error("DER : profondeur excessive.");
|
|
5
|
+
if (start + 2 > end)
|
|
6
|
+
throw new Error("DER : données tronquées.");
|
|
7
|
+
const tag = buf[start];
|
|
8
|
+
if ((tag & 0x1f) === 0x1f)
|
|
9
|
+
throw new Error("DER : tag long non supporté.");
|
|
10
|
+
let pos = start + 1;
|
|
11
|
+
let length = buf[pos++];
|
|
12
|
+
if (length & 0x80) {
|
|
13
|
+
const n = length & 0x7f;
|
|
14
|
+
if (n === 0 || n > 4)
|
|
15
|
+
throw new Error("DER : longueur invalide.");
|
|
16
|
+
length = 0;
|
|
17
|
+
for (let i = 0; i < n; i++)
|
|
18
|
+
length = length * 256 + buf[pos++];
|
|
19
|
+
}
|
|
20
|
+
const headerLength = pos - start;
|
|
21
|
+
const nodeEnd = pos + length;
|
|
22
|
+
if (nodeEnd > end)
|
|
23
|
+
throw new Error("DER : longueur hors limites.");
|
|
24
|
+
const constructed = (tag & 0x20) !== 0;
|
|
25
|
+
const node = { tag, constructed, start, headerLength, length, end: nodeEnd };
|
|
26
|
+
if (constructed) {
|
|
27
|
+
node.children = [];
|
|
28
|
+
let p = pos;
|
|
29
|
+
while (p < nodeEnd) {
|
|
30
|
+
const child = parseDer(buf, p, nodeEnd, depth + 1);
|
|
31
|
+
node.children.push(child);
|
|
32
|
+
p = child.end;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return node;
|
|
36
|
+
}
|
|
37
|
+
export function derValue(buf, n) {
|
|
38
|
+
return buf.subarray(n.start + n.headerLength, n.end);
|
|
39
|
+
}
|
|
40
|
+
export function derRaw(buf, n) {
|
|
41
|
+
return buf.subarray(n.start, n.end);
|
|
42
|
+
}
|
|
43
|
+
export function decodeOid(v) {
|
|
44
|
+
if (v.length === 0)
|
|
45
|
+
throw new Error("DER : OID vide.");
|
|
46
|
+
const parts = [];
|
|
47
|
+
const first = v[0];
|
|
48
|
+
parts.push(first < 80 ? Math.floor(first / 40) : 2, first < 80 ? first % 40 : first - 80);
|
|
49
|
+
let acc = 0;
|
|
50
|
+
for (let i = 1; i < v.length; i++) {
|
|
51
|
+
acc = acc * 128 + (v[i] & 0x7f);
|
|
52
|
+
if (!(v[i] & 0x80)) {
|
|
53
|
+
parts.push(acc);
|
|
54
|
+
acc = 0;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return parts.join(".");
|
|
58
|
+
}
|
|
59
|
+
export function encodeLength(n) {
|
|
60
|
+
if (n < 0x80)
|
|
61
|
+
return Buffer.from([n]);
|
|
62
|
+
const bytes = [];
|
|
63
|
+
while (n > 0) {
|
|
64
|
+
bytes.unshift(n & 0xff);
|
|
65
|
+
n = Math.floor(n / 256);
|
|
66
|
+
}
|
|
67
|
+
return Buffer.from([0x80 | bytes.length, ...bytes]);
|
|
68
|
+
}
|
|
69
|
+
export function tlv(tag, value) {
|
|
70
|
+
return Buffer.concat([Buffer.from([tag]), encodeLength(value.length), value]);
|
|
71
|
+
}
|
|
72
|
+
export function encodeOid(oid) {
|
|
73
|
+
const parts = oid.split(".").map((x) => Number(x));
|
|
74
|
+
const out = [parts[0] * 40 + parts[1]];
|
|
75
|
+
for (const p of parts.slice(2)) {
|
|
76
|
+
const stack = [p & 0x7f];
|
|
77
|
+
let v = Math.floor(p / 128);
|
|
78
|
+
while (v > 0) {
|
|
79
|
+
stack.unshift((v & 0x7f) | 0x80);
|
|
80
|
+
v = Math.floor(v / 128);
|
|
81
|
+
}
|
|
82
|
+
out.push(...stack);
|
|
83
|
+
}
|
|
84
|
+
return tlv(0x06, Buffer.from(out));
|
|
85
|
+
}
|
|
86
|
+
/** Unsigned big-endian bytes as a positive DER INTEGER. */
|
|
87
|
+
export function encodePositiveInteger(bytes) {
|
|
88
|
+
let b = Buffer.from(bytes);
|
|
89
|
+
while (b.length > 1 && b[0] === 0 && !(b[1] & 0x80))
|
|
90
|
+
b = b.subarray(1);
|
|
91
|
+
if (b[0] & 0x80)
|
|
92
|
+
b = Buffer.concat([Buffer.from([0]), b]);
|
|
93
|
+
return tlv(0x02, b);
|
|
94
|
+
}
|
|
95
|
+
/** GeneralizedTime (YYYYMMDDHHMMSS[.fff]Z) to ISO 8601. */
|
|
96
|
+
export function generalizedTimeToIso(s) {
|
|
97
|
+
const m = s.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(?:[.,](\d+))?Z$/);
|
|
98
|
+
if (!m)
|
|
99
|
+
throw new Error("DER : GeneralizedTime invalide.");
|
|
100
|
+
const frac = m[7] ? "." + (m[7] + "000").slice(0, 3) : ".000";
|
|
101
|
+
return `${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}${frac}Z`;
|
|
102
|
+
}
|