emdash 0.6.0 → 0.7.0

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 (97) hide show
  1. package/dist/{apply-B4MsLM-w.mjs → apply-5uslYdUu.mjs} +174 -17
  2. package/dist/apply-5uslYdUu.mjs.map +1 -0
  3. package/dist/astro/index.d.mts +4 -4
  4. package/dist/astro/index.mjs +7 -3
  5. package/dist/astro/index.mjs.map +1 -1
  6. package/dist/astro/middleware/auth.d.mts +4 -4
  7. package/dist/astro/middleware/redirect.mjs +1 -1
  8. package/dist/astro/middleware/request-context.mjs +6 -1
  9. package/dist/astro/middleware/request-context.mjs.map +1 -1
  10. package/dist/astro/middleware.mjs +13 -12
  11. package/dist/astro/middleware.mjs.map +1 -1
  12. package/dist/astro/types.d.mts +13 -4
  13. package/dist/astro/types.d.mts.map +1 -1
  14. package/dist/cli/index.mjs +4 -4
  15. package/dist/{content-BsBoyj8G.mjs → content-D7J5y73J.mjs} +27 -1
  16. package/dist/{content-BsBoyj8G.mjs.map → content-D7J5y73J.mjs.map} +1 -1
  17. package/dist/db/index.d.mts +2 -2
  18. package/dist/db/index.mjs +1 -1
  19. package/dist/{index-BYv0mB9g.d.mts → index-De6_Xv3v.d.mts} +77 -3
  20. package/dist/index-De6_Xv3v.d.mts.map +1 -0
  21. package/dist/index.d.mts +4 -4
  22. package/dist/index.mjs +7 -7
  23. package/dist/media/local-runtime.d.mts +4 -4
  24. package/dist/plugins/adapt-sandbox-entry.d.mts +4 -4
  25. package/dist/{query-Bk_3vKvU.mjs → query-g4Ug-9j9.mjs} +3 -3
  26. package/dist/{query-Bk_3vKvU.mjs.map → query-g4Ug-9j9.mjs.map} +1 -1
  27. package/dist/{redirect-7lGhLBNZ.mjs → redirect-CN0Rt9Ob.mjs} +66 -10
  28. package/dist/redirect-CN0Rt9Ob.mjs.map +1 -0
  29. package/dist/{runner-Fl2NcUUz.d.mts → runner-BR2xKwhn.d.mts} +2 -2
  30. package/dist/{runner-Fl2NcUUz.d.mts.map → runner-BR2xKwhn.d.mts.map} +1 -1
  31. package/dist/{runner-Cd-_WyDo.mjs → runner-tQ7BJ4T7.mjs} +211 -134
  32. package/dist/runner-tQ7BJ4T7.mjs.map +1 -0
  33. package/dist/runtime.d.mts +4 -4
  34. package/dist/{search-DI4bM2w9.mjs → search-B0effn3j.mjs} +117 -23
  35. package/dist/search-B0effn3j.mjs.map +1 -0
  36. package/dist/seed/index.d.mts +2 -2
  37. package/dist/seed/index.mjs +3 -3
  38. package/dist/{taxonomies-DbrKzDju.mjs → taxonomies-K2z0Uhnj.mjs} +2 -2
  39. package/dist/{taxonomies-DbrKzDju.mjs.map → taxonomies-K2z0Uhnj.mjs.map} +1 -1
  40. package/dist/{types-8xrvl_68.d.mts → types-C2v0c34j.d.mts} +10 -1
  41. package/dist/{types-8xrvl_68.d.mts.map → types-C2v0c34j.d.mts.map} +1 -1
  42. package/dist/{validate-CaLH1Ia2.d.mts → validate-kM8Pjuf7.d.mts} +2 -2
  43. package/dist/{validate-CaLH1Ia2.d.mts.map → validate-kM8Pjuf7.d.mts.map} +1 -1
  44. package/dist/version-BnTKdfam.mjs +7 -0
  45. package/dist/{version-Uaf2ynPX.mjs.map → version-BnTKdfam.mjs.map} +1 -1
  46. package/package.json +5 -5
  47. package/src/api/handlers/content.ts +2 -0
  48. package/src/api/schemas/content.ts +8 -0
  49. package/src/astro/integration/font-provider.ts +3 -1
  50. package/src/astro/integration/index.ts +2 -0
  51. package/src/astro/integration/runtime.ts +55 -1
  52. package/src/astro/routes/admin.astro +14 -7
  53. package/src/astro/routes/api/auth/magic-link/send.ts +2 -1
  54. package/src/astro/routes/api/auth/passkey/options.ts +2 -1
  55. package/src/astro/routes/api/auth/signup/request.ts +26 -8
  56. package/src/astro/routes/api/comments/[collection]/[contentId]/index.ts +10 -6
  57. package/src/astro/routes/api/content/[collection]/[id]/compare.ts +1 -1
  58. package/src/astro/routes/api/content/[collection]/[id]/preview-url.ts +1 -1
  59. package/src/astro/routes/api/content/[collection]/[id]/revisions.ts +1 -1
  60. package/src/astro/routes/api/content/[collection]/[id]/translations.ts +26 -0
  61. package/src/astro/routes/api/content/[collection]/[id].ts +30 -2
  62. package/src/astro/routes/api/content/[collection]/index.ts +19 -1
  63. package/src/astro/routes/api/content/[collection]/trash.ts +1 -1
  64. package/src/astro/routes/api/import/wordpress-plugin/analyze.ts +4 -3
  65. package/src/astro/routes/api/import/wordpress-plugin/execute.ts +4 -3
  66. package/src/astro/routes/api/manifest.ts +7 -0
  67. package/src/astro/routes/api/oauth/device/code.ts +2 -1
  68. package/src/astro/routes/api/oauth/device/token.ts +2 -1
  69. package/src/astro/routes/api/setup/admin-verify.ts +30 -5
  70. package/src/astro/routes/api/setup/admin.ts +32 -8
  71. package/src/astro/routes/api/setup/index.ts +5 -2
  72. package/src/astro/types.ts +9 -0
  73. package/src/auth/rate-limit.ts +50 -22
  74. package/src/auth/setup-nonce.ts +22 -0
  75. package/src/auth/trusted-proxy.ts +92 -0
  76. package/src/database/migrations/035_bounded_404_log.ts +112 -0
  77. package/src/database/migrations/runner.ts +2 -0
  78. package/src/database/repositories/content.ts +39 -0
  79. package/src/database/repositories/options.ts +25 -0
  80. package/src/database/repositories/redirect.ts +111 -8
  81. package/src/database/types.ts +9 -0
  82. package/src/emdash-runtime.ts +3 -1
  83. package/src/import/registry.ts +4 -3
  84. package/src/import/ssrf.ts +253 -12
  85. package/src/mcp/server.ts +76 -3
  86. package/src/plugins/context.ts +15 -3
  87. package/src/plugins/manager.ts +6 -0
  88. package/src/plugins/request-meta.ts +66 -15
  89. package/src/plugins/routes.ts +3 -1
  90. package/src/seed/apply.ts +26 -0
  91. package/src/visual-editing/toolbar.ts +6 -1
  92. package/dist/apply-B4MsLM-w.mjs.map +0 -1
  93. package/dist/index-BYv0mB9g.d.mts.map +0 -1
  94. package/dist/redirect-7lGhLBNZ.mjs.map +0 -1
  95. package/dist/runner-Cd-_WyDo.mjs.map +0 -1
  96. package/dist/search-DI4bM2w9.mjs.map +0 -1
  97. package/dist/version-Uaf2ynPX.mjs +0 -7
@@ -29,6 +29,13 @@ const NAT64_HEX_PATTERN = /^64:ff9b::([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;
29
29
 
30
30
  const IPV6_BRACKET_PATTERN = /^\[|\]$/g;
31
31
 
32
+ /** Match fc00::/7 ULA — first byte 0xfc or 0xfd followed by any byte. */
33
+ const IPV6_ULA_FC_PATTERN = /^fc[0-9a-f]{2}:/;
34
+ const IPV6_ULA_FD_PATTERN = /^fd[0-9a-f]{2}:/;
35
+
36
+ /** Strip trailing dots from an FQDN-form hostname ("localhost." -> "localhost"). */
37
+ const TRAILING_DOT_PATTERN = /\.+$/;
38
+
32
39
  /**
33
40
  * Private and reserved IP ranges that should never be fetched.
34
41
  *
@@ -54,13 +61,35 @@ const BLOCKED_PATTERNS: Array<{ start: number; end: number }> = [
54
61
  { start: ip4ToNum(0, 0, 0, 0), end: ip4ToNum(0, 255, 255, 255) },
55
62
  ];
56
63
 
64
+ // Bracket-stripped form is used for lookups (validateExternalUrl strips
65
+ // brackets from parsed.hostname before checking), so "::1" appears here
66
+ // without brackets. The "::1" case is already covered by isPrivateIp, but
67
+ // keeping it here makes the intent explicit and gives a clearer error
68
+ // message for the common `http://[::1]/` form.
57
69
  const BLOCKED_HOSTNAMES = new Set([
58
70
  "localhost",
59
71
  "metadata.google.internal",
60
72
  "metadata.google",
61
- "[::1]",
73
+ "::1",
62
74
  ]);
63
75
 
76
+ /**
77
+ * Wildcard DNS services that publicly resolve arbitrary IPs embedded in the
78
+ * hostname. Commonly used in local dev and by SSRF exploit tooling to bypass
79
+ * hostname-only blocklists (e.g. 127.0.0.1.nip.io -> 127.0.0.1).
80
+ *
81
+ * Matched case-insensitively as a suffix, so both the apex and any subdomain
82
+ * are blocked.
83
+ */
84
+ const BLOCKED_HOSTNAME_SUFFIXES = [
85
+ "nip.io",
86
+ "sslip.io",
87
+ "xip.io",
88
+ "traefik.me",
89
+ "lvh.me",
90
+ "localtest.me",
91
+ ];
92
+
64
93
  /** Blocked URL schemes */
65
94
  const ALLOWED_SCHEMES = new Set(["http:", "https:"]);
66
95
 
@@ -115,22 +144,34 @@ export function normalizeIPv6MappedToIPv4(ip: string): string | null {
115
144
  }
116
145
 
117
146
  function isPrivateIp(ip: string): boolean {
147
+ // Normalize IPv6 strings to lowercase. `new URL().hostname` already
148
+ // lowercases, but resolver output (from DoH or an injected resolver) may
149
+ // not. Without this, "FE80::1" bypasses the link-local check.
150
+ const normalized = ip.toLowerCase();
151
+
118
152
  // Handle IPv6 loopback
119
- if (ip === "::1" || ip === "::ffff:127.0.0.1") return true;
153
+ if (normalized === "::1" || normalized === "::ffff:127.0.0.1") return true;
120
154
 
121
155
  // Handle IPv4-mapped IPv6 in hex form (WHATWG URL parser normalizes to this)
122
156
  // e.g. ::ffff:7f00:1 -> 127.0.0.1, ::ffff:a9fe:a9fe -> 169.254.169.254
123
- const hexIpv4 = normalizeIPv6MappedToIPv4(ip);
157
+ const hexIpv4 = normalizeIPv6MappedToIPv4(normalized);
124
158
  if (hexIpv4) return isPrivateIp(hexIpv4);
125
159
 
126
160
  // Handle IPv4-mapped IPv6 in dotted-decimal form
127
- const v4Match = ip.match(IPV4_MAPPED_IPV6_DOTTED_PATTERN);
128
- const ipv4 = v4Match ? v4Match[1] : ip;
161
+ const v4Match = normalized.match(IPV4_MAPPED_IPV6_DOTTED_PATTERN);
162
+ const ipv4 = v4Match ? v4Match[1] : normalized;
129
163
 
130
164
  const num = parseIpv4(ipv4);
131
165
  if (num === null) {
132
- // If we can't parse it, block IPv6 addresses that look internal
133
- return ip.startsWith("fe80:") || ip.startsWith("fc") || ip.startsWith("fd");
166
+ // If we can't parse it, block IPv6 addresses that look internal.
167
+ // fc00::/7 is Unique Local (first byte 0xfc or 0xfd), fe80::/10 is
168
+ // link-local. Only match when followed by hex digit + colon to avoid
169
+ // collisions with hypothetical non-address strings.
170
+ return (
171
+ normalized.startsWith("fe80:") ||
172
+ IPV6_ULA_FC_PATTERN.test(normalized) ||
173
+ IPV6_ULA_FD_PATTERN.test(normalized)
174
+ );
134
175
  }
135
176
 
136
177
  return BLOCKED_PATTERNS.some((range) => num >= range.start && num <= range.end);
@@ -182,19 +223,215 @@ export function validateExternalUrl(url: string): URL {
182
223
  // Strip brackets from IPv6 hostname
183
224
  const hostname = parsed.hostname.replace(IPV6_BRACKET_PATTERN, "");
184
225
 
226
+ // Normalize the hostname for blocklist matching: lowercase + strip any
227
+ // trailing dots. WHATWG preserves trailing dots on .hostname, so without
228
+ // this normalization "localhost." and "nip.io." bypass the checks.
229
+ const normalizedHost = hostname.toLowerCase().replace(TRAILING_DOT_PATTERN, "");
230
+
185
231
  // Check against known internal hostnames
186
- if (BLOCKED_HOSTNAMES.has(hostname.toLowerCase())) {
232
+ if (BLOCKED_HOSTNAMES.has(normalizedHost)) {
187
233
  throw new SsrfError("URLs targeting internal hosts are not allowed");
188
234
  }
189
235
 
190
- // Check if hostname is an IP address in a private range
191
- if (isPrivateIp(hostname)) {
236
+ // Check against wildcard DNS services used by SSRF tooling to bypass
237
+ // hostname-only checks. Match the apex and any subdomain.
238
+ for (const suffix of BLOCKED_HOSTNAME_SUFFIXES) {
239
+ if (normalizedHost === suffix || normalizedHost.endsWith(`.${suffix}`)) {
240
+ throw new SsrfError("URLs targeting wildcard DNS services are not allowed");
241
+ }
242
+ }
243
+
244
+ // Check if hostname is an IP address in a private range. Use the
245
+ // normalized form so "127.0.0.1.." and friends don't bypass parseIpv4
246
+ // (which rejects extra trailing dots).
247
+ if (isPrivateIp(normalizedHost)) {
192
248
  throw new SsrfError("URLs targeting private IP addresses are not allowed");
193
249
  }
194
250
 
195
251
  return parsed;
196
252
  }
197
253
 
254
+ // ---------------------------------------------------------------------------
255
+ // DNS-aware validation
256
+ // ---------------------------------------------------------------------------
257
+
258
+ /**
259
+ * A resolver that maps a hostname to a list of IPv4/IPv6 addresses.
260
+ * Injectable so callers can swap in OS-level DNS on Node, stub it in tests,
261
+ * or point to a different DoH endpoint.
262
+ */
263
+ export type DnsResolver = (hostname: string) => Promise<string[]>;
264
+
265
+ /**
266
+ * Module-level default resolver. Tests can swap this with a stub so fetch
267
+ * mocks don't see unexpected DoH round-trips. Production code should leave
268
+ * it alone.
269
+ */
270
+ let defaultResolver: DnsResolver | null = null;
271
+
272
+ /** Override the default DNS resolver. Returns the previous value. */
273
+ export function setDefaultDnsResolver(resolver: DnsResolver | null): DnsResolver | null {
274
+ const previous = defaultResolver;
275
+ defaultResolver = resolver;
276
+ return previous;
277
+ }
278
+
279
+ /** Timeout for a single DoH request, in milliseconds. */
280
+ const DOH_TIMEOUT_MS = 3000;
281
+
282
+ /** Default DoH endpoint — Cloudflare's public resolver. */
283
+ const DEFAULT_DOH_URL = "https://cloudflare-dns.com/dns-query";
284
+
285
+ interface DohAnswer {
286
+ data: string;
287
+ }
288
+
289
+ interface DohResponse {
290
+ Status: number;
291
+ Answer: DohAnswer[];
292
+ }
293
+
294
+ function hasProperty<K extends string>(obj: unknown, key: K): obj is Record<K, unknown> {
295
+ return typeof obj === "object" && obj !== null && key in obj;
296
+ }
297
+
298
+ /**
299
+ * Narrow an unknown JSON body to a DohResponse shape we can read safely.
300
+ * Throws if the body doesn't look like a DoH response — a malformed body is
301
+ * indistinguishable from a failure and must not be silently treated as empty.
302
+ */
303
+ function parseDohResponse(raw: unknown): DohResponse {
304
+ if (!hasProperty(raw, "Status") || typeof raw.Status !== "number") {
305
+ throw new Error("DoH response missing Status field");
306
+ }
307
+ const answers: DohAnswer[] = [];
308
+ if (hasProperty(raw, "Answer") && Array.isArray(raw.Answer)) {
309
+ for (const entry of raw.Answer) {
310
+ if (hasProperty(entry, "data") && typeof entry.data === "string") {
311
+ answers.push({ data: entry.data });
312
+ }
313
+ }
314
+ }
315
+ return { Status: raw.Status, Answer: answers };
316
+ }
317
+
318
+ /**
319
+ * Resolve a hostname via DNS over HTTPS (Cloudflare). Returns all A and AAAA
320
+ * records. Works in both Workers and Node without requiring node:dns.
321
+ *
322
+ * Fails closed: any network error, non-2xx response, or DNS rcode != 0
323
+ * causes a rejected promise so the calling validator treats it as a block.
324
+ */
325
+ export const cloudflareDohResolver: DnsResolver = async (hostname) => {
326
+ async function query(type: "A" | "AAAA"): Promise<string[]> {
327
+ const params = new URLSearchParams({ name: hostname, type });
328
+ const controller = new AbortController();
329
+ const timeout = setTimeout(() => controller.abort(), DOH_TIMEOUT_MS);
330
+ try {
331
+ const response = await globalThis.fetch(`${DEFAULT_DOH_URL}?${params.toString()}`, {
332
+ headers: { Accept: "application/dns-json" },
333
+ signal: controller.signal,
334
+ });
335
+ if (!response.ok) {
336
+ throw new Error(`DoH lookup failed: ${response.status}`);
337
+ }
338
+ const raw = await response.json();
339
+ const body = parseDohResponse(raw);
340
+ // NXDOMAIN (3) is a legitimate "does not exist" — treat as empty.
341
+ // Any other non-zero status (SERVFAIL=2, REFUSED=5, etc.) is
342
+ // ambiguous and could be a split-view attacker hiding records
343
+ // from our resolver. Fail closed.
344
+ if (body.Status === 3) return [];
345
+ if (body.Status !== 0) {
346
+ throw new Error(`DoH ${type} lookup failed: rcode=${body.Status}`);
347
+ }
348
+ // DoH Answer arrays often include CNAME records alongside A/AAAA
349
+ // records. Their `data` is a hostname, not an IP. Filter to just
350
+ // IP literals so isPrivateIp sees real addresses.
351
+ return body.Answer.map((a) => a.data).filter(isIpLiteral);
352
+ } finally {
353
+ clearTimeout(timeout);
354
+ }
355
+ }
356
+
357
+ const [a, aaaa] = await Promise.all([query("A"), query("AAAA")]);
358
+ return [...a, ...aaaa];
359
+ };
360
+
361
+ /**
362
+ * Validate a URL and resolve its hostname to check the actual IPs against
363
+ * the private-range blocklist. This catches DNS rebinding attacks using
364
+ * attacker-controlled domains that publicly resolve to private addresses,
365
+ * and wildcard DNS services like nip.io used by exploit tooling.
366
+ *
367
+ * Runs `validateExternalUrl` first for cheap pre-flight checks (scheme,
368
+ * literal IP, known-bad hostnames). Then resolves the hostname and rejects
369
+ * if ANY returned address is private.
370
+ *
371
+ * Fails closed: if resolution fails or returns no records, throws SsrfError.
372
+ *
373
+ * **Caveats.** This does NOT fully close the TOCTOU between check and
374
+ * connect. Attacks that still work against this layer include:
375
+ *
376
+ * - TTL=0 rebind: authoritative server returns public IP to the check, then
377
+ * private IP to the subsequent fetch() a few milliseconds later.
378
+ * - Split-view via EDNS Client Subnet or source-IP inspection: the
379
+ * authoritative server returns public IP to Cloudflare's DoH resolver and
380
+ * private IP to the victim's own resolver (used by fetch()).
381
+ * - Host-file overrides or split-horizon corporate DNS on self-hosted Node.
382
+ * - Attacker-controlled rebinding services the caller has allowlisted.
383
+ *
384
+ * The only complete defense is a network-layer egress firewall. On
385
+ * Cloudflare Workers, the platform fetch pipeline provides most of that.
386
+ * On self-hosted Node, operators must restrict egress themselves.
387
+ */
388
+ export async function resolveAndValidateExternalUrl(
389
+ url: string,
390
+ options?: { resolver?: DnsResolver },
391
+ ): Promise<URL> {
392
+ const parsed = validateExternalUrl(url);
393
+
394
+ // Strip brackets from IPv6 hostnames
395
+ const hostname = parsed.hostname.replace(IPV6_BRACKET_PATTERN, "");
396
+
397
+ // If the hostname is already an IP literal, validateExternalUrl has
398
+ // already checked it against the private-range list. Skip DNS.
399
+ if (isIpLiteral(hostname)) {
400
+ return parsed;
401
+ }
402
+
403
+ const resolver = options?.resolver ?? defaultResolver ?? cloudflareDohResolver;
404
+
405
+ let addresses: string[];
406
+ try {
407
+ addresses = await resolver(hostname);
408
+ } catch (error) {
409
+ throw new SsrfError(
410
+ `Could not resolve hostname: ${error instanceof Error ? error.message : String(error)}`,
411
+ );
412
+ }
413
+
414
+ if (addresses.length === 0) {
415
+ throw new SsrfError("Hostname resolved to no addresses");
416
+ }
417
+
418
+ for (const ip of addresses) {
419
+ if (isPrivateIp(ip)) {
420
+ throw new SsrfError("Hostname resolves to a private IP address");
421
+ }
422
+ }
423
+
424
+ return parsed;
425
+ }
426
+
427
+ /** True when a string looks like an IPv4 or IPv6 literal. */
428
+ function isIpLiteral(host: string): boolean {
429
+ if (parseIpv4(host) !== null) return true;
430
+ // Very loose IPv6 heuristic — matches anything with a colon, which is
431
+ // never valid in DNS hostnames, so this is safe.
432
+ return host.includes(":");
433
+ }
434
+
198
435
  /**
199
436
  * Fetch a URL with SSRF protection on redirects.
200
437
  *
@@ -208,12 +445,16 @@ export function validateExternalUrl(url: string): URL {
208
445
  /** Headers that must be stripped when a redirect crosses origins */
209
446
  const CREDENTIAL_HEADERS = ["authorization", "cookie", "proxy-authorization"];
210
447
 
211
- export async function ssrfSafeFetch(url: string, init?: RequestInit): Promise<Response> {
448
+ export async function ssrfSafeFetch(
449
+ url: string,
450
+ init?: RequestInit,
451
+ options?: { resolver?: DnsResolver },
452
+ ): Promise<Response> {
212
453
  let currentUrl = url;
213
454
  let currentInit = init;
214
455
 
215
456
  for (let i = 0; i <= MAX_REDIRECTS; i++) {
216
- validateExternalUrl(currentUrl);
457
+ await resolveAndValidateExternalUrl(currentUrl, options);
217
458
 
218
459
  const response = await globalThis.fetch(currentUrl, {
219
460
  ...currentInit,
package/src/mcp/server.ts CHANGED
@@ -84,6 +84,15 @@ interface EmDashExtra {
84
84
  tokenScopes?: string[];
85
85
  }
86
86
 
87
+ function isPublished(t: unknown): boolean {
88
+ return (
89
+ typeof t === "object" &&
90
+ t !== null &&
91
+ "status" in t &&
92
+ (t as Record<string, unknown>).status === "published"
93
+ );
94
+ }
95
+
87
96
  function getExtra(extra: { authInfo?: { extra?: Record<string, unknown> } }): EmDashExtra {
88
97
  const payload = extra.authInfo?.extra as EmDashExtra | undefined;
89
98
  if (!payload?.emdash) {
@@ -130,6 +139,26 @@ function requireRole(
130
139
  }
131
140
  }
132
141
 
142
+ /**
143
+ * Whether the current user may read non-published content (drafts, scheduled,
144
+ * trashed, revisions, compare). SUBSCRIBER may hold content:read for
145
+ * member-only published content but must not see drafts.
146
+ */
147
+ function canReadDrafts(extra: { authInfo?: { extra?: Record<string, unknown> } }): boolean {
148
+ const payload = getExtra(extra);
149
+ return hasPermission({ role: payload.userRole }, "content:read_drafts");
150
+ }
151
+
152
+ /**
153
+ * Throw if the current user cannot read non-published content. Used by
154
+ * editor-only views (revisions, compare, trash, preview-url).
155
+ */
156
+ function requireDraftAccess(extra: { authInfo?: { extra?: Record<string, unknown> } }): void {
157
+ if (!canReadDrafts(extra)) {
158
+ throw new McpError(ErrorCode.InvalidRequest, "Insufficient permissions for this operation");
159
+ }
160
+ }
161
+
133
162
  /**
134
163
  * Enforce ownership-based permission checks, mirroring the REST API's
135
164
  * requireOwnerPerm() pattern.
@@ -240,9 +269,12 @@ export function createMcpServer(): McpServer {
240
269
  async (args, extra) => {
241
270
  requireScope(extra, "content:read");
242
271
  const ec = getEmDash(extra);
272
+ // Subscribers must only see published content; force the status
273
+ // filter regardless of caller-supplied value.
274
+ const status = canReadDrafts(extra) ? args.status : "published";
243
275
  return unwrap(
244
276
  await ec.handleContentList(args.collection, {
245
- status: args.status,
277
+ status,
246
278
  limit: args.limit,
247
279
  cursor: args.cursor,
248
280
  orderBy: args.orderBy,
@@ -276,7 +308,29 @@ export function createMcpServer(): McpServer {
276
308
  async (args, extra) => {
277
309
  requireScope(extra, "content:read");
278
310
  const ec = getEmDash(extra);
279
- return unwrap(await ec.handleContentGet(args.collection, args.id, args.locale));
311
+ const result = await ec.handleContentGet(args.collection, args.id, args.locale);
312
+ // Hide non-published items from users without draft access. Return a
313
+ // not-found error so subscribers can't enumerate draft IDs by status.
314
+ if (result.success && !canReadDrafts(extra)) {
315
+ const data =
316
+ result.data && typeof result.data === "object"
317
+ ? // eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- handler returns unknown data; narrowed by typeof check
318
+ (result.data as Record<string, unknown>)
319
+ : undefined;
320
+ const item =
321
+ data?.item && typeof data.item === "object"
322
+ ? // eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- narrowed by typeof check
323
+ (data.item as Record<string, unknown>)
324
+ : undefined;
325
+ const status = typeof item?.status === "string" ? item.status : null;
326
+ if (status !== "published") {
327
+ return unwrap({
328
+ success: false,
329
+ error: { code: "NOT_FOUND", message: `Content item not found: ${args.id}` },
330
+ });
331
+ }
332
+ }
333
+ return unwrap(result);
280
334
  },
281
335
  );
282
336
 
@@ -676,6 +730,7 @@ export function createMcpServer(): McpServer {
676
730
  },
677
731
  async (args, extra) => {
678
732
  requireScope(extra, "content:read");
733
+ requireDraftAccess(extra);
679
734
  const ec = getEmDash(extra);
680
735
  return unwrap(await ec.handleContentCompare(args.collection, args.id));
681
736
  },
@@ -733,6 +788,7 @@ export function createMcpServer(): McpServer {
733
788
  },
734
789
  async (args, extra) => {
735
790
  requireScope(extra, "content:read");
791
+ requireDraftAccess(extra);
736
792
  const ec = getEmDash(extra);
737
793
  return unwrap(
738
794
  await ec.handleContentListTrashed(args.collection, {
@@ -780,7 +836,23 @@ export function createMcpServer(): McpServer {
780
836
  async (args, extra) => {
781
837
  requireScope(extra, "content:read");
782
838
  const ec = getEmDash(extra);
783
- return unwrap(await ec.handleContentTranslations(args.collection, args.id));
839
+ const result = await ec.handleContentTranslations(args.collection, args.id);
840
+ // Filter out non-published translations for users without draft
841
+ // access so a subscriber can't enumerate locales that aren't yet live.
842
+ if (result.success && !canReadDrafts(extra)) {
843
+ const data =
844
+ result.data && typeof result.data === "object"
845
+ ? // eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- handler returns unknown data; narrowed by typeof check
846
+ (result.data as Record<string, unknown>)
847
+ : undefined;
848
+ const translations = Array.isArray(data?.translations) ? data.translations : [];
849
+ const filtered = translations.filter(isPublished);
850
+ return unwrap({
851
+ success: true,
852
+ data: { ...data, translations: filtered },
853
+ });
854
+ }
855
+ return unwrap(result);
784
856
  },
785
857
  );
786
858
 
@@ -1460,6 +1532,7 @@ export function createMcpServer(): McpServer {
1460
1532
  },
1461
1533
  async (args, extra) => {
1462
1534
  requireScope(extra, "content:read");
1535
+ requireDraftAccess(extra);
1463
1536
  const ec = getEmDash(extra);
1464
1537
  return unwrap(
1465
1538
  await ec.handleRevisionList(args.collection, args.id, {
@@ -16,7 +16,11 @@ import { SeoRepository } from "../database/repositories/seo.js";
16
16
  import { UserRepository } from "../database/repositories/user.js";
17
17
  import { withTransaction } from "../database/transaction.js";
18
18
  import type { Database } from "../database/types.js";
19
- import { validateExternalUrl, SsrfError, stripCredentialHeaders } from "../import/ssrf.js";
19
+ import {
20
+ resolveAndValidateExternalUrl,
21
+ SsrfError,
22
+ stripCredentialHeaders,
23
+ } from "../import/ssrf.js";
20
24
  import type { Storage } from "../storage/types.js";
21
25
  import { CronAccessImpl } from "./cron.js";
22
26
  import type { EmailPipeline } from "./email.js";
@@ -599,9 +603,10 @@ export function createUnrestrictedHttpAccess(pluginId: string): HttpAccess {
599
603
  let currentInit = init;
600
604
 
601
605
  for (let i = 0; i <= MAX_PLUGIN_REDIRECTS; i++) {
602
- // Validate each URL against SSRF rules (private IPs, metadata endpoints)
606
+ // Validate each URL against SSRF rules (private IPs, metadata
607
+ // endpoints, wildcard DNS, resolved-IP private ranges).
603
608
  try {
604
- validateExternalUrl(currentUrl);
609
+ await resolveAndValidateExternalUrl(currentUrl);
605
610
  } catch (e) {
606
611
  const msg = e instanceof SsrfError ? e.message : "SSRF validation failed";
607
612
  throw new Error(
@@ -849,6 +854,13 @@ export interface PluginContextFactoryOptions {
849
854
  * If not provided (or no provider configured), ctx.email will be undefined.
850
855
  */
851
856
  emailPipeline?: EmailPipeline;
857
+ /**
858
+ * Pre-resolved list of trusted proxy header names (from the runtime
859
+ * `EmDashConfig.trustedProxyHeaders` or the env var). Plugin route
860
+ * handlers pass this to `extractRequestMeta` so plugins see the same
861
+ * client IP the core auth path does.
862
+ */
863
+ trustedProxyHeaders?: string[];
852
864
  }
853
865
 
854
866
  /**
@@ -62,6 +62,11 @@ export interface PluginManagerOptions {
62
62
  filename: string,
63
63
  contentType: string,
64
64
  ) => Promise<{ uploadUrl: string; mediaId: string }>;
65
+ /**
66
+ * Pre-resolved list of trusted proxy header names for client-IP
67
+ * resolution in plugin route handlers. Thread through from the runtime.
68
+ */
69
+ trustedProxyHeaders?: string[];
65
70
  }
66
71
 
67
72
  /**
@@ -81,6 +86,7 @@ export class PluginManager {
81
86
  db: options.db,
82
87
  storage: options.storage,
83
88
  getUploadUrl: options.getUploadUrl,
89
+ trustedProxyHeaders: options.trustedProxyHeaders,
84
90
  };
85
91
  }
86
92
 
@@ -7,6 +7,8 @@
7
7
  *
8
8
  */
9
9
 
10
+ import type { EmDashConfig } from "../astro/integration/runtime.js";
11
+ import { getTrustedProxyHeaders, normalizeTrustedHeaders } from "../auth/trusted-proxy.js";
10
12
  import type { GeoInfo, RequestMeta } from "./types.js";
11
13
 
12
14
  /**
@@ -40,6 +42,23 @@ function parseFirstForwardedIp(header: string): string | null {
40
42
  return IP_PATTERN.test(trimmed) ? trimmed : null;
41
43
  }
42
44
 
45
+ /**
46
+ * Read an IP from an operator-declared trusted header. XFF-style headers
47
+ * (any name ending in `forwarded-for`) are parsed as comma-separated lists
48
+ * and the first entry is used; everything else is treated as a single
49
+ * trimmed value.
50
+ */
51
+ function readIpFromHeader(headers: Headers, name: string): string | null {
52
+ const value = headers.get(name);
53
+ if (!value) return null;
54
+ if (name.endsWith("forwarded-for")) {
55
+ return parseFirstForwardedIp(value);
56
+ }
57
+ const trimmed = value.trim();
58
+ if (!trimmed) return null;
59
+ return IP_PATTERN.test(trimmed) ? trimmed : null;
60
+ }
61
+
43
62
  /**
44
63
  * Get the Cloudflare `cf` object from the request, if present.
45
64
  * Returns undefined when not running on Cloudflare Workers.
@@ -69,32 +88,52 @@ function extractGeo(cf: CfProperties | undefined): GeoInfo | null {
69
88
  * Extract normalized request metadata from a Request object.
70
89
  *
71
90
  * IP resolution order:
72
- * 1. `CF-Connecting-IP` header — only trusted when a `cf` object is
73
- * present on the request (proving the request came through Cloudflare's
74
- * edge, which strips/overwrites client-supplied values).
75
- * 2. `X-Forwarded-For` header (first entry) — best-effort, spoofable
76
- * when there is no trusted reverse proxy.
77
- * 3. `null`
91
+ * 1. `CF-Connecting-IP` — trusted only when a `cf` object is present on the
92
+ * request. CF edge overwrites any client-supplied value, so this is the
93
+ * cryptographically trustworthy path on Workers. Operator-declared
94
+ * trusted headers cannot override it.
95
+ * 2. `X-Forwarded-For` first entry — trusted only with a `cf` object.
96
+ * 3. Operator-declared trusted proxy headers (from `config.trustedProxyHeaders`
97
+ * or the `EMDASH_TRUSTED_PROXY_HEADERS` env var), tried in order. Used as
98
+ * the primary source off-CF and as a fill-in on CF.
99
+ * 4. `null`
100
+ *
101
+ * The second argument accepts either the EmDash config or a pre-resolved
102
+ * list of trusted headers, so callers that already have the list don't have
103
+ * to round-trip through the config every request.
78
104
  */
79
- export function extractRequestMeta(request: Request): RequestMeta {
105
+ export function extractRequestMeta(
106
+ request: Request,
107
+ configOrTrustedHeaders?: EmDashConfig | null | { trustedProxyHeaders?: string[] } | string[],
108
+ ): RequestMeta {
80
109
  const headers = request.headers;
81
110
  const cf = getCfObject(request);
111
+ const trusted = resolveTrustedHeaders(configOrTrustedHeaders);
82
112
 
83
- // IP: only trust headers when the cf object confirms we're on Cloudflare.
84
- // Without a trusted reverse proxy, X-Forwarded-For is trivially spoofable.
85
113
  let ip: string | null = null;
114
+
115
+ // On Cloudflare, prefer the cryptographically trustworthy headers first.
86
116
  if (cf) {
87
117
  const cfIp = headers.get("cf-connecting-ip")?.trim();
88
118
  if (cfIp && IP_PATTERN.test(cfIp)) {
89
119
  ip = cfIp;
90
120
  }
121
+ if (!ip) {
122
+ const xff = headers.get("x-forwarded-for");
123
+ ip = xff ? parseFirstForwardedIp(xff) : null;
124
+ }
91
125
  }
92
- if (!ip && cf) {
93
- // Only trust X-Forwarded-For when we're behind Cloudflare (which
94
- // overwrites the header). In standalone deployments without a trusted
95
- // proxy, XFF is trivially spoofable.
96
- const xff = headers.get("x-forwarded-for");
97
- ip = xff ? parseFirstForwardedIp(xff) : null;
126
+
127
+ // Fall through to operator-declared trusted headers. On CF this fills
128
+ // in when the CF headers are absent; off-CF it's the primary source.
129
+ if (!ip) {
130
+ for (const name of trusted) {
131
+ const value = readIpFromHeader(headers, name);
132
+ if (value) {
133
+ ip = value;
134
+ break;
135
+ }
136
+ }
98
137
  }
99
138
 
100
139
  const userAgent = headers.get("user-agent")?.trim() || null;
@@ -104,6 +143,18 @@ export function extractRequestMeta(request: Request): RequestMeta {
104
143
  return { ip, userAgent, referer, geo };
105
144
  }
106
145
 
146
+ function resolveTrustedHeaders(
147
+ value: EmDashConfig | null | { trustedProxyHeaders?: string[] } | string[] | undefined,
148
+ ): string[] {
149
+ if (Array.isArray(value)) {
150
+ // Apply the same RFC 7230 validation the config/env path does so a
151
+ // caller passing a pre-resolved list with bad entries can't crash
152
+ // `Headers.get()` downstream.
153
+ return normalizeTrustedHeaders(value);
154
+ }
155
+ return getTrustedProxyHeaders(value);
156
+ }
157
+
107
158
  // =============================================================================
108
159
  // Header Sanitization for Sandbox
109
160
  // =============================================================================
@@ -50,10 +50,12 @@ export interface InvokeRouteOptions {
50
50
  export class PluginRouteHandler {
51
51
  private contextFactory: PluginContextFactory;
52
52
  private plugin: ResolvedPlugin;
53
+ private trustedProxyHeaders: string[];
53
54
 
54
55
  constructor(plugin: ResolvedPlugin, factoryOptions: PluginContextFactoryOptions) {
55
56
  this.plugin = plugin;
56
57
  this.contextFactory = new PluginContextFactory(factoryOptions);
58
+ this.trustedProxyHeaders = factoryOptions.trustedProxyHeaders ?? [];
57
59
  }
58
60
 
59
61
  /**
@@ -99,7 +101,7 @@ export class PluginRouteHandler {
99
101
  ...baseContext,
100
102
  input: validatedInput,
101
103
  request: options.request,
102
- requestMeta: extractRequestMeta(options.request),
104
+ requestMeta: extractRequestMeta(options.request, this.trustedProxyHeaders),
103
105
  };
104
106
 
105
107
  // Execute handler