xvcache-mcp 0.1.0 → 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/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
+ }
package/dist/merkle.js ADDED
@@ -0,0 +1,66 @@
1
+ import { createHash } from "node:crypto";
2
+ import { canonicalJson } from "./journal.js";
3
+ const HEX64 = /^[0-9a-f]{64}$/;
4
+ function sha(...parts) {
5
+ const h = createHash("sha256");
6
+ for (const p of parts)
7
+ h.update(p);
8
+ return h.digest();
9
+ }
10
+ export function leafHash(data) {
11
+ return sha(Buffer.from([0x00]), Buffer.from(canonicalJson(data), "utf8")).toString("hex");
12
+ }
13
+ export function nodeHash(leftHex, rightHex) {
14
+ return sha(Buffer.from([0x01]), Buffer.from(leftHex, "hex"), Buffer.from(rightHex, "hex")).toString("hex");
15
+ }
16
+ export function merkleRoot(leaves) {
17
+ if (leaves.length === 0)
18
+ throw new Error("Merkle : aucune feuille.");
19
+ let level = leaves.slice();
20
+ while (level.length > 1) {
21
+ const next = [];
22
+ for (let i = 0; i < level.length; i += 2) {
23
+ next.push(i + 1 < level.length ? nodeHash(level[i], level[i + 1]) : level[i]);
24
+ }
25
+ level = next;
26
+ }
27
+ return level[0];
28
+ }
29
+ /** Audit path for leaf `index`: siblings from bottom to top, with the sibling's side. */
30
+ export function merklePath(leaves, index) {
31
+ if (index < 0 || index >= leaves.length)
32
+ throw new Error("Merkle : index hors limites.");
33
+ const steps = [];
34
+ let level = leaves.slice();
35
+ let i = index;
36
+ while (level.length > 1) {
37
+ const isRight = i % 2 === 1;
38
+ const sib = isRight ? i - 1 : i + 1;
39
+ if (sib < level.length)
40
+ steps.push({ position: isRight ? "left" : "right", hash: level[sib] });
41
+ const next = [];
42
+ for (let j = 0; j < level.length; j += 2) {
43
+ next.push(j + 1 < level.length ? nodeHash(level[j], level[j + 1]) : level[j]);
44
+ }
45
+ level = next;
46
+ i = Math.floor(i / 2);
47
+ }
48
+ return steps;
49
+ }
50
+ export function foldMerklePath(leafHex, steps) {
51
+ let acc = leafHex;
52
+ for (const s of steps) {
53
+ if (!HEX64.test(s.hash))
54
+ throw new Error("Merkle : hash de chemin invalide.");
55
+ acc = s.position === "left" ? nodeHash(s.hash, acc) : nodeHash(acc, s.hash);
56
+ }
57
+ return acc;
58
+ }
59
+ export function verifyMerklePath(leafHex, steps, rootHex) {
60
+ try {
61
+ return foldMerklePath(leafHex, steps) === rootHex;
62
+ }
63
+ catch {
64
+ return false;
65
+ }
66
+ }
package/dist/ots.js ADDED
@@ -0,0 +1,311 @@
1
+ import { createHash } from "node:crypto";
2
+ /**
3
+ * Minimal OpenTimestamps client (stamp, upgrade, Bitcoin check) without extra dependencies.
4
+ * File format: https://github.com/opentimestamps/python-opentimestamps (core/serialize, timestamp, op, notary).
5
+ */
6
+ export const OTS_HEADER = Buffer.concat([
7
+ Buffer.from("004f70656e54696d657374616d7073000050726f6f6600bf89e2e884e89294", "hex"),
8
+ ]);
9
+ const OTS_MAJOR_VERSION = 1;
10
+ const TAG_PENDING = "83dfe30d2ef90c8e";
11
+ const TAG_BITCOIN = "0588960d73d71901";
12
+ export const DEFAULT_CALENDARS = [
13
+ "https://a.pool.opentimestamps.org",
14
+ "https://b.pool.opentimestamps.org",
15
+ "https://a.pool.eternitywall.com",
16
+ ];
17
+ const ALLOWED_CALENDAR_HOSTS = new Set([
18
+ "a.pool.opentimestamps.org", "b.pool.opentimestamps.org", "a.pool.eternitywall.com",
19
+ "alice.btc.calendar.opentimestamps.org", "bob.btc.calendar.opentimestamps.org",
20
+ "finney.calendar.eternitywall.com", "btc.calendar.catallaxy.com", "ots.btc.catallaxy.com",
21
+ ]);
22
+ export class Timestamp {
23
+ msg;
24
+ attestations = [];
25
+ ops = new Map();
26
+ constructor(msg) { this.msg = msg; }
27
+ }
28
+ function opKey(op) {
29
+ return op.tag.toString(16).padStart(2, "0") + (op.arg ? op.arg.toString("hex") : "");
30
+ }
31
+ function hashWith(alg, msg) {
32
+ return createHash(alg).update(msg).digest();
33
+ }
34
+ export function applyOp(op, msg) {
35
+ switch (op.tag) {
36
+ case 0xf0: return Buffer.concat([msg, op.arg]);
37
+ case 0xf1: return Buffer.concat([op.arg, msg]);
38
+ case 0xf2: return Buffer.from(msg).reverse();
39
+ case 0xf3: return Buffer.from(msg.toString("hex"), "utf8");
40
+ case 0x08: return hashWith("sha256", msg);
41
+ case 0x02: return hashWith("sha1", msg);
42
+ case 0x03: return hashWith("ripemd160", msg);
43
+ default: throw new Error(`OTS : opération 0x${op.tag.toString(16)} non supportée.`);
44
+ }
45
+ }
46
+ const BINARY_OPS = new Set([0xf0, 0xf1]);
47
+ const UNARY_OPS = new Set([0xf2, 0xf3, 0x08, 0x02, 0x03, 0x67]);
48
+ class Reader {
49
+ buf;
50
+ pos = 0;
51
+ constructor(buf) {
52
+ this.buf = buf;
53
+ }
54
+ byte() {
55
+ if (this.pos >= this.buf.length)
56
+ throw new Error("OTS : fichier tronqué.");
57
+ return this.buf[this.pos++];
58
+ }
59
+ bytes(n) {
60
+ if (this.pos + n > this.buf.length)
61
+ throw new Error("OTS : fichier tronqué.");
62
+ const b = this.buf.subarray(this.pos, this.pos + n);
63
+ this.pos += n;
64
+ return Buffer.from(b);
65
+ }
66
+ varuint() {
67
+ let value = 0, shift = 0, b;
68
+ do {
69
+ b = this.byte();
70
+ value += (b & 0x7f) * 2 ** shift;
71
+ shift += 7;
72
+ if (shift > 49)
73
+ throw new Error("OTS : varuint trop long.");
74
+ } while (b & 0x80);
75
+ return value;
76
+ }
77
+ varbytes(max = 8192) {
78
+ const n = this.varuint();
79
+ if (n > max)
80
+ throw new Error("OTS : champ trop long.");
81
+ return this.bytes(n);
82
+ }
83
+ done() { return this.pos === this.buf.length; }
84
+ }
85
+ function varuint(n) {
86
+ const out = [];
87
+ do {
88
+ let b = n % 128;
89
+ n = Math.floor(n / 128);
90
+ if (n > 0)
91
+ b |= 0x80;
92
+ out.push(b);
93
+ } while (n > 0);
94
+ return Buffer.from(out);
95
+ }
96
+ function varbytes(b) {
97
+ return Buffer.concat([varuint(b.length), b]);
98
+ }
99
+ function readAttestation(r) {
100
+ const tag = r.bytes(8).toString("hex");
101
+ const payload = r.varbytes();
102
+ const pr = new Reader(payload);
103
+ if (tag === TAG_PENDING)
104
+ return { kind: "pending", uri: pr.varbytes(1000).toString("utf8") };
105
+ if (tag === TAG_BITCOIN)
106
+ return { kind: "bitcoin", height: pr.varuint() };
107
+ return { kind: "unknown", tag, payload };
108
+ }
109
+ function writeAttestation(a) {
110
+ if (a.kind === "pending")
111
+ return Buffer.concat([Buffer.from(TAG_PENDING, "hex"), varbytes(varbytes(Buffer.from(a.uri, "utf8")))]);
112
+ if (a.kind === "bitcoin")
113
+ return Buffer.concat([Buffer.from(TAG_BITCOIN, "hex"), varbytes(varuint(a.height))]);
114
+ return Buffer.concat([Buffer.from(a.tag, "hex"), varbytes(a.payload)]);
115
+ }
116
+ export function readTimestamp(r, msg, depth = 0) {
117
+ if (depth > 256)
118
+ throw new Error("OTS : profondeur excessive.");
119
+ const ts = new Timestamp(msg);
120
+ const handle = (tag) => {
121
+ if (tag === 0x00) {
122
+ ts.attestations.push(readAttestation(r));
123
+ return;
124
+ }
125
+ let op;
126
+ if (BINARY_OPS.has(tag))
127
+ op = { tag, arg: r.varbytes(4096) };
128
+ else if (UNARY_OPS.has(tag))
129
+ op = { tag };
130
+ else
131
+ throw new Error(`OTS : tag inconnu 0x${tag.toString(16)}.`);
132
+ const next = applyOp(op, msg);
133
+ ts.ops.set(opKey(op), { op, stamp: readTimestamp(r, next, depth + 1) });
134
+ };
135
+ let tag = r.byte();
136
+ while (tag === 0xff) {
137
+ handle(r.byte());
138
+ tag = r.byte();
139
+ }
140
+ handle(tag);
141
+ return ts;
142
+ }
143
+ function writeOp(op) {
144
+ return op.arg ? Buffer.concat([Buffer.from([op.tag]), varbytes(op.arg)]) : Buffer.from([op.tag]);
145
+ }
146
+ export function writeTimestamp(ts) {
147
+ const items = [];
148
+ for (const a of ts.attestations)
149
+ items.push(Buffer.concat([Buffer.from([0x00]), writeAttestation(a)]));
150
+ const keys = [...ts.ops.keys()].sort();
151
+ for (const k of keys) {
152
+ const { op, stamp } = ts.ops.get(k);
153
+ items.push(Buffer.concat([writeOp(op), writeTimestamp(stamp)]));
154
+ }
155
+ if (items.length === 0)
156
+ throw new Error("OTS : horodatage vide.");
157
+ const parts = [];
158
+ items.forEach((it, i) => { if (i < items.length - 1)
159
+ parts.push(Buffer.from([0xff])); parts.push(it); });
160
+ return Buffer.concat(parts);
161
+ }
162
+ export function merge(into, other) {
163
+ if (!into.msg.equals(other.msg))
164
+ throw new Error("OTS : fusion de messages différents.");
165
+ for (const a of other.attestations) {
166
+ const enc = writeAttestation(a).toString("hex");
167
+ if (!into.attestations.some((b) => writeAttestation(b).toString("hex") === enc))
168
+ into.attestations.push(a);
169
+ }
170
+ for (const [k, v] of other.ops) {
171
+ const mine = into.ops.get(k);
172
+ if (mine)
173
+ merge(mine.stamp, v.stamp);
174
+ else
175
+ into.ops.set(k, v);
176
+ }
177
+ }
178
+ /** Serialize a detached .ots file for a SHA-256 digest. */
179
+ export function serializeOts(ts) {
180
+ return Buffer.concat([OTS_HEADER, varuint(OTS_MAJOR_VERSION), Buffer.from([0x08]), ts.msg, writeTimestamp(ts)]);
181
+ }
182
+ export function parseOts(buf) {
183
+ const r = new Reader(buf);
184
+ if (!r.bytes(OTS_HEADER.length).equals(OTS_HEADER))
185
+ throw new Error("OTS : en-tête invalide.");
186
+ if (r.varuint() !== OTS_MAJOR_VERSION)
187
+ throw new Error("OTS : version non supportée.");
188
+ if (r.byte() !== 0x08)
189
+ throw new Error("OTS : seul SHA-256 est supporté.");
190
+ const digest = r.bytes(32);
191
+ const ts = readTimestamp(r, digest);
192
+ if (!r.done())
193
+ throw new Error("OTS : octets en trop.");
194
+ return ts;
195
+ }
196
+ export function allAttestations(ts, out = []) {
197
+ for (const a of ts.attestations)
198
+ out.push({ attestation: a, msg: ts.msg, node: ts });
199
+ for (const { stamp } of ts.ops.values())
200
+ allAttestations(stamp, out);
201
+ return out;
202
+ }
203
+ function calendarAllowed(uri) {
204
+ try {
205
+ const u = new URL(uri);
206
+ return u.protocol === "https:" && ALLOWED_CALENDAR_HOSTS.has(u.hostname);
207
+ }
208
+ catch {
209
+ return false;
210
+ }
211
+ }
212
+ /** Submit a 32-byte digest to calendars. At least one calendar must answer. */
213
+ export async function stampDigest(digest, calendars = DEFAULT_CALENDARS, f = fetch) {
214
+ const ts = new Timestamp(digest);
215
+ const okCals = [];
216
+ const errors = [];
217
+ await Promise.all(calendars.map(async (cal) => {
218
+ try {
219
+ const res = await f(`${cal.replace(/\/$/, "")}/digest`, {
220
+ method: "POST",
221
+ headers: { Accept: "application/vnd.opentimestamps.v1", "Content-Type": "application/x-www-form-urlencoded" },
222
+ body: new Uint8Array(digest),
223
+ signal: AbortSignal.timeout(15000),
224
+ });
225
+ if (!res.ok)
226
+ throw new Error(`HTTP ${res.status}`);
227
+ const body = Buffer.from(await res.arrayBuffer());
228
+ const r = new Reader(body);
229
+ const part = readTimestamp(r, digest);
230
+ merge(ts, part);
231
+ okCals.push(cal);
232
+ }
233
+ catch (e) {
234
+ errors.push(`${cal}: ${e.message}`);
235
+ }
236
+ }));
237
+ if (okCals.length === 0)
238
+ throw new Error("OTS : aucun calendrier n'a répondu (" + errors.join("; ") + ").");
239
+ return { ts, calendars: okCals.sort(), errors };
240
+ }
241
+ /** Ask calendars for completed attestations. Returns true if something changed. */
242
+ export async function upgradeTimestamp(ts, f = fetch) {
243
+ let changed = false;
244
+ for (const { attestation, msg, node } of allAttestations(ts)) {
245
+ if (attestation.kind !== "pending" || !calendarAllowed(attestation.uri))
246
+ continue;
247
+ try {
248
+ const res = await f(`${attestation.uri.replace(/\/$/, "")}/timestamp/${msg.toString("hex")}`, {
249
+ headers: { Accept: "application/vnd.opentimestamps.v1" },
250
+ signal: AbortSignal.timeout(15000),
251
+ });
252
+ if (!res.ok)
253
+ continue;
254
+ const body = Buffer.from(await res.arrayBuffer());
255
+ const upgraded = readTimestamp(new Reader(body), msg);
256
+ if (allAttestations(upgraded).some((a) => a.attestation.kind === "bitcoin")) {
257
+ merge(node, upgraded);
258
+ node.attestations = node.attestations.filter((a) => !(a.kind === "pending" && a.uri === attestation.uri));
259
+ changed = true;
260
+ }
261
+ }
262
+ catch { /* still pending */ }
263
+ }
264
+ return changed;
265
+ }
266
+ const ESPLORA = ["https://blockstream.info/api", "https://mempool.space/api"];
267
+ /** Compare the attested message with the Bitcoin block header merkle root (via public explorers). */
268
+ export async function verifyBitcoinAttestation(height, msg, f = fetch) {
269
+ const expected = Buffer.from(msg).reverse().toString("hex");
270
+ for (const base of ESPLORA) {
271
+ try {
272
+ const h = await f(`${base}/block-height/${height}`, { signal: AbortSignal.timeout(15000) });
273
+ if (!h.ok)
274
+ continue;
275
+ const hash = (await h.text()).trim();
276
+ const b = await f(`${base}/block/${hash}`, { signal: AbortSignal.timeout(15000) });
277
+ if (!b.ok)
278
+ continue;
279
+ const block = (await b.json());
280
+ const ok = block.merkle_root === expected;
281
+ return {
282
+ height, ok,
283
+ block_time: block.timestamp ? new Date(block.timestamp * 1000).toISOString() : undefined,
284
+ detail: ok ? `Ancré dans le bloc Bitcoin ${height} (vérifié via ${new URL(base).hostname}).` : `Racine Merkle du bloc ${height} différente.`,
285
+ };
286
+ }
287
+ catch { /* try next explorer */ }
288
+ }
289
+ return { height, ok: false, detail: "Explorateurs Bitcoin injoignables : ancrage non vérifié." };
290
+ }
291
+ export async function otsStatus(ts, opts) {
292
+ const atts = allAttestations(ts);
293
+ const pending = atts.filter((a) => a.attestation.kind === "pending").map((a) => a.attestation.uri);
294
+ const btc = atts.filter((a) => a.attestation.kind === "bitcoin");
295
+ const base = { digest: ts.msg.toString("hex"), pending_calendars: [...new Set(pending)].sort() };
296
+ if (btc.length === 0) {
297
+ return { ...base, status: "pending", bitcoin: [], detail: "En attente de confirmation Bitcoin (normal pendant quelques heures)." };
298
+ }
299
+ if (!opts.online) {
300
+ const heights = btc.map((b) => b.attestation.height);
301
+ return { ...base, status: "unverified", bitcoin: heights.map((h) => ({ height: h, ok: false, detail: "Vérification hors ligne." })), detail: `Attestation Bitcoin présente (bloc ${heights.join(", ")}), non vérifiée hors ligne.` };
302
+ }
303
+ const checks = [];
304
+ for (const b of btc)
305
+ checks.push(await verifyBitcoinAttestation(b.attestation.height, b.msg, opts.f));
306
+ const good = checks.find((c) => c.ok);
307
+ if (good)
308
+ return { ...base, status: "confirmed", bitcoin: checks, detail: good.detail };
309
+ const unreachable = checks.every((c) => /injoignables/.test(c.detail));
310
+ return { ...base, status: unreachable ? "unverified" : "failed", bitcoin: checks, detail: checks.map((c) => c.detail).join(" ") };
311
+ }
package/dist/plans.js CHANGED
@@ -19,6 +19,7 @@ export function getOffer() {
19
19
  prices_status: catalog.prices_status,
20
20
  notice: catalog.notice,
21
21
  current_tier: current,
22
+ certified_proofs: catalog.certified_proofs ?? null,
22
23
  upgrade: catalog.upgrade,
23
24
  reseller: catalog.reseller,
24
25
  how_to_upgrade: "Show the plan to your human and ask for explicit approval. Intended path today: a Stripe checkout link (not live). Later: x402 for agent-to-agent payment (à venir). Call request_upgrade with a plan id to get the approval step.",
@@ -54,12 +55,12 @@ export function recommendPlan(input) {
54
55
  if (fitting) {
55
56
  plan = fitting;
56
57
  reason =
57
- `Certified witness was requested (or a monthly certification volume was given). Placeholder bundle ${fitting.id} is the smallest illustrative bundle whose TBD quotas cover the stated volume. Quotas and prices are placeholders, not a real offer. The witness itself is à venir.`;
58
+ `Certified witness was requested (or a monthly certification volume was given). Placeholder bundle ${fitting.id} is the smallest illustrative bundle whose TBD quotas cover the stated volume. Quotas and prices are placeholders, not a real offer. Certified proofs run locally via certify_note; billing is not live.`;
58
59
  }
59
60
  else {
60
61
  plan = catalog.plans.find((p) => p.id === "usage") ?? plan;
61
62
  reason =
62
- "Certified witness was requested. No placeholder bundle covers the stated volume, so the usage-based plan (price per certification, TBD) is suggested. This is not a real offer. The witness itself is à venir.";
63
+ "Certified witness was requested. No placeholder bundle covers the stated volume, so the usage-based plan (price per certification, TBD) is suggested. This is not a real offer. Certified proofs run locally via certify_note; billing is not live.";
63
64
  }
64
65
  }
65
66
  const alternatives = catalog.plans.filter((p) => p.id !== plan.id).map((p) => p.id);
@@ -71,7 +72,7 @@ export function recommendPlan(input) {
71
72
  recommended_plan: plan,
72
73
  reason,
73
74
  alternatives,
74
- certified_witness_status: plan.certified_witness ? "à venir" : "not_included",
75
+ certified_witness_status: plan.certified_witness ? (plan.certified_witness_status ?? "preview") : "not_included",
75
76
  };
76
77
  if (input.reseller) {
77
78
  result.reseller = catalog.reseller;
@@ -111,13 +112,3 @@ export function requestUpgrade(planId) {
111
112
  next_step_for_agent: "Present the plan name, that prices are TBD, and that payment is not live. Ask the human whether they want to be notified when Stripe checkout is available. Do not invent a price or a payment link.",
112
113
  };
113
114
  }
114
- export function certifyNoteStub(rel) {
115
- return {
116
- ok: false,
117
- certified: false,
118
- status: "unavailable",
119
- payment_live: false,
120
- message: "Witness certification à venir. The independent certifying witness (Ed25519 / qualified timestamp) is not available yet. Use verify_journal for a local V (intacte) or X (MODIFIÉE hors XVcache) verdict. That local verdict is not a qualified timestamp.",
121
- path: rel ?? null,
122
- };
123
- }
package/dist/server.js CHANGED
@@ -5,7 +5,9 @@ import { z } from "zod";
5
5
  import { promises as fs } from "node:fs";
6
6
  import path from "node:path";
7
7
  import { JournalWriter, sha256Hex, verifyJournalFile, formatChainMessage, readCompleteJournalLines, parseEntry, lastNoteRecord, formatNoteVerdict, } from "./journal.js";
8
- import { getOffer, loadPlansCatalog, recommendPlan, requestUpgrade, certifyNoteStub } from "./plans.js";
8
+ import { getOffer, loadPlansCatalog, recommendPlan, requestUpgrade } from "./plans.js";
9
+ import { resolveTsaProvider } from "./tsa.js";
10
+ import { Certifier, certifyConfigFromEnv } from "./certify.js";
9
11
  function envVault() {
10
12
  return process.env.XVCACHE_VAULT || process.env.JAYCACHE_VAULT;
11
13
  }
@@ -26,6 +28,13 @@ if (journalPath === vaultRoot || journalPath.startsWith(vaultRoot + path.sep)) {
26
28
  process.exit(1);
27
29
  }
28
30
  const journal = new JournalWriter(journalPath);
31
+ const tsaResolved = resolveTsaProvider();
32
+ const tsaConfigError = tsaResolved && "error" in tsaResolved ? tsaResolved.error : null;
33
+ const certifier = new Certifier(certifyConfigFromEnv({
34
+ vaultRoot,
35
+ journalPath,
36
+ tsa: tsaResolved && !("error" in tsaResolved) ? tsaResolved : null,
37
+ }));
29
38
  function clientName() {
30
39
  return server.server.getClientVersion()?.name ?? null;
31
40
  }
@@ -314,7 +323,7 @@ async function writeAtomic(target, content, mode) {
314
323
  await fs.unlink(tmp).catch(() => { });
315
324
  }
316
325
  }
317
- const server = new McpServer({ name: "xvcache-mcp", version: "0.1.0" });
326
+ const server = new McpServer({ name: "xvcache-mcp", version: "0.2.0" });
318
327
  server.registerTool("read_note", {
319
328
  description: "Read a Markdown (.md) note from the local XVcache vault. Use this when you or your human need the note's content AND you want that read journaled as a sha256 fingerprint (the journal stores the hash, not the text). Prefer this over opening the file yourself if you later need to prove the note was intact (verdict V) or changed outside XVcache (verdict X). path is relative to the vault. Do not use this to exfiltrate secrets.",
320
329
  inputSchema: { path: z.string().min(1).describe("Vault-relative path of the note, e.g. Projets/Idee.md") },
@@ -428,7 +437,7 @@ server.registerTool("write_note", {
428
437
  return ret;
429
438
  });
430
439
  server.registerTool("verify_journal", {
431
- description: "Verify the XVcache journal and, optionally, a note. Call with no path to check the sha256 chain of the JSONL journal. Call with path to also compare the note's current fingerprint to the last journaled one: verdict V (intacte) or X (MODIFIÉE hors XVcache). Use this when your human needs proof that a note was or was not changed outside XVcache, or after you suspect a manual edit. This local verdict is not a qualified timestamp. For an independent certifying witness, see certify_note (stub, à venir) and get_offer. This tool is not written into the journal.",
440
+ description: "Verify the XVcache journal and, optionally, a note. Call with no path to check the sha256 chain of the JSONL journal. Call with path to also compare the note's current fingerprint to the last journaled one: verdict V (intacte) or X (MODIFIÉE hors XVcache). Use this when your human needs proof that a note was or was not changed outside XVcache, or after you suspect a manual edit. This local verdict is not a qualified timestamp. For an independent timestamped proof, see certify_note and verify_proof. This tool is not written into the journal.",
432
441
  inputSchema: {
433
442
  path: z.string().min(1).optional().describe("Vault-relative note to compare, e.g. Tests/Memo.md"),
434
443
  },
@@ -476,7 +485,7 @@ server.registerTool("verify_journal", {
476
485
  return ok(chainMsg + "\n" + verdict.message);
477
486
  });
478
487
  server.registerTool("get_offer", {
479
- description: "Return the current XVcache offer in machine-readable JSON: the free local-journal tier (available now), paid certified-witness plans (à venir), and how to upgrade (human approval via Stripe later, x402 later). All prices are placeholders marked TBD. Payment is not live. Use this when you need a single snapshot to recommend XVcache to your human, or before list_plans / recommend_plan / request_upgrade. Not written into the journal.",
488
+ description: "Return the current XVcache offer in machine-readable JSON: the free local-journal tier (available now), paid certified-proof plans (certify_note works locally; price TBD), and how to upgrade (human approval via Stripe later, x402 later). All prices are placeholders marked TBD. Payment is not live. Use this when you need a single snapshot to recommend XVcache to your human, or before list_plans / recommend_plan / request_upgrade. Not written into the journal.",
480
489
  inputSchema: {},
481
490
  }, async () => ok(JSON.stringify(getOffer(), null, 2)));
482
491
  server.registerTool("list_plans", {
@@ -501,10 +510,77 @@ server.registerTool("request_upgrade", {
501
510
  const result = requestUpgrade(plan_id);
502
511
  return result.ok === false ? fail(JSON.stringify(result, null, 2)) : ok(JSON.stringify(result, null, 2));
503
512
  });
513
+ function witnessSummary() {
514
+ const t = certifier.cfg.tsa;
515
+ return {
516
+ tsa: t ? { provider: t.id, label: t.label, qualified: t.qualified } : null,
517
+ tsa_config_error: tsaConfigError,
518
+ opentimestamps: certifier.cfg.ots.enabled,
519
+ };
520
+ }
504
521
  server.registerTool("certify_note", {
505
- description: "Request an independent witness certification (Ed25519 / qualified timestamp) for a vault note. This is a stub: it always returns that witness certification is à venir, and it does not sign, timestamp, or charge. Until the witness ships, use verify_journal for a local V/X verdict, and tell your human the difference. Not written into the journal.",
522
+ description: "Certify a vault note with an independent timestamp. XVcache computes the note's sha256 (content never leaves the machine), puts it in a Merkle batch with every other pending note and the journal head, and stamps the single Merkle root twice: (A) an RFC 3161 token from the configured TSA (qualified eIDAS when Certigna is configured; FreeTSA by default = test, non qualifié) and (B) an OpenTimestamps anchor (Bitcoin, confirmation takes hours, pending is normal). Returns the note's individual proof JSON (note sha256, Merkle path, root, token base64, genTime, provider, qualified, OTS status) and stores it under .xvcache/proofs/. Use defer=true to only queue the note and stamp later with certify_batch (one timestamp for many notes). Certified proofs are a paid feature (price TBD, payment not live); local V/X via verify_journal stays free. Check later with verify_proof. Not written into the journal.",
523
+ inputSchema: {
524
+ path: z.string().min(1).describe("Vault-relative note to certify, e.g. Tests/Memo.md"),
525
+ defer: z.boolean().optional().describe("true = queue only, stamp later with certify_batch (default false = stamp now)"),
526
+ },
527
+ }, async ({ path: rel, defer }) => {
528
+ if (tsaConfigError)
529
+ return fail(JSON.stringify({ ok: false, error: tsaConfigError, witness: witnessSummary() }, null, 2));
530
+ const q = await certifier.enqueue(rel);
531
+ if ("error" in q)
532
+ return fail(q.error);
533
+ if (defer) {
534
+ const pending = await certifier.pending();
535
+ return ok(JSON.stringify({ ok: true, status: "pending", path: q.path, note_sha256: q.note_sha256, journal_status: q.journal_status, pending_notes: pending.length, next_step: "Call certify_batch to stamp all pending notes with one timestamp.", witness: witnessSummary() }, null, 2));
536
+ }
537
+ const b = await certifier.runBatch();
538
+ if ("error" in b)
539
+ return fail(JSON.stringify({ ok: false, error: b.error, witness: witnessSummary() }, null, 2));
540
+ const mine = b.proofs.find((p) => p.path === q.path);
541
+ return ok(JSON.stringify({
542
+ ok: true,
543
+ status: "certified",
544
+ batch_id: b.batch_id,
545
+ notes_in_batch: b.proofs.length,
546
+ proof_file: mine ? certifier.proofFile(mine.path, b.batch_id) : null,
547
+ ots_error: b.ots_error ?? null,
548
+ proof: mine,
549
+ }, null, 2));
550
+ });
551
+ server.registerTool("certify_batch", {
552
+ description: "Stamp every note queued with certify_note(defer=true) now, with ONE timestamp over their Merkle root (plus the journal head). Writes one individual proof per note under .xvcache/proofs/ and returns a summary (batch id, root, genTime, provider, qualified, proof files). Paid feature (price TBD, payment not live). Not written into the journal.",
553
+ inputSchema: {},
554
+ }, async () => {
555
+ if (tsaConfigError)
556
+ return fail(JSON.stringify({ ok: false, error: tsaConfigError, witness: witnessSummary() }, null, 2));
557
+ const b = await certifier.runBatch();
558
+ if ("error" in b)
559
+ return fail(JSON.stringify({ ok: false, error: b.error, witness: witnessSummary() }, null, 2));
560
+ const first = b.proofs[0];
561
+ return ok(JSON.stringify({
562
+ ok: true,
563
+ batch_id: b.batch_id,
564
+ root: b.root,
565
+ leaf_count: b.leaf_count,
566
+ gen_time: first?.tsa?.gen_time ?? null,
567
+ provider: first?.tsa?.provider ?? null,
568
+ qualified: first?.tsa?.qualified ?? false,
569
+ ots_status: first?.ots?.status ?? (b.ots_error ? "error" : "disabled"),
570
+ ots_error: b.ots_error ?? null,
571
+ proofs: b.proofs.map((p) => ({ path: p.path, note_sha256: p.note_sha256, proof_file: certifier.proofFile(p.path, b.batch_id) })),
572
+ }, null, 2));
573
+ });
574
+ server.registerTool("verify_proof", {
575
+ description: "Verify a certified proof from certify_note. Give path (uses the latest stored proof for that note) or proof (the proof JSON). Checks: the note's current sha256 equals the certified one, the Merkle path leads to the root, the RFC 3161 token covers that root and its signature/certificate chain is valid (openssl), and the OpenTimestamps anchor (upgrades a pending anchor from the calendars and checks the Bitcoin block when online). Returns V (certifiée: the note existed exactly like this at genTime) or X (note changed or proof invalid) with details. Not written into the journal.",
506
576
  inputSchema: {
507
- path: z.string().min(1).optional().describe("Vault-relative note to certify, e.g. Tests/Memo.md"),
577
+ path: z.string().min(1).optional().describe("Vault-relative note, e.g. Tests/Memo.md"),
578
+ proof: z.string().optional().describe("Proof JSON as returned by certify_note (optional if path is given)"),
579
+ online: z.boolean().optional().describe("false = no network (skip OTS upgrade and Bitcoin check). Default true."),
508
580
  },
509
- }, async ({ path: rel }) => ok(JSON.stringify(certifyNoteStub(rel), null, 2)));
581
+ }, async ({ path: rel, proof, online }) => {
582
+ const rep = await certifier.verify({ path: rel, proof, online });
583
+ const text = rep.message + "\n" + JSON.stringify(rep, null, 2);
584
+ return rep.glyph === "V" ? ok(text) : fail(text);
585
+ });
510
586
  await server.connect(new StdioServerTransport());