@squirrelnotes.app/mcp 2.7.1 → 2.8.0-test.397
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/README.md +2 -2
- package/dist/stdio-handler.js +735 -51
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -90,9 +90,9 @@ For a note over about 8,000 characters (about 2,000 tokens), an agent should not
|
|
|
90
90
|
|
|
91
91
|
| Tool | Description |
|
|
92
92
|
|------|-------------|
|
|
93
|
-
| `share_note` | Publishes a note as a public link protected by a share passphrase, with optional `expiry` and `allowDownload` (default off). The note is decrypted here and re-encrypted under a key derived from the share passphrase, so the server never sees plaintext. Returns the share URL and token. The share passphrase is a tool argument, so it passes through your agent and its model provider; send it to recipients separately from the link. |
|
|
93
|
+
| `share_note` | Publishes a note as a public link protected by a share passphrase of at least 8 characters, with optional `expiry` and `allowDownload` (default off). The note is decrypted here and re-encrypted under a key derived from the share passphrase, so the server never sees plaintext. Returns the share URL and token. The share passphrase is a tool argument, so it passes through your agent and its model provider; send it to recipients separately from the link. |
|
|
94
94
|
| `get_share_status` | Returns a note's share URL, view count, expiry and settings, or `null` if it is not shared. |
|
|
95
|
-
| `republish_share` | Re-encrypts an existing share with the note's latest content. Needs the share passphrase (the same one or a new one). |
|
|
95
|
+
| `republish_share` | Re-encrypts an existing share with the note's latest content. Needs the share passphrase (the same one or a new one, at least 8 characters). |
|
|
96
96
|
| `update_share_settings` | Changes a share's `expiry` and/or `allowDownload` without changing its content. |
|
|
97
97
|
| `revoke_share` | Revokes a share link permanently; it stops working at once. The note is not affected. |
|
|
98
98
|
|
package/dist/stdio-handler.js
CHANGED
|
@@ -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,25 @@ 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 since it was read, so nothing was written. Read it again and retry.",
|
|
41681
|
+
// ADR-0523 §7, §8: the account's storage (notes, files and the Trash
|
|
41682
|
+
// until it is emptied) is full. The server's answer carries no size.
|
|
41683
|
+
"storage-full": "The account's storage is full, so nothing was written. Ask the user to free space: delete notes or files, or empty the Trash.",
|
|
41684
|
+
// #668: update_note writes long content first, then the title; the server
|
|
41685
|
+
// refused only the title. `status` is the HTTP status, `reason` the
|
|
41686
|
+
// refusal it maps to when it is one of the above (ADR-0460: no server text).
|
|
41687
|
+
"title-not-saved": "The content was saved, but the title was not: the server refused it (status, and reason when it is a known refusal such as storage-full). Fix the cause, then retry update_note with the title alone."
|
|
41656
41688
|
};
|
|
41657
41689
|
refuse2 = (error62, details) => details === void 0 ? { kind: "refused", error: error62 } : { kind: "refused", error: error62, details };
|
|
41658
41690
|
isRefusal = (x) => "kind" in x && x.kind === "refused";
|
|
@@ -41687,6 +41719,591 @@ var init_note_text = __esm({
|
|
|
41687
41719
|
}
|
|
41688
41720
|
});
|
|
41689
41721
|
|
|
41722
|
+
// src/note-limits.ts
|
|
41723
|
+
function utf8Bytes(text) {
|
|
41724
|
+
return Buffer.byteLength(text, "utf8");
|
|
41725
|
+
}
|
|
41726
|
+
var NOTE_BODY_MAX_BYTES, NOTE_TITLE_MAX_BYTES, SHARE_PASSPHRASE_MIN_LENGTH, SHARE_PBKDF2_ITERATIONS;
|
|
41727
|
+
var init_note_limits = __esm({
|
|
41728
|
+
"src/note-limits.ts"() {
|
|
41729
|
+
"use strict";
|
|
41730
|
+
NOTE_BODY_MAX_BYTES = 75e4;
|
|
41731
|
+
NOTE_TITLE_MAX_BYTES = 12e3;
|
|
41732
|
+
SHARE_PASSPHRASE_MIN_LENGTH = 8;
|
|
41733
|
+
SHARE_PBKDF2_ITERATIONS = 6e5;
|
|
41734
|
+
}
|
|
41735
|
+
});
|
|
41736
|
+
|
|
41737
|
+
// src/note-chunks.ts
|
|
41738
|
+
function chunkAadText(noteId, chunkId, versionId) {
|
|
41739
|
+
return `sqn-note-chunk-v1:${noteId}:${chunkId}:${versionId}`;
|
|
41740
|
+
}
|
|
41741
|
+
function manifestAadText(noteId, revision) {
|
|
41742
|
+
return `sqn-note-manifest-v1:${noteId}:${revision}`;
|
|
41743
|
+
}
|
|
41744
|
+
function isUuidV4(value) {
|
|
41745
|
+
return typeof value === "string" && UUID_V4.test(value);
|
|
41746
|
+
}
|
|
41747
|
+
function isCount(value, max) {
|
|
41748
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= max;
|
|
41749
|
+
}
|
|
41750
|
+
function checkManifest(value, noteId, revision) {
|
|
41751
|
+
const fail2 = () => {
|
|
41752
|
+
throw new NoteBodyUnreadableError();
|
|
41753
|
+
};
|
|
41754
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) fail2();
|
|
41755
|
+
const m = value;
|
|
41756
|
+
if (Object.keys(m).sort().join(",") !== "chunker,chunks,noteId,revision,totalBytes,v") fail2();
|
|
41757
|
+
if (m.v !== 1 || m.chunker !== NOTE_CHUNKER) fail2();
|
|
41758
|
+
if (m.noteId !== noteId || m.revision !== revision) fail2();
|
|
41759
|
+
if (!isCount(m.totalBytes, NOTE_BODY_MAX_BYTES2)) fail2();
|
|
41760
|
+
if (!Array.isArray(m.chunks) || m.chunks.length > NOTE_MANIFEST_MAX_CHUNKS) fail2();
|
|
41761
|
+
const chunks = m.chunks;
|
|
41762
|
+
if (chunks.length === 0 && m.totalBytes !== 0) fail2();
|
|
41763
|
+
const ids = /* @__PURE__ */ new Set();
|
|
41764
|
+
let sum = 0;
|
|
41765
|
+
const out = [];
|
|
41766
|
+
for (const raw of chunks) {
|
|
41767
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) fail2();
|
|
41768
|
+
const c = raw;
|
|
41769
|
+
if (Object.keys(c).sort().join(",") !== "id,len,lines,sha256,ver") fail2();
|
|
41770
|
+
if (!isUuidV4(c.id) || !isUuidV4(c.ver)) fail2();
|
|
41771
|
+
if (!isCount(c.len, CHUNK_MAX_BYTES) || c.len === 0) fail2();
|
|
41772
|
+
if (!isCount(c.lines, CHUNK_MAX_BYTES)) fail2();
|
|
41773
|
+
if (typeof c.sha256 !== "string" || !HEX_64.test(c.sha256)) fail2();
|
|
41774
|
+
const id = c.id;
|
|
41775
|
+
if (ids.has(id)) fail2();
|
|
41776
|
+
ids.add(id);
|
|
41777
|
+
sum += c.len;
|
|
41778
|
+
out.push({ id, ver: c.ver, len: c.len, lines: c.lines, sha256: c.sha256 });
|
|
41779
|
+
}
|
|
41780
|
+
if (sum !== m.totalBytes) fail2();
|
|
41781
|
+
return { v: 1, noteId, revision, chunker: NOTE_CHUNKER, totalBytes: sum, chunks: out };
|
|
41782
|
+
}
|
|
41783
|
+
function refsOf(manifest) {
|
|
41784
|
+
return manifest.chunks.map((c) => `${c.id}:${c.ver}`).sort();
|
|
41785
|
+
}
|
|
41786
|
+
function countLines(bytes, start = 0, end = bytes.length) {
|
|
41787
|
+
let n = 0;
|
|
41788
|
+
for (let i = start; i < end; i++) if (bytes[i] === NEWLINE) n += 1;
|
|
41789
|
+
return n;
|
|
41790
|
+
}
|
|
41791
|
+
function paddedLength(len) {
|
|
41792
|
+
return Math.max(1, Math.ceil(len / CHUNK_PAD_BYTES)) * CHUNK_PAD_BYTES;
|
|
41793
|
+
}
|
|
41794
|
+
function padChunk(bytes) {
|
|
41795
|
+
const out = new Uint8Array(paddedLength(bytes.length));
|
|
41796
|
+
out.set(bytes);
|
|
41797
|
+
return out;
|
|
41798
|
+
}
|
|
41799
|
+
function unpadChunk(padded, len) {
|
|
41800
|
+
if (padded.length !== paddedLength(len)) throw new NoteBodyUnreadableError();
|
|
41801
|
+
for (let i = len; i < padded.length; i++) {
|
|
41802
|
+
if (padded[i] !== 0) throw new NoteBodyUnreadableError();
|
|
41803
|
+
}
|
|
41804
|
+
return padded.subarray(0, len);
|
|
41805
|
+
}
|
|
41806
|
+
function gearTableFrom(bytes) {
|
|
41807
|
+
if (bytes.length !== GEAR_TABLE_BYTES) throw new Error("Gear table must be 1024 bytes");
|
|
41808
|
+
const table = new Uint32Array(256);
|
|
41809
|
+
for (let i = 0; i < 256; i++) {
|
|
41810
|
+
table[i] = (bytes[4 * i] << 24 | bytes[4 * i + 1] << 16 | bytes[4 * i + 2] << 8 | bytes[4 * i + 3]) >>> 0;
|
|
41811
|
+
}
|
|
41812
|
+
return table;
|
|
41813
|
+
}
|
|
41814
|
+
function nextCut(bytes, start, to, gear) {
|
|
41815
|
+
if (to - start <= CHUNK_MIN_BYTES) return to;
|
|
41816
|
+
const limit = Math.min(to, start + CHUNK_MAX_BYTES);
|
|
41817
|
+
let hash2 = 0;
|
|
41818
|
+
let armed = false;
|
|
41819
|
+
let lastLineStart = -1;
|
|
41820
|
+
for (let i = start; i < limit; i++) {
|
|
41821
|
+
const b = bytes[i];
|
|
41822
|
+
hash2 = (hash2 << 1) + gear[b] >>> 0;
|
|
41823
|
+
if (b === NEWLINE && i + 1 - start >= CHUNK_MIN_BYTES) {
|
|
41824
|
+
if (armed) return i + 1;
|
|
41825
|
+
lastLineStart = i + 1;
|
|
41826
|
+
}
|
|
41827
|
+
if (!armed && i + 1 - start >= CHUNK_MIN_BYTES && (hash2 & GEAR_ARM_MASK) === 0) armed = true;
|
|
41828
|
+
}
|
|
41829
|
+
if (limit === to) return to;
|
|
41830
|
+
if (lastLineStart > 0) return lastLineStart;
|
|
41831
|
+
let cut = limit;
|
|
41832
|
+
while (cut > start + 1 && (bytes[cut] & 192) === 128) cut -= 1;
|
|
41833
|
+
return cut;
|
|
41834
|
+
}
|
|
41835
|
+
function cdcSplit(bytes, from, to, gear) {
|
|
41836
|
+
const ends = [];
|
|
41837
|
+
let start = from;
|
|
41838
|
+
while (start < to) {
|
|
41839
|
+
const end = nextCut(bytes, start, to, gear);
|
|
41840
|
+
ends.push(end);
|
|
41841
|
+
start = end;
|
|
41842
|
+
}
|
|
41843
|
+
return ends;
|
|
41844
|
+
}
|
|
41845
|
+
function commonPrefix(a, b) {
|
|
41846
|
+
const n = Math.min(a.length, b.length);
|
|
41847
|
+
let i = 0;
|
|
41848
|
+
while (i < n && a[i] === b[i]) i += 1;
|
|
41849
|
+
return i;
|
|
41850
|
+
}
|
|
41851
|
+
function commonSuffix(a, b, max) {
|
|
41852
|
+
let i = 0;
|
|
41853
|
+
while (i < max && a[a.length - 1 - i] === b[b.length - 1 - i]) i += 1;
|
|
41854
|
+
return i;
|
|
41855
|
+
}
|
|
41856
|
+
function sameBytes(a, aStart, b, bStart, len) {
|
|
41857
|
+
for (let i = 0; i < len; i++) if (a[aStart + i] !== b[bStart + i]) return false;
|
|
41858
|
+
return true;
|
|
41859
|
+
}
|
|
41860
|
+
function planChunks(bytes, gear, previous) {
|
|
41861
|
+
if (bytes.length === 0) return [];
|
|
41862
|
+
const old = previous?.manifest.chunks ?? [];
|
|
41863
|
+
if (!previous || old.length === 0) {
|
|
41864
|
+
let start = 0;
|
|
41865
|
+
return cdcSplit(bytes, 0, bytes.length, gear).map((end) => {
|
|
41866
|
+
const chunk = { start, end, keepId: null, reuse: null };
|
|
41867
|
+
start = end;
|
|
41868
|
+
return chunk;
|
|
41869
|
+
});
|
|
41870
|
+
}
|
|
41871
|
+
const oldBytes = previous.bytes;
|
|
41872
|
+
const prefix = commonPrefix(oldBytes, bytes);
|
|
41873
|
+
const suffix = commonSuffix(oldBytes, bytes, Math.min(oldBytes.length, bytes.length) - prefix);
|
|
41874
|
+
const delta = bytes.length - oldBytes.length;
|
|
41875
|
+
const map2 = (b) => {
|
|
41876
|
+
if (b <= prefix) return b;
|
|
41877
|
+
if (b >= oldBytes.length - suffix) return b + delta;
|
|
41878
|
+
return -1;
|
|
41879
|
+
};
|
|
41880
|
+
const oldStarts = [];
|
|
41881
|
+
let offset = 0;
|
|
41882
|
+
for (const c of old) {
|
|
41883
|
+
oldStarts.push(offset);
|
|
41884
|
+
offset += c.len;
|
|
41885
|
+
}
|
|
41886
|
+
const kept = [{ pos: 0, index: 0 }];
|
|
41887
|
+
for (let i = 1; i < old.length; i++) {
|
|
41888
|
+
const pos = map2(oldStarts[i]);
|
|
41889
|
+
if (pos <= kept[kept.length - 1].pos || pos >= bytes.length) continue;
|
|
41890
|
+
if (bytes[pos - 1] !== NEWLINE) continue;
|
|
41891
|
+
kept.push({ pos, index: i });
|
|
41892
|
+
}
|
|
41893
|
+
const spans = [];
|
|
41894
|
+
for (let k = 0; k < kept.length; k++) {
|
|
41895
|
+
const here = kept[k];
|
|
41896
|
+
const next = k + 1 < kept.length ? kept[k + 1].pos : bytes.length;
|
|
41897
|
+
if (spans.length > 0 && next - here.pos < CHUNK_MIN_BYTES && k + 1 < kept.length) continue;
|
|
41898
|
+
spans.push(here);
|
|
41899
|
+
}
|
|
41900
|
+
if (spans.length > 1 && spans[1].pos - spans[0].pos < CHUNK_MIN_BYTES) spans.splice(1, 1);
|
|
41901
|
+
const planned = [];
|
|
41902
|
+
for (let s = 0; s < spans.length; s++) {
|
|
41903
|
+
const span2 = spans[s];
|
|
41904
|
+
const from = span2.pos;
|
|
41905
|
+
const to = s + 1 < spans.length ? spans[s + 1].pos : bytes.length;
|
|
41906
|
+
const ends = to - from > CHUNK_MAX_BYTES ? cdcSplit(bytes, from, to, gear) : [to];
|
|
41907
|
+
let start = from;
|
|
41908
|
+
for (const [n, end] of ends.entries()) {
|
|
41909
|
+
const prev = old[span2.index];
|
|
41910
|
+
const keepId = n === 0 ? prev.id : null;
|
|
41911
|
+
let reuse = null;
|
|
41912
|
+
if (n === 0) {
|
|
41913
|
+
const prevStart = oldStarts[span2.index];
|
|
41914
|
+
if (prev.len === end - start && sameBytes(oldBytes, prevStart, bytes, start, prev.len)) reuse = prev;
|
|
41915
|
+
}
|
|
41916
|
+
planned.push({ start, end, keepId, reuse });
|
|
41917
|
+
start = end;
|
|
41918
|
+
}
|
|
41919
|
+
}
|
|
41920
|
+
return planned;
|
|
41921
|
+
}
|
|
41922
|
+
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, CHUNK_CIPHERTEXT_OVERHEAD, NOTE_CHUNKER_INFO, GEAR_TABLE_BYTES, GEAR_ARM_MASK, NEWLINE, NoteBodyUnreadableError, UUID_V4, HEX_64;
|
|
41923
|
+
var init_note_chunks = __esm({
|
|
41924
|
+
"src/note-chunks.ts"() {
|
|
41925
|
+
"use strict";
|
|
41926
|
+
NOTE_CHUNKER = "cdc-v1";
|
|
41927
|
+
NOTE_BODY_FORMAT_CHUNKS = "chunks-v1";
|
|
41928
|
+
CHUNK_MIN_BYTES = 16 * 1024;
|
|
41929
|
+
CHUNK_MAX_BYTES = 128 * 1024;
|
|
41930
|
+
CHUNK_PAD_BYTES = 1024;
|
|
41931
|
+
NOTE_CHUNKING_THRESHOLD_BYTES = 256 * 1024;
|
|
41932
|
+
NOTE_BODY_MAX_BYTES2 = 3 * 1024 * 1024;
|
|
41933
|
+
NOTE_MANIFEST_MAX_CHUNKS = Math.floor(NOTE_BODY_MAX_BYTES2 / CHUNK_MIN_BYTES) + Math.floor(NOTE_BODY_MAX_BYTES2 / (CHUNK_MAX_BYTES + 1)) + 1;
|
|
41934
|
+
CHUNK_CIPHERTEXT_OVERHEAD = CHUNK_PAD_BYTES - 1 + 16 + 2;
|
|
41935
|
+
NOTE_CHUNKER_INFO = "sqn-note-chunker-v1";
|
|
41936
|
+
GEAR_TABLE_BYTES = 1024;
|
|
41937
|
+
GEAR_ARM_MASK = 4294705152;
|
|
41938
|
+
NEWLINE = 10;
|
|
41939
|
+
NoteBodyUnreadableError = class extends Error {
|
|
41940
|
+
constructor() {
|
|
41941
|
+
super("This note could not be read in full");
|
|
41942
|
+
this.name = "NoteBodyUnreadableError";
|
|
41943
|
+
}
|
|
41944
|
+
};
|
|
41945
|
+
UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
41946
|
+
HEX_64 = /^[0-9a-f]{64}$/;
|
|
41947
|
+
}
|
|
41948
|
+
});
|
|
41949
|
+
|
|
41950
|
+
// src/note-body.ts
|
|
41951
|
+
import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, createHash as createHash2, hkdfSync, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "node:crypto";
|
|
41952
|
+
function gcmEncrypt(key, iv, plaintext, aad) {
|
|
41953
|
+
const cipher = createCipheriv2("aes-256-gcm", key, iv, { authTagLength: TAG_BYTES });
|
|
41954
|
+
cipher.setAAD(Buffer.from(aad, "utf8"));
|
|
41955
|
+
const body = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
|
41956
|
+
return Buffer.concat([body, cipher.getAuthTag()]).toString("base64");
|
|
41957
|
+
}
|
|
41958
|
+
function gcmDecrypt(key, ivBase64, ciphertextBase64, aad) {
|
|
41959
|
+
const iv = Buffer.from(ivBase64, "base64");
|
|
41960
|
+
const combined = Buffer.from(ciphertextBase64, "base64");
|
|
41961
|
+
if (iv.length !== IV_BYTES || combined.length < TAG_BYTES) throw new NoteBodyUnreadableError();
|
|
41962
|
+
try {
|
|
41963
|
+
const decipher = createDecipheriv2("aes-256-gcm", key, iv, { authTagLength: TAG_BYTES });
|
|
41964
|
+
decipher.setAAD(Buffer.from(aad, "utf8"));
|
|
41965
|
+
decipher.setAuthTag(combined.subarray(combined.length - TAG_BYTES));
|
|
41966
|
+
return Buffer.concat([decipher.update(combined.subarray(0, combined.length - TAG_BYTES)), decipher.final()]);
|
|
41967
|
+
} catch {
|
|
41968
|
+
throw new NoteBodyUnreadableError();
|
|
41969
|
+
}
|
|
41970
|
+
}
|
|
41971
|
+
function chunkDigest(ivBase64, ciphertextBase64) {
|
|
41972
|
+
return createHash2("sha256").update(Buffer.from(ivBase64, "base64")).update(Buffer.from(ciphertextBase64, "base64")).digest("hex");
|
|
41973
|
+
}
|
|
41974
|
+
function noteChunkerGear(dek) {
|
|
41975
|
+
const ikm = Buffer.from(gcmEncrypt(dek, Buffer.alloc(IV_BYTES), Buffer.from(NOTE_CHUNKER_INFO, "utf8"), ""), "base64");
|
|
41976
|
+
const okm = hkdfSync("sha256", ikm, Buffer.alloc(0), Buffer.from(NOTE_CHUNKER_INFO, "utf8"), GEAR_TABLE_BYTES);
|
|
41977
|
+
return gearTableFrom(new Uint8Array(okm));
|
|
41978
|
+
}
|
|
41979
|
+
function encryptNoteChunk(dek, noteId, chunkId, bytes, fixed = {}) {
|
|
41980
|
+
const versionId = fixed.versionId ?? randomUUID2();
|
|
41981
|
+
const iv = fixed.iv ?? randomBytes2(IV_BYTES);
|
|
41982
|
+
const ciphertext = gcmEncrypt(dek, iv, padChunk(bytes), chunkAadText(noteId, chunkId, versionId));
|
|
41983
|
+
const ivBase64 = iv.toString("base64");
|
|
41984
|
+
return {
|
|
41985
|
+
chunk: { chunkId, versionId, ciphertext, iv: ivBase64 },
|
|
41986
|
+
entry: {
|
|
41987
|
+
id: chunkId,
|
|
41988
|
+
ver: versionId,
|
|
41989
|
+
len: bytes.length,
|
|
41990
|
+
lines: countLines(bytes),
|
|
41991
|
+
sha256: chunkDigest(ivBase64, ciphertext)
|
|
41992
|
+
}
|
|
41993
|
+
};
|
|
41994
|
+
}
|
|
41995
|
+
function decryptNoteChunk(dek, noteId, chunk, expected) {
|
|
41996
|
+
if (chunk.chunkId !== expected.id || chunk.versionId !== expected.ver) throw new NoteBodyUnreadableError();
|
|
41997
|
+
if (chunkDigest(chunk.iv, chunk.ciphertext) !== expected.sha256) throw new NoteBodyUnreadableError();
|
|
41998
|
+
const padded = gcmDecrypt(dek, chunk.iv, chunk.ciphertext, chunkAadText(noteId, chunk.chunkId, chunk.versionId));
|
|
41999
|
+
return unpadChunk(new Uint8Array(padded), expected.len);
|
|
42000
|
+
}
|
|
42001
|
+
function encryptNoteManifest(dek, manifest, fixed = {}) {
|
|
42002
|
+
checkManifest(manifest, manifest.noteId, manifest.revision);
|
|
42003
|
+
const iv = fixed.iv ?? randomBytes2(IV_BYTES);
|
|
42004
|
+
const plaintext = Buffer.from(JSON.stringify(manifest), "utf8");
|
|
42005
|
+
return {
|
|
42006
|
+
ciphertext: gcmEncrypt(dek, iv, plaintext, manifestAadText(manifest.noteId, manifest.revision)),
|
|
42007
|
+
iv: iv.toString("base64")
|
|
42008
|
+
};
|
|
42009
|
+
}
|
|
42010
|
+
function decryptNoteManifest(dek, noteId, revision, ciphertext, iv) {
|
|
42011
|
+
const plaintext = gcmDecrypt(dek, iv, ciphertext, manifestAadText(noteId, revision));
|
|
42012
|
+
let parsed;
|
|
42013
|
+
try {
|
|
42014
|
+
parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(plaintext));
|
|
42015
|
+
} catch {
|
|
42016
|
+
throw new NoteBodyUnreadableError();
|
|
42017
|
+
}
|
|
42018
|
+
return checkManifest(parsed, noteId, revision);
|
|
42019
|
+
}
|
|
42020
|
+
function readChunkedBody(dek, noteId, body) {
|
|
42021
|
+
const manifest = decryptNoteManifest(dek, noteId, body.revision, body.encryptedManifest, body.manifestIv);
|
|
42022
|
+
const served = new Map(body.chunks.map((c) => [`${c.chunkId}:${c.versionId}`, c]));
|
|
42023
|
+
const bytes = new Uint8Array(manifest.totalBytes);
|
|
42024
|
+
const parts = [];
|
|
42025
|
+
let offset = 0;
|
|
42026
|
+
for (const entry2 of manifest.chunks) {
|
|
42027
|
+
const chunk = served.get(`${entry2.id}:${entry2.ver}`);
|
|
42028
|
+
if (!chunk) throw new NoteBodyUnreadableError();
|
|
42029
|
+
const part = decryptNoteChunk(dek, noteId, chunk, entry2);
|
|
42030
|
+
try {
|
|
42031
|
+
parts.push(new TextDecoder("utf-8", { fatal: true }).decode(part));
|
|
42032
|
+
} catch {
|
|
42033
|
+
throw new NoteBodyUnreadableError();
|
|
42034
|
+
}
|
|
42035
|
+
bytes.set(part, offset);
|
|
42036
|
+
offset += entry2.len;
|
|
42037
|
+
}
|
|
42038
|
+
return { text: parts.join(""), revision: body.revision, manifest, bytes };
|
|
42039
|
+
}
|
|
42040
|
+
function buildChunkedCommit(dek, noteId, text, base) {
|
|
42041
|
+
const bytes = new TextEncoder().encode(text);
|
|
42042
|
+
if (bytes.length > NOTE_BODY_MAX_BYTES2) throw new NoteBodyTooLargeError(bytes.length);
|
|
42043
|
+
const plan = planChunks(bytes, noteChunkerGear(dek), base ? { bytes: base.bytes, manifest: base.manifest } : void 0);
|
|
42044
|
+
const entries = [];
|
|
42045
|
+
const fresh = [];
|
|
42046
|
+
for (const p of plan) {
|
|
42047
|
+
if (p.reuse) {
|
|
42048
|
+
entries.push(p.reuse);
|
|
42049
|
+
continue;
|
|
42050
|
+
}
|
|
42051
|
+
const { chunk, entry: entry2 } = encryptNoteChunk(dek, noteId, p.keepId ?? randomUUID2(), bytes.subarray(p.start, p.end));
|
|
42052
|
+
entries.push(entry2);
|
|
42053
|
+
fresh.push(chunk);
|
|
42054
|
+
}
|
|
42055
|
+
const revision = (base?.revision ?? 0) + 1;
|
|
42056
|
+
const manifest = {
|
|
42057
|
+
v: 1,
|
|
42058
|
+
noteId,
|
|
42059
|
+
revision,
|
|
42060
|
+
chunker: NOTE_CHUNKER,
|
|
42061
|
+
totalBytes: bytes.length,
|
|
42062
|
+
chunks: entries
|
|
42063
|
+
};
|
|
42064
|
+
const { ciphertext, iv } = encryptNoteManifest(dek, manifest);
|
|
42065
|
+
fresh.sort((a, b) => a.chunkId === b.chunkId ? cmp(a.versionId, b.versionId) : cmp(a.chunkId, b.chunkId));
|
|
42066
|
+
return {
|
|
42067
|
+
commit: {
|
|
42068
|
+
baseRevision: base?.revision ?? 0,
|
|
42069
|
+
encryptedManifest: ciphertext,
|
|
42070
|
+
manifestIv: iv,
|
|
42071
|
+
refs: refsOf(manifest),
|
|
42072
|
+
chunks: fresh
|
|
42073
|
+
},
|
|
42074
|
+
manifest
|
|
42075
|
+
};
|
|
42076
|
+
}
|
|
42077
|
+
function cmp(a, b) {
|
|
42078
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
42079
|
+
}
|
|
42080
|
+
var IV_BYTES, TAG_BYTES, NoteBodyTooLargeError;
|
|
42081
|
+
var init_note_body = __esm({
|
|
42082
|
+
"src/note-body.ts"() {
|
|
42083
|
+
"use strict";
|
|
42084
|
+
init_note_chunks();
|
|
42085
|
+
IV_BYTES = 12;
|
|
42086
|
+
TAG_BYTES = 16;
|
|
42087
|
+
NoteBodyTooLargeError = class extends Error {
|
|
42088
|
+
constructor(bytes) {
|
|
42089
|
+
super("Note body over the limit");
|
|
42090
|
+
this.bytes = bytes;
|
|
42091
|
+
this.name = "NoteBodyTooLargeError";
|
|
42092
|
+
}
|
|
42093
|
+
bytes;
|
|
42094
|
+
};
|
|
42095
|
+
}
|
|
42096
|
+
});
|
|
42097
|
+
|
|
42098
|
+
// src/note-content.ts
|
|
42099
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
42100
|
+
function inlineContentFields(sealed) {
|
|
42101
|
+
return { encryptedContent: sealed.ciphertext, contentIv: sealed.iv };
|
|
42102
|
+
}
|
|
42103
|
+
function listedBodyOf(n) {
|
|
42104
|
+
return n.encryptedContent !== void 0 ? { encryptedContent: n.encryptedContent, contentIv: n.contentIv } : null;
|
|
42105
|
+
}
|
|
42106
|
+
function bodyOfEntry(b) {
|
|
42107
|
+
return b.bodyFormat === NOTE_BODY_FORMAT_CHUNKS ? { encryptedContent: "", contentIv: null, bodyFormat: NOTE_BODY_FORMAT_CHUNKS, body: b.body } : { encryptedContent: b.encryptedContent, contentIv: b.contentIv };
|
|
42108
|
+
}
|
|
42109
|
+
function bodyOfNote(n) {
|
|
42110
|
+
return {
|
|
42111
|
+
encryptedContent: n.encryptedContent,
|
|
42112
|
+
contentIv: n.contentIv,
|
|
42113
|
+
...n.bodyFormat ? { bodyFormat: n.bodyFormat } : {},
|
|
42114
|
+
...n.body ? { body: n.body } : {}
|
|
42115
|
+
};
|
|
42116
|
+
}
|
|
42117
|
+
function readNoteContent(note, key) {
|
|
42118
|
+
if (note.bodyFormat === NOTE_BODY_FORMAT_CHUNKS) {
|
|
42119
|
+
if (!note.body) throw new NoteBodyUnreadableError();
|
|
42120
|
+
const chunked = readChunkedBody(key, note.id, note.body);
|
|
42121
|
+
if (note.encryptedContent) throw new NoteBodyUnreadableError();
|
|
42122
|
+
return { text: chunked.text, chunked, inlineIv: null };
|
|
42123
|
+
}
|
|
42124
|
+
const text = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
|
|
42125
|
+
return { text, chunked: null, inlineIv: note.contentIv ?? null };
|
|
42126
|
+
}
|
|
42127
|
+
function refused(error62, details) {
|
|
42128
|
+
return details === void 0 ? { kind: "refused", error: error62 } : { kind: "refused", error: error62, details };
|
|
42129
|
+
}
|
|
42130
|
+
function lostRace(err) {
|
|
42131
|
+
return err instanceof SquirrelApiError && err.status === 409 && /NOTE_BODY_(CONFLICT|CHUNKED)/.test(err.responseBody);
|
|
42132
|
+
}
|
|
42133
|
+
function codeOf(err) {
|
|
42134
|
+
try {
|
|
42135
|
+
const body = JSON.parse(err.responseBody);
|
|
42136
|
+
return typeof body === "object" && body !== null ? body.code : void 0;
|
|
42137
|
+
} catch {
|
|
42138
|
+
return void 0;
|
|
42139
|
+
}
|
|
42140
|
+
}
|
|
42141
|
+
function serverRefusal(err, bytes) {
|
|
42142
|
+
if (!(err instanceof SquirrelApiError)) return null;
|
|
42143
|
+
const code = codeOf(err);
|
|
42144
|
+
if (err.status === 413 && code === "NOTE_OVER_PLAN_LIMIT") {
|
|
42145
|
+
return refused("too-long", bytes === void 0 ? { limit: NOTE_BODY_MAX_BYTES2 } : { bytes, limit: NOTE_BODY_MAX_BYTES2 });
|
|
42146
|
+
}
|
|
42147
|
+
if ((err.status === 422 || err.status === 400) && code === "STORAGE_LIMIT_EXCEEDED") return refused("storage-full");
|
|
42148
|
+
return null;
|
|
42149
|
+
}
|
|
42150
|
+
function overThreshold(bytes) {
|
|
42151
|
+
return bytes > NOTE_CHUNKING_THRESHOLD_BYTES;
|
|
42152
|
+
}
|
|
42153
|
+
function overInlineCap(bytes) {
|
|
42154
|
+
return bytes > NOTE_BODY_MAX_BYTES ? refused("too-long", { bytes, limit: NOTE_BODY_MAX_BYTES }) : null;
|
|
42155
|
+
}
|
|
42156
|
+
async function writeNoteContent(client, key, noteId, text, current) {
|
|
42157
|
+
const tooLong = newContentTooLong(text);
|
|
42158
|
+
if (tooLong) return tooLong;
|
|
42159
|
+
const bytes = utf8Bytes(text);
|
|
42160
|
+
if (current.chunked || overThreshold(bytes)) {
|
|
42161
|
+
const { commit } = buildChunkedCommit(key, noteId, text, current.chunked ?? void 0);
|
|
42162
|
+
try {
|
|
42163
|
+
const saved = await client.putNoteBody(noteId, commit);
|
|
42164
|
+
return { kind: "written", updatedAt: saved.updatedAt };
|
|
42165
|
+
} catch (err) {
|
|
42166
|
+
if (lostRace(err)) return refused("write-conflict");
|
|
42167
|
+
const refusal = serverRefusal(err, bytes);
|
|
42168
|
+
if (refusal) return refusal;
|
|
42169
|
+
throw err;
|
|
42170
|
+
}
|
|
42171
|
+
}
|
|
42172
|
+
const capped = overInlineCap(bytes);
|
|
42173
|
+
if (capped) return capped;
|
|
42174
|
+
const enc = encrypt(text, key);
|
|
42175
|
+
try {
|
|
42176
|
+
const saved = await client.updateNote(noteId, { ...inlineContentFields(enc), baseContentIv: current.inlineIv });
|
|
42177
|
+
return { kind: "written", updatedAt: saved.updatedAt };
|
|
42178
|
+
} catch (err) {
|
|
42179
|
+
if (lostRace(err)) return refused("write-conflict");
|
|
42180
|
+
const refusal = serverRefusal(err, bytes);
|
|
42181
|
+
if (refusal) return refusal;
|
|
42182
|
+
throw err;
|
|
42183
|
+
}
|
|
42184
|
+
}
|
|
42185
|
+
function newContentTooLong(text) {
|
|
42186
|
+
const bytes = utf8Bytes(text);
|
|
42187
|
+
return bytes > NOTE_BODY_MAX_BYTES2 ? refused("too-long", { bytes, limit: NOTE_BODY_MAX_BYTES2 }) : null;
|
|
42188
|
+
}
|
|
42189
|
+
async function createNoteWithContent(client, key, fields, text) {
|
|
42190
|
+
if (text === void 0) return { kind: "created", note: await client.createNote(fields) };
|
|
42191
|
+
const tooLong = newContentTooLong(text);
|
|
42192
|
+
if (tooLong) return tooLong;
|
|
42193
|
+
const bytes = utf8Bytes(text);
|
|
42194
|
+
if (overThreshold(bytes)) {
|
|
42195
|
+
const id = randomUUID3();
|
|
42196
|
+
let note;
|
|
42197
|
+
try {
|
|
42198
|
+
note = await client.createNote({ ...fields, id, body: buildChunkedCommit(key, id, text).commit });
|
|
42199
|
+
} catch (err) {
|
|
42200
|
+
const refusal = serverRefusal(err, bytes);
|
|
42201
|
+
if (refusal) return refusal;
|
|
42202
|
+
throw err;
|
|
42203
|
+
}
|
|
42204
|
+
if (note.bodyFormat === NOTE_BODY_FORMAT_CHUNKS) return { kind: "created", note };
|
|
42205
|
+
const capped = overInlineCap(bytes);
|
|
42206
|
+
if (capped) return capped;
|
|
42207
|
+
return { kind: "created", note: await client.updateNote(note.id, inlineContentFields(encrypt(text, key))) };
|
|
42208
|
+
}
|
|
42209
|
+
try {
|
|
42210
|
+
return { kind: "created", note: await client.createNote({ ...fields, ...inlineContentFields(encrypt(text, key)) }) };
|
|
42211
|
+
} catch (err) {
|
|
42212
|
+
const refusal = serverRefusal(err, bytes);
|
|
42213
|
+
if (refusal) return refusal;
|
|
42214
|
+
throw err;
|
|
42215
|
+
}
|
|
42216
|
+
}
|
|
42217
|
+
var init_note_content = __esm({
|
|
42218
|
+
"src/note-content.ts"() {
|
|
42219
|
+
"use strict";
|
|
42220
|
+
init_api_error();
|
|
42221
|
+
init_crypto();
|
|
42222
|
+
init_note_body();
|
|
42223
|
+
init_note_chunks();
|
|
42224
|
+
init_note_limits();
|
|
42225
|
+
}
|
|
42226
|
+
});
|
|
42227
|
+
|
|
42228
|
+
// src/note-bodies.ts
|
|
42229
|
+
function isTransient(err) {
|
|
42230
|
+
return err instanceof SquirrelNetworkError || err instanceof SquirrelApiError && (err.status === 429 || err.status >= 500);
|
|
42231
|
+
}
|
|
42232
|
+
async function withBodies(client, listed, options = {}) {
|
|
42233
|
+
const delays = options.retryDelaysMs ?? NOTE_BODIES_RETRY_DELAYS_MS;
|
|
42234
|
+
const bodies = /* @__PURE__ */ new Map();
|
|
42235
|
+
for (const n of listed) {
|
|
42236
|
+
const body = listedBodyOf(n);
|
|
42237
|
+
if (body) bodies.set(n.id, body);
|
|
42238
|
+
}
|
|
42239
|
+
const missing = /* @__PURE__ */ new Set();
|
|
42240
|
+
let owed = listed.map((n) => n.id).filter((id) => !bodies.has(id));
|
|
42241
|
+
const attempt = async (call) => {
|
|
42242
|
+
for (let i = 0; ; i++) {
|
|
42243
|
+
try {
|
|
42244
|
+
return await call();
|
|
42245
|
+
} catch (err) {
|
|
42246
|
+
if (!isTransient(err)) throw err;
|
|
42247
|
+
if (i >= delays.length) throw new NoteBodiesIncompleteError();
|
|
42248
|
+
await sleep(delays[i]);
|
|
42249
|
+
}
|
|
42250
|
+
}
|
|
42251
|
+
};
|
|
42252
|
+
while (owed.length > 0) {
|
|
42253
|
+
const batch = owed.slice(0, NOTE_BODIES_BATCH);
|
|
42254
|
+
let page;
|
|
42255
|
+
try {
|
|
42256
|
+
page = await attempt(() => client.fetchNoteBodies(batch));
|
|
42257
|
+
} catch (err) {
|
|
42258
|
+
if (err instanceof SquirrelApiError && err.status === 404) {
|
|
42259
|
+
await oneAtATime(client, owed, bodies, missing, attempt);
|
|
42260
|
+
break;
|
|
42261
|
+
}
|
|
42262
|
+
throw err;
|
|
42263
|
+
}
|
|
42264
|
+
for (const b of page.bodies) {
|
|
42265
|
+
bodies.set(b.id, bodyOfEntry(b));
|
|
42266
|
+
}
|
|
42267
|
+
for (const id of page.missing) missing.add(id);
|
|
42268
|
+
if (page.bodies.length === 0 && page.missing.length === 0) {
|
|
42269
|
+
throw new NoteBodiesIncompleteError();
|
|
42270
|
+
}
|
|
42271
|
+
owed = owed.filter((id) => !bodies.has(id) && !missing.has(id));
|
|
42272
|
+
}
|
|
42273
|
+
return listed.flatMap((n) => {
|
|
42274
|
+
const body = bodies.get(n.id);
|
|
42275
|
+
return body ? [{ ...n, ...body }] : [];
|
|
42276
|
+
});
|
|
42277
|
+
}
|
|
42278
|
+
async function oneAtATime(client, ids, bodies, missing, attempt) {
|
|
42279
|
+
for (const id of ids) {
|
|
42280
|
+
try {
|
|
42281
|
+
const n = await attempt(() => client.getNote(id));
|
|
42282
|
+
bodies.set(id, bodyOfNote(n));
|
|
42283
|
+
} catch (err) {
|
|
42284
|
+
if (err instanceof SquirrelApiError && err.status === 404) missing.add(id);
|
|
42285
|
+
else throw err;
|
|
42286
|
+
}
|
|
42287
|
+
}
|
|
42288
|
+
}
|
|
42289
|
+
var NOTE_BODIES_BATCH, NOTE_BODIES_RETRY_DELAYS_MS, NoteBodiesIncompleteError, sleep;
|
|
42290
|
+
var init_note_bodies = __esm({
|
|
42291
|
+
"src/note-bodies.ts"() {
|
|
42292
|
+
"use strict";
|
|
42293
|
+
init_api_error();
|
|
42294
|
+
init_note_content();
|
|
42295
|
+
NOTE_BODIES_BATCH = 500;
|
|
42296
|
+
NOTE_BODIES_RETRY_DELAYS_MS = [250, 1e3];
|
|
42297
|
+
NoteBodiesIncompleteError = class extends Error {
|
|
42298
|
+
constructor() {
|
|
42299
|
+
super("not every note body could be read");
|
|
42300
|
+
this.name = "NoteBodiesIncompleteError";
|
|
42301
|
+
}
|
|
42302
|
+
};
|
|
42303
|
+
sleep = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
42304
|
+
}
|
|
42305
|
+
});
|
|
42306
|
+
|
|
41690
42307
|
// src/server.ts
|
|
41691
42308
|
var server_exports = {};
|
|
41692
42309
|
__export(server_exports, {
|
|
@@ -41733,7 +42350,7 @@ function decryptNoteTitle(note, key) {
|
|
|
41733
42350
|
}
|
|
41734
42351
|
function decryptNote(note, key) {
|
|
41735
42352
|
const title = decrypt(note.encryptedTitle, note.titleIv, key);
|
|
41736
|
-
const content =
|
|
42353
|
+
const content = readNoteContent(note, key).text;
|
|
41737
42354
|
const tagIds = note.tags?.map((t) => t.id) ?? [];
|
|
41738
42355
|
return { ...note, title, content, tagIds };
|
|
41739
42356
|
}
|
|
@@ -41757,6 +42374,31 @@ function inferMimeType(filePath) {
|
|
|
41757
42374
|
function refusalResult(r) {
|
|
41758
42375
|
return { content: [{ type: "text", text: refusalJson(r) }], isError: true };
|
|
41759
42376
|
}
|
|
42377
|
+
function bodyTooLong(text, error62 = "too-long") {
|
|
42378
|
+
const bytes = utf8Bytes(text);
|
|
42379
|
+
return bytes > NOTE_BODY_MAX_BYTES ? { kind: "refused", error: error62, details: { bytes, limit: NOTE_BODY_MAX_BYTES } } : null;
|
|
42380
|
+
}
|
|
42381
|
+
function titleTooLong(title) {
|
|
42382
|
+
const bytes = utf8Bytes(title);
|
|
42383
|
+
return bytes > NOTE_TITLE_MAX_BYTES ? { kind: "refused", error: "title-too-long", details: { bytes, limit: NOTE_TITLE_MAX_BYTES } } : null;
|
|
42384
|
+
}
|
|
42385
|
+
function refuseUnreadableBodies(server) {
|
|
42386
|
+
const register = server.tool.bind(server);
|
|
42387
|
+
server.tool = (...args) => {
|
|
42388
|
+
const handler = args[args.length - 1];
|
|
42389
|
+
args[args.length - 1] = async (...a) => {
|
|
42390
|
+
try {
|
|
42391
|
+
return await handler(...a);
|
|
42392
|
+
} catch (err) {
|
|
42393
|
+
if (err instanceof NoteBodyUnreadableError) return refusalResult({ kind: "refused", error: "unreadable" });
|
|
42394
|
+
const refusal = serverRefusal(err);
|
|
42395
|
+
if (refusal) return refusalResult(refusal);
|
|
42396
|
+
throw err;
|
|
42397
|
+
}
|
|
42398
|
+
};
|
|
42399
|
+
return register(...args);
|
|
42400
|
+
};
|
|
42401
|
+
}
|
|
41760
42402
|
function jsonResult(value) {
|
|
41761
42403
|
return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
|
|
41762
42404
|
}
|
|
@@ -41768,6 +42410,7 @@ function createMcpServer(creds, opts = {}) {
|
|
|
41768
42410
|
const context = createContextProvider(
|
|
41769
42411
|
(onUnauthorized) => buildContext(creds, onUnauthorized)
|
|
41770
42412
|
);
|
|
42413
|
+
refuseUnreadableBodies(server);
|
|
41771
42414
|
server.prompt(
|
|
41772
42415
|
"markdown_capabilities",
|
|
41773
42416
|
"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,15 +42508,18 @@ function createMcpServer(creds, opts = {}) {
|
|
|
41865
42508
|
collectionId: external_exports.string().optional().describe("Collection ID to place the note in. Omit to create in scratchpad.")
|
|
41866
42509
|
},
|
|
41867
42510
|
async ({ title, content, collectionId }) => {
|
|
42511
|
+
const tooLong = titleTooLong(title) ?? (content !== void 0 ? newContentTooLong(content) : null);
|
|
42512
|
+
if (tooLong) return refusalResult(tooLong);
|
|
41868
42513
|
const { client, key } = await context.get();
|
|
41869
42514
|
const encTitle = encrypt(title, key);
|
|
41870
|
-
const
|
|
41871
|
-
|
|
41872
|
-
|
|
41873
|
-
titleIv: encTitle.iv,
|
|
41874
|
-
|
|
41875
|
-
|
|
41876
|
-
|
|
42515
|
+
const created = await createNoteWithContent(
|
|
42516
|
+
client,
|
|
42517
|
+
key,
|
|
42518
|
+
{ encryptedTitle: encTitle.ciphertext, titleIv: encTitle.iv, collectionId: collectionId ?? null },
|
|
42519
|
+
content
|
|
42520
|
+
);
|
|
42521
|
+
if (created.kind === "refused") return refusalResult(created);
|
|
42522
|
+
const { note } = created;
|
|
41877
42523
|
return {
|
|
41878
42524
|
content: [
|
|
41879
42525
|
{
|
|
@@ -41893,6 +42539,8 @@ function createMcpServer(creds, opts = {}) {
|
|
|
41893
42539
|
content: external_exports.string().optional().describe("New content in Markdown (replaces existing content)")
|
|
41894
42540
|
},
|
|
41895
42541
|
async ({ id, title, content }) => {
|
|
42542
|
+
const titleRefusal = title !== void 0 ? titleTooLong(title) : null;
|
|
42543
|
+
if (titleRefusal) return refusalResult(titleRefusal);
|
|
41896
42544
|
const { client, key } = await context.get();
|
|
41897
42545
|
const dto = {};
|
|
41898
42546
|
if (title !== void 0) {
|
|
@@ -41900,15 +42548,34 @@ function createMcpServer(creds, opts = {}) {
|
|
|
41900
42548
|
dto.encryptedTitle = enc.ciphertext;
|
|
41901
42549
|
dto.titleIv = enc.iv;
|
|
41902
42550
|
}
|
|
41903
|
-
if (content !== void 0) {
|
|
42551
|
+
if (content !== void 0 && utf8Bytes(content) <= NOTE_CHUNKING_THRESHOLD_BYTES) {
|
|
41904
42552
|
const enc = encrypt(content, key);
|
|
41905
|
-
|
|
41906
|
-
|
|
42553
|
+
try {
|
|
42554
|
+
const note = await client.updateNote(id, { ...dto, ...inlineContentFields(enc) });
|
|
42555
|
+
return { content: [{ type: "text", text: JSON.stringify({ id: note.id, updated: true }, null, 2) }] };
|
|
42556
|
+
} catch (err) {
|
|
42557
|
+
if (!(err instanceof SquirrelApiError && err.status === 409 && err.responseBody.includes("NOTE_BODY_CHUNKED"))) throw err;
|
|
42558
|
+
}
|
|
41907
42559
|
}
|
|
41908
|
-
|
|
41909
|
-
|
|
41910
|
-
content: [{ type: "text", text: JSON.stringify({ id: note.id, updated: true }, null, 2) }]
|
|
41911
|
-
}
|
|
42560
|
+
if (content === void 0) {
|
|
42561
|
+
const note = await client.updateNote(id, dto);
|
|
42562
|
+
return { content: [{ type: "text", text: JSON.stringify({ id: note.id, updated: true }, null, 2) }] };
|
|
42563
|
+
}
|
|
42564
|
+
const tooLong = newContentTooLong(content);
|
|
42565
|
+
if (tooLong) return refusalResult(tooLong);
|
|
42566
|
+
const current = readNoteContent(await client.getNote(id), key);
|
|
42567
|
+
const written = await writeNoteContent(client, key, id, content, current);
|
|
42568
|
+
if (written.kind === "refused") return refusalResult(written);
|
|
42569
|
+
if (title !== void 0) {
|
|
42570
|
+
try {
|
|
42571
|
+
await client.updateNote(id, dto);
|
|
42572
|
+
} catch (err) {
|
|
42573
|
+
if (!(err instanceof SquirrelApiError)) throw err;
|
|
42574
|
+
const reason = serverRefusal(err)?.error;
|
|
42575
|
+
return refusalResult({ kind: "refused", error: "title-not-saved", details: { ...reason ? { reason } : {}, status: err.status } });
|
|
42576
|
+
}
|
|
42577
|
+
}
|
|
42578
|
+
return { content: [{ type: "text", text: JSON.stringify({ id, updated: true }, null, 2) }] };
|
|
41912
42579
|
}
|
|
41913
42580
|
);
|
|
41914
42581
|
const staleCheck = (updatedAt, expected) => expected !== void 0 && expected !== updatedAt ? { kind: "refused", error: "stale", details: { updatedAt } } : null;
|
|
@@ -41929,14 +42596,12 @@ function createMcpServer(creds, opts = {}) {
|
|
|
41929
42596
|
const note = await client.getNote(id);
|
|
41930
42597
|
const stale = staleCheck(note.updatedAt, expectedUpdatedAt);
|
|
41931
42598
|
if (stale) return refusalResult(stale);
|
|
41932
|
-
const
|
|
42599
|
+
const current = readNoteContent(note, key);
|
|
42600
|
+
const existingContent = current.text;
|
|
41933
42601
|
const newContent = existingContent ? `${existingContent}${separator2}${content}` : content;
|
|
41934
|
-
const
|
|
41935
|
-
|
|
41936
|
-
|
|
41937
|
-
contentIv: encContent.iv
|
|
41938
|
-
});
|
|
41939
|
-
const answer = expectedUpdatedAt === void 0 ? { id, appended: true } : { id, appended: true, updatedAt: saved.updatedAt };
|
|
42602
|
+
const written = await writeNoteContent(client, key, id, newContent, current);
|
|
42603
|
+
if (written.kind === "refused") return refusalResult(written);
|
|
42604
|
+
const answer = expectedUpdatedAt === void 0 ? { id, appended: true } : { id, appended: true, updatedAt: written.updatedAt };
|
|
41940
42605
|
return {
|
|
41941
42606
|
content: [{ type: "text", text: JSON.stringify(answer, null, 2) }]
|
|
41942
42607
|
};
|
|
@@ -41945,13 +42610,12 @@ function createMcpServer(creds, opts = {}) {
|
|
|
41945
42610
|
const loadNote = async (id) => {
|
|
41946
42611
|
const { client, key } = await context.get();
|
|
41947
42612
|
const note = await client.getNote(id);
|
|
41948
|
-
const
|
|
41949
|
-
return { client, key, note, nt: noteText(
|
|
42613
|
+
const body = readNoteContent(note, key);
|
|
42614
|
+
return { client, key, note, body, nt: noteText(body.text) };
|
|
41950
42615
|
};
|
|
41951
42616
|
const writeContent = async (ctx, id, raw) => {
|
|
41952
|
-
const
|
|
41953
|
-
|
|
41954
|
-
return saved.updatedAt;
|
|
42617
|
+
const written = await writeNoteContent(ctx.client, ctx.key, id, raw, ctx.body);
|
|
42618
|
+
return written.kind === "written" ? written.updatedAt : written;
|
|
41955
42619
|
};
|
|
41956
42620
|
const headingSchema = external_exports.string().describe(`A heading's text exactly as get_note_outline lists it (at most ${HEADING_TEXT_MAX} characters)`);
|
|
41957
42621
|
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 +42679,7 @@ function createMcpServer(creds, opts = {}) {
|
|
|
42015
42679
|
if (isRefusal(r)) return refusalResult(r);
|
|
42016
42680
|
if (r.kind === "unchanged") return jsonResult({ id, changed: false, updatedAt: ctx.note.updatedAt });
|
|
42017
42681
|
const updatedAt = await writeContent(ctx, id, r.raw);
|
|
42682
|
+
if (typeof updatedAt !== "string") return refusalResult(updatedAt);
|
|
42018
42683
|
return jsonResult({ id, changed: true, startLine: r.startLine, endLine: r.endLine, updatedAt });
|
|
42019
42684
|
}
|
|
42020
42685
|
);
|
|
@@ -42037,6 +42702,7 @@ function createMcpServer(creds, opts = {}) {
|
|
|
42037
42702
|
const r = replaceSection(ctx.nt, h, content);
|
|
42038
42703
|
if (r.kind === "unchanged") return jsonResult({ id, changed: false, removedSubheadings: r.removedSubheadings, updatedAt: ctx.note.updatedAt });
|
|
42039
42704
|
const updatedAt = await writeContent(ctx, id, r.raw);
|
|
42705
|
+
if (typeof updatedAt !== "string") return refusalResult(updatedAt);
|
|
42040
42706
|
return jsonResult({ id, changed: true, startLine: r.startLine, endLine: r.endLine, removedSubheadings: r.removedSubheadings, updatedAt });
|
|
42041
42707
|
}
|
|
42042
42708
|
);
|
|
@@ -42060,6 +42726,7 @@ function createMcpServer(creds, opts = {}) {
|
|
|
42060
42726
|
const r = insertInSection(ctx.nt, h, content, position);
|
|
42061
42727
|
if (isRefusal(r)) return refusalResult(r);
|
|
42062
42728
|
const updatedAt = await writeContent(ctx, id, r.raw);
|
|
42729
|
+
if (typeof updatedAt !== "string") return refusalResult(updatedAt);
|
|
42063
42730
|
return jsonResult({ id, changed: true, startLine: r.startLine, endLine: r.endLine, updatedAt });
|
|
42064
42731
|
}
|
|
42065
42732
|
);
|
|
@@ -42080,6 +42747,7 @@ function createMcpServer(creds, opts = {}) {
|
|
|
42080
42747
|
if (isRefusal(h)) return refusalResult(h);
|
|
42081
42748
|
const r = deleteSection(ctx.nt, h);
|
|
42082
42749
|
const updatedAt = await writeContent(ctx, id, r.raw);
|
|
42750
|
+
if (typeof updatedAt !== "string") return refusalResult(updatedAt);
|
|
42083
42751
|
return jsonResult({ id, changed: true, removedLines: { startLine: r.startLine, endLine: r.endLine }, removedSubheadings: r.removedSubheadings, updatedAt });
|
|
42084
42752
|
}
|
|
42085
42753
|
);
|
|
@@ -42099,6 +42767,7 @@ function createMcpServer(creds, opts = {}) {
|
|
|
42099
42767
|
const r = insertAtLine(ctx.nt, line, content);
|
|
42100
42768
|
if (isRefusal(r)) return refusalResult(r);
|
|
42101
42769
|
const updatedAt = await writeContent(ctx, id, r.raw);
|
|
42770
|
+
if (typeof updatedAt !== "string") return refusalResult(updatedAt);
|
|
42102
42771
|
return jsonResult({ id, changed: true, startLine: r.startLine, endLine: r.endLine, updatedAt });
|
|
42103
42772
|
}
|
|
42104
42773
|
);
|
|
@@ -42226,7 +42895,15 @@ function createMcpServer(creds, opts = {}) {
|
|
|
42226
42895
|
},
|
|
42227
42896
|
async ({ query, includeContent = false, limit }) => {
|
|
42228
42897
|
const { client, key } = await context.get();
|
|
42229
|
-
|
|
42898
|
+
let notes;
|
|
42899
|
+
try {
|
|
42900
|
+
notes = await withBodies(client, await client.listNotes(), {
|
|
42901
|
+
...opts.noteBodiesRetryDelaysMs ? { retryDelaysMs: opts.noteBodiesRetryDelaysMs } : {}
|
|
42902
|
+
});
|
|
42903
|
+
} catch (err) {
|
|
42904
|
+
if (err instanceof NoteBodiesIncompleteError) return refusalResult({ kind: "refused", error: "search-incomplete" });
|
|
42905
|
+
throw err;
|
|
42906
|
+
}
|
|
42230
42907
|
const fq = foldForSearch(query);
|
|
42231
42908
|
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
42909
|
if (includeContent) {
|
|
@@ -42571,7 +43248,7 @@ function createMcpServer(creds, opts = {}) {
|
|
|
42571
43248
|
"Publish a note as a public, passphrase-protected link. The note content is decrypted in this process and then re-encrypted with a share-specific key derived from the share passphrase \u2014 the server never sees plaintext. The share URL and token are returned. Pro tier required.",
|
|
42572
43249
|
{
|
|
42573
43250
|
noteId: external_exports.string().describe("ID of the note to share"),
|
|
42574
|
-
sharePassphrase: external_exports.string().min(
|
|
43251
|
+
sharePassphrase: external_exports.string().min(SHARE_PASSPHRASE_MIN_LENGTH).describe("Passphrase recipients must enter to read the note. Choose something memorable but not easily guessed."),
|
|
42575
43252
|
expiry: expirySchema,
|
|
42576
43253
|
allowDownload: external_exports.boolean().optional().describe('When true, viewers see a "Download as Markdown" button (default: false)')
|
|
42577
43254
|
},
|
|
@@ -42579,19 +43256,20 @@ function createMcpServer(creds, opts = {}) {
|
|
|
42579
43256
|
const { client, key } = await context.get();
|
|
42580
43257
|
const note = await client.getNote(noteId);
|
|
42581
43258
|
const title = decrypt(note.encryptedTitle, note.titleIv, key);
|
|
42582
|
-
const content =
|
|
43259
|
+
const content = readNoteContent(note, key).text;
|
|
43260
|
+
const tooLarge = bodyTooLong(content, "too-large-to-share");
|
|
43261
|
+
if (tooLarge) return refusalResult(tooLarge);
|
|
42583
43262
|
const shareSalt = generateSalt();
|
|
42584
|
-
const shareKey = await deriveKey(sharePassphrase, shareSalt);
|
|
43263
|
+
const shareKey = await deriveKey(sharePassphrase, shareSalt, SHARE_PBKDF2_ITERATIONS);
|
|
42585
43264
|
const encTitle = encrypt(title, shareKey);
|
|
42586
43265
|
const encContent = encrypt(content, shareKey);
|
|
42587
43266
|
const status = await client.publishShare({
|
|
42588
43267
|
noteId,
|
|
42589
43268
|
encryptedTitle: encTitle.ciphertext,
|
|
42590
43269
|
titleIv: encTitle.iv,
|
|
42591
|
-
|
|
42592
|
-
contentIv: encContent.iv,
|
|
43270
|
+
...inlineContentFields(encContent),
|
|
42593
43271
|
salt: shareSalt,
|
|
42594
|
-
pbkdf2Iterations:
|
|
43272
|
+
pbkdf2Iterations: SHARE_PBKDF2_ITERATIONS,
|
|
42595
43273
|
expiry,
|
|
42596
43274
|
allowDownload: allowDownload ?? false
|
|
42597
43275
|
});
|
|
@@ -42636,24 +43314,25 @@ function createMcpServer(creds, opts = {}) {
|
|
|
42636
43314
|
{
|
|
42637
43315
|
shareToken: external_exports.string().describe("Share token from get_share_status"),
|
|
42638
43316
|
noteId: external_exports.string().describe("Note ID (needed to fetch the latest content)"),
|
|
42639
|
-
sharePassphrase: external_exports.string().min(
|
|
43317
|
+
sharePassphrase: external_exports.string().min(SHARE_PASSPHRASE_MIN_LENGTH).describe("Passphrase for the share (can be same as before or a new one)")
|
|
42640
43318
|
},
|
|
42641
43319
|
async ({ shareToken, noteId, sharePassphrase }) => {
|
|
42642
43320
|
const { client, key } = await context.get();
|
|
42643
43321
|
const note = await client.getNote(noteId);
|
|
42644
43322
|
const title = decrypt(note.encryptedTitle, note.titleIv, key);
|
|
42645
|
-
const content =
|
|
43323
|
+
const content = readNoteContent(note, key).text;
|
|
43324
|
+
const tooLarge = bodyTooLong(content, "too-large-to-share");
|
|
43325
|
+
if (tooLarge) return refusalResult(tooLarge);
|
|
42646
43326
|
const shareSalt = generateSalt();
|
|
42647
|
-
const shareKey = await deriveKey(sharePassphrase, shareSalt);
|
|
43327
|
+
const shareKey = await deriveKey(sharePassphrase, shareSalt, SHARE_PBKDF2_ITERATIONS);
|
|
42648
43328
|
const encTitle = encrypt(title, shareKey);
|
|
42649
43329
|
const encContent = encrypt(content, shareKey);
|
|
42650
43330
|
const status = await client.republishShare(shareToken, {
|
|
42651
43331
|
encryptedTitle: encTitle.ciphertext,
|
|
42652
43332
|
titleIv: encTitle.iv,
|
|
42653
|
-
|
|
42654
|
-
contentIv: encContent.iv,
|
|
43333
|
+
...inlineContentFields(encContent),
|
|
42655
43334
|
salt: shareSalt,
|
|
42656
|
-
pbkdf2Iterations:
|
|
43335
|
+
pbkdf2Iterations: SHARE_PBKDF2_ITERATIONS
|
|
42657
43336
|
});
|
|
42658
43337
|
return {
|
|
42659
43338
|
content: [
|
|
@@ -42887,6 +43566,11 @@ var init_server3 = __esm({
|
|
|
42887
43566
|
init_search_fold();
|
|
42888
43567
|
init_upload_path();
|
|
42889
43568
|
init_note_text();
|
|
43569
|
+
init_note_limits();
|
|
43570
|
+
init_note_bodies();
|
|
43571
|
+
init_note_content();
|
|
43572
|
+
init_note_chunks();
|
|
43573
|
+
init_note_chunks();
|
|
42890
43574
|
SQUIRREL_API_BASE_URL = process.env.SQUIRREL_API_BASE_URL;
|
|
42891
43575
|
if (!SQUIRREL_API_BASE_URL) {
|
|
42892
43576
|
throw new Error("SQUIRREL_API_BASE_URL environment variable is required");
|
|
@@ -42967,11 +43651,11 @@ __export(vector_cache_exports, {
|
|
|
42967
43651
|
vectorFilePathForId: () => vectorFilePathForId,
|
|
42968
43652
|
writeVectorFile: () => writeVectorFile
|
|
42969
43653
|
});
|
|
42970
|
-
import { createCipheriv as
|
|
43654
|
+
import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, hkdfSync as hkdfSync2, randomBytes as randomBytes3, randomUUID as randomUUID4 } from "node:crypto";
|
|
42971
43655
|
import { chmod, mkdir as mkdir2, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
42972
43656
|
import path from "node:path";
|
|
42973
43657
|
function vectorFileId(dek) {
|
|
42974
|
-
return Buffer.from(
|
|
43658
|
+
return Buffer.from(hkdfSync2("sha256", dek, Buffer.alloc(0), FILE_ID_INFO, 8)).toString("hex");
|
|
42975
43659
|
}
|
|
42976
43660
|
function vectorFilePath(cacheDir, dek) {
|
|
42977
43661
|
return vectorFilePathForId(cacheDir, vectorFileId(dek));
|
|
@@ -42988,7 +43672,7 @@ function defaultCacheDir(platform, env, home) {
|
|
|
42988
43672
|
return env.XDG_CACHE_HOME || path.join(home, ".cache");
|
|
42989
43673
|
}
|
|
42990
43674
|
function deriveFileKey(dek, salt) {
|
|
42991
|
-
return Buffer.from(
|
|
43675
|
+
return Buffer.from(hkdfSync2("sha256", dek, salt, KEY_INFO, 32));
|
|
42992
43676
|
}
|
|
42993
43677
|
function headerBytes(model, recipe = EMBEDDING_TEXT_RECIPE) {
|
|
42994
43678
|
return Buffer.from(
|
|
@@ -43041,10 +43725,10 @@ function sealVectorFile(entries, model, dek) {
|
|
|
43041
43725
|
MAGIC.copy(prefix, 0);
|
|
43042
43726
|
prefix.writeUInt8(VECTOR_FILE_FORMAT, MAGIC.length);
|
|
43043
43727
|
prefix.writeUInt16BE(header.length, MAGIC.length + 1);
|
|
43044
|
-
const salt =
|
|
43045
|
-
const iv =
|
|
43728
|
+
const salt = randomBytes3(SALT_LENGTH);
|
|
43729
|
+
const iv = randomBytes3(IV_LENGTH2);
|
|
43046
43730
|
const aad = Buffer.concat([prefix, header, salt, iv]);
|
|
43047
|
-
const cipher =
|
|
43731
|
+
const cipher = createCipheriv3("aes-256-gcm", deriveFileKey(dek, salt), iv);
|
|
43048
43732
|
cipher.setAAD(aad);
|
|
43049
43733
|
const sealed = Buffer.concat([cipher.update(encodeBody(entries, model.dimensions)), cipher.final(), cipher.getAuthTag()]);
|
|
43050
43734
|
return Buffer.concat([aad, sealed]);
|
|
@@ -43062,7 +43746,7 @@ function openVectorFile(file2, model, dek) {
|
|
|
43062
43746
|
if (!file2.subarray(fixed, fixed + headerLength).equals(headerBytes(model))) return null;
|
|
43063
43747
|
const salt = file2.subarray(fixed + headerLength, fixed + headerLength + SALT_LENGTH);
|
|
43064
43748
|
const iv = file2.subarray(aadEnd - IV_LENGTH2, aadEnd);
|
|
43065
|
-
const decipher =
|
|
43749
|
+
const decipher = createDecipheriv3("aes-256-gcm", deriveFileKey(dek, salt), iv);
|
|
43066
43750
|
decipher.setAAD(file2.subarray(0, aadEnd));
|
|
43067
43751
|
decipher.setAuthTag(file2.subarray(file2.length - TAG_LENGTH));
|
|
43068
43752
|
const body = Buffer.concat([decipher.update(file2.subarray(aadEnd, file2.length - TAG_LENGTH)), decipher.final()]);
|
|
@@ -43084,7 +43768,7 @@ async function writeVectorFile(filePath, entries, model, dek) {
|
|
|
43084
43768
|
const dir = path.dirname(filePath);
|
|
43085
43769
|
await mkdir2(dir, { recursive: true, mode: 448 });
|
|
43086
43770
|
await chmod(dir, 448);
|
|
43087
|
-
const tmp = path.join(dir, `.${path.basename(filePath)}.${
|
|
43771
|
+
const tmp = path.join(dir, `.${path.basename(filePath)}.${randomUUID4()}.tmp`);
|
|
43088
43772
|
try {
|
|
43089
43773
|
await writeFile(tmp, sealVectorFile(entries, model, dek), { mode: 384, flag: "wx" });
|
|
43090
43774
|
await chmod(tmp, 384);
|