standardnotes-mcp 0.0.0-stage → 3.0.1

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 (49) hide show
  1. package/CHANGELOG.md +183 -0
  2. package/LICENSE +22 -0
  3. package/README.md +336 -3
  4. package/SECURITY.md +56 -0
  5. package/dist/cli/install.js +180 -0
  6. package/dist/cli/isMain.js +21 -0
  7. package/dist/cli/login.js +117 -0
  8. package/dist/cli/logout.js +22 -0
  9. package/dist/cli/setup.js +192 -0
  10. package/dist/config.js +60 -0
  11. package/dist/index.js +10 -0
  12. package/dist/security/errors.js +20 -0
  13. package/dist/security/logger.js +17 -0
  14. package/dist/security/redact.js +31 -0
  15. package/dist/security/regex.js +27 -0
  16. package/dist/server.js +329 -0
  17. package/dist/sn/cache.js +53 -0
  18. package/dist/sn/client.js +1999 -0
  19. package/dist/sn/crypto.js +63 -0
  20. package/dist/sn/dates.js +157 -0
  21. package/dist/sn/entitlement.js +75 -0
  22. package/dist/sn/frontmatter.js +171 -0
  23. package/dist/sn/governance.js +40 -0
  24. package/dist/sn/http.js +289 -0
  25. package/dist/sn/links.js +78 -0
  26. package/dist/sn/markdownSections.js +141 -0
  27. package/dist/sn/predicates.js +135 -0
  28. package/dist/sn/protocol004.js +401 -0
  29. package/dist/sn/scope.js +68 -0
  30. package/dist/sn/search.js +260 -0
  31. package/dist/sn/session.js +55 -0
  32. package/dist/sn/tagHierarchy.js +105 -0
  33. package/dist/sn/tasks.js +32 -0
  34. package/dist/sn/templates.js +23 -0
  35. package/dist/sn/types.js +12 -0
  36. package/dist/tools/daily.js +126 -0
  37. package/dist/tools/export.js +96 -0
  38. package/dist/tools/history.js +41 -0
  39. package/dist/tools/links.js +51 -0
  40. package/dist/tools/notes.js +404 -0
  41. package/dist/tools/smartviews.js +52 -0
  42. package/dist/tools/tags.js +82 -0
  43. package/dist/tools/tasks.js +43 -0
  44. package/dist/tools/templates.js +145 -0
  45. package/dist/version.js +12 -0
  46. package/docs/protocol-004.md +72 -0
  47. package/docs/self-hosted.md +120 -0
  48. package/docs/troubleshooting.md +89 -0
  49. package/package.json +86 -6
@@ -0,0 +1,401 @@
1
+ /**
2
+ * Standard Notes protocol 004 framing.
3
+ *
4
+ * Payload content format (string):
5
+ * "004:<nonce_hex>:<ciphertext_b64>:<aad_b64>"
6
+ *
7
+ * AAD is a JSON object, authenticated as associated data of XChaCha20-Poly1305:
8
+ * { u: <item_uuid>, v: "004", kp: <keyParams_for_items_keys | items_key_uuid_for_others> }
9
+ *
10
+ * Keys:
11
+ * - rootKey: derived from user password via Argon2id. 64 bytes split into
12
+ * masterKey (first 32, hex) and serverPassword (last 32, hex).
13
+ * - items_key items are encrypted with rootKey.masterKey. Their AAD kp
14
+ * contains the account keyParams.
15
+ * - other items are encrypted with the referenced items_key.itemsKey.
16
+ * Their AAD kp contains the items_key uuid as a string.
17
+ *
18
+ * Spec reference: https://standardnotes.com/help/security/encryption
19
+ */
20
+ import { argon2id64, bytesToString, fromBase64, fromHex, randomBytes, sha256Hex, stringToBytes, toBase64, toHex, xchachaDecrypt, xchachaEncrypt, } from "./crypto.js";
21
+ const SN_APP_DOMAIN = "org.standardnotes.sn";
22
+ const EDITOR_IDENTIFIERS = {
23
+ markdown: "org.standardnotes.advanced-markdown-editor",
24
+ super: "com.standardnotes.super-editor",
25
+ code: "org.standardnotes.code-editor",
26
+ };
27
+ const NONCE_BYTES = 24;
28
+ const KEY_BYTES = 32;
29
+ export async function deriveRootKey(password, keyParams) {
30
+ if (keyParams.version !== "004") {
31
+ throw new Error(`Only protocol 004 is supported; got version ${keyParams.version}. ` +
32
+ "Upgrade your account via the Standard Notes app first.");
33
+ }
34
+ // Use identifier verbatim as returned by the server (do not lowercase).
35
+ const saltInput = `${keyParams.identifier}:${keyParams.pw_nonce}`;
36
+ const saltHex = (await sha256Hex(saltInput)).substring(0, 32);
37
+ const saltBytes = await fromHex(saltHex);
38
+ // SN 004 fixed Argon2id parameters (see whitepaper):
39
+ const OPS_LIMIT = 5;
40
+ const MEM_LIMIT = 64 * 1024 * 1024;
41
+ const derived = await argon2id64(password, saltBytes, OPS_LIMIT, MEM_LIMIT);
42
+ const masterKey = derived.slice(0, KEY_BYTES);
43
+ const serverPasswordBytes = derived.slice(KEY_BYTES, KEY_BYTES * 2);
44
+ const serverPassword = await toHex(serverPasswordBytes);
45
+ return { masterKey, serverPassword, keyParams };
46
+ }
47
+ // 004 symmetric payload format: "version:nonce:ciphertext:aad[:additionalData]"
48
+ // The 5th (additionalData) is optional; older payloads omit it.
49
+ export async function parseEncryptedString(content) {
50
+ if (content.startsWith("004_Asym:")) {
51
+ throw new Error("Asymmetric 004 payload (shared vault invite) is not supported");
52
+ }
53
+ const parts = content.split(":");
54
+ if (parts.length !== 4 && parts.length !== 5) {
55
+ throw new Error(`Invalid 004 payload: expected 4 or 5 parts, got ${parts.length}`);
56
+ }
57
+ const [version, nonceHex, ctB64, aadB64] = parts;
58
+ const additionalDataB64 = parts[4] ?? "e30=";
59
+ if (version !== "004") {
60
+ throw new Error(`Unsupported payload version: ${version}`);
61
+ }
62
+ const aadDecodedBytes = await fromBase64(aadB64);
63
+ const aadJson = bytesToString(aadDecodedBytes);
64
+ let aad;
65
+ try {
66
+ aad = JSON.parse(aadJson);
67
+ }
68
+ catch {
69
+ throw new Error("004 payload AAD is not valid JSON");
70
+ }
71
+ return {
72
+ version,
73
+ nonce: await fromHex(nonceHex),
74
+ ciphertext: await fromBase64(ctB64),
75
+ aadB64,
76
+ aad,
77
+ additionalDataB64,
78
+ };
79
+ }
80
+ /**
81
+ * `JSON.parse` for already-decrypted item content. The plaintext is
82
+ * AEAD-authenticated (XChaCha20-Poly1305) — only data encrypted under our own
83
+ * key reaches here, so it can't be attacker-forged — but a genuinely corrupt
84
+ * item would make `JSON.parse` throw an opaque `SyntaxError`. Wrapping it names
85
+ * the offending item and kind, so the per-item `catch` in `fullSync` skips it
86
+ * cleanly instead of surfacing a context-free parser error.
87
+ */
88
+ function parseDecryptedContent(json, kind, uuid) {
89
+ try {
90
+ return JSON.parse(json);
91
+ }
92
+ catch {
93
+ throw new Error(`Decrypted ${kind} content for ${uuid} is not valid JSON`);
94
+ }
95
+ }
96
+ export async function decryptString(content, key, expectedUuid) {
97
+ const p = await parseEncryptedString(content);
98
+ if (p.aad["u"] !== expectedUuid) {
99
+ throw new Error(`Payload AAD uuid mismatch: expected ${expectedUuid}, got ${String(p.aad["u"])}`);
100
+ }
101
+ // AAD for xchacha20 = UTF-8 bytes of the base64 string itself (SN convention).
102
+ const aadBytes = await stringToBytes(p.aadB64);
103
+ const plain = await xchachaDecrypt(p.ciphertext, aadBytes, p.nonce, key);
104
+ return bytesToString(plain);
105
+ }
106
+ export async function encryptString(plaintext, key, aadObject) {
107
+ const nonce = await randomBytes(NONCE_BYTES);
108
+ const aadJson = JSON.stringify(aadObject);
109
+ const aadB64 = await toBase64(await stringToBytes(aadJson));
110
+ // AAD for xchacha20 = bytes of the base64 string, not of the JSON itself.
111
+ const aadForAead = await stringToBytes(aadB64);
112
+ const ct = await xchachaEncrypt(await stringToBytes(plaintext), aadForAead, nonce, key);
113
+ const EMPTY_ADDITIONAL = "e30=";
114
+ return `004:${await toHex(nonce)}:${await toBase64(ct)}:${aadB64}:${EMPTY_ADDITIONAL}`;
115
+ }
116
+ export async function generateItemsKeyRaw() {
117
+ return randomBytes(KEY_BYTES);
118
+ }
119
+ /**
120
+ * Decrypts an items_key item (content_type = "SN|ItemsKey").
121
+ *
122
+ * - enc_item_key : encrypted under rootKey.masterKey → yields hex of a
123
+ * "wrapping" key K1 used only to decrypt this item's `content`.
124
+ * - content : encrypted under K1 → JSON whose `itemsKey` field contains
125
+ * the ACTUAL items_key (K2) used to wrap other items.
126
+ *
127
+ * Only K2 is kept and exposed as the items_key for note decryption.
128
+ */
129
+ export async function decryptItemsKey(item, rootKey) {
130
+ const wrappingKeyHex = await decryptString(item.enc_item_key, rootKey.masterKey, item.uuid);
131
+ const wrappingKey = await fromHex(wrappingKeyHex);
132
+ const contentJson = await decryptString(item.content, wrappingKey, item.uuid);
133
+ const content = parseDecryptedContent(contentJson, "items_key", item.uuid);
134
+ if (content.version && content.version !== "004") {
135
+ throw new Error(`items_key has non-004 version: ${content.version}`);
136
+ }
137
+ if (!content.itemsKey || !/^[0-9a-f]{64}$/i.test(content.itemsKey)) {
138
+ throw new Error(`items_key content missing valid 'itemsKey' field for ${item.uuid}`);
139
+ }
140
+ const itemsKey = await fromHex(content.itemsKey);
141
+ return { uuid: item.uuid, itemsKey, version: "004" };
142
+ }
143
+ /**
144
+ * Content keys encryptNote manages itself. Everything else from the
145
+ * decrypted content is preserved through `DecryptedNote.extra`.
146
+ */
147
+ const MANAGED_NOTE_KEYS = new Set([
148
+ "title",
149
+ "text",
150
+ "noteType",
151
+ "references",
152
+ "trashed",
153
+ "archived",
154
+ "pinned",
155
+ "editorIdentifier",
156
+ "preview_plain",
157
+ "preview_html",
158
+ ]);
159
+ function parseReferences(raw) {
160
+ if (!Array.isArray(raw))
161
+ return [];
162
+ return raw.filter((r) => typeof r === "object" &&
163
+ r !== null &&
164
+ typeof r.uuid === "string" &&
165
+ typeof r.content_type === "string");
166
+ }
167
+ export async function decryptNote(item, itemsKeyByUuid) {
168
+ const keyId = item.items_key_id;
169
+ if (!keyId) {
170
+ throw new Error(`Note ${item.uuid} has no items_key_id`);
171
+ }
172
+ const itemsKey = itemsKeyByUuid.get(keyId);
173
+ if (!itemsKey) {
174
+ throw new Error(`Unknown items_key ${keyId} for note ${item.uuid}`);
175
+ }
176
+ const itemKeyHex = await decryptString(item.enc_item_key, itemsKey, item.uuid);
177
+ const perItemKey = await fromHex(itemKeyHex);
178
+ const contentJson = await decryptString(item.content, perItemKey, item.uuid);
179
+ const content = parseDecryptedContent(contentJson, "note", item.uuid);
180
+ const extra = {};
181
+ for (const [k, v] of Object.entries(content)) {
182
+ if (!MANAGED_NOTE_KEYS.has(k))
183
+ extra[k] = v;
184
+ }
185
+ // SN stores the edit-lock under the appData domain "org.standardnotes.sn".
186
+ // Anything else (legacy keys, future extension points) we deliberately
187
+ // ignore here — the field is exposed only as a boolean to the tool layer.
188
+ const snAppData = content.appData?.["org.standardnotes.sn"];
189
+ const locked = typeof snAppData === "object" &&
190
+ snAppData !== null &&
191
+ snAppData.locked === true;
192
+ return {
193
+ uuid: item.uuid,
194
+ title: content.title ?? "",
195
+ text: content.text ?? "",
196
+ trashed: content.trashed === true,
197
+ protected: content.protected === true,
198
+ locked,
199
+ archived: content.archived === true,
200
+ pinned: content.pinned === true,
201
+ noteType: content.noteType ?? "plain-text",
202
+ createdAt: item.created_at ?? "",
203
+ updatedAt: item.updated_at ?? "",
204
+ created_at_timestamp: item.created_at_timestamp ?? 0,
205
+ updated_at_timestamp: item.updated_at_timestamp ?? 0,
206
+ references: parseReferences(content.references),
207
+ extra,
208
+ };
209
+ }
210
+ export async function encryptNote(note, itemsKey) {
211
+ const perItemKey = await generateItemsKeyRaw();
212
+ // AAD for items-key-encrypted payloads MUST be {u, v} only.
213
+ // `kp` is reserved for root-key-encrypted payloads (items_keys themselves).
214
+ // Including it here causes the SN app to fail AEAD verification and drop the note.
215
+ const aad = { u: note.uuid, v: "004" };
216
+ const resolvedType = note.noteType ?? "plain-text";
217
+ // Editor identifier is a hint for legacy SN clients that route by editor
218
+ // rather than by `noteType`. Modern SN routes by `noteType` alone, so we
219
+ // only set this for editors with a stable, well-known identifier. For
220
+ // `rich-text` / `task` / `spreadsheet` / `authentication` we omit it
221
+ // intentionally — `noteType` is sufficient and a wrong identifier would
222
+ // mask the type.
223
+ const editorIdentifier = EDITOR_IDENTIFIERS[resolvedType];
224
+ const previewPlain = resolvedType === "plain-text" || resolvedType === "markdown"
225
+ ? note.text.slice(0, 160)
226
+ : undefined;
227
+ // Start from the unmodelled keys of the original so edits never strip
228
+ // app state we don't manage, then lay the managed fields on top.
229
+ const extra = note.extra ?? {};
230
+ const prevAppData = typeof extra.appData === "object" && extra.appData !== null
231
+ ? extra.appData
232
+ : {};
233
+ const prevSnDomain = typeof prevAppData[SN_APP_DOMAIN] === "object" &&
234
+ prevAppData[SN_APP_DOMAIN] !== null
235
+ ? prevAppData[SN_APP_DOMAIN]
236
+ : {};
237
+ const contentObj = {
238
+ ...extra,
239
+ text: note.text,
240
+ title: note.title,
241
+ noteType: resolvedType,
242
+ references: note.references ?? [],
243
+ appData: {
244
+ ...prevAppData,
245
+ [SN_APP_DOMAIN]: {
246
+ ...prevSnDomain,
247
+ client_updated_at: new Date().toISOString(),
248
+ },
249
+ },
250
+ };
251
+ if (editorIdentifier)
252
+ contentObj.editorIdentifier = editorIdentifier;
253
+ if (previewPlain !== undefined)
254
+ contentObj.preview_plain = previewPlain;
255
+ if (note.trashed)
256
+ contentObj.trashed = true;
257
+ if (note.archived)
258
+ contentObj.archived = true;
259
+ if (note.pinned)
260
+ contentObj.pinned = true;
261
+ const contentJson = JSON.stringify(contentObj);
262
+ const content = await encryptString(contentJson, perItemKey, aad);
263
+ const enc_item_key = await encryptString(await toHex(perItemKey), itemsKey.itemsKey, aad);
264
+ return {
265
+ content,
266
+ enc_item_key,
267
+ items_key_id: itemsKey.uuid,
268
+ };
269
+ }
270
+ export async function decryptTag(item, itemsKeyByUuid) {
271
+ const keyId = item.items_key_id;
272
+ if (!keyId) {
273
+ throw new Error(`Tag ${item.uuid} has no items_key_id`);
274
+ }
275
+ const itemsKey = itemsKeyByUuid.get(keyId);
276
+ if (!itemsKey) {
277
+ throw new Error(`Unknown items_key ${keyId} for tag ${item.uuid}`);
278
+ }
279
+ const itemKeyHex = await decryptString(item.enc_item_key, itemsKey, item.uuid);
280
+ const perItemKey = await fromHex(itemKeyHex);
281
+ const contentJson = await decryptString(item.content, perItemKey, item.uuid);
282
+ const content = parseDecryptedContent(contentJson, "tag", item.uuid);
283
+ const references = Array.isArray(content.references)
284
+ ? content.references
285
+ .filter((r) => typeof r?.uuid === "string" && typeof r?.content_type === "string")
286
+ .map((r) => {
287
+ const out = { uuid: r.uuid, content_type: r.content_type };
288
+ if (typeof r.reference_type === "string") {
289
+ out.reference_type = r.reference_type;
290
+ }
291
+ return out;
292
+ })
293
+ : [];
294
+ return {
295
+ uuid: item.uuid,
296
+ title: content.title ?? "",
297
+ references,
298
+ createdAt: item.created_at ?? "",
299
+ updatedAt: item.updated_at ?? "",
300
+ created_at_timestamp: item.created_at_timestamp ?? 0,
301
+ updated_at_timestamp: item.updated_at_timestamp ?? 0,
302
+ };
303
+ }
304
+ export async function encryptTag(tag, itemsKey) {
305
+ const perItemKey = await generateItemsKeyRaw();
306
+ // Same AAD rule as notes: {u, v} only. `kp` would cause the official app
307
+ // to drop the item silently (see project memory "SN 004 AAD rule").
308
+ const aad = { u: tag.uuid, v: "004" };
309
+ const contentObj = {
310
+ title: tag.title,
311
+ references: tag.references,
312
+ appData: {
313
+ [SN_APP_DOMAIN]: {
314
+ client_updated_at: new Date().toISOString(),
315
+ },
316
+ },
317
+ };
318
+ const contentJson = JSON.stringify(contentObj);
319
+ const content = await encryptString(contentJson, perItemKey, aad);
320
+ const enc_item_key = await encryptString(await toHex(perItemKey), itemsKey.itemsKey, aad);
321
+ return {
322
+ content,
323
+ enc_item_key,
324
+ items_key_id: itemsKey.uuid,
325
+ };
326
+ }
327
+ export function normalizeSuperText(text) {
328
+ try {
329
+ const parsed = JSON.parse(text);
330
+ if (parsed &&
331
+ typeof parsed === "object" &&
332
+ "root" in parsed &&
333
+ parsed.root &&
334
+ typeof parsed.root === "object" &&
335
+ parsed.root.type === "root" &&
336
+ Array.isArray(parsed.root.children)) {
337
+ return text;
338
+ }
339
+ }
340
+ catch {
341
+ // fall through to wrap
342
+ }
343
+ return JSON.stringify({
344
+ root: {
345
+ children: [
346
+ {
347
+ children: [
348
+ {
349
+ detail: 0,
350
+ format: 0,
351
+ mode: "normal",
352
+ style: "",
353
+ text,
354
+ type: "text",
355
+ version: 1,
356
+ },
357
+ ],
358
+ direction: "ltr",
359
+ format: "",
360
+ indent: 0,
361
+ type: "paragraph",
362
+ version: 1,
363
+ },
364
+ ],
365
+ direction: "ltr",
366
+ format: "",
367
+ indent: 0,
368
+ type: "root",
369
+ version: 1,
370
+ },
371
+ });
372
+ }
373
+ /**
374
+ * Smart Views are saved searches: syncable items with content_type
375
+ * "SN|SmartView" whose decrypted content is { title, predicate }. The
376
+ * predicate tree is evaluated locally by src/sn/predicates.ts.
377
+ */
378
+ export async function decryptSmartView(item, itemsKeyByUuid) {
379
+ const keyId = item.items_key_id;
380
+ if (!keyId) {
381
+ throw new Error(`SmartView ${item.uuid} has no items_key_id`);
382
+ }
383
+ const itemsKey = itemsKeyByUuid.get(keyId);
384
+ if (!itemsKey) {
385
+ throw new Error(`Unknown items_key ${keyId} for smart view ${item.uuid}`);
386
+ }
387
+ const itemKeyHex = await decryptString(item.enc_item_key, itemsKey, item.uuid);
388
+ const perItemKey = await fromHex(itemKeyHex);
389
+ const contentJson = await decryptString(item.content, perItemKey, item.uuid);
390
+ const content = parseDecryptedContent(contentJson, "smart view", item.uuid);
391
+ return {
392
+ uuid: item.uuid,
393
+ title: content.title ?? "",
394
+ predicate: content.predicate ?? null,
395
+ createdAt: item.created_at ?? "",
396
+ updatedAt: item.updated_at ?? "",
397
+ created_at_timestamp: item.created_at_timestamp ?? 0,
398
+ updated_at_timestamp: item.updated_at_timestamp ?? 0,
399
+ };
400
+ }
401
+ //# sourceMappingURL=protocol004.js.map
@@ -0,0 +1,68 @@
1
+ import { subtreeTagUuids } from "./tagHierarchy.js";
2
+ import { logger } from "../security/logger.js";
3
+ function resolveTag(tags, name) {
4
+ return (tags.get(name) ??
5
+ [...tags.values()].find((t) => t.title.toLowerCase() === name.toLowerCase()) ??
6
+ null);
7
+ }
8
+ function notesUnder(tags, names, label) {
9
+ const notes = new Set();
10
+ const tagUuids = new Set();
11
+ for (const name of names) {
12
+ const matched = resolveTag(tags, name);
13
+ if (!matched) {
14
+ logger.warn(`Scope entry "${name}" (${label}) matches no tag; skipping`);
15
+ continue;
16
+ }
17
+ for (const uuid of subtreeTagUuids(tags, matched.uuid)) {
18
+ tagUuids.add(uuid);
19
+ const t = tags.get(uuid);
20
+ if (!t)
21
+ continue;
22
+ for (const r of t.references) {
23
+ if (r.content_type === "Note")
24
+ notes.add(r.uuid);
25
+ }
26
+ }
27
+ }
28
+ return { notes, tagUuids };
29
+ }
30
+ /**
31
+ * Resolve the configured scope against the current tag cache. Returns null
32
+ * when no scoping is configured so callers can skip filtering entirely.
33
+ * Re-resolved per call: tag membership changes with every sync.
34
+ */
35
+ export function resolveScope(tags, scope) {
36
+ if (scope.readTags === null && scope.denyTags.length === 0)
37
+ return null;
38
+ const read = scope.readTags !== null
39
+ ? notesUnder(tags, scope.readTags, "SN_READ_TAGS")
40
+ : null;
41
+ const denied = notesUnder(tags, scope.denyTags, "SN_DENY_TAGS");
42
+ let allowRoots = null;
43
+ if (scope.readTags !== null) {
44
+ allowRoots = new Set();
45
+ for (const name of scope.readTags) {
46
+ const matched = resolveTag(tags, name);
47
+ if (matched)
48
+ allowRoots.add(matched.uuid);
49
+ }
50
+ }
51
+ return {
52
+ allow: read !== null ? read.notes : null,
53
+ deny: denied.notes,
54
+ hiddenTags: denied.tagUuids,
55
+ allowTags: read !== null ? read.tagUuids : null,
56
+ allowRoots,
57
+ };
58
+ }
59
+ export function scopeAllows(scope, noteUuid) {
60
+ if (scope === null)
61
+ return true;
62
+ if (scope.deny.has(noteUuid))
63
+ return false;
64
+ if (scope.allow !== null && !scope.allow.has(noteUuid))
65
+ return false;
66
+ return true;
67
+ }
68
+ //# sourceMappingURL=scope.js.map