@squirrelnotes.app/mcp 2.7.1-test.377 → 2.7.1-test.379

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 +659 -40
  2. package/package.json +1 -1
@@ -38049,7 +38049,7 @@ function redactBody(body, target) {
38049
38049
  const spellings = [.../* @__PURE__ */ new Set([target.secret, encodeURIComponent(target.secret)])];
38050
38050
  return spellings.reduce((text, spelling) => text.split(spelling).join(TOKEN_LABEL), body);
38051
38051
  }
38052
- var MEMORY_PAGE_LIMIT, TOKEN_LABEL, pathOf, labelOf, CLIENT_HEADER, CLIENT_NAME, SquirrelApiClient;
38052
+ var MEMORY_PAGE_LIMIT, TOKEN_LABEL, pathOf, labelOf, CLIENT_HEADER, CLIENT_NAME, NOTE_BODY_HEADER, NOTE_BODY_CAPABILITY, SquirrelApiClient;
38053
38053
  var init_api2 = __esm({
38054
38054
  "src/api.ts"() {
38055
38055
  "use strict";
@@ -38061,6 +38061,8 @@ var init_api2 = __esm({
38061
38061
  labelOf = (target) => typeof target === "string" ? target : target.label;
38062
38062
  CLIENT_HEADER = "X-Squirrel-Client";
38063
38063
  CLIENT_NAME = "mcp";
38064
+ NOTE_BODY_HEADER = "X-Squirrel-Note-Body";
38065
+ NOTE_BODY_CAPABILITY = "chunks-v1";
38064
38066
  SquirrelApiClient = class {
38065
38067
  baseUrl;
38066
38068
  apiKey;
@@ -38083,7 +38085,8 @@ var init_api2 = __esm({
38083
38085
  headers: {
38084
38086
  Authorization: `Bearer ${this.apiKey}`,
38085
38087
  "Content-Type": "application/json",
38086
- [CLIENT_HEADER]: CLIENT_NAME
38088
+ [CLIENT_HEADER]: CLIENT_NAME,
38089
+ [NOTE_BODY_HEADER]: NOTE_BODY_CAPABILITY
38087
38090
  },
38088
38091
  body: body !== void 0 ? JSON.stringify(body) : void 0
38089
38092
  });
@@ -38109,9 +38112,16 @@ var init_api2 = __esm({
38109
38112
  getEncryption() {
38110
38113
  return this.request("GET", "/public/encryption");
38111
38114
  }
38115
+ /** Titles and metadata, no bodies (the capability header); an old backend still sends them. */
38112
38116
  listNotes() {
38113
38117
  return this.request("GET", "/public/notes");
38114
38118
  }
38119
+ /** One batch of bodies, at most 500 ids (proposal 0110 §4.11.2). */
38120
+ fetchNoteBodies(ids) {
38121
+ return this.request("POST", "/public/notes/bodies", {
38122
+ notes: ids.map((id) => ({ id }))
38123
+ });
38124
+ }
38115
38125
  getNote(id) {
38116
38126
  return this.request("GET", `/public/notes/${id}`);
38117
38127
  }
@@ -38121,6 +38131,10 @@ var init_api2 = __esm({
38121
38131
  updateNote(id, dto) {
38122
38132
  return this.request("PATCH", `/public/notes/${id}`, dto);
38123
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
+ }
38124
38138
  deleteNote(id) {
38125
38139
  return this.requestVoid("DELETE", `/public/notes/${id}`);
38126
38140
  }
@@ -41652,7 +41666,18 @@ var init_note_text = __esm({
41652
41666
  "range-inverted": "endLine is before startLine.",
41653
41667
  "empty-content": "content is empty, so there is nothing to insert (insert_in_section also counts blank lines alone as empty).",
41654
41668
  "insert-line-out-of-range": "line is outside the note: insert before a line from minLine to totalLines, or pass maxLine (totalLines + 1) to add at the end.",
41655
- stale: "The note has changed since the updatedAt you passed as expectedUpdatedAt (an edit, or a pin, tag or move), so nothing was written. Read it again and retry with the updatedAt given here."
41669
+ stale: "The note has changed since the updatedAt you passed as expectedUpdatedAt (an edit, or a pin, tag or move), so nothing was written. Read it again and retry with the updatedAt given here.",
41670
+ // Proposal 0110 §4.9, AC5, AC6, AC54 and infosec A2: sizes travel as
41671
+ // `bytes` and `limit`; nothing from the note or an input is quoted.
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.",
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.",
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.",
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."
41656
41681
  };
41657
41682
  refuse2 = (error62, details) => details === void 0 ? { kind: "refused", error: error62 } : { kind: "refused", error: error62, details };
41658
41683
  isRefusal = (x) => "kind" in x && x.kind === "refused";
@@ -41687,6 +41712,535 @@ var init_note_text = __esm({
41687
41712
  }
41688
41713
  });
41689
41714
 
41715
+ // src/note-limits.ts
41716
+ function utf8Bytes(text) {
41717
+ return Buffer.byteLength(text, "utf8");
41718
+ }
41719
+ var NOTE_BODY_MAX_BYTES, NOTE_TITLE_MAX_BYTES;
41720
+ var init_note_limits = __esm({
41721
+ "src/note-limits.ts"() {
41722
+ "use strict";
41723
+ NOTE_BODY_MAX_BYTES = 75e4;
41724
+ NOTE_TITLE_MAX_BYTES = 12e3;
41725
+ }
41726
+ });
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
+ function inlineContentFields(sealed) {
42090
+ return { encryptedContent: sealed.ciphertext, contentIv: sealed.iv };
42091
+ }
42092
+ function listedBodyOf(n) {
42093
+ return n.encryptedContent !== void 0 ? { encryptedContent: n.encryptedContent, contentIv: n.contentIv } : null;
42094
+ }
42095
+ function bodyOfEntry(b) {
42096
+ return b.bodyFormat === NOTE_BODY_FORMAT_CHUNKS ? { encryptedContent: "", contentIv: null, bodyFormat: NOTE_BODY_FORMAT_CHUNKS, body: b.body } : { encryptedContent: b.encryptedContent, contentIv: b.contentIv };
42097
+ }
42098
+ function bodyOfNote(n) {
42099
+ return {
42100
+ encryptedContent: n.encryptedContent,
42101
+ contentIv: n.contentIv,
42102
+ ...n.bodyFormat ? { bodyFormat: n.bodyFormat } : {},
42103
+ ...n.body ? { body: n.body } : {}
42104
+ };
42105
+ }
42106
+ function readNoteContent(note, key) {
42107
+ if (note.bodyFormat === NOTE_BODY_FORMAT_CHUNKS) {
42108
+ if (!note.body) throw new NoteBodyUnreadableError();
42109
+ const chunked = readChunkedBody(key, note.id, note.body);
42110
+ if (note.encryptedContent) throw new NoteBodyUnreadableError();
42111
+ return { text: chunked.text, chunked };
42112
+ }
42113
+ const text = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
42114
+ return { text, chunked: null };
42115
+ }
42116
+ function refused(error62, details) {
42117
+ return details === void 0 ? { kind: "refused", error: error62 } : { kind: "refused", error: error62, details };
42118
+ }
42119
+ function lostRace(err) {
42120
+ return err instanceof SquirrelApiError && err.status === 409 && /NOTE_BODY_(CONFLICT|CHUNKED)/.test(err.responseBody);
42121
+ }
42122
+ async function writeNoteContent(client, key, noteId, text, current, options = {}) {
42123
+ const bytes = utf8Bytes(text);
42124
+ const convert = (options.conversionsOn ?? MCP_CONVERTS_TO_CHUNKS) && bytes > NOTE_CHUNKING_THRESHOLD_BYTES;
42125
+ if (current.chunked || convert) {
42126
+ if (bytes > NOTE_BODY_MAX_BYTES2) return refused("too-long", { bytes, limit: NOTE_BODY_MAX_BYTES2 });
42127
+ const { commit } = buildChunkedCommit(key, noteId, text, current.chunked ?? void 0);
42128
+ try {
42129
+ const saved = await client.putNoteBody(noteId, commit);
42130
+ return { kind: "written", updatedAt: saved.updatedAt };
42131
+ } catch (err) {
42132
+ if (lostRace(err)) return refused("write-conflict");
42133
+ throw err;
42134
+ }
42135
+ }
42136
+ if (bytes > NOTE_BODY_MAX_BYTES) return refused("too-long", { bytes, limit: NOTE_BODY_MAX_BYTES });
42137
+ const enc = encrypt(text, key);
42138
+ try {
42139
+ const saved = await client.updateNote(noteId, inlineContentFields(enc));
42140
+ return { kind: "written", updatedAt: saved.updatedAt };
42141
+ } catch (err) {
42142
+ if (lostRace(err)) return refused("write-conflict");
42143
+ throw err;
42144
+ }
42145
+ }
42146
+ function newContentTooLong(text, options = {}) {
42147
+ const bytes = utf8Bytes(text);
42148
+ const chunked = (options.conversionsOn ?? MCP_CONVERTS_TO_CHUNKS) && bytes > NOTE_CHUNKING_THRESHOLD_BYTES;
42149
+ const limit = chunked ? NOTE_BODY_MAX_BYTES2 : NOTE_BODY_MAX_BYTES;
42150
+ return bytes > limit ? refused("too-long", { bytes, limit }) : null;
42151
+ }
42152
+ var MCP_CONVERTS_TO_CHUNKS;
42153
+ var init_note_content = __esm({
42154
+ "src/note-content.ts"() {
42155
+ "use strict";
42156
+ init_api_error();
42157
+ init_crypto();
42158
+ init_note_body();
42159
+ init_note_chunks();
42160
+ init_note_limits();
42161
+ MCP_CONVERTS_TO_CHUNKS = false;
42162
+ }
42163
+ });
42164
+
42165
+ // src/note-bodies.ts
42166
+ function isTransient(err) {
42167
+ return err instanceof SquirrelNetworkError || err instanceof SquirrelApiError && (err.status === 429 || err.status >= 500);
42168
+ }
42169
+ async function withBodies(client, listed, options = {}) {
42170
+ const delays = options.retryDelaysMs ?? NOTE_BODIES_RETRY_DELAYS_MS;
42171
+ const bodies = /* @__PURE__ */ new Map();
42172
+ for (const n of listed) {
42173
+ const body = listedBodyOf(n);
42174
+ if (body) bodies.set(n.id, body);
42175
+ }
42176
+ const missing = /* @__PURE__ */ new Set();
42177
+ let owed = listed.map((n) => n.id).filter((id) => !bodies.has(id));
42178
+ const attempt = async (call) => {
42179
+ for (let i = 0; ; i++) {
42180
+ try {
42181
+ return await call();
42182
+ } catch (err) {
42183
+ if (!isTransient(err)) throw err;
42184
+ if (i >= delays.length) throw new NoteBodiesIncompleteError();
42185
+ await sleep(delays[i]);
42186
+ }
42187
+ }
42188
+ };
42189
+ while (owed.length > 0) {
42190
+ const batch = owed.slice(0, NOTE_BODIES_BATCH);
42191
+ let page;
42192
+ try {
42193
+ page = await attempt(() => client.fetchNoteBodies(batch));
42194
+ } catch (err) {
42195
+ if (err instanceof SquirrelApiError && err.status === 404) {
42196
+ await oneAtATime(client, owed, bodies, missing, attempt);
42197
+ break;
42198
+ }
42199
+ throw err;
42200
+ }
42201
+ for (const b of page.bodies) {
42202
+ bodies.set(b.id, bodyOfEntry(b));
42203
+ }
42204
+ for (const id of page.missing) missing.add(id);
42205
+ if (page.bodies.length === 0 && page.missing.length === 0) {
42206
+ throw new NoteBodiesIncompleteError();
42207
+ }
42208
+ owed = owed.filter((id) => !bodies.has(id) && !missing.has(id));
42209
+ }
42210
+ return listed.flatMap((n) => {
42211
+ const body = bodies.get(n.id);
42212
+ return body ? [{ ...n, ...body }] : [];
42213
+ });
42214
+ }
42215
+ async function oneAtATime(client, ids, bodies, missing, attempt) {
42216
+ for (const id of ids) {
42217
+ try {
42218
+ const n = await attempt(() => client.getNote(id));
42219
+ bodies.set(id, bodyOfNote(n));
42220
+ } catch (err) {
42221
+ if (err instanceof SquirrelApiError && err.status === 404) missing.add(id);
42222
+ else throw err;
42223
+ }
42224
+ }
42225
+ }
42226
+ var NOTE_BODIES_BATCH, NOTE_BODIES_RETRY_DELAYS_MS, NoteBodiesIncompleteError, sleep;
42227
+ var init_note_bodies = __esm({
42228
+ "src/note-bodies.ts"() {
42229
+ "use strict";
42230
+ init_api_error();
42231
+ init_note_content();
42232
+ NOTE_BODIES_BATCH = 500;
42233
+ NOTE_BODIES_RETRY_DELAYS_MS = [250, 1e3];
42234
+ NoteBodiesIncompleteError = class extends Error {
42235
+ constructor() {
42236
+ super("not every note body could be read");
42237
+ this.name = "NoteBodiesIncompleteError";
42238
+ }
42239
+ };
42240
+ sleep = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
42241
+ }
42242
+ });
42243
+
41690
42244
  // src/server.ts
41691
42245
  var server_exports = {};
41692
42246
  __export(server_exports, {
@@ -41699,6 +42253,7 @@ __export(server_exports, {
41699
42253
  inferMimeType: () => inferMimeType
41700
42254
  });
41701
42255
  import { basename as basename2, extname, resolve as resolve2 } from "node:path";
42256
+ import { randomUUID as randomUUID3 } from "node:crypto";
41702
42257
  async function buildContext(creds, onUnauthorized) {
41703
42258
  const client = new SquirrelApiClient(SQUIRREL_API_BASE_URL, creds.apiKey, { onUnauthorized });
41704
42259
  const { salt, keyCheck, wrappedDek, dekIv } = await client.getEncryption();
@@ -41733,7 +42288,7 @@ function decryptNoteTitle(note, key) {
41733
42288
  }
41734
42289
  function decryptNote(note, key) {
41735
42290
  const title = decrypt(note.encryptedTitle, note.titleIv, key);
41736
- const content = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
42291
+ const content = readNoteContent(note, key).text;
41737
42292
  const tagIds = note.tags?.map((t) => t.id) ?? [];
41738
42293
  return { ...note, title, content, tagIds };
41739
42294
  }
@@ -41757,6 +42312,29 @@ function inferMimeType(filePath) {
41757
42312
  function refusalResult(r) {
41758
42313
  return { content: [{ type: "text", text: refusalJson(r) }], isError: true };
41759
42314
  }
42315
+ function bodyTooLong(text, error62 = "too-long") {
42316
+ const bytes = utf8Bytes(text);
42317
+ return bytes > NOTE_BODY_MAX_BYTES ? { kind: "refused", error: error62, details: { bytes, limit: NOTE_BODY_MAX_BYTES } } : null;
42318
+ }
42319
+ function titleTooLong(title) {
42320
+ const bytes = utf8Bytes(title);
42321
+ return bytes > NOTE_TITLE_MAX_BYTES ? { kind: "refused", error: "title-too-long", details: { bytes, limit: NOTE_TITLE_MAX_BYTES } } : null;
42322
+ }
42323
+ function refuseUnreadableBodies(server) {
42324
+ const register = server.tool.bind(server);
42325
+ server.tool = (...args) => {
42326
+ const handler = args[args.length - 1];
42327
+ args[args.length - 1] = async (...a) => {
42328
+ try {
42329
+ return await handler(...a);
42330
+ } catch (err) {
42331
+ if (err instanceof NoteBodyUnreadableError) return refusalResult({ kind: "refused", error: "unreadable" });
42332
+ throw err;
42333
+ }
42334
+ };
42335
+ return register(...args);
42336
+ };
42337
+ }
41760
42338
  function jsonResult(value) {
41761
42339
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
41762
42340
  }
@@ -41768,6 +42346,7 @@ function createMcpServer(creds, opts = {}) {
41768
42346
  const context = createContextProvider(
41769
42347
  (onUnauthorized) => buildContext(creds, onUnauthorized)
41770
42348
  );
42349
+ refuseUnreadableBodies(server);
41771
42350
  server.prompt(
41772
42351
  "markdown_capabilities",
41773
42352
  "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.",
@@ -41865,13 +42444,18 @@ function createMcpServer(creds, opts = {}) {
41865
42444
  collectionId: external_exports.string().optional().describe("Collection ID to place the note in. Omit to create in scratchpad.")
41866
42445
  },
41867
42446
  async ({ title, content, collectionId }) => {
42447
+ const tooLong = titleTooLong(title) ?? (content !== void 0 ? newContentTooLong(content) : null);
42448
+ if (tooLong) return refusalResult(tooLong);
41868
42449
  const { client, key } = await context.get();
41869
42450
  const encTitle = encrypt(title, key);
41870
- const encContent = content !== void 0 ? encrypt(content, key) : null;
42451
+ const chunked = content !== void 0 && MCP_CONVERTS_TO_CHUNKS && utf8Bytes(content) > NOTE_CHUNKING_THRESHOLD_BYTES;
42452
+ const newId = randomUUID3();
42453
+ const encContent = content !== void 0 && !chunked ? encrypt(content, key) : null;
41871
42454
  const note = await client.createNote({
42455
+ ...chunked ? { id: newId, body: buildChunkedCommit(key, newId, content).commit } : {},
41872
42456
  encryptedTitle: encTitle.ciphertext,
41873
42457
  titleIv: encTitle.iv,
41874
- ...encContent ? { encryptedContent: encContent.ciphertext, contentIv: encContent.iv } : {},
42458
+ ...encContent ? inlineContentFields(encContent) : {},
41875
42459
  collectionId: collectionId ?? null
41876
42460
  });
41877
42461
  return {
@@ -41893,6 +42477,8 @@ function createMcpServer(creds, opts = {}) {
41893
42477
  content: external_exports.string().optional().describe("New content in Markdown (replaces existing content)")
41894
42478
  },
41895
42479
  async ({ id, title, content }) => {
42480
+ const titleRefusal = title !== void 0 ? titleTooLong(title) : null;
42481
+ if (titleRefusal) return refusalResult(titleRefusal);
41896
42482
  const { client, key } = await context.get();
41897
42483
  const dto = {};
41898
42484
  if (title !== void 0) {
@@ -41900,15 +42486,29 @@ function createMcpServer(creds, opts = {}) {
41900
42486
  dto.encryptedTitle = enc.ciphertext;
41901
42487
  dto.titleIv = enc.iv;
41902
42488
  }
41903
- if (content !== void 0) {
42489
+ const converts = content !== void 0 && MCP_CONVERTS_TO_CHUNKS && utf8Bytes(content) > NOTE_CHUNKING_THRESHOLD_BYTES;
42490
+ if (content !== void 0 && !bodyTooLong(content) && !converts) {
41904
42491
  const enc = encrypt(content, key);
41905
- dto.encryptedContent = enc.ciphertext;
41906
- dto.contentIv = enc.iv;
42492
+ try {
42493
+ const note = await client.updateNote(id, { ...dto, ...inlineContentFields(enc) });
42494
+ return { content: [{ type: "text", text: JSON.stringify({ id: note.id, updated: true }, null, 2) }] };
42495
+ } catch (err) {
42496
+ if (!(err instanceof SquirrelApiError && err.status === 409 && err.responseBody.includes("NOTE_BODY_CHUNKED"))) throw err;
42497
+ }
41907
42498
  }
41908
- const note = await client.updateNote(id, dto);
41909
- return {
41910
- content: [{ type: "text", text: JSON.stringify({ id: note.id, updated: true }, null, 2) }]
41911
- };
42499
+ if (content === void 0) {
42500
+ const note = await client.updateNote(id, dto);
42501
+ return { content: [{ type: "text", text: JSON.stringify({ id: note.id, updated: true }, null, 2) }] };
42502
+ }
42503
+ const current = readNoteContent(await client.getNote(id), key);
42504
+ if (!current.chunked) {
42505
+ const tooLong = bodyTooLong(content) ?? newContentTooLong(content);
42506
+ if (tooLong) return refusalResult(tooLong);
42507
+ }
42508
+ if (title !== void 0) await client.updateNote(id, dto);
42509
+ const written = await writeNoteContent(client, key, id, content, current);
42510
+ if (written.kind === "refused") return refusalResult(written);
42511
+ return { content: [{ type: "text", text: JSON.stringify({ id, updated: true }, null, 2) }] };
41912
42512
  }
41913
42513
  );
41914
42514
  const staleCheck = (updatedAt, expected) => expected !== void 0 && expected !== updatedAt ? { kind: "refused", error: "stale", details: { updatedAt } } : null;
@@ -41929,14 +42529,12 @@ function createMcpServer(creds, opts = {}) {
41929
42529
  const note = await client.getNote(id);
41930
42530
  const stale = staleCheck(note.updatedAt, expectedUpdatedAt);
41931
42531
  if (stale) return refusalResult(stale);
41932
- const existingContent = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
42532
+ const current = readNoteContent(note, key);
42533
+ const existingContent = current.text;
41933
42534
  const newContent = existingContent ? `${existingContent}${separator2}${content}` : content;
41934
- const encContent = encrypt(newContent, key);
41935
- const saved = await client.updateNote(id, {
41936
- encryptedContent: encContent.ciphertext,
41937
- contentIv: encContent.iv
41938
- });
41939
- const answer = expectedUpdatedAt === void 0 ? { id, appended: true } : { id, appended: true, updatedAt: saved.updatedAt };
42535
+ const written = await writeNoteContent(client, key, id, newContent, current);
42536
+ if (written.kind === "refused") return refusalResult(written);
42537
+ const answer = expectedUpdatedAt === void 0 ? { id, appended: true } : { id, appended: true, updatedAt: written.updatedAt };
41940
42538
  return {
41941
42539
  content: [{ type: "text", text: JSON.stringify(answer, null, 2) }]
41942
42540
  };
@@ -41945,13 +42543,12 @@ function createMcpServer(creds, opts = {}) {
41945
42543
  const loadNote = async (id) => {
41946
42544
  const { client, key } = await context.get();
41947
42545
  const note = await client.getNote(id);
41948
- const content = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
41949
- return { client, key, note, nt: noteText(content) };
42546
+ const body = readNoteContent(note, key);
42547
+ return { client, key, note, body, nt: noteText(body.text) };
41950
42548
  };
41951
42549
  const writeContent = async (ctx, id, raw) => {
41952
- const enc = encrypt(raw, ctx.key);
41953
- const saved = await ctx.client.updateNote(id, { encryptedContent: enc.ciphertext, contentIv: enc.iv });
41954
- return saved.updatedAt;
42550
+ const written = await writeNoteContent(ctx.client, ctx.key, id, raw, ctx.body);
42551
+ return written.kind === "written" ? written.updatedAt : written;
41955
42552
  };
41956
42553
  const headingSchema = external_exports.string().describe(`A heading's text exactly as get_note_outline lists it (at most ${HEADING_TEXT_MAX} characters)`);
41957
42554
  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.");
@@ -42015,6 +42612,7 @@ function createMcpServer(creds, opts = {}) {
42015
42612
  if (isRefusal(r)) return refusalResult(r);
42016
42613
  if (r.kind === "unchanged") return jsonResult({ id, changed: false, updatedAt: ctx.note.updatedAt });
42017
42614
  const updatedAt = await writeContent(ctx, id, r.raw);
42615
+ if (typeof updatedAt !== "string") return refusalResult(updatedAt);
42018
42616
  return jsonResult({ id, changed: true, startLine: r.startLine, endLine: r.endLine, updatedAt });
42019
42617
  }
42020
42618
  );
@@ -42037,6 +42635,7 @@ function createMcpServer(creds, opts = {}) {
42037
42635
  const r = replaceSection(ctx.nt, h, content);
42038
42636
  if (r.kind === "unchanged") return jsonResult({ id, changed: false, removedSubheadings: r.removedSubheadings, updatedAt: ctx.note.updatedAt });
42039
42637
  const updatedAt = await writeContent(ctx, id, r.raw);
42638
+ if (typeof updatedAt !== "string") return refusalResult(updatedAt);
42040
42639
  return jsonResult({ id, changed: true, startLine: r.startLine, endLine: r.endLine, removedSubheadings: r.removedSubheadings, updatedAt });
42041
42640
  }
42042
42641
  );
@@ -42060,6 +42659,7 @@ function createMcpServer(creds, opts = {}) {
42060
42659
  const r = insertInSection(ctx.nt, h, content, position);
42061
42660
  if (isRefusal(r)) return refusalResult(r);
42062
42661
  const updatedAt = await writeContent(ctx, id, r.raw);
42662
+ if (typeof updatedAt !== "string") return refusalResult(updatedAt);
42063
42663
  return jsonResult({ id, changed: true, startLine: r.startLine, endLine: r.endLine, updatedAt });
42064
42664
  }
42065
42665
  );
@@ -42080,6 +42680,7 @@ function createMcpServer(creds, opts = {}) {
42080
42680
  if (isRefusal(h)) return refusalResult(h);
42081
42681
  const r = deleteSection(ctx.nt, h);
42082
42682
  const updatedAt = await writeContent(ctx, id, r.raw);
42683
+ if (typeof updatedAt !== "string") return refusalResult(updatedAt);
42083
42684
  return jsonResult({ id, changed: true, removedLines: { startLine: r.startLine, endLine: r.endLine }, removedSubheadings: r.removedSubheadings, updatedAt });
42084
42685
  }
42085
42686
  );
@@ -42099,6 +42700,7 @@ function createMcpServer(creds, opts = {}) {
42099
42700
  const r = insertAtLine(ctx.nt, line, content);
42100
42701
  if (isRefusal(r)) return refusalResult(r);
42101
42702
  const updatedAt = await writeContent(ctx, id, r.raw);
42703
+ if (typeof updatedAt !== "string") return refusalResult(updatedAt);
42102
42704
  return jsonResult({ id, changed: true, startLine: r.startLine, endLine: r.endLine, updatedAt });
42103
42705
  }
42104
42706
  );
@@ -42226,7 +42828,15 @@ function createMcpServer(creds, opts = {}) {
42226
42828
  },
42227
42829
  async ({ query, includeContent = false, limit }) => {
42228
42830
  const { client, key } = await context.get();
42229
- const notes = await client.listNotes();
42831
+ let notes;
42832
+ try {
42833
+ notes = await withBodies(client, await client.listNotes(), {
42834
+ ...opts.noteBodiesRetryDelaysMs ? { retryDelaysMs: opts.noteBodiesRetryDelaysMs } : {}
42835
+ });
42836
+ } catch (err) {
42837
+ if (err instanceof NoteBodiesIncompleteError) return refusalResult({ kind: "refused", error: "search-incomplete" });
42838
+ throw err;
42839
+ }
42230
42840
  const fq = foldForSearch(query);
42231
42841
  const matches = notes.map((n) => decryptNote(n, key)).map((n) => ({ n, titleMatch: foldForSearch(n.title).includes(fq) })).filter(({ n, titleMatch }) => titleMatch || foldForSearch(n.content).includes(fq));
42232
42842
  if (includeContent) {
@@ -42579,7 +43189,9 @@ function createMcpServer(creds, opts = {}) {
42579
43189
  const { client, key } = await context.get();
42580
43190
  const note = await client.getNote(noteId);
42581
43191
  const title = decrypt(note.encryptedTitle, note.titleIv, key);
42582
- const content = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
43192
+ const content = readNoteContent(note, key).text;
43193
+ const tooLarge = bodyTooLong(content, "too-large-to-share");
43194
+ if (tooLarge) return refusalResult(tooLarge);
42583
43195
  const shareSalt = generateSalt();
42584
43196
  const shareKey = await deriveKey(sharePassphrase, shareSalt);
42585
43197
  const encTitle = encrypt(title, shareKey);
@@ -42588,8 +43200,7 @@ function createMcpServer(creds, opts = {}) {
42588
43200
  noteId,
42589
43201
  encryptedTitle: encTitle.ciphertext,
42590
43202
  titleIv: encTitle.iv,
42591
- encryptedContent: encContent.ciphertext,
42592
- contentIv: encContent.iv,
43203
+ ...inlineContentFields(encContent),
42593
43204
  salt: shareSalt,
42594
43205
  pbkdf2Iterations: 6e5,
42595
43206
  expiry,
@@ -42642,7 +43253,9 @@ function createMcpServer(creds, opts = {}) {
42642
43253
  const { client, key } = await context.get();
42643
43254
  const note = await client.getNote(noteId);
42644
43255
  const title = decrypt(note.encryptedTitle, note.titleIv, key);
42645
- const content = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
43256
+ const content = readNoteContent(note, key).text;
43257
+ const tooLarge = bodyTooLong(content, "too-large-to-share");
43258
+ if (tooLarge) return refusalResult(tooLarge);
42646
43259
  const shareSalt = generateSalt();
42647
43260
  const shareKey = await deriveKey(sharePassphrase, shareSalt);
42648
43261
  const encTitle = encrypt(title, shareKey);
@@ -42650,8 +43263,7 @@ function createMcpServer(creds, opts = {}) {
42650
43263
  const status = await client.republishShare(shareToken, {
42651
43264
  encryptedTitle: encTitle.ciphertext,
42652
43265
  titleIv: encTitle.iv,
42653
- encryptedContent: encContent.ciphertext,
42654
- contentIv: encContent.iv,
43266
+ ...inlineContentFields(encContent),
42655
43267
  salt: shareSalt,
42656
43268
  pbkdf2Iterations: 6e5
42657
43269
  });
@@ -42887,6 +43499,13 @@ var init_server3 = __esm({
42887
43499
  init_search_fold();
42888
43500
  init_upload_path();
42889
43501
  init_note_text();
43502
+ init_note_limits();
43503
+ init_note_bodies();
43504
+ init_note_content();
43505
+ init_note_chunks();
43506
+ init_note_body();
43507
+ init_note_content();
43508
+ init_note_chunks();
42890
43509
  SQUIRREL_API_BASE_URL = process.env.SQUIRREL_API_BASE_URL;
42891
43510
  if (!SQUIRREL_API_BASE_URL) {
42892
43511
  throw new Error("SQUIRREL_API_BASE_URL environment variable is required");
@@ -42967,11 +43586,11 @@ __export(vector_cache_exports, {
42967
43586
  vectorFilePathForId: () => vectorFilePathForId,
42968
43587
  writeVectorFile: () => writeVectorFile
42969
43588
  });
42970
- import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, hkdfSync, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "node:crypto";
43589
+ import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, hkdfSync as hkdfSync2, randomBytes as randomBytes3, randomUUID as randomUUID4 } from "node:crypto";
42971
43590
  import { chmod, mkdir as mkdir2, readFile, rename, rm, writeFile } from "node:fs/promises";
42972
43591
  import path from "node:path";
42973
43592
  function vectorFileId(dek) {
42974
- return Buffer.from(hkdfSync("sha256", dek, Buffer.alloc(0), FILE_ID_INFO, 8)).toString("hex");
43593
+ return Buffer.from(hkdfSync2("sha256", dek, Buffer.alloc(0), FILE_ID_INFO, 8)).toString("hex");
42975
43594
  }
42976
43595
  function vectorFilePath(cacheDir, dek) {
42977
43596
  return vectorFilePathForId(cacheDir, vectorFileId(dek));
@@ -42988,7 +43607,7 @@ function defaultCacheDir(platform, env, home) {
42988
43607
  return env.XDG_CACHE_HOME || path.join(home, ".cache");
42989
43608
  }
42990
43609
  function deriveFileKey(dek, salt) {
42991
- return Buffer.from(hkdfSync("sha256", dek, salt, KEY_INFO, 32));
43610
+ return Buffer.from(hkdfSync2("sha256", dek, salt, KEY_INFO, 32));
42992
43611
  }
42993
43612
  function headerBytes(model, recipe = EMBEDDING_TEXT_RECIPE) {
42994
43613
  return Buffer.from(
@@ -43041,10 +43660,10 @@ function sealVectorFile(entries, model, dek) {
43041
43660
  MAGIC.copy(prefix, 0);
43042
43661
  prefix.writeUInt8(VECTOR_FILE_FORMAT, MAGIC.length);
43043
43662
  prefix.writeUInt16BE(header.length, MAGIC.length + 1);
43044
- const salt = randomBytes2(SALT_LENGTH);
43045
- const iv = randomBytes2(IV_LENGTH2);
43663
+ const salt = randomBytes3(SALT_LENGTH);
43664
+ const iv = randomBytes3(IV_LENGTH2);
43046
43665
  const aad = Buffer.concat([prefix, header, salt, iv]);
43047
- const cipher = createCipheriv2("aes-256-gcm", deriveFileKey(dek, salt), iv);
43666
+ const cipher = createCipheriv3("aes-256-gcm", deriveFileKey(dek, salt), iv);
43048
43667
  cipher.setAAD(aad);
43049
43668
  const sealed = Buffer.concat([cipher.update(encodeBody(entries, model.dimensions)), cipher.final(), cipher.getAuthTag()]);
43050
43669
  return Buffer.concat([aad, sealed]);
@@ -43062,7 +43681,7 @@ function openVectorFile(file2, model, dek) {
43062
43681
  if (!file2.subarray(fixed, fixed + headerLength).equals(headerBytes(model))) return null;
43063
43682
  const salt = file2.subarray(fixed + headerLength, fixed + headerLength + SALT_LENGTH);
43064
43683
  const iv = file2.subarray(aadEnd - IV_LENGTH2, aadEnd);
43065
- const decipher = createDecipheriv2("aes-256-gcm", deriveFileKey(dek, salt), iv);
43684
+ const decipher = createDecipheriv3("aes-256-gcm", deriveFileKey(dek, salt), iv);
43066
43685
  decipher.setAAD(file2.subarray(0, aadEnd));
43067
43686
  decipher.setAuthTag(file2.subarray(file2.length - TAG_LENGTH));
43068
43687
  const body = Buffer.concat([decipher.update(file2.subarray(aadEnd, file2.length - TAG_LENGTH)), decipher.final()]);
@@ -43084,7 +43703,7 @@ async function writeVectorFile(filePath, entries, model, dek) {
43084
43703
  const dir = path.dirname(filePath);
43085
43704
  await mkdir2(dir, { recursive: true, mode: 448 });
43086
43705
  await chmod(dir, 448);
43087
- const tmp = path.join(dir, `.${path.basename(filePath)}.${randomUUID2()}.tmp`);
43706
+ const tmp = path.join(dir, `.${path.basename(filePath)}.${randomUUID4()}.tmp`);
43088
43707
  try {
43089
43708
  await writeFile(tmp, sealVectorFile(entries, model, dek), { mode: 384, flag: "wx" });
43090
43709
  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.377",
3
+ "version": "2.7.1-test.379",
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": {