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/server.js
ADDED
|
@@ -0,0 +1,586 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { promises as fs } from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { JournalWriter, sha256Hex, verifyJournalFile, formatChainMessage, readCompleteJournalLines, parseEntry, lastNoteRecord, formatNoteVerdict, } from "./journal.js";
|
|
8
|
+
import { getOffer, loadPlansCatalog, recommendPlan, requestUpgrade } from "./plans.js";
|
|
9
|
+
import { resolveTsaProvider } from "./tsa.js";
|
|
10
|
+
import { Certifier, certifyConfigFromEnv } from "./certify.js";
|
|
11
|
+
function envVault() {
|
|
12
|
+
return process.env.XVCACHE_VAULT || process.env.JAYCACHE_VAULT;
|
|
13
|
+
}
|
|
14
|
+
function envLog() {
|
|
15
|
+
return process.env.XVCACHE_LOG || process.env.JAYCACHE_LOG;
|
|
16
|
+
}
|
|
17
|
+
const VAULT = envVault();
|
|
18
|
+
if (!VAULT) {
|
|
19
|
+
console.error("XVCACHE_VAULT manquant (JAYCACHE_VAULT accepté comme alias)");
|
|
20
|
+
process.exit(1);
|
|
21
|
+
}
|
|
22
|
+
const vaultRoot = await fs.realpath(path.resolve(VAULT));
|
|
23
|
+
const defaultLog = path.resolve(vaultRoot, "..", "xvcache-journal.jsonl");
|
|
24
|
+
const logEnv = envLog();
|
|
25
|
+
const journalPath = logEnv ? path.resolve(logEnv) : defaultLog;
|
|
26
|
+
if (journalPath === vaultRoot || journalPath.startsWith(vaultRoot + path.sep)) {
|
|
27
|
+
console.error("XVCACHE_LOG ne doit pas être à l'intérieur du coffre (JAYCACHE_LOG accepté comme alias)");
|
|
28
|
+
process.exit(1);
|
|
29
|
+
}
|
|
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
|
+
}));
|
|
38
|
+
function clientName() {
|
|
39
|
+
return server.server.getClientVersion()?.name ?? null;
|
|
40
|
+
}
|
|
41
|
+
async function logTool(tool, args, result, note_sha256) {
|
|
42
|
+
await journal.append({ tool, args, client: clientName(), result, note_sha256 });
|
|
43
|
+
}
|
|
44
|
+
function toolText(result) {
|
|
45
|
+
return result.content.filter((c) => c.type === "text").map((c) => c.text ?? "").join("");
|
|
46
|
+
}
|
|
47
|
+
function fail(msg) {
|
|
48
|
+
return { isError: true, content: [{ type: "text", text: msg }] };
|
|
49
|
+
}
|
|
50
|
+
function ok(text) {
|
|
51
|
+
return { content: [{ type: "text", text }] };
|
|
52
|
+
}
|
|
53
|
+
function fold(s) {
|
|
54
|
+
return s.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase();
|
|
55
|
+
}
|
|
56
|
+
/** Maps each character of the folded string back to an index in the original. */
|
|
57
|
+
function foldMap(s) {
|
|
58
|
+
let folded = "";
|
|
59
|
+
const map = [];
|
|
60
|
+
for (let i = 0; i < s.length; i++) {
|
|
61
|
+
const f = s[i].normalize("NFD").replace(/\p{M}/gu, "").toLowerCase();
|
|
62
|
+
for (const ch of f) {
|
|
63
|
+
folded += ch;
|
|
64
|
+
map.push(i);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return { folded, map };
|
|
68
|
+
}
|
|
69
|
+
function countHits(haystack, needle) {
|
|
70
|
+
if (!needle)
|
|
71
|
+
return 0;
|
|
72
|
+
const h = fold(haystack);
|
|
73
|
+
let count = 0;
|
|
74
|
+
let pos = 0;
|
|
75
|
+
while (pos <= h.length - needle.length) {
|
|
76
|
+
const i = h.indexOf(needle, pos);
|
|
77
|
+
if (i < 0)
|
|
78
|
+
break;
|
|
79
|
+
count++;
|
|
80
|
+
pos = i + needle.length;
|
|
81
|
+
}
|
|
82
|
+
return count;
|
|
83
|
+
}
|
|
84
|
+
function snippetAround(text, needle, width = 160) {
|
|
85
|
+
const { folded, map } = foldMap(text);
|
|
86
|
+
const i = folded.indexOf(needle);
|
|
87
|
+
if (i < 0 || map.length === 0) {
|
|
88
|
+
const cut = text.replace(/\s+/g, " ").trim().slice(0, width);
|
|
89
|
+
return text.trim().length > width ? cut + "…" : cut;
|
|
90
|
+
}
|
|
91
|
+
const startOrig = map[i];
|
|
92
|
+
const lastFold = i + needle.length - 1;
|
|
93
|
+
const endOrig = (lastFold >= 0 && lastFold < map.length ? map[lastFold] : startOrig) + 1;
|
|
94
|
+
const pad = Math.max(0, Math.floor((width - (endOrig - startOrig)) / 2));
|
|
95
|
+
let from = Math.max(0, startOrig - pad);
|
|
96
|
+
let to = Math.min(text.length, from + width);
|
|
97
|
+
if (to - from < width)
|
|
98
|
+
from = Math.max(0, to - width);
|
|
99
|
+
let snip = text.slice(from, to).replace(/\s+/g, " ").trim();
|
|
100
|
+
if (from > 0)
|
|
101
|
+
snip = "…" + snip;
|
|
102
|
+
if (to < text.length)
|
|
103
|
+
snip = snip + "…";
|
|
104
|
+
return snip;
|
|
105
|
+
}
|
|
106
|
+
function parseNote(text) {
|
|
107
|
+
const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
|
|
108
|
+
if (!m)
|
|
109
|
+
return { title: undefined, tags: [], body: text };
|
|
110
|
+
const fm = m[1];
|
|
111
|
+
const body = text.slice(m[0].length);
|
|
112
|
+
let title;
|
|
113
|
+
const titleM = fm.match(/^title:\s*(.+)$/m);
|
|
114
|
+
if (titleM)
|
|
115
|
+
title = titleM[1].trim().replace(/^['"]|['"]$/g, "");
|
|
116
|
+
const tags = [];
|
|
117
|
+
const tagsInline = fm.match(/^tags:\s*\[([^\]]*)\]/m);
|
|
118
|
+
if (tagsInline) {
|
|
119
|
+
for (const t of tagsInline[1].split(",")) {
|
|
120
|
+
const v = t.trim().replace(/^['"]|['"]$/g, "");
|
|
121
|
+
if (v)
|
|
122
|
+
tags.push(v);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
const block = fm.match(/^tags:\s*\r?\n((?:[ \t]+- .+(?:\r?\n|$))*)/m);
|
|
127
|
+
if (block) {
|
|
128
|
+
for (const line of block[1].split(/\r?\n/)) {
|
|
129
|
+
const tm = line.match(/^\s*-\s+(.+)$/);
|
|
130
|
+
if (tm)
|
|
131
|
+
tags.push(tm[1].trim().replace(/^['"]|['"]$/g, ""));
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { title, tags, body };
|
|
136
|
+
}
|
|
137
|
+
function insideVault(real) {
|
|
138
|
+
return real === vaultRoot || real.startsWith(vaultRoot + path.sep);
|
|
139
|
+
}
|
|
140
|
+
async function listVaultMarkdown() {
|
|
141
|
+
const files = [];
|
|
142
|
+
const visited = new Set();
|
|
143
|
+
async function walk(dirReal) {
|
|
144
|
+
if (visited.has(dirReal))
|
|
145
|
+
return;
|
|
146
|
+
visited.add(dirReal);
|
|
147
|
+
let entries;
|
|
148
|
+
try {
|
|
149
|
+
entries = await fs.readdir(dirReal, { withFileTypes: true });
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
for (const ent of entries) {
|
|
155
|
+
const full = path.join(dirReal, ent.name);
|
|
156
|
+
let real;
|
|
157
|
+
try {
|
|
158
|
+
real = await fs.realpath(full);
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
if (!insideVault(real))
|
|
164
|
+
continue;
|
|
165
|
+
let st;
|
|
166
|
+
try {
|
|
167
|
+
st = await fs.stat(real);
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (st.isDirectory())
|
|
173
|
+
await walk(real);
|
|
174
|
+
else if (st.isFile() && real.toLowerCase().endsWith(".md"))
|
|
175
|
+
files.push(real);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
await walk(vaultRoot);
|
|
179
|
+
return files;
|
|
180
|
+
}
|
|
181
|
+
const TITLE_W = 1_000_000;
|
|
182
|
+
const TAG_W = 1_000;
|
|
183
|
+
const BODY_W = 1;
|
|
184
|
+
async function searchNotes(query, limit) {
|
|
185
|
+
const trimmed = query.trim();
|
|
186
|
+
const needle = fold(trimmed);
|
|
187
|
+
if (!trimmed || !needle)
|
|
188
|
+
return { error: "Refusé : requête vide." };
|
|
189
|
+
const files = await listVaultMarkdown();
|
|
190
|
+
const hits = [];
|
|
191
|
+
for (const real of files) {
|
|
192
|
+
if (!insideVault(real))
|
|
193
|
+
continue;
|
|
194
|
+
let text;
|
|
195
|
+
try {
|
|
196
|
+
text = await fs.readFile(real, "utf8");
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
const parsed = parseNote(text);
|
|
202
|
+
const rel = path.relative(vaultRoot, real).split(path.sep).join("/");
|
|
203
|
+
const title = parsed.title || path.basename(rel, path.extname(rel));
|
|
204
|
+
const tags = parsed.tags;
|
|
205
|
+
const body = parsed.body;
|
|
206
|
+
const titleHits = countHits(title, needle);
|
|
207
|
+
const tagHits = tags.reduce((n, t) => n + countHits(t, needle), 0);
|
|
208
|
+
const bodyHits = countHits(body, needle);
|
|
209
|
+
if (titleHits + tagHits + bodyHits === 0)
|
|
210
|
+
continue;
|
|
211
|
+
const score = titleHits * TITLE_W + tagHits * TAG_W + bodyHits * BODY_W;
|
|
212
|
+
const snippetSource = titleHits ? title : tagHits ? tags.join(", ") : body;
|
|
213
|
+
hits.push({ path: rel, title, tags, score, snippet: snippetAround(snippetSource, needle) });
|
|
214
|
+
}
|
|
215
|
+
hits.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
|
|
216
|
+
return hits.slice(0, limit);
|
|
217
|
+
}
|
|
218
|
+
const MAX_CONTENT_BYTES = 256 * 1024;
|
|
219
|
+
const WRITE_MODES = ["create", "overwrite", "append"];
|
|
220
|
+
function isAbsPath(rel) {
|
|
221
|
+
return path.isAbsolute(rel) || /^[A-Za-z]:[\\/]/.test(rel) || rel.startsWith("\\\\");
|
|
222
|
+
}
|
|
223
|
+
function hasDotDot(rel) {
|
|
224
|
+
return rel.replace(/\\/g, "/").split("/").some((p) => p === "..");
|
|
225
|
+
}
|
|
226
|
+
function ensureMd(rel) {
|
|
227
|
+
return rel.toLowerCase().endsWith(".md") ? rel : rel + ".md";
|
|
228
|
+
}
|
|
229
|
+
function isErrno(e, code) {
|
|
230
|
+
return typeof e === "object" && e !== null && "code" in e && e.code === code;
|
|
231
|
+
}
|
|
232
|
+
async function resolveWritableTarget(relRaw) {
|
|
233
|
+
if (isAbsPath(relRaw))
|
|
234
|
+
return { error: "Refusé : chemin absolu interdit." };
|
|
235
|
+
if (hasDotDot(relRaw))
|
|
236
|
+
return { error: "Refusé : chemin hors du coffre." };
|
|
237
|
+
const relNorm = ensureMd(relRaw.replace(/\\/g, "/"));
|
|
238
|
+
if (path.extname(relNorm).toLowerCase() !== ".md") {
|
|
239
|
+
return { error: "Refusé : seules les notes .md sont autorisées." };
|
|
240
|
+
}
|
|
241
|
+
const target = path.resolve(vaultRoot, relNorm);
|
|
242
|
+
if (target === vaultRoot || !target.startsWith(vaultRoot + path.sep)) {
|
|
243
|
+
return { error: "Refusé : chemin hors du coffre." };
|
|
244
|
+
}
|
|
245
|
+
const relFromRoot = path.relative(vaultRoot, target);
|
|
246
|
+
if (hasDotDot(relFromRoot) || path.isAbsolute(relFromRoot)) {
|
|
247
|
+
return { error: "Refusé : chemin hors du coffre." };
|
|
248
|
+
}
|
|
249
|
+
const parts = relFromRoot.split(path.sep);
|
|
250
|
+
let current = vaultRoot;
|
|
251
|
+
for (let i = 0; i < parts.length; i++) {
|
|
252
|
+
current = path.join(current, parts[i]);
|
|
253
|
+
let st;
|
|
254
|
+
try {
|
|
255
|
+
st = await fs.lstat(current);
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
break;
|
|
259
|
+
}
|
|
260
|
+
if (st.isSymbolicLink()) {
|
|
261
|
+
return { error: "Refusé : écriture à travers un lien symbolique interdite." };
|
|
262
|
+
}
|
|
263
|
+
if (i < parts.length - 1 && !st.isDirectory()) {
|
|
264
|
+
return { error: "Refusé : un élément du chemin n'est pas un dossier." };
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
const parent = path.dirname(target);
|
|
268
|
+
let ancestor = parent;
|
|
269
|
+
while (ancestor.startsWith(vaultRoot + path.sep) || ancestor === vaultRoot) {
|
|
270
|
+
try {
|
|
271
|
+
const real = await fs.realpath(ancestor);
|
|
272
|
+
if (!insideVault(real))
|
|
273
|
+
return { error: "Refusé : chemin hors du coffre." };
|
|
274
|
+
break;
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
const next = path.dirname(ancestor);
|
|
278
|
+
if (next === ancestor)
|
|
279
|
+
break;
|
|
280
|
+
ancestor = next;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
const rel = relFromRoot.split(path.sep).join("/");
|
|
284
|
+
return { rel, target, parent };
|
|
285
|
+
}
|
|
286
|
+
async function ensureParentDir(parent) {
|
|
287
|
+
await fs.mkdir(parent, { recursive: true });
|
|
288
|
+
let parentReal;
|
|
289
|
+
try {
|
|
290
|
+
parentReal = await fs.realpath(parent);
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
return { error: "Refusé : dossier parent introuvable." };
|
|
294
|
+
}
|
|
295
|
+
if (!insideVault(parentReal))
|
|
296
|
+
return { error: "Refusé : chemin hors du coffre." };
|
|
297
|
+
return parentReal;
|
|
298
|
+
}
|
|
299
|
+
async function writeAtomic(target, content, mode) {
|
|
300
|
+
const dir = path.dirname(target);
|
|
301
|
+
const tmp = path.join(dir, `.xvcache-tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp`);
|
|
302
|
+
await fs.writeFile(tmp, content, { encoding: "utf8", flag: "wx", mode: 0o644 });
|
|
303
|
+
let renamed = false;
|
|
304
|
+
try {
|
|
305
|
+
if (mode === "create") {
|
|
306
|
+
try {
|
|
307
|
+
await fs.link(tmp, target);
|
|
308
|
+
}
|
|
309
|
+
catch (e) {
|
|
310
|
+
if (isErrno(e, "EEXIST")) {
|
|
311
|
+
throw Object.assign(new Error("exists"), { code: "EEXIST" });
|
|
312
|
+
}
|
|
313
|
+
throw e;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
else {
|
|
317
|
+
await fs.rename(tmp, target);
|
|
318
|
+
renamed = true;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
finally {
|
|
322
|
+
if (!renamed)
|
|
323
|
+
await fs.unlink(tmp).catch(() => { });
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
const server = new McpServer({ name: "xvcache-mcp", version: "0.2.0" });
|
|
327
|
+
server.registerTool("read_note", {
|
|
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.",
|
|
329
|
+
inputSchema: { path: z.string().min(1).describe("Vault-relative path of the note, e.g. Projets/Idee.md") },
|
|
330
|
+
}, async ({ path: rel }) => {
|
|
331
|
+
const args = { path: rel.replace(/\\/g, "/") };
|
|
332
|
+
const ret = await (async () => {
|
|
333
|
+
if (path.isAbsolute(rel))
|
|
334
|
+
return fail("Refusé : chemin absolu interdit.");
|
|
335
|
+
if (path.extname(rel).toLowerCase() !== ".md")
|
|
336
|
+
return fail("Refusé : seules les notes .md sont lisibles.");
|
|
337
|
+
const target = path.resolve(vaultRoot, rel);
|
|
338
|
+
if (!target.startsWith(vaultRoot + path.sep))
|
|
339
|
+
return fail("Refusé : chemin hors du coffre.");
|
|
340
|
+
let real;
|
|
341
|
+
try {
|
|
342
|
+
real = await fs.realpath(target);
|
|
343
|
+
}
|
|
344
|
+
catch {
|
|
345
|
+
return fail("Note introuvable.");
|
|
346
|
+
}
|
|
347
|
+
if (!real.startsWith(vaultRoot + path.sep))
|
|
348
|
+
return fail("Refusé : lien symbolique hors du coffre.");
|
|
349
|
+
const text = await fs.readFile(real, "utf8");
|
|
350
|
+
return ok(text);
|
|
351
|
+
})();
|
|
352
|
+
const noteSha = ret.isError ? null : sha256Hex(toolText(ret));
|
|
353
|
+
await logTool("read_note", args, ret.isError ? "erreur" : "ok", noteSha);
|
|
354
|
+
return ret;
|
|
355
|
+
});
|
|
356
|
+
server.registerTool("search_notes", {
|
|
357
|
+
description: "Search Markdown notes in the local XVcache vault (title, tags, body). Case- and accent-insensitive. Use this to find a note before read_note or verify_journal. Each search is journaled (the query is stored, not the note content). Do not search for secrets to exfiltrate them.",
|
|
358
|
+
inputSchema: {
|
|
359
|
+
query: z.string().describe("Text to search for in the vault"),
|
|
360
|
+
limit: z.number().int().min(1).max(50).optional().describe("Max hits (default 10, max 50)"),
|
|
361
|
+
},
|
|
362
|
+
}, async ({ query, limit }) => {
|
|
363
|
+
const args = { query };
|
|
364
|
+
const ret = await (async () => {
|
|
365
|
+
const result = await searchNotes(query, limit ?? 10);
|
|
366
|
+
if ("error" in result)
|
|
367
|
+
return fail(result.error);
|
|
368
|
+
return ok(JSON.stringify(result));
|
|
369
|
+
})();
|
|
370
|
+
await logTool("search_notes", args, ret.isError ? "erreur" : "ok", null);
|
|
371
|
+
return ret;
|
|
372
|
+
});
|
|
373
|
+
server.registerTool("write_note", {
|
|
374
|
+
description: "Write a Markdown (.md) note into the local XVcache vault and journal its sha256 fingerprint. Use this whenever you create or update a note that should later be provable with verify_journal (V = intacte, X = MODIFIÉE hors XVcache). path is vault-relative (.md is added if missing). mode: create (default, fails if the note exists), overwrite, or append. Creates intermediate folders. Atomic write for create and overwrite. Max 256 KiB. Never write secrets that do not belong in the vault. Editing the file outside this tool will later yield verdict X.",
|
|
375
|
+
inputSchema: {
|
|
376
|
+
path: z.string().min(1).describe("Vault-relative path, e.g. Projets/Idee.md; .md is added if missing"),
|
|
377
|
+
content: z.string().describe("Markdown content of the note"),
|
|
378
|
+
mode: z.enum(["create", "overwrite", "append"]).optional().describe("create (default), overwrite, or append"),
|
|
379
|
+
},
|
|
380
|
+
}, async ({ path: rel, content, mode: modeIn }) => {
|
|
381
|
+
const mode = modeIn ?? "create";
|
|
382
|
+
const args = { path: rel.replace(/\\/g, "/"), mode };
|
|
383
|
+
let noteSha = null;
|
|
384
|
+
const ret = await (async () => {
|
|
385
|
+
const bytesIn = Buffer.byteLength(content, "utf8");
|
|
386
|
+
if (bytesIn > MAX_CONTENT_BYTES) {
|
|
387
|
+
return fail("Refusé : contenu trop volumineux (max 256 Ko).");
|
|
388
|
+
}
|
|
389
|
+
if (bytesIn === 0 && (mode === "create" || mode === "overwrite")) {
|
|
390
|
+
return fail("Refusé : contenu vide.");
|
|
391
|
+
}
|
|
392
|
+
const resolved = await resolveWritableTarget(rel);
|
|
393
|
+
if ("error" in resolved)
|
|
394
|
+
return fail(resolved.error);
|
|
395
|
+
const { target, parent } = resolved;
|
|
396
|
+
args.path = resolved.rel;
|
|
397
|
+
const parentOk = await ensureParentDir(parent);
|
|
398
|
+
if (typeof parentOk !== "string")
|
|
399
|
+
return fail(parentOk.error);
|
|
400
|
+
let st;
|
|
401
|
+
try {
|
|
402
|
+
st = await fs.lstat(target);
|
|
403
|
+
}
|
|
404
|
+
catch {
|
|
405
|
+
st = undefined;
|
|
406
|
+
}
|
|
407
|
+
if (st?.isSymbolicLink()) {
|
|
408
|
+
return fail("Refusé : écriture à travers un lien symbolique interdite.");
|
|
409
|
+
}
|
|
410
|
+
if (st && !st.isFile()) {
|
|
411
|
+
return fail("Refusé : la cible n'est pas un fichier.");
|
|
412
|
+
}
|
|
413
|
+
if (mode === "create" && st) {
|
|
414
|
+
return fail("Refusé : la note existe déjà.");
|
|
415
|
+
}
|
|
416
|
+
if (mode === "append" && !st) {
|
|
417
|
+
return fail("Note introuvable.");
|
|
418
|
+
}
|
|
419
|
+
try {
|
|
420
|
+
if (mode === "append") {
|
|
421
|
+
await fs.appendFile(target, content, { encoding: "utf8" });
|
|
422
|
+
}
|
|
423
|
+
else {
|
|
424
|
+
await writeAtomic(target, content, mode);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
catch (e) {
|
|
428
|
+
if (isErrno(e, "EEXIST"))
|
|
429
|
+
return fail("Refusé : la note existe déjà.");
|
|
430
|
+
throw e;
|
|
431
|
+
}
|
|
432
|
+
const after = await fs.stat(target);
|
|
433
|
+
noteSha = sha256Hex(await fs.readFile(target));
|
|
434
|
+
return ok(JSON.stringify({ path: resolved.rel, bytes: after.size, mode }));
|
|
435
|
+
})();
|
|
436
|
+
await logTool("write_note", args, ret.isError ? "erreur" : "ok", noteSha);
|
|
437
|
+
return ret;
|
|
438
|
+
});
|
|
439
|
+
server.registerTool("verify_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.",
|
|
441
|
+
inputSchema: {
|
|
442
|
+
path: z.string().min(1).optional().describe("Vault-relative note to compare, e.g. Tests/Memo.md"),
|
|
443
|
+
},
|
|
444
|
+
}, async ({ path: rel }) => {
|
|
445
|
+
const chain = await verifyJournalFile(journal.path);
|
|
446
|
+
const chainMsg = formatChainMessage(chain);
|
|
447
|
+
if (!rel) {
|
|
448
|
+
return chain.ok ? ok(chainMsg) : fail(chainMsg);
|
|
449
|
+
}
|
|
450
|
+
if (!chain.ok) {
|
|
451
|
+
return fail(chainMsg + " Comparaison de la note non fiable.");
|
|
452
|
+
}
|
|
453
|
+
const lines = await readCompleteJournalLines(journal.path);
|
|
454
|
+
const entries = [];
|
|
455
|
+
for (const line of lines) {
|
|
456
|
+
const parsed = parseEntry(line);
|
|
457
|
+
if ("error" in parsed)
|
|
458
|
+
return fail(chainMsg + " Comparaison de la note non fiable.");
|
|
459
|
+
entries.push(parsed);
|
|
460
|
+
}
|
|
461
|
+
const rec = lastNoteRecord(entries, rel);
|
|
462
|
+
if (!rec) {
|
|
463
|
+
return ok(chainMsg + `\nAucune entrée journalisée pour ${rel}.`);
|
|
464
|
+
}
|
|
465
|
+
if (path.isAbsolute(rel))
|
|
466
|
+
return fail("Refusé : chemin absolu interdit.");
|
|
467
|
+
if (rel.replace(/\\/g, "/").split("/").some((p) => p === "..")) {
|
|
468
|
+
return fail("Refusé : chemin hors du coffre.");
|
|
469
|
+
}
|
|
470
|
+
const relMd = rel.toLowerCase().endsWith(".md") ? rel : rel + ".md";
|
|
471
|
+
const target = path.resolve(vaultRoot, relMd);
|
|
472
|
+
if (!target.startsWith(vaultRoot + path.sep))
|
|
473
|
+
return fail("Refusé : chemin hors du coffre.");
|
|
474
|
+
let real;
|
|
475
|
+
try {
|
|
476
|
+
real = await fs.realpath(target);
|
|
477
|
+
}
|
|
478
|
+
catch {
|
|
479
|
+
return fail("Note introuvable.");
|
|
480
|
+
}
|
|
481
|
+
if (!real.startsWith(vaultRoot + path.sep))
|
|
482
|
+
return fail("Refusé : lien symbolique hors du coffre.");
|
|
483
|
+
const current = sha256Hex(await fs.readFile(real));
|
|
484
|
+
const verdict = formatNoteVerdict(relMd, rec, current);
|
|
485
|
+
return ok(chainMsg + "\n" + verdict.message);
|
|
486
|
+
});
|
|
487
|
+
server.registerTool("get_offer", {
|
|
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.",
|
|
489
|
+
inputSchema: {},
|
|
490
|
+
}, async () => ok(JSON.stringify(getOffer(), null, 2)));
|
|
491
|
+
server.registerTool("list_plans", {
|
|
492
|
+
description: "Return the full XVcache plans catalog (plans.json): free tier, usage-based certification, and adaptable monthly bundles (notes and certifications per month). Every price and most quotas are placeholders marked TBD. Payment is not live. Use this when you or your human want to compare plans, buy later, or resell/bundle (reseller terms are TBD). Not written into the journal.",
|
|
493
|
+
inputSchema: {},
|
|
494
|
+
}, async () => ok(JSON.stringify(loadPlansCatalog(), null, 2)));
|
|
495
|
+
server.registerTool("recommend_plan", {
|
|
496
|
+
description: "Suggest an XVcache plan from expected volume and needs. Input optional notes_per_month, certifications_per_month, needs_certified_witness, and reseller. Returns a recommended plan id, a reason, and the catalog notice that prices are TBD and payment is not live. Use this before asking a human to approve an upgrade. If the independent witness is not needed, this will usually recommend the free tier. Not written into the journal.",
|
|
497
|
+
inputSchema: {
|
|
498
|
+
notes_per_month: z.number().int().min(0).optional().describe("Expected notes written or verified per month (estimate)"),
|
|
499
|
+
certifications_per_month: z.number().int().min(0).optional().describe("Expected independent witness certifications per month (estimate)"),
|
|
500
|
+
needs_certified_witness: z.boolean().optional().describe("True if a third-party certifying witness is required, not only local V/X"),
|
|
501
|
+
reseller: z.boolean().optional().describe("True if you want to resell or bundle XVcache for your own clients (terms TBD)"),
|
|
502
|
+
},
|
|
503
|
+
}, async (input) => ok(JSON.stringify(recommendPlan(input), null, 2)));
|
|
504
|
+
server.registerTool("request_upgrade", {
|
|
505
|
+
description: "Start an upgrade request for a plan id from list_plans or recommend_plan. This is a stub: it does not charge anyone and does not open Stripe or x402. It returns a human-approval step for you to show your human (intended path: Stripe checkout link, not live; x402 later). Never invent a price or a payment URL. Not written into the journal.",
|
|
506
|
+
inputSchema: {
|
|
507
|
+
plan_id: z.string().min(1).describe("Plan id to request, e.g. usage, bundle-starter, bundle-standard, bundle-plus"),
|
|
508
|
+
},
|
|
509
|
+
}, async ({ plan_id }) => {
|
|
510
|
+
const result = requestUpgrade(plan_id);
|
|
511
|
+
return result.ok === false ? fail(JSON.stringify(result, null, 2)) : ok(JSON.stringify(result, null, 2));
|
|
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
|
+
}
|
|
521
|
+
server.registerTool("certify_note", {
|
|
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.",
|
|
576
|
+
inputSchema: {
|
|
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."),
|
|
580
|
+
},
|
|
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
|
+
});
|
|
586
|
+
await server.connect(new StdioServerTransport());
|