@squirrelnotes.app/mcp 2.7.1-test.378 → 2.7.1-test.380

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.
Files changed (2) hide show
  1. package/dist/stdio-handler.js +551 -54
  2. package/package.json +1 -1
@@ -38131,6 +38131,10 @@ var init_api2 = __esm({
38131
38131
  updateNote(id, dto) {
38132
38132
  return this.request("PATCH", `/public/notes/${id}`, dto);
38133
38133
  }
38134
+ /** A chunked body's commit (proposal 0110 §4.4): one transaction, with the revision precondition. */
38135
+ putNoteBody(id, dto) {
38136
+ return this.request("PUT", `/public/notes/${id}/body`, dto);
38137
+ }
38134
38138
  deleteNote(id) {
38135
38139
  return this.requestVoid("DELETE", `/public/notes/${id}`);
38136
38140
  }
@@ -41668,7 +41672,12 @@ var init_note_text = __esm({
41668
41672
  "too-long": "The note's content would be over the size limit (bytes and limit, in bytes of UTF-8 text), so nothing was written. Move part of it to a new note.",
41669
41673
  "title-too-long": "The title is over the size limit (bytes and limit, in bytes of UTF-8 text), so nothing was written. Use a shorter title.",
41670
41674
  "too-large-to-share": "This note is too large to share: its content is over the size limit (bytes and limit, in bytes of UTF-8 text). Nothing was shared.",
41671
- "search-incomplete": "The search could not read every note; nothing was matched. Try again."
41675
+ "search-incomplete": "The search could not read every note; nothing was matched. Try again.",
41676
+ // Proposal 0110 R1b, §4.2's reader rule and §4.4's conflict: a long note
41677
+ // stored in parts that does not verify is never shown in part or written
41678
+ // over; a write that lost a race to another writer writes nothing.
41679
+ unreadable: "This note could not be read in full. Nothing has been changed.",
41680
+ "write-conflict": "The note changed on the server while this was being written, so nothing was written. Read it again and retry."
41672
41681
  };
41673
41682
  refuse2 = (error62, details) => details === void 0 ? { kind: "refused", error: error62 } : { kind: "refused", error: error62, details };
41674
41683
  isRefusal = (x) => "kind" in x && x.kind === "refused";
@@ -41716,6 +41725,472 @@ var init_note_limits = __esm({
41716
41725
  }
41717
41726
  });
41718
41727
 
41728
+ // src/note-chunks.ts
41729
+ function chunkAadText(noteId, chunkId, versionId) {
41730
+ return `sqn-note-chunk-v1:${noteId}:${chunkId}:${versionId}`;
41731
+ }
41732
+ function manifestAadText(noteId, revision) {
41733
+ return `sqn-note-manifest-v1:${noteId}:${revision}`;
41734
+ }
41735
+ function isUuidV4(value) {
41736
+ return typeof value === "string" && UUID_V4.test(value);
41737
+ }
41738
+ function isCount(value, max) {
41739
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= max;
41740
+ }
41741
+ function checkManifest(value, noteId, revision) {
41742
+ const fail2 = () => {
41743
+ throw new NoteBodyUnreadableError();
41744
+ };
41745
+ if (typeof value !== "object" || value === null || Array.isArray(value)) fail2();
41746
+ const m = value;
41747
+ if (Object.keys(m).sort().join(",") !== "chunker,chunks,noteId,revision,totalBytes,v") fail2();
41748
+ if (m.v !== 1 || m.chunker !== NOTE_CHUNKER) fail2();
41749
+ if (m.noteId !== noteId || m.revision !== revision) fail2();
41750
+ if (!isCount(m.totalBytes, NOTE_BODY_MAX_BYTES2)) fail2();
41751
+ if (!Array.isArray(m.chunks) || m.chunks.length > NOTE_MANIFEST_MAX_CHUNKS) fail2();
41752
+ const chunks = m.chunks;
41753
+ if (chunks.length === 0 && m.totalBytes !== 0) fail2();
41754
+ const ids = /* @__PURE__ */ new Set();
41755
+ let sum = 0;
41756
+ const out = [];
41757
+ for (const raw of chunks) {
41758
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) fail2();
41759
+ const c = raw;
41760
+ if (Object.keys(c).sort().join(",") !== "id,len,lines,sha256,ver") fail2();
41761
+ if (!isUuidV4(c.id) || !isUuidV4(c.ver)) fail2();
41762
+ if (!isCount(c.len, CHUNK_MAX_BYTES) || c.len === 0) fail2();
41763
+ if (!isCount(c.lines, CHUNK_MAX_BYTES)) fail2();
41764
+ if (typeof c.sha256 !== "string" || !HEX_64.test(c.sha256)) fail2();
41765
+ const id = c.id;
41766
+ if (ids.has(id)) fail2();
41767
+ ids.add(id);
41768
+ sum += c.len;
41769
+ out.push({ id, ver: c.ver, len: c.len, lines: c.lines, sha256: c.sha256 });
41770
+ }
41771
+ if (sum !== m.totalBytes) fail2();
41772
+ return { v: 1, noteId, revision, chunker: NOTE_CHUNKER, totalBytes: sum, chunks: out };
41773
+ }
41774
+ function refsOf(manifest) {
41775
+ return manifest.chunks.map((c) => `${c.id}:${c.ver}`).sort();
41776
+ }
41777
+ function countLines(bytes, start = 0, end = bytes.length) {
41778
+ let n = 0;
41779
+ for (let i = start; i < end; i++) if (bytes[i] === NEWLINE) n += 1;
41780
+ return n;
41781
+ }
41782
+ function paddedLength(len) {
41783
+ return Math.max(1, Math.ceil(len / CHUNK_PAD_BYTES)) * CHUNK_PAD_BYTES;
41784
+ }
41785
+ function padChunk(bytes) {
41786
+ const out = new Uint8Array(paddedLength(bytes.length));
41787
+ out.set(bytes);
41788
+ return out;
41789
+ }
41790
+ function unpadChunk(padded, len) {
41791
+ if (padded.length !== paddedLength(len)) throw new NoteBodyUnreadableError();
41792
+ for (let i = len; i < padded.length; i++) {
41793
+ if (padded[i] !== 0) throw new NoteBodyUnreadableError();
41794
+ }
41795
+ return padded.subarray(0, len);
41796
+ }
41797
+ function gearTableFrom(bytes) {
41798
+ if (bytes.length !== GEAR_TABLE_BYTES) throw new Error("Gear table must be 1024 bytes");
41799
+ const table = new Uint32Array(256);
41800
+ for (let i = 0; i < 256; i++) {
41801
+ table[i] = (bytes[4 * i] << 24 | bytes[4 * i + 1] << 16 | bytes[4 * i + 2] << 8 | bytes[4 * i + 3]) >>> 0;
41802
+ }
41803
+ return table;
41804
+ }
41805
+ function nextCut(bytes, start, to, gear) {
41806
+ if (to - start <= CHUNK_MIN_BYTES) return to;
41807
+ const limit = Math.min(to, start + CHUNK_MAX_BYTES);
41808
+ let hash2 = 0;
41809
+ let armed = false;
41810
+ let lastLineStart = -1;
41811
+ for (let i = start; i < limit; i++) {
41812
+ const b = bytes[i];
41813
+ hash2 = (hash2 << 1) + gear[b] >>> 0;
41814
+ if (b === NEWLINE && i + 1 - start >= CHUNK_MIN_BYTES) {
41815
+ if (armed) return i + 1;
41816
+ lastLineStart = i + 1;
41817
+ }
41818
+ if (!armed && i + 1 - start >= CHUNK_MIN_BYTES && (hash2 & GEAR_ARM_MASK) === 0) armed = true;
41819
+ }
41820
+ if (limit === to) return to;
41821
+ if (lastLineStart > 0) return lastLineStart;
41822
+ let cut = limit;
41823
+ while (cut > start + 1 && (bytes[cut] & 192) === 128) cut -= 1;
41824
+ return cut;
41825
+ }
41826
+ function cdcSplit(bytes, from, to, gear) {
41827
+ const ends = [];
41828
+ let start = from;
41829
+ while (start < to) {
41830
+ const end = nextCut(bytes, start, to, gear);
41831
+ ends.push(end);
41832
+ start = end;
41833
+ }
41834
+ return ends;
41835
+ }
41836
+ function commonPrefix(a, b) {
41837
+ const n = Math.min(a.length, b.length);
41838
+ let i = 0;
41839
+ while (i < n && a[i] === b[i]) i += 1;
41840
+ return i;
41841
+ }
41842
+ function commonSuffix(a, b, max) {
41843
+ let i = 0;
41844
+ while (i < max && a[a.length - 1 - i] === b[b.length - 1 - i]) i += 1;
41845
+ return i;
41846
+ }
41847
+ function sameBytes(a, aStart, b, bStart, len) {
41848
+ for (let i = 0; i < len; i++) if (a[aStart + i] !== b[bStart + i]) return false;
41849
+ return true;
41850
+ }
41851
+ function planChunks(bytes, gear, previous) {
41852
+ if (bytes.length === 0) return [];
41853
+ const old = previous?.manifest.chunks ?? [];
41854
+ if (!previous || old.length === 0) {
41855
+ let start = 0;
41856
+ return cdcSplit(bytes, 0, bytes.length, gear).map((end) => {
41857
+ const chunk = { start, end, keepId: null, reuse: null };
41858
+ start = end;
41859
+ return chunk;
41860
+ });
41861
+ }
41862
+ const oldBytes = previous.bytes;
41863
+ const prefix = commonPrefix(oldBytes, bytes);
41864
+ const suffix = commonSuffix(oldBytes, bytes, Math.min(oldBytes.length, bytes.length) - prefix);
41865
+ const delta = bytes.length - oldBytes.length;
41866
+ const map2 = (b) => {
41867
+ if (b <= prefix) return b;
41868
+ if (b >= oldBytes.length - suffix) return b + delta;
41869
+ return -1;
41870
+ };
41871
+ const oldStarts = [];
41872
+ let offset = 0;
41873
+ for (const c of old) {
41874
+ oldStarts.push(offset);
41875
+ offset += c.len;
41876
+ }
41877
+ const kept = [{ pos: 0, index: 0 }];
41878
+ for (let i = 1; i < old.length; i++) {
41879
+ const pos = map2(oldStarts[i]);
41880
+ if (pos <= kept[kept.length - 1].pos || pos >= bytes.length) continue;
41881
+ if (bytes[pos - 1] !== NEWLINE) continue;
41882
+ kept.push({ pos, index: i });
41883
+ }
41884
+ const spans = [];
41885
+ for (let k = 0; k < kept.length; k++) {
41886
+ const here = kept[k];
41887
+ const next = k + 1 < kept.length ? kept[k + 1].pos : bytes.length;
41888
+ if (spans.length > 0 && next - here.pos < CHUNK_MIN_BYTES && k + 1 < kept.length) continue;
41889
+ spans.push(here);
41890
+ }
41891
+ if (spans.length > 1 && spans[1].pos - spans[0].pos < CHUNK_MIN_BYTES) spans.splice(1, 1);
41892
+ const planned = [];
41893
+ for (let s = 0; s < spans.length; s++) {
41894
+ const span2 = spans[s];
41895
+ const from = span2.pos;
41896
+ const to = s + 1 < spans.length ? spans[s + 1].pos : bytes.length;
41897
+ const ends = to - from > CHUNK_MAX_BYTES ? cdcSplit(bytes, from, to, gear) : [to];
41898
+ let start = from;
41899
+ for (const [n, end] of ends.entries()) {
41900
+ const prev = old[span2.index];
41901
+ const keepId = n === 0 ? prev.id : null;
41902
+ let reuse = null;
41903
+ if (n === 0) {
41904
+ const prevStart = oldStarts[span2.index];
41905
+ if (prev.len === end - start && sameBytes(oldBytes, prevStart, bytes, start, prev.len)) reuse = prev;
41906
+ }
41907
+ planned.push({ start, end, keepId, reuse });
41908
+ start = end;
41909
+ }
41910
+ }
41911
+ return planned;
41912
+ }
41913
+ var NOTE_CHUNKER, NOTE_BODY_FORMAT_CHUNKS, CHUNK_MIN_BYTES, CHUNK_MAX_BYTES, CHUNK_PAD_BYTES, NOTE_CHUNKING_THRESHOLD_BYTES, NOTE_BODY_MAX_BYTES2, NOTE_MANIFEST_MAX_CHUNKS, NOTE_CHUNKER_INFO, GEAR_TABLE_BYTES, GEAR_ARM_MASK, NEWLINE, NoteBodyUnreadableError, UUID_V4, HEX_64;
41914
+ var init_note_chunks = __esm({
41915
+ "src/note-chunks.ts"() {
41916
+ "use strict";
41917
+ NOTE_CHUNKER = "cdc-v1";
41918
+ NOTE_BODY_FORMAT_CHUNKS = "chunks-v1";
41919
+ CHUNK_MIN_BYTES = 16 * 1024;
41920
+ CHUNK_MAX_BYTES = 128 * 1024;
41921
+ CHUNK_PAD_BYTES = 1024;
41922
+ NOTE_CHUNKING_THRESHOLD_BYTES = 256 * 1024;
41923
+ NOTE_BODY_MAX_BYTES2 = 3 * 1024 * 1024;
41924
+ NOTE_MANIFEST_MAX_CHUNKS = 1024;
41925
+ NOTE_CHUNKER_INFO = "sqn-note-chunker-v1";
41926
+ GEAR_TABLE_BYTES = 1024;
41927
+ GEAR_ARM_MASK = 4294705152;
41928
+ NEWLINE = 10;
41929
+ NoteBodyUnreadableError = class extends Error {
41930
+ constructor() {
41931
+ super("This note could not be read in full");
41932
+ this.name = "NoteBodyUnreadableError";
41933
+ }
41934
+ };
41935
+ UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
41936
+ HEX_64 = /^[0-9a-f]{64}$/;
41937
+ }
41938
+ });
41939
+
41940
+ // src/note-body.ts
41941
+ import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, createHash as createHash2, hkdfSync, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "node:crypto";
41942
+ function gcmEncrypt(key, iv, plaintext, aad) {
41943
+ const cipher = createCipheriv2("aes-256-gcm", key, iv, { authTagLength: TAG_BYTES });
41944
+ cipher.setAAD(Buffer.from(aad, "utf8"));
41945
+ const body = Buffer.concat([cipher.update(plaintext), cipher.final()]);
41946
+ return Buffer.concat([body, cipher.getAuthTag()]).toString("base64");
41947
+ }
41948
+ function gcmDecrypt(key, ivBase64, ciphertextBase64, aad) {
41949
+ const iv = Buffer.from(ivBase64, "base64");
41950
+ const combined = Buffer.from(ciphertextBase64, "base64");
41951
+ if (iv.length !== IV_BYTES || combined.length < TAG_BYTES) throw new NoteBodyUnreadableError();
41952
+ try {
41953
+ const decipher = createDecipheriv2("aes-256-gcm", key, iv, { authTagLength: TAG_BYTES });
41954
+ decipher.setAAD(Buffer.from(aad, "utf8"));
41955
+ decipher.setAuthTag(combined.subarray(combined.length - TAG_BYTES));
41956
+ return Buffer.concat([decipher.update(combined.subarray(0, combined.length - TAG_BYTES)), decipher.final()]);
41957
+ } catch {
41958
+ throw new NoteBodyUnreadableError();
41959
+ }
41960
+ }
41961
+ function chunkDigest(ivBase64, ciphertextBase64) {
41962
+ return createHash2("sha256").update(Buffer.from(ivBase64, "base64")).update(Buffer.from(ciphertextBase64, "base64")).digest("hex");
41963
+ }
41964
+ function noteChunkerGear(dek) {
41965
+ const ikm = Buffer.from(gcmEncrypt(dek, Buffer.alloc(IV_BYTES), Buffer.from(NOTE_CHUNKER_INFO, "utf8"), ""), "base64");
41966
+ const okm = hkdfSync("sha256", ikm, Buffer.alloc(0), Buffer.from(NOTE_CHUNKER_INFO, "utf8"), GEAR_TABLE_BYTES);
41967
+ return gearTableFrom(new Uint8Array(okm));
41968
+ }
41969
+ function encryptNoteChunk(dek, noteId, chunkId, bytes, fixed = {}) {
41970
+ const versionId = fixed.versionId ?? randomUUID2();
41971
+ const iv = fixed.iv ?? randomBytes2(IV_BYTES);
41972
+ const ciphertext = gcmEncrypt(dek, iv, padChunk(bytes), chunkAadText(noteId, chunkId, versionId));
41973
+ const ivBase64 = iv.toString("base64");
41974
+ return {
41975
+ chunk: { chunkId, versionId, ciphertext, iv: ivBase64 },
41976
+ entry: {
41977
+ id: chunkId,
41978
+ ver: versionId,
41979
+ len: bytes.length,
41980
+ lines: countLines(bytes),
41981
+ sha256: chunkDigest(ivBase64, ciphertext)
41982
+ }
41983
+ };
41984
+ }
41985
+ function decryptNoteChunk(dek, noteId, chunk, expected) {
41986
+ if (chunk.chunkId !== expected.id || chunk.versionId !== expected.ver) throw new NoteBodyUnreadableError();
41987
+ if (chunkDigest(chunk.iv, chunk.ciphertext) !== expected.sha256) throw new NoteBodyUnreadableError();
41988
+ const padded = gcmDecrypt(dek, chunk.iv, chunk.ciphertext, chunkAadText(noteId, chunk.chunkId, chunk.versionId));
41989
+ return unpadChunk(new Uint8Array(padded), expected.len);
41990
+ }
41991
+ function encryptNoteManifest(dek, manifest, fixed = {}) {
41992
+ checkManifest(manifest, manifest.noteId, manifest.revision);
41993
+ const iv = fixed.iv ?? randomBytes2(IV_BYTES);
41994
+ const plaintext = Buffer.from(JSON.stringify(manifest), "utf8");
41995
+ return {
41996
+ ciphertext: gcmEncrypt(dek, iv, plaintext, manifestAadText(manifest.noteId, manifest.revision)),
41997
+ iv: iv.toString("base64")
41998
+ };
41999
+ }
42000
+ function decryptNoteManifest(dek, noteId, revision, ciphertext, iv) {
42001
+ const plaintext = gcmDecrypt(dek, iv, ciphertext, manifestAadText(noteId, revision));
42002
+ let parsed;
42003
+ try {
42004
+ parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(plaintext));
42005
+ } catch {
42006
+ throw new NoteBodyUnreadableError();
42007
+ }
42008
+ return checkManifest(parsed, noteId, revision);
42009
+ }
42010
+ function readChunkedBody(dek, noteId, body) {
42011
+ const manifest = decryptNoteManifest(dek, noteId, body.revision, body.encryptedManifest, body.manifestIv);
42012
+ const served = new Map(body.chunks.map((c) => [`${c.chunkId}:${c.versionId}`, c]));
42013
+ const bytes = new Uint8Array(manifest.totalBytes);
42014
+ const parts = [];
42015
+ let offset = 0;
42016
+ for (const entry2 of manifest.chunks) {
42017
+ const chunk = served.get(`${entry2.id}:${entry2.ver}`);
42018
+ if (!chunk) throw new NoteBodyUnreadableError();
42019
+ const part = decryptNoteChunk(dek, noteId, chunk, entry2);
42020
+ try {
42021
+ parts.push(new TextDecoder("utf-8", { fatal: true }).decode(part));
42022
+ } catch {
42023
+ throw new NoteBodyUnreadableError();
42024
+ }
42025
+ bytes.set(part, offset);
42026
+ offset += entry2.len;
42027
+ }
42028
+ return { text: parts.join(""), revision: body.revision, manifest, bytes };
42029
+ }
42030
+ function buildChunkedCommit(dek, noteId, text, base) {
42031
+ const bytes = new TextEncoder().encode(text);
42032
+ if (bytes.length > NOTE_BODY_MAX_BYTES2) throw new NoteBodyTooLargeError(bytes.length);
42033
+ const plan = planChunks(bytes, noteChunkerGear(dek), base ? { bytes: base.bytes, manifest: base.manifest } : void 0);
42034
+ const entries = [];
42035
+ const fresh = [];
42036
+ for (const p of plan) {
42037
+ if (p.reuse) {
42038
+ entries.push(p.reuse);
42039
+ continue;
42040
+ }
42041
+ const { chunk, entry: entry2 } = encryptNoteChunk(dek, noteId, p.keepId ?? randomUUID2(), bytes.subarray(p.start, p.end));
42042
+ entries.push(entry2);
42043
+ fresh.push(chunk);
42044
+ }
42045
+ const revision = (base?.revision ?? 0) + 1;
42046
+ const manifest = {
42047
+ v: 1,
42048
+ noteId,
42049
+ revision,
42050
+ chunker: NOTE_CHUNKER,
42051
+ totalBytes: bytes.length,
42052
+ chunks: entries
42053
+ };
42054
+ const { ciphertext, iv } = encryptNoteManifest(dek, manifest);
42055
+ fresh.sort((a, b) => a.chunkId === b.chunkId ? cmp(a.versionId, b.versionId) : cmp(a.chunkId, b.chunkId));
42056
+ return {
42057
+ commit: {
42058
+ baseRevision: base?.revision ?? 0,
42059
+ encryptedManifest: ciphertext,
42060
+ manifestIv: iv,
42061
+ refs: refsOf(manifest),
42062
+ chunks: fresh
42063
+ },
42064
+ manifest
42065
+ };
42066
+ }
42067
+ function cmp(a, b) {
42068
+ return a < b ? -1 : a > b ? 1 : 0;
42069
+ }
42070
+ var IV_BYTES, TAG_BYTES, NoteBodyTooLargeError;
42071
+ var init_note_body = __esm({
42072
+ "src/note-body.ts"() {
42073
+ "use strict";
42074
+ init_note_chunks();
42075
+ IV_BYTES = 12;
42076
+ TAG_BYTES = 16;
42077
+ NoteBodyTooLargeError = class extends Error {
42078
+ constructor(bytes) {
42079
+ super("Note body over the limit");
42080
+ this.bytes = bytes;
42081
+ this.name = "NoteBodyTooLargeError";
42082
+ }
42083
+ bytes;
42084
+ };
42085
+ }
42086
+ });
42087
+
42088
+ // src/note-content.ts
42089
+ import { randomUUID as randomUUID3 } from "node:crypto";
42090
+ function inlineContentFields(sealed) {
42091
+ return { encryptedContent: sealed.ciphertext, contentIv: sealed.iv };
42092
+ }
42093
+ function listedBodyOf(n) {
42094
+ return n.encryptedContent !== void 0 ? { encryptedContent: n.encryptedContent, contentIv: n.contentIv } : null;
42095
+ }
42096
+ function bodyOfEntry(b) {
42097
+ return b.bodyFormat === NOTE_BODY_FORMAT_CHUNKS ? { encryptedContent: "", contentIv: null, bodyFormat: NOTE_BODY_FORMAT_CHUNKS, body: b.body } : { encryptedContent: b.encryptedContent, contentIv: b.contentIv };
42098
+ }
42099
+ function bodyOfNote(n) {
42100
+ return {
42101
+ encryptedContent: n.encryptedContent,
42102
+ contentIv: n.contentIv,
42103
+ ...n.bodyFormat ? { bodyFormat: n.bodyFormat } : {},
42104
+ ...n.body ? { body: n.body } : {}
42105
+ };
42106
+ }
42107
+ function readNoteContent(note, key) {
42108
+ if (note.bodyFormat === NOTE_BODY_FORMAT_CHUNKS) {
42109
+ if (!note.body) throw new NoteBodyUnreadableError();
42110
+ const chunked = readChunkedBody(key, note.id, note.body);
42111
+ if (note.encryptedContent) throw new NoteBodyUnreadableError();
42112
+ return { text: chunked.text, chunked };
42113
+ }
42114
+ const text = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
42115
+ return { text, chunked: null };
42116
+ }
42117
+ function refused(error62, details) {
42118
+ return details === void 0 ? { kind: "refused", error: error62 } : { kind: "refused", error: error62, details };
42119
+ }
42120
+ function lostRace(err) {
42121
+ return err instanceof SquirrelApiError && err.status === 409 && /NOTE_BODY_(CONFLICT|CHUNKED)/.test(err.responseBody);
42122
+ }
42123
+ function conversionsOff(err) {
42124
+ return err instanceof SquirrelApiError && err.status === 409 && err.responseBody.includes("NOTE_BODY_CONVERSIONS_OFF");
42125
+ }
42126
+ function overThreshold(bytes) {
42127
+ return bytes > NOTE_CHUNKING_THRESHOLD_BYTES;
42128
+ }
42129
+ function overInlineCap(bytes) {
42130
+ return bytes > NOTE_BODY_MAX_BYTES ? refused("too-long", { bytes, limit: NOTE_BODY_MAX_BYTES }) : null;
42131
+ }
42132
+ async function writeNoteContent(client, key, noteId, text, current) {
42133
+ const tooLong = newContentTooLong(text);
42134
+ if (tooLong) return tooLong;
42135
+ const bytes = utf8Bytes(text);
42136
+ if (current.chunked || overThreshold(bytes)) {
42137
+ const { commit } = buildChunkedCommit(key, noteId, text, current.chunked ?? void 0);
42138
+ try {
42139
+ const saved = await client.putNoteBody(noteId, commit);
42140
+ return { kind: "written", updatedAt: saved.updatedAt };
42141
+ } catch (err) {
42142
+ if (lostRace(err)) return refused("write-conflict");
42143
+ if (current.chunked || !conversionsOff(err)) throw err;
42144
+ }
42145
+ }
42146
+ const capped = overInlineCap(bytes);
42147
+ if (capped) return capped;
42148
+ const enc = encrypt(text, key);
42149
+ try {
42150
+ const saved = await client.updateNote(noteId, inlineContentFields(enc));
42151
+ return { kind: "written", updatedAt: saved.updatedAt };
42152
+ } catch (err) {
42153
+ if (lostRace(err)) return refused("write-conflict");
42154
+ throw err;
42155
+ }
42156
+ }
42157
+ function newContentTooLong(text) {
42158
+ const bytes = utf8Bytes(text);
42159
+ return bytes > NOTE_BODY_MAX_BYTES2 ? refused("too-long", { bytes, limit: NOTE_BODY_MAX_BYTES2 }) : null;
42160
+ }
42161
+ async function createNoteWithContent(client, key, fields, text) {
42162
+ if (text === void 0) return { kind: "created", note: await client.createNote(fields) };
42163
+ const tooLong = newContentTooLong(text);
42164
+ if (tooLong) return tooLong;
42165
+ const bytes = utf8Bytes(text);
42166
+ if (overThreshold(bytes)) {
42167
+ const id = randomUUID3();
42168
+ let note = null;
42169
+ try {
42170
+ note = await client.createNote({ ...fields, id, body: buildChunkedCommit(key, id, text).commit });
42171
+ } catch (err) {
42172
+ if (!conversionsOff(err)) throw err;
42173
+ }
42174
+ if (note?.bodyFormat === NOTE_BODY_FORMAT_CHUNKS) return { kind: "created", note };
42175
+ const capped = overInlineCap(bytes);
42176
+ if (capped) return capped;
42177
+ if (note) {
42178
+ return { kind: "created", note: await client.updateNote(note.id, inlineContentFields(encrypt(text, key))) };
42179
+ }
42180
+ }
42181
+ return { kind: "created", note: await client.createNote({ ...fields, ...inlineContentFields(encrypt(text, key)) }) };
42182
+ }
42183
+ var init_note_content = __esm({
42184
+ "src/note-content.ts"() {
42185
+ "use strict";
42186
+ init_api_error();
42187
+ init_crypto();
42188
+ init_note_body();
42189
+ init_note_chunks();
42190
+ init_note_limits();
42191
+ }
42192
+ });
42193
+
41719
42194
  // src/note-bodies.ts
41720
42195
  function isTransient(err) {
41721
42196
  return err instanceof SquirrelNetworkError || err instanceof SquirrelApiError && (err.status === 429 || err.status >= 500);
@@ -41724,9 +42199,8 @@ async function withBodies(client, listed, options = {}) {
41724
42199
  const delays = options.retryDelaysMs ?? NOTE_BODIES_RETRY_DELAYS_MS;
41725
42200
  const bodies = /* @__PURE__ */ new Map();
41726
42201
  for (const n of listed) {
41727
- if (n.encryptedContent !== void 0) {
41728
- bodies.set(n.id, { encryptedContent: n.encryptedContent, contentIv: n.contentIv });
41729
- }
42202
+ const body = listedBodyOf(n);
42203
+ if (body) bodies.set(n.id, body);
41730
42204
  }
41731
42205
  const missing = /* @__PURE__ */ new Set();
41732
42206
  let owed = listed.map((n) => n.id).filter((id) => !bodies.has(id));
@@ -41754,7 +42228,7 @@ async function withBodies(client, listed, options = {}) {
41754
42228
  throw err;
41755
42229
  }
41756
42230
  for (const b of page.bodies) {
41757
- bodies.set(b.id, { encryptedContent: b.encryptedContent, contentIv: b.contentIv });
42231
+ bodies.set(b.id, bodyOfEntry(b));
41758
42232
  }
41759
42233
  for (const id of page.missing) missing.add(id);
41760
42234
  if (page.bodies.length === 0 && page.missing.length === 0) {
@@ -41771,7 +42245,7 @@ async function oneAtATime(client, ids, bodies, missing, attempt) {
41771
42245
  for (const id of ids) {
41772
42246
  try {
41773
42247
  const n = await attempt(() => client.getNote(id));
41774
- bodies.set(id, { encryptedContent: n.encryptedContent, contentIv: n.contentIv });
42248
+ bodies.set(id, bodyOfNote(n));
41775
42249
  } catch (err) {
41776
42250
  if (err instanceof SquirrelApiError && err.status === 404) missing.add(id);
41777
42251
  else throw err;
@@ -41783,6 +42257,7 @@ var init_note_bodies = __esm({
41783
42257
  "src/note-bodies.ts"() {
41784
42258
  "use strict";
41785
42259
  init_api_error();
42260
+ init_note_content();
41786
42261
  NOTE_BODIES_BATCH = 500;
41787
42262
  NOTE_BODIES_RETRY_DELAYS_MS = [250, 1e3];
41788
42263
  NoteBodiesIncompleteError = class extends Error {
@@ -41841,7 +42316,7 @@ function decryptNoteTitle(note, key) {
41841
42316
  }
41842
42317
  function decryptNote(note, key) {
41843
42318
  const title = decrypt(note.encryptedTitle, note.titleIv, key);
41844
- const content = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
42319
+ const content = readNoteContent(note, key).text;
41845
42320
  const tagIds = note.tags?.map((t) => t.id) ?? [];
41846
42321
  return { ...note, title, content, tagIds };
41847
42322
  }
@@ -41873,6 +42348,21 @@ function titleTooLong(title) {
41873
42348
  const bytes = utf8Bytes(title);
41874
42349
  return bytes > NOTE_TITLE_MAX_BYTES ? { kind: "refused", error: "title-too-long", details: { bytes, limit: NOTE_TITLE_MAX_BYTES } } : null;
41875
42350
  }
42351
+ function refuseUnreadableBodies(server) {
42352
+ const register = server.tool.bind(server);
42353
+ server.tool = (...args) => {
42354
+ const handler = args[args.length - 1];
42355
+ args[args.length - 1] = async (...a) => {
42356
+ try {
42357
+ return await handler(...a);
42358
+ } catch (err) {
42359
+ if (err instanceof NoteBodyUnreadableError) return refusalResult({ kind: "refused", error: "unreadable" });
42360
+ throw err;
42361
+ }
42362
+ };
42363
+ return register(...args);
42364
+ };
42365
+ }
41876
42366
  function jsonResult(value) {
41877
42367
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
41878
42368
  }
@@ -41884,6 +42374,7 @@ function createMcpServer(creds, opts = {}) {
41884
42374
  const context = createContextProvider(
41885
42375
  (onUnauthorized) => buildContext(creds, onUnauthorized)
41886
42376
  );
42377
+ refuseUnreadableBodies(server);
41887
42378
  server.prompt(
41888
42379
  "markdown_capabilities",
41889
42380
  "Describes the Markdown and Mermaid diagram features supported by Squirrel Notes. Use this to understand what rich content you can include when creating or updating notes.",
@@ -41981,17 +42472,18 @@ function createMcpServer(creds, opts = {}) {
41981
42472
  collectionId: external_exports.string().optional().describe("Collection ID to place the note in. Omit to create in scratchpad.")
41982
42473
  },
41983
42474
  async ({ title, content, collectionId }) => {
41984
- const tooLong = titleTooLong(title) ?? (content !== void 0 ? bodyTooLong(content) : null);
42475
+ const tooLong = titleTooLong(title) ?? (content !== void 0 ? newContentTooLong(content) : null);
41985
42476
  if (tooLong) return refusalResult(tooLong);
41986
42477
  const { client, key } = await context.get();
41987
42478
  const encTitle = encrypt(title, key);
41988
- const encContent = content !== void 0 ? encrypt(content, key) : null;
41989
- const note = await client.createNote({
41990
- encryptedTitle: encTitle.ciphertext,
41991
- titleIv: encTitle.iv,
41992
- ...encContent ? { encryptedContent: encContent.ciphertext, contentIv: encContent.iv } : {},
41993
- collectionId: collectionId ?? null
41994
- });
42479
+ const created = await createNoteWithContent(
42480
+ client,
42481
+ key,
42482
+ { encryptedTitle: encTitle.ciphertext, titleIv: encTitle.iv, collectionId: collectionId ?? null },
42483
+ content
42484
+ );
42485
+ if (created.kind === "refused") return refusalResult(created);
42486
+ const { note } = created;
41995
42487
  return {
41996
42488
  content: [
41997
42489
  {
@@ -42011,8 +42503,8 @@ function createMcpServer(creds, opts = {}) {
42011
42503
  content: external_exports.string().optional().describe("New content in Markdown (replaces existing content)")
42012
42504
  },
42013
42505
  async ({ id, title, content }) => {
42014
- const tooLong = (title !== void 0 ? titleTooLong(title) : null) ?? (content !== void 0 ? bodyTooLong(content) : null);
42015
- if (tooLong) return refusalResult(tooLong);
42506
+ const titleRefusal = title !== void 0 ? titleTooLong(title) : null;
42507
+ if (titleRefusal) return refusalResult(titleRefusal);
42016
42508
  const { client, key } = await context.get();
42017
42509
  const dto = {};
42018
42510
  if (title !== void 0) {
@@ -42020,15 +42512,26 @@ function createMcpServer(creds, opts = {}) {
42020
42512
  dto.encryptedTitle = enc.ciphertext;
42021
42513
  dto.titleIv = enc.iv;
42022
42514
  }
42023
- if (content !== void 0) {
42515
+ if (content !== void 0 && utf8Bytes(content) <= NOTE_CHUNKING_THRESHOLD_BYTES) {
42024
42516
  const enc = encrypt(content, key);
42025
- dto.encryptedContent = enc.ciphertext;
42026
- dto.contentIv = enc.iv;
42517
+ try {
42518
+ const note = await client.updateNote(id, { ...dto, ...inlineContentFields(enc) });
42519
+ return { content: [{ type: "text", text: JSON.stringify({ id: note.id, updated: true }, null, 2) }] };
42520
+ } catch (err) {
42521
+ if (!(err instanceof SquirrelApiError && err.status === 409 && err.responseBody.includes("NOTE_BODY_CHUNKED"))) throw err;
42522
+ }
42027
42523
  }
42028
- const note = await client.updateNote(id, dto);
42029
- return {
42030
- content: [{ type: "text", text: JSON.stringify({ id: note.id, updated: true }, null, 2) }]
42031
- };
42524
+ if (content === void 0) {
42525
+ const note = await client.updateNote(id, dto);
42526
+ return { content: [{ type: "text", text: JSON.stringify({ id: note.id, updated: true }, null, 2) }] };
42527
+ }
42528
+ const tooLong = newContentTooLong(content);
42529
+ if (tooLong) return refusalResult(tooLong);
42530
+ const current = readNoteContent(await client.getNote(id), key);
42531
+ const written = await writeNoteContent(client, key, id, content, current);
42532
+ if (written.kind === "refused") return refusalResult(written);
42533
+ if (title !== void 0) await client.updateNote(id, dto);
42534
+ return { content: [{ type: "text", text: JSON.stringify({ id, updated: true }, null, 2) }] };
42032
42535
  }
42033
42536
  );
42034
42537
  const staleCheck = (updatedAt, expected) => expected !== void 0 && expected !== updatedAt ? { kind: "refused", error: "stale", details: { updatedAt } } : null;
@@ -42049,16 +42552,12 @@ function createMcpServer(creds, opts = {}) {
42049
42552
  const note = await client.getNote(id);
42050
42553
  const stale = staleCheck(note.updatedAt, expectedUpdatedAt);
42051
42554
  if (stale) return refusalResult(stale);
42052
- const existingContent = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
42555
+ const current = readNoteContent(note, key);
42556
+ const existingContent = current.text;
42053
42557
  const newContent = existingContent ? `${existingContent}${separator2}${content}` : content;
42054
- const tooLong = bodyTooLong(newContent);
42055
- if (tooLong) return refusalResult(tooLong);
42056
- const encContent = encrypt(newContent, key);
42057
- const saved = await client.updateNote(id, {
42058
- encryptedContent: encContent.ciphertext,
42059
- contentIv: encContent.iv
42060
- });
42061
- const answer = expectedUpdatedAt === void 0 ? { id, appended: true } : { id, appended: true, updatedAt: saved.updatedAt };
42558
+ const written = await writeNoteContent(client, key, id, newContent, current);
42559
+ if (written.kind === "refused") return refusalResult(written);
42560
+ const answer = expectedUpdatedAt === void 0 ? { id, appended: true } : { id, appended: true, updatedAt: written.updatedAt };
42062
42561
  return {
42063
42562
  content: [{ type: "text", text: JSON.stringify(answer, null, 2) }]
42064
42563
  };
@@ -42067,15 +42566,12 @@ function createMcpServer(creds, opts = {}) {
42067
42566
  const loadNote = async (id) => {
42068
42567
  const { client, key } = await context.get();
42069
42568
  const note = await client.getNote(id);
42070
- const content = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
42071
- return { client, key, note, nt: noteText(content) };
42569
+ const body = readNoteContent(note, key);
42570
+ return { client, key, note, body, nt: noteText(body.text) };
42072
42571
  };
42073
42572
  const writeContent = async (ctx, id, raw) => {
42074
- const tooLong = bodyTooLong(raw);
42075
- if (tooLong) return tooLong;
42076
- const enc = encrypt(raw, ctx.key);
42077
- const saved = await ctx.client.updateNote(id, { encryptedContent: enc.ciphertext, contentIv: enc.iv });
42078
- return saved.updatedAt;
42573
+ const written = await writeNoteContent(ctx.client, ctx.key, id, raw, ctx.body);
42574
+ return written.kind === "written" ? written.updatedAt : written;
42079
42575
  };
42080
42576
  const headingSchema = external_exports.string().describe(`A heading's text exactly as get_note_outline lists it (at most ${HEADING_TEXT_MAX} characters)`);
42081
42577
  const occurrenceSchema = external_exports.number().int().min(1).optional().describe("Which heading with that text, 1 for the first. Needed only when the text appears more than once.");
@@ -42716,7 +43212,7 @@ function createMcpServer(creds, opts = {}) {
42716
43212
  const { client, key } = await context.get();
42717
43213
  const note = await client.getNote(noteId);
42718
43214
  const title = decrypt(note.encryptedTitle, note.titleIv, key);
42719
- const content = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
43215
+ const content = readNoteContent(note, key).text;
42720
43216
  const tooLarge = bodyTooLong(content, "too-large-to-share");
42721
43217
  if (tooLarge) return refusalResult(tooLarge);
42722
43218
  const shareSalt = generateSalt();
@@ -42727,8 +43223,7 @@ function createMcpServer(creds, opts = {}) {
42727
43223
  noteId,
42728
43224
  encryptedTitle: encTitle.ciphertext,
42729
43225
  titleIv: encTitle.iv,
42730
- encryptedContent: encContent.ciphertext,
42731
- contentIv: encContent.iv,
43226
+ ...inlineContentFields(encContent),
42732
43227
  salt: shareSalt,
42733
43228
  pbkdf2Iterations: 6e5,
42734
43229
  expiry,
@@ -42781,7 +43276,7 @@ function createMcpServer(creds, opts = {}) {
42781
43276
  const { client, key } = await context.get();
42782
43277
  const note = await client.getNote(noteId);
42783
43278
  const title = decrypt(note.encryptedTitle, note.titleIv, key);
42784
- const content = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
43279
+ const content = readNoteContent(note, key).text;
42785
43280
  const tooLarge = bodyTooLong(content, "too-large-to-share");
42786
43281
  if (tooLarge) return refusalResult(tooLarge);
42787
43282
  const shareSalt = generateSalt();
@@ -42791,8 +43286,7 @@ function createMcpServer(creds, opts = {}) {
42791
43286
  const status = await client.republishShare(shareToken, {
42792
43287
  encryptedTitle: encTitle.ciphertext,
42793
43288
  titleIv: encTitle.iv,
42794
- encryptedContent: encContent.ciphertext,
42795
- contentIv: encContent.iv,
43289
+ ...inlineContentFields(encContent),
42796
43290
  salt: shareSalt,
42797
43291
  pbkdf2Iterations: 6e5
42798
43292
  });
@@ -43030,6 +43524,9 @@ var init_server3 = __esm({
43030
43524
  init_note_text();
43031
43525
  init_note_limits();
43032
43526
  init_note_bodies();
43527
+ init_note_content();
43528
+ init_note_chunks();
43529
+ init_note_chunks();
43033
43530
  SQUIRREL_API_BASE_URL = process.env.SQUIRREL_API_BASE_URL;
43034
43531
  if (!SQUIRREL_API_BASE_URL) {
43035
43532
  throw new Error("SQUIRREL_API_BASE_URL environment variable is required");
@@ -43110,11 +43607,11 @@ __export(vector_cache_exports, {
43110
43607
  vectorFilePathForId: () => vectorFilePathForId,
43111
43608
  writeVectorFile: () => writeVectorFile
43112
43609
  });
43113
- import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, hkdfSync, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "node:crypto";
43610
+ import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, hkdfSync as hkdfSync2, randomBytes as randomBytes3, randomUUID as randomUUID4 } from "node:crypto";
43114
43611
  import { chmod, mkdir as mkdir2, readFile, rename, rm, writeFile } from "node:fs/promises";
43115
43612
  import path from "node:path";
43116
43613
  function vectorFileId(dek) {
43117
- return Buffer.from(hkdfSync("sha256", dek, Buffer.alloc(0), FILE_ID_INFO, 8)).toString("hex");
43614
+ return Buffer.from(hkdfSync2("sha256", dek, Buffer.alloc(0), FILE_ID_INFO, 8)).toString("hex");
43118
43615
  }
43119
43616
  function vectorFilePath(cacheDir, dek) {
43120
43617
  return vectorFilePathForId(cacheDir, vectorFileId(dek));
@@ -43131,7 +43628,7 @@ function defaultCacheDir(platform, env, home) {
43131
43628
  return env.XDG_CACHE_HOME || path.join(home, ".cache");
43132
43629
  }
43133
43630
  function deriveFileKey(dek, salt) {
43134
- return Buffer.from(hkdfSync("sha256", dek, salt, KEY_INFO, 32));
43631
+ return Buffer.from(hkdfSync2("sha256", dek, salt, KEY_INFO, 32));
43135
43632
  }
43136
43633
  function headerBytes(model, recipe = EMBEDDING_TEXT_RECIPE) {
43137
43634
  return Buffer.from(
@@ -43184,10 +43681,10 @@ function sealVectorFile(entries, model, dek) {
43184
43681
  MAGIC.copy(prefix, 0);
43185
43682
  prefix.writeUInt8(VECTOR_FILE_FORMAT, MAGIC.length);
43186
43683
  prefix.writeUInt16BE(header.length, MAGIC.length + 1);
43187
- const salt = randomBytes2(SALT_LENGTH);
43188
- const iv = randomBytes2(IV_LENGTH2);
43684
+ const salt = randomBytes3(SALT_LENGTH);
43685
+ const iv = randomBytes3(IV_LENGTH2);
43189
43686
  const aad = Buffer.concat([prefix, header, salt, iv]);
43190
- const cipher = createCipheriv2("aes-256-gcm", deriveFileKey(dek, salt), iv);
43687
+ const cipher = createCipheriv3("aes-256-gcm", deriveFileKey(dek, salt), iv);
43191
43688
  cipher.setAAD(aad);
43192
43689
  const sealed = Buffer.concat([cipher.update(encodeBody(entries, model.dimensions)), cipher.final(), cipher.getAuthTag()]);
43193
43690
  return Buffer.concat([aad, sealed]);
@@ -43205,7 +43702,7 @@ function openVectorFile(file2, model, dek) {
43205
43702
  if (!file2.subarray(fixed, fixed + headerLength).equals(headerBytes(model))) return null;
43206
43703
  const salt = file2.subarray(fixed + headerLength, fixed + headerLength + SALT_LENGTH);
43207
43704
  const iv = file2.subarray(aadEnd - IV_LENGTH2, aadEnd);
43208
- const decipher = createDecipheriv2("aes-256-gcm", deriveFileKey(dek, salt), iv);
43705
+ const decipher = createDecipheriv3("aes-256-gcm", deriveFileKey(dek, salt), iv);
43209
43706
  decipher.setAAD(file2.subarray(0, aadEnd));
43210
43707
  decipher.setAuthTag(file2.subarray(file2.length - TAG_LENGTH));
43211
43708
  const body = Buffer.concat([decipher.update(file2.subarray(aadEnd, file2.length - TAG_LENGTH)), decipher.final()]);
@@ -43227,7 +43724,7 @@ async function writeVectorFile(filePath, entries, model, dek) {
43227
43724
  const dir = path.dirname(filePath);
43228
43725
  await mkdir2(dir, { recursive: true, mode: 448 });
43229
43726
  await chmod(dir, 448);
43230
- const tmp = path.join(dir, `.${path.basename(filePath)}.${randomUUID2()}.tmp`);
43727
+ const tmp = path.join(dir, `.${path.basename(filePath)}.${randomUUID4()}.tmp`);
43231
43728
  try {
43232
43729
  await writeFile(tmp, sealVectorFile(entries, model, dek), { mode: 384, flag: "wx" });
43233
43730
  await chmod(tmp, 384);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@squirrelnotes.app/mcp",
3
- "version": "2.7.1-test.378",
3
+ "version": "2.7.1-test.380",
4
4
  "description": "MCP stdio CLI for Squirrel Notes — bridges AI agents to the encrypted note-taking API",
5
5
  "type": "module",
6
6
  "repository": {