feedkeeper 0.36.4 → 0.36.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "feedkeeper",
3
- "version": "0.36.4",
3
+ "version": "0.36.6",
4
4
  "description": "A lightweight, self-hosted RSS reader and remote MCP server for your news, blogs, and AI workflows.",
5
5
  "keywords": [
6
6
  "rss",
@@ -673,7 +673,7 @@ resourcesRouter.get("/items/:id/image", imageLimiter, async (req, res) => {
673
673
  res.status(503).json({ error: "image_busy" });
674
674
  return;
675
675
  }
676
- console.error(`[image_proxy] Failed to fetch image for item ${req.params.id} (${src}):`, error instanceof Error ? error.message : error);
676
+ console.error("[image_proxy] Failed to fetch image for item %s (%s):", req.params.id, src, error instanceof Error ? error.message : error);
677
677
  res.status(502).json({ error: "image_unavailable" });
678
678
  }
679
679
  });
@@ -1,6 +1,8 @@
1
1
  export const AVATAR_MAX_BYTES = 512 * 1024;
2
2
  /** Identify an uploaded image by its signature instead of trusting the declared type. */
3
3
  export function detectAvatarType(data) {
4
+ if (!data || (!Buffer.isBuffer(data) && !(data instanceof Uint8Array)))
5
+ return null;
4
6
  if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff)
5
7
  return "image/jpeg";
6
8
  if (data.length >= 8 && [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every((byte, index) => data[index] === byte))
@@ -3,7 +3,7 @@ import { TOTP, Secret } from "otpauth";
3
3
  import { db } from "../db/index.js";
4
4
  import { config } from "../config.js";
5
5
  export const opaque = () => randomBytes(32).toString("base64url");
6
- const hash = (text) => createHash("sha256").update(text).digest("hex");
6
+ const tokenDigest = (text) => createHash("sha256").update(text).digest("hex");
7
7
  const encryptionKey = () => createHash("sha256").update(`feedkeeper-totp:${config.sessionSecret}`).digest();
8
8
  export function seal(text) {
9
9
  const iv = randomBytes(12);
@@ -32,16 +32,16 @@ export function securityBinding(req, channel) {
32
32
  if (channel === "native-login")
33
33
  return channel;
34
34
  if (req.headers.authorization)
35
- return hash(`${channel}:${req.headers.authorization}`);
35
+ return tokenDigest(`${channel}:${req.headers.authorization}`);
36
36
  req.session ??= {};
37
37
  req.session.securityBinding ??= opaque();
38
- return hash(`${channel}:${req.session.securityBinding}`);
38
+ return tokenDigest(`${channel}:${req.session.securityBinding}`);
39
39
  }
40
40
  export function issueSecurityChallenge(purpose, userId, binding, payload, ttl = 5 * 60_000) {
41
41
  db.prepare("DELETE FROM security_challenges WHERE expires_at <= ?").run(Date.now());
42
42
  const id = opaque();
43
43
  db.prepare("INSERT INTO security_challenges (id_hash, purpose, user_id, binding, version, payload, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
44
- .run(hash(id), purpose, userId, binding, userId ? securityVersion(userId) : 0, JSON.stringify(payload), Date.now() + ttl);
44
+ .run(tokenDigest(id), purpose, userId, binding, userId ? securityVersion(userId) : 0, JSON.stringify(payload), Date.now() + ttl);
45
45
  return id;
46
46
  }
47
47
  /** Count attempts before checking the factor, including requests that end in an error. */
@@ -49,17 +49,17 @@ export function readSecurityChallenge(id, purpose, binding, consume = false) {
49
49
  if (typeof id !== "string" || !/^[\w-]{43}$/.test(id))
50
50
  return null;
51
51
  return db.transaction(() => {
52
- const row = db.prepare("SELECT * FROM security_challenges WHERE id_hash = ?").get(hash(id));
52
+ const row = db.prepare("SELECT * FROM security_challenges WHERE id_hash = ?").get(tokenDigest(id));
53
53
  if (!row || row.purpose !== purpose || row.binding !== binding || row.expires_at <= Date.now() || row.attempts >= 15 || (row.user_id && row.version !== securityVersion(row.user_id)))
54
54
  return null;
55
55
  if (consume)
56
- db.prepare("DELETE FROM security_challenges WHERE id_hash = ?").run(hash(id));
56
+ db.prepare("DELETE FROM security_challenges WHERE id_hash = ?").run(tokenDigest(id));
57
57
  else
58
- db.prepare("UPDATE security_challenges SET attempts = attempts + 1 WHERE id_hash = ?").run(hash(id));
58
+ db.prepare("UPDATE security_challenges SET attempts = attempts + 1 WHERE id_hash = ?").run(tokenDigest(id));
59
59
  return row;
60
60
  })();
61
61
  }
62
- export function discardSecurityChallenge(id) { db.prepare("DELETE FROM security_challenges WHERE id_hash = ?").run(hash(id)); }
62
+ export function discardSecurityChallenge(id) { db.prepare("DELETE FROM security_challenges WHERE id_hash = ?").run(tokenDigest(id)); }
63
63
  export function totpFor(secret, label = "FeedKeeper") {
64
64
  return new TOTP({ issuer: "FeedKeeper", label, algorithm: "SHA1", digits: 6, period: 30, secret: secret ? Secret.fromBase32(secret) : new Secret({ size: 20 }) });
65
65
  }
@@ -86,14 +86,14 @@ export function verifySecondFactor(userId, code) {
86
86
  const normalized = code.toUpperCase().replace(/[ -]/g, "");
87
87
  if (!/^[A-F0-9]{24}$/.test(normalized))
88
88
  return false;
89
- return db.prepare("DELETE FROM recovery_codes WHERE user_id = ? AND code_hash = ?").run(userId, hash(normalized)).changes === 1;
89
+ return db.prepare("DELETE FROM recovery_codes WHERE user_id = ? AND code_hash = ?").run(userId, tokenDigest(normalized)).changes === 1;
90
90
  })();
91
91
  }
92
92
  export function newRecoveryCodes(userId) {
93
93
  db.prepare("DELETE FROM recovery_codes WHERE user_id = ?").run(userId);
94
94
  const codes = Array.from({ length: 10 }, () => randomBytes(12).toString("hex").toUpperCase());
95
95
  for (const code of codes)
96
- db.prepare("INSERT INTO recovery_codes (user_id, code_hash) VALUES (?, ?)").run(userId, hash(code));
96
+ db.prepare("INSERT INTO recovery_codes (user_id, code_hash) VALUES (?, ?)").run(userId, tokenDigest(code));
97
97
  return codes.map(code => code.match(/.{6}/g).join("-"));
98
98
  }
99
99
  /**
@@ -16,7 +16,10 @@ export function pruneEmpty(node) {
16
16
  export function linkParagraph(document, url, text) {
17
17
  const paragraph = document.createElement("p");
18
18
  const link = document.createElement("a");
19
- link.setAttribute("href", url);
19
+ const parsed = parseAddress(url);
20
+ if (parsed && (parsed.protocol === "https:" || parsed.protocol === "http:")) {
21
+ link.setAttribute("href", parsed.href);
22
+ }
20
23
  link.textContent = text;
21
24
  paragraph.append(link);
22
25
  return paragraph;
@@ -174,7 +174,7 @@ export function extractFeedsFromHtml(html, baseUrl) {
174
174
  for (const match of html.matchAll(/<a\b([^>]*href=["']([^"']+)["'][^>]*)>(.*?)<\/a>/gis)) {
175
175
  const href = match[2];
176
176
  if (href.endsWith("/feed") || href.endsWith(".rss") || href.endsWith(".xml") || href.includes("/rss/")) {
177
- add(href, decodeEntities(match[3].replace(/<[^>]+>/g, "").trim()) || null, "application/rss+xml");
177
+ add(href, decodeEntities(stripHtmlTags(match[3]).trim()) || null, "application/rss+xml");
178
178
  }
179
179
  }
180
180
  for (const match of decodeEntities(html).matchAll(FEED_URL_IN_TEXT)) {
@@ -189,4 +189,13 @@ function getAttr(attrsStr, attrName) {
189
189
  return null;
190
190
  return match[1] ?? match[2] ?? match[3] ?? null;
191
191
  }
192
+ function stripHtmlTags(input) {
193
+ let text = input;
194
+ let previous;
195
+ do {
196
+ previous = text;
197
+ text = text.replace(/<[^>]+>/g, "");
198
+ } while (text !== previous);
199
+ return text;
200
+ }
192
201
  //# sourceMappingURL=discovery.js.map
@@ -37,6 +37,14 @@ function cleanConsentDom(doc) {
37
37
  }
38
38
  }
39
39
  }
40
+ function isSafeSource(value) {
41
+ if (!value)
42
+ return false;
43
+ const trimmed = value.trim();
44
+ if (trimmed.length === 0 || trimmed.length > 4000 || /^javascript:/i.test(trimmed))
45
+ return false;
46
+ return /^https?:\/\//i.test(trimmed) || /^data:image\//i.test(trimmed) || trimmed.startsWith("/");
47
+ }
40
48
  function resolveLazyImages(doc) {
41
49
  const images = doc.querySelectorAll("img");
42
50
  for (const img of images) {
@@ -45,20 +53,20 @@ function resolveLazyImages(doc) {
45
53
  img.getAttribute("data-original") ||
46
54
  img.getAttribute("data-actualsrc");
47
55
  const src = img.getAttribute("src");
48
- if (lazySrc && (!src || src.startsWith("data:") || src.length < 10 || SCRIPT_IMAGE_SOURCE.test(src))) {
49
- img.setAttribute("src", lazySrc);
56
+ if (isSafeSource(lazySrc) && (!src || src.startsWith("data:") || src.length < 10 || SCRIPT_IMAGE_SOURCE.test(src))) {
57
+ img.setAttribute("src", lazySrc.trim());
50
58
  }
51
59
  const lazySrcset = img.getAttribute("data-lazy-srcset") || img.getAttribute("data-srcset");
52
60
  const srcset = img.getAttribute("srcset");
53
- if (lazySrcset && (!srcset || srcset.startsWith("data:"))) {
54
- img.setAttribute("srcset", lazySrcset);
61
+ if (isSafeSource(lazySrcset) && (!srcset || srcset.startsWith("data:"))) {
62
+ img.setAttribute("srcset", lazySrcset.trim());
55
63
  }
56
64
  }
57
65
  const sources = doc.querySelectorAll("source");
58
66
  for (const source of sources) {
59
67
  const lazySrcset = source.getAttribute("data-lazy-srcset") || source.getAttribute("data-srcset");
60
- if (lazySrcset) {
61
- source.setAttribute("srcset", lazySrcset);
68
+ if (isSafeSource(lazySrcset)) {
69
+ source.setAttribute("srcset", lazySrcset.trim());
62
70
  }
63
71
  }
64
72
  }
@@ -58,17 +58,27 @@ function extractFeedIconUrls(parsed, baseUrl) {
58
58
  return result;
59
59
  }
60
60
  function cleanImageUrl(url) {
61
- return url.trim().replace(/&#038;/g, "&").replace(/&amp;/g, "&");
61
+ return url.trim().replace(/&(?:#038|amp);/g, "&");
62
62
  }
63
63
  function isValidImageUrl(url) {
64
64
  if (typeof url !== "string")
65
65
  return false;
66
66
  const trimmed = url.trim();
67
- if (!trimmed.startsWith("http://") && !trimmed.startsWith("https://"))
67
+ let parsed;
68
+ try {
69
+ parsed = new URL(trimmed);
70
+ }
71
+ catch {
72
+ return false;
73
+ }
74
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
75
+ return false;
76
+ const host = parsed.hostname.toLowerCase();
77
+ if (host === "pixel.wp.com" || host.endsWith(".pixel.wp.com"))
78
+ return false;
79
+ const pathAndQuery = (parsed.pathname + parsed.search).toLowerCase();
80
+ if (pathAndQuery.includes("/1x1") || pathAndQuery.includes("pixel") || pathAndQuery.includes("tracking") || pathAndQuery.includes("beacon")) {
68
81
  return false;
69
- if (trimmed.includes("/1x1") || trimmed.includes("pixel.wp.com") || trimmed.includes("tracking") || trimmed.includes("beacon")) {
70
- if (trimmed.includes("pixel") || trimmed.includes("1x1"))
71
- return false;
72
82
  }
73
83
  return true;
74
84
  }
@@ -22,7 +22,15 @@ function decodeOnce(text) {
22
22
  const TITLE_MARKUP = /<\/?(?:b|i|u|em|strong|mark|span|small|sub|sup|font|a|br)\b[^>]*>/gi;
23
23
  /** A title as one line of text: entities decoded, inline markup removed, line breaks and runs of spaces collapsed to one space, trimmed. */
24
24
  export function plainTitle(text) {
25
- const cleaned = decodeEntities(text)?.replace(TITLE_MARKUP, tag => (/^<br/i.test(tag) ? " " : "")).replace(/\s+/g, " ").trim();
25
+ let cleaned = decodeEntities(text);
26
+ if (!cleaned)
27
+ return undefined;
28
+ let previous;
29
+ do {
30
+ previous = cleaned;
31
+ cleaned = cleaned.replace(TITLE_MARKUP, tag => (/^<br/i.test(tag) ? " " : ""));
32
+ } while (cleaned !== previous);
33
+ cleaned = cleaned.replace(/\s+/g, " ").trim();
26
34
  return cleaned || undefined;
27
35
  }
28
36
  export function decodeEntities(text) {
@@ -1,9 +1,17 @@
1
1
  import { Router } from "express";
2
+ import rateLimit from "express-rate-limit";
2
3
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
3
4
  import { requireBearerToken } from "../auth/middleware.js";
4
5
  import { requireCapability } from "../auth/capabilities.js";
5
6
  import { createMcpServerForUser } from "./server.js";
7
+ const mcpLimiter = rateLimit({
8
+ windowMs: 60 * 1000,
9
+ limit: 240,
10
+ standardHeaders: true,
11
+ legacyHeaders: false,
12
+ });
6
13
  export const mcpRouter = Router();
14
+ mcpRouter.use(mcpLimiter);
7
15
  // Stateless mode: a fresh McpServer + transport per request, scoped to the
8
16
  // user resolved from the bearer token. This is what makes the same endpoint
9
17
  // safely usable by many different users/clients from anywhere.
@@ -46,9 +46,46 @@ export function createMcpServerForUser(userId, scope) {
46
46
  "and read or publish curated newspaper editions.",
47
47
  });
48
48
  const mcpUrlSchema = z.preprocess((val) => (typeof val === "string" ? normalizeUrlCandidate(val) : val), z.string().url());
49
+ const readOnlyAnnotations = {
50
+ readOnlyHint: true,
51
+ destructiveHint: false,
52
+ idempotentHint: true,
53
+ openWorldHint: false,
54
+ };
55
+ const readOnlyOpenWorldAnnotations = {
56
+ readOnlyHint: true,
57
+ destructiveHint: false,
58
+ idempotentHint: true,
59
+ openWorldHint: true,
60
+ };
61
+ const writeAdditiveAnnotations = {
62
+ readOnlyHint: false,
63
+ destructiveHint: false,
64
+ idempotentHint: false,
65
+ openWorldHint: false,
66
+ };
67
+ const writeAdditiveIdempotentAnnotations = {
68
+ readOnlyHint: false,
69
+ destructiveHint: false,
70
+ idempotentHint: true,
71
+ openWorldHint: false,
72
+ };
73
+ const writeOpenWorldAnnotations = {
74
+ readOnlyHint: false,
75
+ destructiveHint: false,
76
+ idempotentHint: false,
77
+ openWorldHint: true,
78
+ };
79
+ const writeDestructiveAnnotations = {
80
+ readOnlyHint: false,
81
+ destructiveHint: true,
82
+ idempotentHint: true,
83
+ openWorldHint: false,
84
+ };
49
85
  server.registerTool("list_feeds", {
50
86
  title: "List subscribed feeds",
51
87
  description: "Lists all RSS/Atom feeds the current user is subscribed to, including subscription settings, unread counts, and polling health status. Safe read-only operation. To inspect a single feed in detail, use get_feed. To discover new feeds, use discover_feeds.",
88
+ annotations: readOnlyAnnotations,
52
89
  inputSchema: {
53
90
  onlyWithErrors: z.boolean().optional().describe("When true, only returns feeds whose last poll failed or that have consecutive errors"),
54
91
  },
@@ -59,6 +96,7 @@ export function createMcpServerForUser(userId, scope) {
59
96
  server.registerTool("get_feed", {
60
97
  title: "Get subscribed feed details",
61
98
  description: "Returns metadata, subscription settings, polling health status, and unread count for a single subscribed feed by its numeric feed ID. Safe read-only operation. Use list_feeds to view all subscribed feeds.",
99
+ annotations: readOnlyAnnotations,
62
100
  inputSchema: {
63
101
  feedId: z.number().int().positive().describe("The numeric ID of the subscribed feed to inspect"),
64
102
  },
@@ -71,7 +109,13 @@ export function createMcpServerForUser(userId, scope) {
71
109
  if (scope === "write")
72
110
  server.registerTool("subscribe_feed", {
73
111
  title: "Subscribe to a feed",
74
- description: "Subscribes the current user to an RSS/Atom feed URL or website URL (auto-discovering the feed link if a website URL is provided). Requires write scope. Idempotent: subscribing to an already subscribed feed returns the existing subscription. Returns the subscription record.",
112
+ description: "Subscribes the current user to an RSS/Atom feed URL or website URL (auto-discovering the feed link if a website URL is provided). Requires write scope. Idempotent: subscribing to an already subscribed feed returns the existing subscription. Returns the subscription record. For API documentation, see https://github.com/visualfusion/feedkeeper.",
113
+ annotations: {
114
+ readOnlyHint: false,
115
+ destructiveHint: false,
116
+ idempotentHint: true,
117
+ openWorldHint: true,
118
+ },
75
119
  inputSchema: {
76
120
  url: mcpUrlSchema.describe("The RSS/Atom feed URL or website URL to subscribe to"),
77
121
  label: z.string().max(200).optional().describe("Optional custom display name for this feed subscription"),
@@ -101,7 +145,8 @@ export function createMcpServerForUser(userId, scope) {
101
145
  });
102
146
  server.registerTool("discover_feeds", {
103
147
  title: "Discover feeds on a website",
104
- description: "Inspects a website URL and discovers available RSS, Atom, and JSON feed links from HTML link tags. Safe read-only operation: does NOT subscribe to any feed. Returns a list of discovered candidate feed URLs and titles. Use subscribe_feed to subscribe to one of the discovered URLs.",
148
+ description: "Inspects a website URL and discovers available RSS, Atom, and JSON feed links from HTML link tags. Safe read-only operation: does NOT subscribe to any feed. Returns a list of discovered candidate feed URLs and titles. Use subscribe_feed to subscribe to one of the discovered URLs. For API documentation, see https://github.com/visualfusion/feedkeeper.",
149
+ annotations: readOnlyOpenWorldAnnotations,
105
150
  inputSchema: {
106
151
  url: mcpUrlSchema.describe("The website URL to scan for available RSS/Atom feed links"),
107
152
  },
@@ -122,6 +167,7 @@ export function createMcpServerForUser(userId, scope) {
122
167
  server.registerTool("unsubscribe_feed", {
123
168
  title: "Unsubscribe from a feed",
124
169
  description: "Unsubscribes the current user from a feed by its feed ID. Destructive action. Feeds and other users' subscriptions are unaffected. Returns { ok: true } on success.",
170
+ annotations: writeDestructiveAnnotations,
125
171
  inputSchema: {
126
172
  feedId: z.number().int().positive().describe("The numeric ID of the feed to unsubscribe from"),
127
173
  },
@@ -137,7 +183,8 @@ export function createMcpServerForUser(userId, scope) {
137
183
  if (scope === "write")
138
184
  server.registerTool("save_to_inbox", {
139
185
  title: "Save article or clipping to Universal Inbox",
140
- description: "Saves a web article URL, raw HTML, plain text/markdown clipping, or personal note directly into the user's Universal Inbox. At least one of url, contentHtml, or textContent must be provided. Returns { success: true, itemId: number, title: string, url: string, hasNote: boolean }.",
186
+ description: "Saves a web article URL, raw HTML, plain text/markdown clipping, or personal note directly into the user's Universal Inbox. At least one of url, contentHtml, or textContent must be provided. Returns { success: true, itemId: number, title: string, url: string, hasNote: boolean }. For API documentation, see https://github.com/visualfusion/feedkeeper.",
187
+ annotations: writeOpenWorldAnnotations,
141
188
  inputSchema: {
142
189
  url: mcpUrlSchema.optional().describe("Web page URL to fetch, extract via Readability, and save"),
143
190
  title: z.string().max(500).optional().describe("Optional custom title for the saved inbox item"),
@@ -171,12 +218,14 @@ export function createMcpServerForUser(userId, scope) {
171
218
  server.registerTool("list_folders", {
172
219
  title: "List folders / categories",
173
220
  description: "Lists all feed categories/folders created by the current user, including feed counts and unread article counts per folder. Safe read-only operation.",
221
+ annotations: readOnlyAnnotations,
174
222
  inputSchema: {},
175
223
  }, async () => textResult(listFoldersForUser(userId)));
176
224
  if (scope === "write")
177
225
  server.registerTool("create_folder", {
178
226
  title: "Create a feed folder",
179
227
  description: "Creates a new category folder to organize feed subscriptions. Requires write scope. Returns the created folder object with its assigned id, name, and position. Folders can be assigned to feeds using move_feed_to_folder.",
228
+ annotations: writeAdditiveAnnotations,
180
229
  inputSchema: {
181
230
  name: z.string().trim().min(1).max(100).describe("The unique display name for the new folder (1 to 100 characters)"),
182
231
  },
@@ -185,6 +234,7 @@ export function createMcpServerForUser(userId, scope) {
185
234
  server.registerTool("move_feed_to_folder", {
186
235
  title: "Move feed to folder",
187
236
  description: "Assigns a subscribed feed to a folder, or removes it from all folders (unfiled) if folderId is null. Requires write scope. Returns { ok: true } on success.",
237
+ annotations: writeAdditiveIdempotentAnnotations,
188
238
  inputSchema: {
189
239
  feedId: z.number().int().positive().describe("The numeric ID of the subscribed feed to move"),
190
240
  folderId: z.number().int().positive().nullable().describe("The target folder ID, or null to move the feed to unfiled (root level)"),
@@ -200,7 +250,13 @@ export function createMcpServerForUser(userId, scope) {
200
250
  if (scope === "write")
201
251
  server.registerTool("update_feed", {
202
252
  title: "Update feed settings",
203
- description: "Updates subscription settings for a feed: custom display name, poll interval, full-text extraction policy, push notification preference, badge counter inclusion, or updates the feed URL if the publisher relocated. Returns the updated subscription record.",
253
+ description: "Updates subscription settings for a feed: custom display name, poll interval, full-text extraction policy, push notification preference, badge counter inclusion, or updates the feed URL if the publisher relocated. Returns the updated subscription record. For API documentation, see https://github.com/visualfusion/feedkeeper.",
254
+ annotations: {
255
+ readOnlyHint: false,
256
+ destructiveHint: false,
257
+ idempotentHint: true,
258
+ openWorldHint: true,
259
+ },
204
260
  inputSchema: {
205
261
  feedId: z.number().int().positive().describe("The numeric ID of the subscribed feed to update"),
206
262
  url: mcpUrlSchema.optional().describe("New feed URL or website URL if the feed moved (auto-discovered and validated)"),
@@ -241,6 +297,7 @@ export function createMcpServerForUser(userId, scope) {
241
297
  server.registerTool("rename_folder", {
242
298
  title: "Rename a feed folder",
243
299
  description: "Renames an existing feed category folder for the current user. Requires write scope. Returns the updated folder record { id, name, position }. Returns error if folderId is not found or name is already taken.",
300
+ annotations: writeAdditiveIdempotentAnnotations,
244
301
  inputSchema: {
245
302
  folderId: z.number().int().positive().describe("The numeric ID of the folder to rename"),
246
303
  name: z.string().trim().min(1).max(100).describe("The new unique display name for the folder (1 to 100 characters)"),
@@ -259,6 +316,7 @@ export function createMcpServerForUser(userId, scope) {
259
316
  server.registerTool("delete_folder", {
260
317
  title: "Delete a feed folder",
261
318
  description: "Deletes a feed category folder. Subscribed feeds inside the folder remain intact and are moved to the root level (unfiled). Destructive action for the folder organization. Returns { ok: true } on success.",
319
+ annotations: writeDestructiveAnnotations,
262
320
  inputSchema: {
263
321
  folderId: z.number().int().positive().describe("The numeric ID of the folder to delete"),
264
322
  },
@@ -271,6 +329,7 @@ export function createMcpServerForUser(userId, scope) {
271
329
  server.registerTool("get_digest", {
272
330
  title: "Digest of recent articles grouped by feed",
273
331
  description: "Returns recent articles grouped by subscribed feed with short summaries (newest first). This is the fastest and most token-efficient way to scan what is new. Defaults to unread articles. Do NOT use this tool for pagination, full text, or deep filtering—use list_items for cursor pagination or get_new_items for unread filtering, and follow up with get_item for full article bodies.",
332
+ annotations: readOnlyAnnotations,
274
333
  inputSchema: {
275
334
  feedId: z.number().int().positive().optional().describe("Optional feed ID to limit the digest to a single feed"),
276
335
  folderId: z.number().int().positive().optional().describe("Optional folder ID to limit the digest to feeds in that folder"),
@@ -284,11 +343,13 @@ export function createMcpServerForUser(userId, scope) {
284
343
  server.registerTool("get_overview", {
285
344
  title: "Account overview and reading statistics",
286
345
  description: "Returns account-wide statistics: total subscribed feeds, total unread articles, saved/bookmarked count, top feeds with the most unread items, folder unread counts, and feeds currently experiencing poll failures. Safe read-only overview.",
346
+ annotations: readOnlyAnnotations,
287
347
  inputSchema: {},
288
348
  }, async () => textResult(buildOverview(userId)));
289
349
  server.registerTool("get_new_items", {
290
350
  title: "List unread articles with optional filters",
291
351
  description: "Returns a flat list of unread articles matching specified filters (feed, folder, search query, bookmarked status, date range). Use this tool when you specifically need unread articles as a flat list or need article HTML content. Unlike get_digest, articles are flat rather than grouped. Unlike list_items, this tool returns only unread articles and does not use cursors. Follow up with get_item for individual full articles.",
352
+ annotations: readOnlyAnnotations,
292
353
  inputSchema: {
293
354
  feedId: z.number().int().positive().optional().describe("Optional feed ID filter"),
294
355
  folderId: z.number().int().positive().optional().describe("Optional folder ID filter"),
@@ -309,6 +370,7 @@ export function createMcpServerForUser(userId, scope) {
309
370
  server.registerTool("list_items", {
310
371
  title: "Paginate items chronologically with cursors",
311
372
  description: "Lists articles chronologically with bidirectional cursor-based pagination. Use this tool for comprehensive browsing or historical paging through both read and unread articles. Pass nextCursor as 'before' to page backwards into older history, or newestCursor as 'after' to stream newly added items. Do NOT use for quick digests (use get_digest) or unread-only triage (use get_new_items).",
373
+ annotations: readOnlyAnnotations,
312
374
  inputSchema: {
313
375
  feedId: z.number().int().positive().optional().describe("Optional feed ID filter"),
314
376
  folderId: z.number().int().positive().optional().describe("Optional folder ID filter"),
@@ -330,6 +392,7 @@ export function createMcpServerForUser(userId, scope) {
330
392
  server.registerTool("get_item", {
331
393
  title: "Get single article content and metadata",
332
394
  description: "Returns full metadata and stored content (HTML or plain text) for a single subscribed article by its numeric itemId. Content is chunked at 40,000 characters; use offset and content.revision to paginate large articles. If an article only has an RSS teaser/summary and full web text is desired, call fetch_full_text.",
395
+ annotations: readOnlyAnnotations,
333
396
  inputSchema: {
334
397
  itemId: z.number().int().positive().describe("The numeric ID of the article to retrieve"),
335
398
  maxChars: z.number().int().positive().max(40_000).optional().describe("Maximum character length of content to return (up to 40,000)"),
@@ -350,6 +413,12 @@ export function createMcpServerForUser(userId, scope) {
350
413
  server.registerTool("fetch_full_text", {
351
414
  title: "Extract full web article text",
352
415
  description: "Downloads and extracts the clean, full-length article text from the original publisher website via Readability, permanently caching it on the server and returning it. Use this tool ONLY when get_item indicates that the feed provided only an excerpt or teaser. If full text is already cached, it returns cached content unless force=true is passed.",
416
+ annotations: {
417
+ readOnlyHint: false,
418
+ destructiveHint: false,
419
+ idempotentHint: true,
420
+ openWorldHint: true,
421
+ },
353
422
  inputSchema: {
354
423
  itemId: z.number().int().positive().describe("The numeric ID of the article whose full web content should be extracted"),
355
424
  force: z.boolean().optional().describe("When true, forces re-downloading and re-extracting from the web even if already cached"),
@@ -371,6 +440,7 @@ export function createMcpServerForUser(userId, scope) {
371
440
  server.registerTool("search_items", {
372
441
  title: "Search articles by keyword or phrase",
373
442
  description: "Searches article titles and summaries using SQLite FTS5 full-text search across all accessible items. Returns matching articles matching the query phrase, with optional feed, folder, bookmark, and date filters. Safe read-only search.",
443
+ annotations: readOnlyAnnotations,
374
444
  inputSchema: {
375
445
  query: z.string().min(1).max(200).describe("The search term or phrase to find in article titles and content summaries"),
376
446
  feedId: z.number().int().positive().optional().describe("Optional feed ID filter"),
@@ -383,15 +453,15 @@ export function createMcpServerForUser(userId, scope) {
383
453
  search: query, feedId, folderId, bookmarkedOnly, limit, publishedSince: since, publishedUntil: until,
384
454
  })));
385
455
  const itemActions = [
386
- ["mark_read", "Mark articles as read", "Marks one or more subscribed articles as read. Accepts a single itemId or an array of itemIds for batch processing. Idempotent: already-read articles remain read. Returns { ok: true, updated: number } where updated is the count of items that actually transitioned from unread to read.", markItemRead],
387
- ["mark_unread", "Mark articles as unread", "Marks one or more subscribed articles as unread. Accepts a single itemId or an array of itemIds for batch processing. Idempotent. Returns { ok: true, updated: number } where updated is the count of items that actually transitioned to unread.", markItemUnread],
388
- ["bookmark_item", "Bookmark articles for later", "Bookmarks (stars) one or more articles for permanent retention. Bookmarked articles retain full text and images and survive automatic retention cleanup and feed unsubscription. Idempotent. Returns { ok: true, updated: number }.", (userId, itemId) => {
456
+ ["mark_read", "Mark articles as read", "Marks one or more subscribed articles as read. Accepts a single itemId or an array of itemIds for batch processing. Idempotent: already-read articles remain read. Returns { ok: true, updated: number } where updated is the count of items that actually transitioned from unread to read.", writeAdditiveIdempotentAnnotations, markItemRead],
457
+ ["mark_unread", "Mark articles as unread", "Marks one or more subscribed articles as unread. Accepts a single itemId or an array of itemIds for batch processing. Idempotent. Returns { ok: true, updated: number } where updated is the count of items that actually transitioned to unread.", writeAdditiveIdempotentAnnotations, markItemUnread],
458
+ ["bookmark_item", "Bookmark articles for later", "Bookmarks (stars) one or more articles for permanent retention. Bookmarked articles retain full text and images and survive automatic retention cleanup and feed unsubscription. Idempotent. Returns { ok: true, updated: number }.", writeAdditiveIdempotentAnnotations, (userId, itemId) => {
389
459
  const changed = bookmarkItem(userId, itemId);
390
460
  if (changed)
391
461
  scheduleArchive(itemId);
392
462
  return changed;
393
463
  }],
394
- ["unbookmark_item", "Remove article bookmarks", "Removes bookmark status from one or more articles. Safely triggers archive pruning for unreferenced cached assets. Idempotent. Returns { ok: true, updated: number }.", (userId, itemId) => {
464
+ ["unbookmark_item", "Remove article bookmarks", "Removes bookmark status from one or more articles. Safely triggers archive pruning for unreferenced cached assets. Idempotent. Returns { ok: true, updated: number }.", writeDestructiveAnnotations, (userId, itemId) => {
395
465
  const changed = unbookmarkItem(userId, itemId);
396
466
  if (changed)
397
467
  pruneArchive();
@@ -399,8 +469,8 @@ export function createMcpServerForUser(userId, scope) {
399
469
  }],
400
470
  ];
401
471
  if (scope === "write")
402
- for (const [name, title, description, change] of itemActions) {
403
- server.registerTool(name, { title, description, inputSchema: itemSelection }, async (args) => {
472
+ for (const [name, title, description, annotations, change] of itemActions) {
473
+ server.registerTool(name, { title, description, annotations, inputSchema: itemSelection }, async (args) => {
404
474
  if (!hasUserCapability(userId, "sync"))
405
475
  return { ...textResult(capabilityDenial(userId, "sync")), isError: true };
406
476
  const itemIds = selectedItemIds(args);
@@ -413,6 +483,7 @@ export function createMcpServerForUser(userId, scope) {
413
483
  server.registerTool("mark_all_read", {
414
484
  title: "Mark all articles as read",
415
485
  description: "Marks all unread articles as read in a single operation. Can be scoped to a single feed or an entire folder. Idempotent. Returns { marked: number } with the count of newly read items.",
486
+ annotations: writeDestructiveAnnotations,
416
487
  inputSchema: {
417
488
  feedId: z.number().int().positive().optional().describe("Optional feed ID to limit the mark-all-read operation to one feed"),
418
489
  folderId: z.number().int().positive().optional().describe("Optional folder ID to limit the mark-all-read operation to one folder"),
@@ -423,12 +494,14 @@ export function createMcpServerForUser(userId, scope) {
423
494
  server.registerTool("list_muted_keywords", {
424
495
  title: "List muted keywords",
425
496
  description: "Lists all keyword filters configured for the current user. Articles matching any active muted keyword are automatically filtered out from new item views and newspaper editions. Safe read-only.",
497
+ annotations: readOnlyAnnotations,
426
498
  inputSchema: {},
427
499
  }, async () => textResult(listMutedKeywords(userId)));
428
500
  if (scope === "write")
429
501
  server.registerTool("add_muted_keyword", {
430
502
  title: "Add a muted keyword filter",
431
503
  description: "Adds a new keyword filter rule. Articles whose title or summary contains this keyword (case-insensitive) will be suppressed from feeds and editions. Requires write scope. Returns the created keyword rule { id, keyword, created_at }.",
504
+ annotations: writeAdditiveAnnotations,
432
505
  inputSchema: {
433
506
  keyword: z.string().trim().min(1).max(100).describe("The keyword phrase to filter out from feeds and editions (1 to 100 characters)"),
434
507
  },
@@ -437,6 +510,7 @@ export function createMcpServerForUser(userId, scope) {
437
510
  server.registerTool("unmute_keyword", {
438
511
  title: "Remove a muted keyword filter",
439
512
  description: "Removes an existing muted keyword filter by its numeric keywordId. Future and existing articles matching this keyword will once again be visible. Returns { ok: true } on success.",
513
+ annotations: writeDestructiveAnnotations,
440
514
  inputSchema: {
441
515
  keywordId: z.number().int().positive().describe("The numeric ID of the muted keyword rule to remove"),
442
516
  },
@@ -447,12 +521,14 @@ export function createMcpServerForUser(userId, scope) {
447
521
  server.registerTool("export_opml", {
448
522
  title: "Export feeds as OPML XML",
449
523
  description: "Exports all subscribed feeds and folder structures of the current user as an OPML 2.0 XML document. Safe read-only operation.",
524
+ annotations: readOnlyAnnotations,
450
525
  inputSchema: {},
451
526
  }, async () => ({ content: [{ type: "text", text: generateOpml(userId) }] }));
452
527
  if (scope === "write")
453
528
  server.registerTool("import_opml", {
454
529
  title: "Import feeds from OPML XML",
455
530
  description: "Imports feed subscriptions and folders from an OPML 2.0 XML string for the current user. Existing subscriptions are preserved. Requires write scope. Returns { imported: number, failed: number, foldersCreated: number }.",
531
+ annotations: writeAdditiveAnnotations,
456
532
  inputSchema: {
457
533
  opml: z.string().min(1).describe("The OPML 2.0 XML document string to parse and import"),
458
534
  },
@@ -471,6 +547,12 @@ export function createMcpServerForUser(userId, scope) {
471
547
  server.registerTool("refresh_feed", {
472
548
  title: "Refresh feed poll",
473
549
  description: "Requests an immediate poll of a subscribed feed from its origin URL and returns its updated health status, number of new items found, and error state. Respects origin HTTP cache headers and backoff pauses. Returns { success: boolean, newItems: number, error: string | null, deferred: boolean, retryAt: string | null, feed: object }.",
550
+ annotations: {
551
+ readOnlyHint: false,
552
+ destructiveHint: false,
553
+ idempotentHint: false,
554
+ openWorldHint: true,
555
+ },
474
556
  inputSchema: {
475
557
  feedId: z.number().int().positive().describe("The numeric ID of the subscribed feed to refresh"),
476
558
  },
@@ -515,11 +597,13 @@ export function createMcpServerForUser(userId, scope) {
515
597
  server.registerTool("get_edition", {
516
598
  title: "Get current curated newspaper edition",
517
599
  description: "Returns the authoritative edition state, publication metadata, article list, and revision number for the user's curated newspaper edition ('Deine Zeitung'). Returns the current revision (even if empty, expired, or dismissed), which must be passed as expectedRevision when calling publish_edition. Safe read-only.",
600
+ annotations: readOnlyAnnotations,
518
601
  inputSchema: {},
519
602
  }, async () => textResult(getEditionState(userId)));
520
603
  server.registerTool("get_edition_candidates", {
521
604
  title: "Get candidate articles for newspaper curation",
522
605
  description: "Use this tool ONLY when preparing to curate a newspaper edition with publish_edition. Returns a bounded shortlist of unread articles from the last 7 days scored for editorial curation, user reading preferences, and current revision. Do NOT use for general reading or browsing (use get_digest or get_new_items instead).",
606
+ annotations: readOnlyAnnotations,
523
607
  inputSchema: {
524
608
  limit: z.number().int().min(1).max(200).default(100).describe("Maximum number of candidate articles to evaluate (1 to 200, default: 100)"),
525
609
  },
@@ -528,12 +612,14 @@ export function createMcpServerForUser(userId, scope) {
528
612
  server.registerTool("publish_edition", {
529
613
  title: "Publish curated newspaper edition",
530
614
  description: "Publishes an ordered selection of 1 to 24 article IDs as the user's official curated edition ('Deine Zeitung'). The published edition remains available until the next edition is published or expires. Pass the revision from get_edition as expectedRevision for optimistic concurrency, and a UUID requestId for idempotent retries. Does NOT alter underlying articles. Requires write scope.",
615
+ annotations: writeAdditiveIdempotentAnnotations,
531
616
  inputSchema: publishEditionFields,
532
617
  }, async (input) => capabilityAction("editions", () => publishCuratedEdition(userId, input)));
533
618
  if (scope === "write")
534
619
  server.registerTool("dismiss_edition", {
535
620
  title: "Dismiss the current newspaper edition",
536
621
  description: "Explicitly dismisses the current curated edition so it is no longer shown as active. Requires a UUID requestId and the current revision as expectedRevision for conflict detection. Requires write scope. Returns { ok: true } on success.",
622
+ annotations: writeDestructiveAnnotations,
537
623
  inputSchema: {
538
624
  requestId: z.uuid().describe("Unique idempotency UUID for this dismiss operation"),
539
625
  expectedRevision: z.number().int().min(0).describe("The current edition revision number obtained from get_edition"),
@@ -21,7 +21,12 @@ function oauthError(res, status, error, description) {
21
21
  res.status(status).json({ error, ...(description ? { error_description: description } : {}) });
22
22
  }
23
23
  function sameResource(value) {
24
- return typeof value === "string" && value.replace(/\/+$/, "") === MCP_RESOURCE;
24
+ if (typeof value !== "string")
25
+ return false;
26
+ let normalized = value;
27
+ while (normalized.endsWith("/"))
28
+ normalized = normalized.slice(0, -1);
29
+ return normalized === MCP_RESOURCE;
25
30
  }
26
31
  const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
27
32
  /** https anywhere (optionally limited to OAUTH_ALLOWED_REDIRECT_HOSTS) or plain http on this machine. */
@@ -190,6 +195,7 @@ oauthPublicRouter.post("/oauth/revoke", tokenLimiter, ...formBodies, (req, res)
190
195
  export const oauthAuthorizeRouter = Router();
191
196
  const publicOrigin = new URL(issuer).origin;
192
197
  const loginLimiter = rateLimit({ windowMs: 15 * 60 * 1000, limit: 10, standardHeaders: true, legacyHeaders: false });
198
+ const authorizeLimiter = rateLimit({ windowMs: 15 * 60 * 1000, limit: 100, standardHeaders: true, legacyHeaders: false });
193
199
  const formOnly = express.urlencoded({ extended: false, limit: "20kb" });
194
200
  /**
195
201
  * The consent and login forms only ever post from our own pages. Browsers state that themselves in
@@ -271,7 +277,7 @@ function mayUseMcp(req, res, userId) {
271
277
  page(res, 403, renderError(req, "noAccess", getUserCapabilities(userId).manageUrl));
272
278
  return false;
273
279
  }
274
- oauthAuthorizeRouter.get("/oauth/authorize", (req, res) => {
280
+ oauthAuthorizeRouter.get("/oauth/authorize", authorizeLimiter, (req, res) => {
275
281
  const parsed = parseAuthorization(req.query);
276
282
  if (parsed.kind === "fatal") {
277
283
  page(res, 400, renderError(req, parsed.message));
@@ -332,7 +338,7 @@ oauthAuthorizeRouter.post("/oauth/authorize/login", sameOriginOnly, loginLimiter
332
338
  req.session = { userId: user.id, securityVersion: securityVersion(user.id) };
333
339
  res.redirect(303, returnTo);
334
340
  });
335
- oauthAuthorizeRouter.post("/oauth/authorize/decision", sameOriginOnly, formOnly, (req, res) => {
341
+ oauthAuthorizeRouter.post("/oauth/authorize/decision", authorizeLimiter, sameOriginOnly, formOnly, (req, res) => {
336
342
  const body = (req.body ?? {});
337
343
  const parsed = parseAuthorization(body);
338
344
  if (parsed.kind === "fatal") {
@@ -71,6 +71,34 @@ app.use(cookieSession({
71
71
  sameSite: "lax",
72
72
  secure: config.publicUrl.startsWith("https://"),
73
73
  }));
74
+ // CSRF defense for cookie-authenticated mutating requests:
75
+ // Bearer-token requests (native apps, MCP, API clients) are immune to browser cross-site forgery.
76
+ app.use((req, res, next) => {
77
+ if (req.method === "GET" || req.method === "HEAD" || req.method === "OPTIONS")
78
+ return next();
79
+ if (req.headers.authorization)
80
+ return next();
81
+ const site = req.headers["sec-fetch-site"];
82
+ if (site === "cross-site") {
83
+ res.status(403).json({ error: "csrf_forbidden" });
84
+ return;
85
+ }
86
+ const origin = req.headers.origin;
87
+ if (origin) {
88
+ try {
89
+ const publicOrigin = new URL(config.publicUrl).origin;
90
+ if (new URL(origin).origin !== publicOrigin) {
91
+ res.status(403).json({ error: "csrf_forbidden" });
92
+ return;
93
+ }
94
+ }
95
+ catch {
96
+ res.status(403).json({ error: "csrf_forbidden" });
97
+ return;
98
+ }
99
+ }
100
+ next();
101
+ });
74
102
  // Generic API rate limit as defense in depth on top of the stricter
75
103
  // per-route limiter on /api/auth/login.
76
104
  app.use("/api", rateLimit({
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feedkeeper/server",
3
- "version": "0.36.4",
3
+ "version": "0.36.6",
4
4
  "private": true,
5
5
  "type": "module"
6
6
  }