langmail-mcp 0.0.0 → 0.2.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 (138) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +89 -169
  3. package/dist/chunk-0fxfqny0.js +12642 -0
  4. package/dist/langmail-mcp.js +7 -0
  5. package/package.json +93 -98
  6. package/THIRD_PARTY_NOTICES.md +0 -388
  7. package/dist/attachments/download.js +0 -69
  8. package/dist/attachments/routes.js +0 -42
  9. package/dist/attachments/tickets.js +0 -45
  10. package/dist/attachments/upload-tickets.js +0 -43
  11. package/dist/attachments/upload.js +0 -136
  12. package/dist/caldav/account-settings.js +0 -92
  13. package/dist/caldav/agenda.js +0 -277
  14. package/dist/caldav/alarm.js +0 -97
  15. package/dist/caldav/client.js +0 -408
  16. package/dist/caldav/ical.js +0 -248
  17. package/dist/caldav/occurrence.js +0 -534
  18. package/dist/caldav/recurrence.js +0 -313
  19. package/dist/caldav/rsvp.js +0 -107
  20. package/dist/caldav/scheduling-handover.js +0 -22
  21. package/dist/caldav/timezone.js +0 -103
  22. package/dist/caldav/types.js +0 -5
  23. package/dist/config.js +0 -219
  24. package/dist/contacts/address-class.js +0 -79
  25. package/dist/contacts/birthdays.js +0 -81
  26. package/dist/contacts/card.js +0 -58
  27. package/dist/contacts/constants.js +0 -46
  28. package/dist/contacts/fold.js +0 -309
  29. package/dist/contacts/index.js +0 -10
  30. package/dist/contacts/merge.js +0 -388
  31. package/dist/contacts/observations.js +0 -115
  32. package/dist/contacts/profile.js +0 -402
  33. package/dist/contacts/scoring.js +0 -146
  34. package/dist/contacts/types.js +0 -7
  35. package/dist/contacts/upsert.js +0 -131
  36. package/dist/drafts/attachments.js +0 -254
  37. package/dist/drafts/idempotency.js +0 -60
  38. package/dist/drafts/send-guard.js +0 -184
  39. package/dist/email-render/email-viewer.html +0 -143
  40. package/dist/email-render/image-proxy.js +0 -389
  41. package/dist/email-render/meta.js +0 -48
  42. package/dist/email-render/sanitize.js +0 -93
  43. package/dist/email-render/viewer-resource.js +0 -104
  44. package/dist/http/bearer.js +0 -30
  45. package/dist/http/guard.js +0 -57
  46. package/dist/http/hosts.js +0 -10
  47. package/dist/http/listener.js +0 -170
  48. package/dist/http/routes.js +0 -72
  49. package/dist/ical/ical-parse.js +0 -357
  50. package/dist/ical/index.js +0 -4
  51. package/dist/ical/timezone.js +0 -22
  52. package/dist/ical/windows-zones.js +0 -155
  53. package/dist/index.js +0 -79
  54. package/dist/jmap/blob.js +0 -49
  55. package/dist/jmap/contacts.js +0 -226
  56. package/dist/jmap/drafts.js +0 -480
  57. package/dist/jmap/email.js +0 -668
  58. package/dist/jmap/index.js +0 -12
  59. package/dist/jmap/keywords.js +0 -22
  60. package/dist/jmap/live.js +0 -21
  61. package/dist/jmap/origin.js +0 -113
  62. package/dist/jmap/patch.js +0 -29
  63. package/dist/jmap/request.js +0 -37
  64. package/dist/jmap/session.js +0 -89
  65. package/dist/jmap/sieve.js +0 -71
  66. package/dist/jmap/submission.js +0 -107
  67. package/dist/jmap/timeout.js +0 -30
  68. package/dist/jmap/types.js +0 -6
  69. package/dist/logger.js +0 -48
  70. package/dist/mcp/handler.js +0 -255
  71. package/dist/mcp/http.js +0 -29
  72. package/dist/mcp/instructions.js +0 -44
  73. package/dist/mcp/links.js +0 -64
  74. package/dist/mcp/test-client.js +0 -43
  75. package/dist/mcp/tool-logging.js +0 -67
  76. package/dist/observability/errors.js +0 -41
  77. package/dist/rules/apply.js +0 -236
  78. package/dist/rules/rule.js +0 -280
  79. package/dist/rules/store.js +0 -92
  80. package/dist/tools/annotations.js +0 -71
  81. package/dist/tools/archive-emails.js +0 -40
  82. package/dist/tools/calendar-lookup.js +0 -64
  83. package/dist/tools/contact-common.js +0 -146
  84. package/dist/tools/contact-format.js +0 -72
  85. package/dist/tools/contact-write-through.js +0 -37
  86. package/dist/tools/create-calendar-event.js +0 -231
  87. package/dist/tools/create-calendar.js +0 -54
  88. package/dist/tools/create-contact.js +0 -172
  89. package/dist/tools/create-draft.js +0 -369
  90. package/dist/tools/create-mail-rule.js +0 -101
  91. package/dist/tools/delete-calendar-event.js +0 -165
  92. package/dist/tools/delete-contact.js +0 -60
  93. package/dist/tools/delete-draft.js +0 -129
  94. package/dist/tools/delete-mail-rule.js +0 -38
  95. package/dist/tools/download-attachment.js +0 -90
  96. package/dist/tools/download-email.js +0 -112
  97. package/dist/tools/draft-common.js +0 -600
  98. package/dist/tools/email-types.js +0 -58
  99. package/dist/tools/error-detail.js +0 -10
  100. package/dist/tools/file-emails-common.js +0 -75
  101. package/dist/tools/format.js +0 -131
  102. package/dist/tools/forward-message.js +0 -237
  103. package/dist/tools/forward-quote.js +0 -179
  104. package/dist/tools/get-draft.js +0 -61
  105. package/dist/tools/get-email.js +0 -164
  106. package/dist/tools/get-thread.js +0 -67
  107. package/dist/tools/keywords.js +0 -43
  108. package/dist/tools/list-calendar-events.js +0 -180
  109. package/dist/tools/list-calendars.js +0 -44
  110. package/dist/tools/list-drafts.js +0 -134
  111. package/dist/tools/list-mail-rules.js +0 -28
  112. package/dist/tools/list-unsubscribe.js +0 -152
  113. package/dist/tools/list-upcoming-birthdays.js +0 -165
  114. package/dist/tools/mail-rule-common.js +0 -43
  115. package/dist/tools/mail-rule-format.js +0 -79
  116. package/dist/tools/mailbox-lookup.js +0 -13
  117. package/dist/tools/mark-emails.js +0 -78
  118. package/dist/tools/merge-contacts.js +0 -145
  119. package/dist/tools/move-calendar-events.js +0 -340
  120. package/dist/tools/move-emails.js +0 -64
  121. package/dist/tools/one-click-post.js +0 -275
  122. package/dist/tools/preview-email.js +0 -204
  123. package/dist/tools/preview-mail-rule.js +0 -79
  124. package/dist/tools/reply-quote.js +0 -426
  125. package/dist/tools/reply-to-message.js +0 -292
  126. package/dist/tools/respond-to-event.js +0 -110
  127. package/dist/tools/result.js +0 -9
  128. package/dist/tools/search-contacts.js +0 -431
  129. package/dist/tools/search-emails.js +0 -570
  130. package/dist/tools/send-draft.js +0 -308
  131. package/dist/tools/trash-emails.js +0 -36
  132. package/dist/tools/unsubscribe-from-list.js +0 -249
  133. package/dist/tools/update-calendar-event.js +0 -973
  134. package/dist/tools/update-calendar.js +0 -100
  135. package/dist/tools/update-contact.js +0 -382
  136. package/dist/tools/update-draft.js +0 -714
  137. package/dist/tools/update-mail-rule.js +0 -103
  138. package/dist/tools/upload-attachments.js +0 -126
@@ -1,389 +0,0 @@
1
- // Image proxy for the email-viewer: remote images referenced by an email's
2
- // HTML are fetched by this server and streamed to the iframe, so the
3
- // client never contacts the sender's (tracking) domains.
4
- //
5
- // This is traffic to hosts the sender chose, so it exists only when the user
6
- // turns it on (LANGMAIL_MCP_ALLOW_REMOTE_IMAGES). Without the flag there is no
7
- // store and no route, and preview_email drops remote images.
8
- //
9
- // Same capability-URL model as /attachments/<ticket>: preview_email mints an
10
- // unguessable token per remote URL; GET /image-proxy/<token> redeems it.
11
- // In-memory state is fine — one process, and a restart only breaks image
12
- // URLs inside an already-rendered preview until the tool is re-called.
13
- //
14
- // The upstream URL is sender-controlled, so this is an SSRF surface:
15
- // `isProxyableImageUrl` gates what gets minted (https, default port, public
16
- // hostname shape, no credentials); at fetch time the hostname is resolved,
17
- // every address must be public, and the connection is pinned to the checked
18
- // address (resolve-and-pin), so a DNS-rebinding domain cannot swap in an
19
- // internal one between check and connect. Redirects are refused rather than
20
- // followed, and the response must be a raster image type within a byte cap
21
- // enforced on the actual stream, not the declared length.
22
- import { lookup } from "node:dns/promises";
23
- import https from "node:https";
24
- import { BlockList, isIPv4, isIPv6 } from "node:net";
25
- import { Readable } from "node:stream";
26
- import { logger } from "../logger.js";
27
- // A day, not minutes: these URLs are embedded in a rendered preview the user
28
- // re-opens from conversation scrollback — a short TTL turns every image into
29
- // a broken icon an hour later. The store is in-memory, so a restart still
30
- // invalidates everything; that residual gap needs signed stateless URLs.
31
- const IMAGE_PROXY_TTL_HOURS = 24;
32
- const TTL_MS = IMAGE_PROXY_TTL_HOURS * 60 * 60 * 1000;
33
- // Big enough for any real inline/hero image; a 4K photo attachment is not
34
- // what an email body embeds.
35
- const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
36
- const FETCH_TIMEOUT_MS = 10_000;
37
- // Hostname shapes that smell like an internal target rather than a public
38
- // image host. A cheap mint-time filter; the resolved address is checked again
39
- // at fetch time (`isPublicAddress`), which is the actual SSRF defense.
40
- const IP_LITERAL_RE = /^(\d{1,3}\.){3}\d{1,3}$/;
41
- const INTERNAL_SUFFIXES = [".internal", ".local", ".localdomain"];
42
- export const isProxyableImageUrl = (raw) => {
43
- let url;
44
- try {
45
- url = new URL(raw);
46
- }
47
- catch {
48
- return false;
49
- }
50
- if (url.protocol !== "https:" ||
51
- url.port !== "" ||
52
- url.username !== "" ||
53
- url.password !== "") {
54
- return false;
55
- }
56
- const host = url.hostname.toLowerCase();
57
- if (host === "localhost" ||
58
- IP_LITERAL_RE.test(host) ||
59
- host.startsWith("[")) {
60
- return false;
61
- }
62
- if (!host.includes(".") || INTERNAL_SUFFIXES.some((s) => host.endsWith(s))) {
63
- return false;
64
- }
65
- return true;
66
- };
67
- // Non-public ranges a resolved upstream address must not fall into. An
68
- // IPv4-mapped IPv6 address (::ffff:10.0.0.1) is matched against the IPv4
69
- // rules by BlockList itself.
70
- const NON_PUBLIC_RANGES = [
71
- ["0.0.0.0", 8, "ipv4"], // "this network"
72
- ["10.0.0.0", 8, "ipv4"], // RFC 1918
73
- ["100.64.0.0", 10, "ipv4"], // CGNAT, also the tailnet range
74
- ["127.0.0.0", 8, "ipv4"], // loopback
75
- ["169.254.0.0", 16, "ipv4"], // link-local, cloud metadata
76
- ["172.16.0.0", 12, "ipv4"], // RFC 1918
77
- ["192.0.0.0", 24, "ipv4"], // IETF protocol assignments
78
- ["192.168.0.0", 16, "ipv4"], // RFC 1918
79
- ["198.18.0.0", 15, "ipv4"], // benchmarking
80
- ["224.0.0.0", 4, "ipv4"], // multicast
81
- ["240.0.0.0", 4, "ipv4"], // reserved, broadcast
82
- ["::", 96, "ipv6"], // unspecified, loopback, IPv4-compatible
83
- ["::ffff:0:0:0", 96, "ipv6"], // SIIT, embeds an IPv4 address
84
- ["64:ff9b::", 96, "ipv6"], // NAT64, embeds an IPv4 address
85
- ["64:ff9b:1::", 48, "ipv6"], // local-use NAT64
86
- ["2002::", 16, "ipv6"], // 6to4, embeds an IPv4 address
87
- ["fc00::", 7, "ipv6"], // unique local
88
- ["fec0::", 10, "ipv6"], // deprecated site-local
89
- ["fe80::", 10, "ipv6"], // link-local
90
- ["ff00::", 8, "ipv6"], // multicast
91
- ];
92
- const nonPublic = new BlockList();
93
- for (const [network, prefix, family] of NON_PUBLIC_RANGES) {
94
- nonPublic.addSubnet(network, prefix, family);
95
- }
96
- // Fails closed: BlockList.check reports an unparseable string as unblocked,
97
- // so anything that is not an IP literal is refused here.
98
- export const isPublicAddress = (address) => {
99
- if (isIPv6(address)) {
100
- return !nonPublic.check(address, "ipv6");
101
- }
102
- return isIPv4(address) && !nonPublic.check(address, "ipv4");
103
- };
104
- const resolveHost = async (hostname) => (await lookup(hostname, { all: true })).map((entry) => entry.address);
105
- const mintToken = () => {
106
- const bytes = new Uint8Array(32);
107
- crypto.getRandomValues(bytes);
108
- return Buffer.from(bytes).toString("base64url");
109
- };
110
- export const createImageProxyStore = (now = Date.now) => {
111
- const byToken = new Map();
112
- const byUrl = new Map();
113
- // Lazy sweep on mint/lookup keeps both maps bounded without a timer.
114
- const sweep = () => {
115
- const t = now();
116
- for (const [token, entry] of byToken) {
117
- if (entry.expiresAt <= t) {
118
- byToken.delete(token);
119
- byUrl.delete(entry.url);
120
- }
121
- }
122
- };
123
- return {
124
- lookup: (token) => {
125
- sweep();
126
- return byToken.get(token)?.url ?? null;
127
- },
128
- mint: (url) => {
129
- sweep();
130
- const existing = byUrl.get(url);
131
- if (existing) {
132
- // Restart the window: the preview minted just now must not ship
133
- // image URLs that inherit a nearly-spent TTL from an earlier one.
134
- const entry = byToken.get(existing);
135
- if (entry) {
136
- entry.expiresAt = now() + TTL_MS;
137
- }
138
- return existing;
139
- }
140
- const token = mintToken();
141
- byToken.set(token, { expiresAt: now() + TTL_MS, url });
142
- byUrl.set(url, token);
143
- return token;
144
- },
145
- };
146
- };
147
- const notFound = () => new Response("not found\n", { status: 404 });
148
- const upstreamError = () => new Response("upstream error\n", { status: 502 });
149
- // Raster types only. image/svg+xml deliberately fails this check: it is the
150
- // one image subtype that executes script when a browser navigates to it
151
- // directly, and this proxy serves from our origin.
152
- const RASTER_TYPES = new Set([
153
- "image/avif",
154
- "image/gif",
155
- "image/jpeg",
156
- "image/png",
157
- "image/webp",
158
- ]);
159
- const isRasterImageType = (contentType) => {
160
- const bare = (contentType.split(";")[0] ?? "").trim().toLowerCase();
161
- return RASTER_TYPES.has(bare);
162
- };
163
- // Enforce the size cap on the actual bytes, not the declared content-length —
164
- // a chunked response (no length header) must not stream unbounded. Exceeding
165
- // the limit errors the stream, which truncates the response mid-flight.
166
- export const byteLimit = (maxBytes) => {
167
- let seen = 0;
168
- return new TransformStream({
169
- transform(chunk, controller) {
170
- seen += chunk.byteLength;
171
- if (seen > maxBytes) {
172
- controller.error(new Error("image proxy byte limit exceeded"));
173
- return;
174
- }
175
- controller.enqueue(chunk);
176
- },
177
- });
178
- };
179
- // dns.lookup takes no signal, so the request deadline is raced against it:
180
- // a sender domain whose nameservers never answer must not hold the request
181
- // past FETCH_TIMEOUT_MS.
182
- const withDeadline = (promise, signal) => new Promise((resolve, reject) => {
183
- const onAbort = () => reject(signal.reason);
184
- if (signal.aborted) {
185
- onAbort();
186
- return;
187
- }
188
- signal.addEventListener("abort", onAbort, { once: true });
189
- promise
190
- .then(resolve, reject)
191
- .finally(() => signal.removeEventListener("abort", onAbort));
192
- });
193
- // Resolve the upstream hostname into the addresses to try, in order. Every
194
- // resolved address must be public: a mixed answer is a rebinding tell, not a
195
- // host worth serving images from. IPv4 goes first regardless of resolver
196
- // order: a server in a container often has no IPv6 route out.
197
- const pinCandidates = async (hostname, resolve, signal) => {
198
- const addresses = await withDeadline(resolve(hostname), signal);
199
- if (!addresses.every(isPublicAddress)) {
200
- return [];
201
- }
202
- return [
203
- ...addresses.filter((address) => !isIPv6(address)),
204
- ...addresses.filter((address) => isIPv6(address)),
205
- ];
206
- };
207
- // The URL with its hostname swapped for the pinned address. The original
208
- // hostname still goes out as the Host header and as the TLS server name, so
209
- // virtual hosting works and the certificate is verified against the name
210
- // the sender wrote, not the IP.
211
- const pinnedUrl = (url, address) => {
212
- const pinned = new URL(url);
213
- const host = isIPv6(address) ? `[${address}]` : address;
214
- pinned.hostname = host;
215
- // The hostname setter silently ignores a value it cannot parse, which
216
- // would leave the fetch unpinned; refuse instead.
217
- if (pinned.hostname !== new URL(`https://${host}`).hostname) {
218
- throw new Error("image proxy could not pin the upstream address");
219
- }
220
- return pinned.toString();
221
- };
222
- const HTTP_REDIRECT_MIN = 300;
223
- const HTTP_REDIRECT_MAX = 399;
224
- const HTTP_NO_CONTENT = 204;
225
- const HTTP_NOT_MODIFIED = 304;
226
- const firstHeader = (value) => (Array.isArray(value) ? value[0] : value) ?? "";
227
- // The upstream's answer as a `Response` whose body streams as it arrives.
228
- // Throws for what the proxy never passes on: a redirect, an encoded body.
229
- const responseOf = (res) => {
230
- const status = res.statusCode ?? 0;
231
- if (status >= HTTP_REDIRECT_MIN && status <= HTTP_REDIRECT_MAX) {
232
- throw new Error("image proxy upstream redirected");
233
- }
234
- const encoding = firstHeader(res.headers["content-encoding"]).toLowerCase();
235
- if (encoding !== "" && encoding !== "identity") {
236
- throw new Error("image proxy upstream sent an encoded body");
237
- }
238
- const headers = new Headers();
239
- for (const name of ["content-length", "content-type"]) {
240
- const value = firstHeader(res.headers[name]);
241
- if (value !== "") {
242
- headers.set(name, value);
243
- }
244
- }
245
- if (status === HTTP_NO_CONTENT || status === HTTP_NOT_MODIFIED) {
246
- res.resume();
247
- return new Response(null, { headers, status });
248
- }
249
- return new Response(Readable.toWeb(res), {
250
- headers,
251
- status,
252
- });
253
- };
254
- /**
255
- * A GET to an address-pinned https URL, on `node:https`: the global `fetch`
256
- * cannot connect to one address while checking the certificate against
257
- * another name. The socket goes to the address in `url`; the certificate must
258
- * be valid for `init.tls.serverName`, which is also what SNI and the Host
259
- * header carry. Nothing is followed: a redirect rejects. `ca` replaces the
260
- * system's trust store and is for tests.
261
- */
262
- export const makePinnedFetch = (tlsOptions = {}) => (url, init) => new Promise((resolve, reject) => {
263
- const req = https.request(url, {
264
- ...tlsOptions,
265
- // One connection per image, closed after it: nothing is pooled
266
- // under the pinned address for a later request to reuse.
267
- agent: false,
268
- headers: {
269
- // The body is passed on as it arrives, so it must arrive
270
- // unencoded.
271
- "accept-encoding": "identity",
272
- host: init.headers.host,
273
- },
274
- method: "GET",
275
- servername: init.tls.serverName,
276
- signal: init.signal,
277
- }, (res) => {
278
- try {
279
- resolve(responseOf(res));
280
- }
281
- catch (error) {
282
- res.destroy();
283
- reject(error);
284
- }
285
- });
286
- req.on("error", reject);
287
- req.end();
288
- });
289
- const pinnedFetch = makePinnedFetch();
290
- // Fetch from each checked address in turn until one connects. A pinned fetch
291
- // has no fallback of its own, so a host with one dead A record would
292
- // otherwise 502 although its other checked addresses are healthy. All tries
293
- // share the request deadline; once it passes, nothing more is tried.
294
- const fetchPinned = async (url, candidates, fetchImpl, signal) => {
295
- let lastError = new Error("image proxy has no address to try");
296
- for (const address of candidates) {
297
- try {
298
- // redirect: 'error' — a redirect could bounce to a host neither check
299
- // ever saw, so it is refused instead of followed. `pinnedFetch`
300
- // verifies the certificate against tls.serverName, not the IP, and
301
- // sends the host override; image-proxy.test.ts checks both against a
302
- // real TLS server.
303
- return await fetchImpl(pinnedUrl(url, address), {
304
- headers: { host: url.host },
305
- redirect: "error",
306
- signal,
307
- tls: { serverName: url.hostname },
308
- });
309
- }
310
- catch (error) {
311
- if (signal.aborted) {
312
- throw error;
313
- }
314
- lastError = error;
315
- }
316
- }
317
- throw lastError;
318
- };
319
- export const createImageProxy = (store, fetchImpl = pinnedFetch, resolve = resolveHost, timeoutMs = FETCH_TIMEOUT_MS) => {
320
- return async (token) => {
321
- const raw = store.lookup(token);
322
- if (!raw) {
323
- return notFound();
324
- }
325
- const url = new URL(raw);
326
- let upstream;
327
- // One deadline for the DNS lookup and the fetch together.
328
- const signal = AbortSignal.timeout(timeoutMs);
329
- try {
330
- const candidates = await pinCandidates(url.hostname, resolve, signal);
331
- if (candidates.length === 0) {
332
- // Logs neither the URL nor the resolved addresses: both are sender
333
- // infrastructure (see below).
334
- logger.warn("image proxy upstream has no public address");
335
- return upstreamError();
336
- }
337
- upstream = await fetchPinned(url, candidates, fetchImpl, signal);
338
- }
339
- catch {
340
- // Log carries no URL: the target embeds sender infrastructure and the
341
- // occasional tracking id.
342
- // A timeout during DNS is told apart from a failed connection.
343
- logger.warn(signal.aborted
344
- ? "image proxy upstream timed out"
345
- : "image proxy upstream fetch failed");
346
- return upstreamError();
347
- }
348
- const type = upstream.headers.get("content-type") ?? "";
349
- // The declared length is a fast reject; byteLimit below enforces the cap
350
- // on the real bytes for chunked/lying upstreams.
351
- const length = Number(upstream.headers.get("content-length") ?? "0");
352
- if (!(upstream.ok && isRasterImageType(type)) || length > MAX_IMAGE_BYTES) {
353
- logger.warn({ status: upstream.status }, "image proxy upstream not a usable image");
354
- return upstreamError();
355
- }
356
- const headers = new Headers({
357
- "cache-control": "private, max-age=300",
358
- // Belt and braces against active content on our origin: no sniffing
359
- // away from the raster type, and a sandbox with no capabilities if a
360
- // browser ever navigates to this URL directly.
361
- "content-security-policy": "sandbox; default-src 'none'",
362
- "content-type": type,
363
- "x-content-type-options": "nosniff",
364
- });
365
- // No content-length forwarded: fetch transparently decompresses a
366
- // gzip/brotli-encoded upstream, so the header would describe the encoded
367
- // bytes and make browsers truncate the image. Chunked streaming is fine.
368
- // Streamed through, never buffered.
369
- return new Response(upstream.body?.pipeThrough(byteLimit(MAX_IMAGE_BYTES)) ?? null, { headers });
370
- };
371
- };
372
- const IMAGE_PROXY_PREFIX = "/image-proxy/";
373
- /**
374
- * The route that redeems image-proxy tokens: `GET /image-proxy/<token>`.
375
- * Anything but a clean GET of a single token segment is a plain 404,
376
- * indistinguishable from an unknown or expired token. No `logAs`: the path is
377
- * the credential. A listener serves this route only when the user has turned
378
- * remote images on.
379
- */
380
- export const imageProxyRoute = (proxy) => ({
381
- handle: (req, url) => {
382
- const token = url.pathname.slice(IMAGE_PROXY_PREFIX.length);
383
- if (req.method === "GET" && token && !token.includes("/")) {
384
- return proxy(token);
385
- }
386
- return notFound();
387
- },
388
- path: IMAGE_PROXY_PREFIX,
389
- });
@@ -1,48 +0,0 @@
1
- // Shared between the preview_email tool (server) and the email-viewer view
2
- // (browser bundle) — keep this module dependency-free so the view bundle
3
- // stays lean.
4
- // The pre-declared MCP Apps template (SEP-1865) the preview_email tool
5
- // binds to via _meta.ui.resourceUri.
6
- export const EMAIL_VIEWER_RESOURCE_URI = "ui://langmail/email-viewer";
7
- // Result-_meta key carrying the sanitized document from tool to view. _meta
8
- // is forwarded to the iframe via ui/notifications/tool-result but is not
9
- // model context — that separation is the point (the body can be huge).
10
- export const PREVIEW_META_KEY = "me.langmail/email-preview";
11
- // The origin as a CSP source, or nothing when it is not a plain http(s)
12
- // origin. `URL.origin` cannot carry a space, a quote or a semicolon, so the
13
- // value cannot add a directive of its own.
14
- const cspImageSource = (imageOrigin) => {
15
- if (!imageOrigin) {
16
- return "";
17
- }
18
- try {
19
- const url = new URL(imageOrigin);
20
- return url.protocol === "http:" || url.protocol === "https:"
21
- ? ` ${url.origin}`
22
- : "";
23
- }
24
- catch {
25
- return "";
26
- }
27
- };
28
- // The Content-Security-Policy of the email document itself.
29
- //
30
- // The sender's CSS is kept for layout (`<style>`, `style=`), and CSS can name
31
- // URLs: `url(...)`, `@import`, `@font-face`. The MCP Apps host is meant to
32
- // stop those with the CSP the viewer template declares, but a host that does
33
- // not enforce it would let the user's client fetch from the sender, which
34
- // tells the sender the mail was opened. So the document carries its own
35
- // policy, which the browser enforces whatever the host does:
36
- // - nothing loads by default: no scripts, fonts, frames, media, connections;
37
- // - images only from `data:` URIs and this server's own origin;
38
- // - styles only inline, so `@import` of a remote sheet is refused.
39
- export const emailDocumentCsp = (imageOrigin) => `default-src 'none'; img-src data:${cspImageSource(imageOrigin)}; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'`;
40
- // Complete srcdoc document around the sanitized body. Forces a light canvas:
41
- // with no declaration of its own, a nested srcdoc document inherits the
42
- // embedder's color-scheme, and on a dark host that meant a black canvas with
43
- // white UA text — email HTML is authored against a white page, the way every
44
- // mail client renders it. The CSP comes first, before anything it governs.
45
- export const emailDocument = (body, imageOrigin) => `<!doctype html><html><head><meta charset="utf-8">` +
46
- `<meta http-equiv="Content-Security-Policy" content="${emailDocumentCsp(imageOrigin)}">` +
47
- `<meta name="color-scheme" content="light">` +
48
- `<style>body{margin:12px;background:#fff;color:#000}</style></head><body>${body}</body></html>`;
@@ -1,93 +0,0 @@
1
- // Sanitize an email's text/html part for rendering inside the MCP Apps
2
- // email-viewer iframe. Security-relevant: the input is authored by an
3
- // arbitrary sender. Scripts, event handlers, forms, and embedded frames are
4
- // removed; presentational markup (2005-era table layouts, inline styles,
5
- // <style> blocks) is kept so tickets and invoices render at full fidelity.
6
- //
7
- // Images never load from sender-controlled origins. Every <img> src is
8
- // rewritten through the caller's resolvers: `cid:` parts to a same-origin
9
- // capability URL (the ticket machinery in attachments/), remote URLs to the image
10
- // proxy. Unresolvable images are dropped. data: URIs (restricted to
11
- // data:image/) pass through — an inline QR code is exactly this shape.
12
- import sanitizeHtml from "sanitize-html";
13
- // Transform target for refused images; not in allowedTags, so sanitize-html
14
- // removes it in the same pass.
15
- const DROP_TAG = "x-dropped-img";
16
- // Raster subtypes only: data:image/svg+xml is the one image shape that can
17
- // carry markup/script, and nothing legitimate in email needs it inline.
18
- export const DATA_IMAGE_RE = /^data:image\/(?:png|jpeg|jpg|gif|webp|avif)[;,]/i;
19
- const REMOTE_RE = /^https?:\/\//i;
20
- const resolveImgSrc = (src, resolvers) => {
21
- if (!src) {
22
- return null;
23
- }
24
- if (src.startsWith("cid:")) {
25
- return resolvers.resolveCid(src.slice("cid:".length));
26
- }
27
- if (DATA_IMAGE_RE.test(src)) {
28
- return src;
29
- }
30
- if (REMOTE_RE.test(src)) {
31
- return resolvers.resolveRemote(src);
32
- }
33
- return null;
34
- };
35
- // Presentational attributes legacy email HTML leans on, allowed on any tag.
36
- const PRESENTATION_ATTRIBUTES = [
37
- "align",
38
- "valign",
39
- "bgcolor",
40
- "width",
41
- "height",
42
- "border",
43
- "cellpadding",
44
- "cellspacing",
45
- "class",
46
- "dir",
47
- "lang",
48
- "style",
49
- ];
50
- export const sanitizeEmailHtml = (html, resolvers) => sanitizeHtml(html, {
51
- allowedAttributes: {
52
- "*": PRESENTATION_ATTRIBUTES,
53
- a: [...PRESENTATION_ATTRIBUTES, "href", "name"],
54
- img: [...PRESENTATION_ATTRIBUTES, "src", "alt"],
55
- td: [...PRESENTATION_ATTRIBUTES, "colspan", "rowspan"],
56
- th: [...PRESENTATION_ATTRIBUTES, "colspan", "rowspan"],
57
- },
58
- // Links may point anywhere (the iframe sandbox governs navigation);
59
- // javascript:/data: hrefs are stripped by the scheme filter.
60
- allowedSchemes: ["http", "https", "mailto", "tel"],
61
- // Every img src surviving the transform below is either a vetted raster
62
- // data: URI or a URL our own resolvers minted under MCP_PUBLIC_URL —
63
- // http is in the list because the dev public URL is http, not because
64
- // sender-supplied http images are allowed (the transform already
65
- // rewrote or dropped those).
66
- allowedSchemesByTag: { img: ["http", "https", "data"] },
67
- allowedTags: [
68
- ...sanitizeHtml.defaults.allowedTags,
69
- "img",
70
- "style",
71
- "center",
72
- "font",
73
- "u",
74
- "big",
75
- "small",
76
- ],
77
- // <style> is required for real-world email layouts and is the one allowed
78
- // tag sanitize-html flags. The residual risk is CSS-initiated requests
79
- // (url(...), @import, @font-face), and those are contained a layer down:
80
- // the viewer renders this HTML in a script-less sandboxed iframe whose
81
- // document carries its own CSP (`emailDocumentCsp` in meta.ts), on top
82
- // of the one the host enforces for the template.
83
- allowVulnerableTags: true,
84
- transformTags: {
85
- img: (tagName, attribs) => {
86
- const src = resolveImgSrc(attribs.src, resolvers);
87
- if (!src) {
88
- return { attribs: {}, tagName: DROP_TAG };
89
- }
90
- return { attribs: { ...attribs, src }, tagName };
91
- },
92
- },
93
- });
@@ -1,104 +0,0 @@
1
- // The ui://langmail/email-viewer template: a single self-contained HTML
2
- // document, pre-declared as an MCP resource so hosts can prefetch, cache,
3
- // and security-review it before any tool runs (SEP-1865). Per-email data
4
- // never appears here — it arrives through the tool result at call time.
5
- //
6
- // The view's TypeScript (viewer/email-viewer.ts + the ext-apps App SDK) is
7
- // bundled into that document when the package is built
8
- // (scripts/build-viewer.ts writes dist/email-render/email-viewer.html). The
9
- // server only reads the file, once, and needs no bundler at run time.
10
- import { readFile } from "node:fs/promises";
11
- import { RESOURCE_MIME_TYPE, registerAppResource, } from "@modelcontextprotocol/ext-apps/server";
12
- import { EMAIL_VIEWER_RESOURCE_URI } from "./meta.js";
13
- // The built document. The same relative path leads to it from this file in
14
- // `src/email-render/` (a server run from source after a build) and from its
15
- // compiled copy in `dist/email-render/` (the package).
16
- const VIEWER_FILE = new URL("../../dist/email-render/email-viewer.html", import.meta.url);
17
- // Minimal shell the bundled view script fills in. Theme-neutral colors that
18
- // hold up on light and dark hosts; the email itself renders on white inside
19
- // the nested iframe, matching how mail clients present HTML mail.
20
- const shell = (script) => `<!doctype html>
21
- <html>
22
- <head>
23
- <meta charset="utf-8">
24
- <style>
25
- html, body { margin: 0; padding: 0; }
26
- body { font: 14px/1.5 ui-sans-serif, system-ui, sans-serif; }
27
- #header { padding: 12px 16px 10px; border-bottom: 1px solid rgba(128,128,128,.35); }
28
- #subject { font-weight: 600; font-size: 15px; margin-bottom: 2px; }
29
- #from, #date { font-size: 12.5px; opacity: .75; }
30
- #frame { display: block; width: 100%; border: 0; background: #fff; }
31
- </style>
32
- </head>
33
- <body>
34
- <div id="header"><div id="subject"></div><div id="from"></div><div id="date"></div></div>
35
- <iframe id="frame" sandbox="allow-same-origin" referrerpolicy="no-referrer" title="Email"></iframe>
36
- <script type="module">${script}</script>
37
- </body>
38
- </html>
39
- `;
40
- /**
41
- * The viewer document around its bundled script. Used by the build; the
42
- * server reads the result from disk.
43
- */
44
- export const viewerDocument = (script) =>
45
- // "</script>" inside a JS string literal would terminate the inline tag.
46
- shell(script.replaceAll("</script>", "<\\/script>"));
47
- /** A reader for the built viewer document at `file` that reads it once. */
48
- export const createViewerHtmlLoader = (file = VIEWER_FILE) => {
49
- // Memoize the promise, not the string, so concurrent first readers share
50
- // one read instead of racing their own.
51
- let cached = null;
52
- return () => {
53
- cached ??= readFile(file, "utf8").catch((err) => {
54
- // A failed read must not poison every later one.
55
- cached = null;
56
- throw new Error("the email viewer is not built: dist/email-render/email-viewer.html cannot be read. Run `npm run build`.", { cause: err });
57
- });
58
- return cached;
59
- };
60
- };
61
- export const emailViewerHtml = createViewerHtmlLoader();
62
- /**
63
- * Registers the viewer template.
64
- *
65
- * `publicUrl` is the address the previewed email's images are served under
66
- * (attachment tickets for cid images, the image proxy for remote ones): the
67
- * only origin the view may load from. Pass a string when it is known now, as
68
- * over HTTP; the listing then carries the CSP too. Pass a function when
69
- * finding it out has a cost, as over stdio, where it starts the loopback
70
- * listener: it is then called only when a host reads the template, and the
71
- * listing stays static. Hosts take the CSP from the content they read; the
72
- * listing is a fallback.
73
- */
74
- export const registerEmailViewerResource = (server, publicUrl, loadHtml = emailViewerHtml) => {
75
- // Annotated because ui is built in one place to serve both sites below:
76
- // excess-property checking only reaches fresh literals, so without the
77
- // SDK's own shape a misspelled key would travel straight to the host.
78
- const uiFor = (url) => ({
79
- // Images — cid capability URLs and proxied remote images — load from
80
- // this server only. No connectDomains: the view makes no fetches.
81
- // CSP wants origins; the public URL may carry a trailing slash or path.
82
- csp: { resourceDomains: [new URL(url).origin] },
83
- prefersBorder: true,
84
- });
85
- const listed = typeof publicUrl === "string" ? uiFor(publicUrl) : { prefersBorder: true };
86
- registerAppResource(server, "email-viewer", EMAIL_VIEWER_RESOURCE_URI, {
87
- _meta: { ui: listed },
88
- description: "Inline full-fidelity rendering of one email, fed by the preview_email tool.",
89
- mimeType: RESOURCE_MIME_TYPE,
90
- }, async () => {
91
- const text = await loadHtml();
92
- const ui = typeof publicUrl === "string" ? listed : uiFor(await publicUrl());
93
- return {
94
- contents: [
95
- {
96
- _meta: { ui },
97
- mimeType: RESOURCE_MIME_TYPE,
98
- text,
99
- uri: EMAIL_VIEWER_RESOURCE_URI,
100
- },
101
- ],
102
- };
103
- });
104
- };
@@ -1,30 +0,0 @@
1
- // The static bearer token that guards the HTTP transport.
2
- //
3
- // A caller proves it may use the server by sending
4
- // `Authorization: Bearer <MCP_AUTH_TOKEN>`. Anything else — no header, another
5
- // scheme, a wrong token — gets the same 401, and that answer says nothing
6
- // about the server behind it.
7
- import { createHash, timingSafeEqual } from "node:crypto";
8
- const HTTP_UNAUTHORIZED = 401;
9
- // The scheme name is case-insensitive (RFC 9110 §11.1); the token is not.
10
- const BEARER_RE = /^Bearer +(\S+)$/iu;
11
- const digest = (value) => createHash("sha256").update(value, "utf8").digest();
12
- const unauthorized = () => new Response(`${JSON.stringify({ error: "unauthorized" })}\n`, {
13
- headers: {
14
- "cache-control": "no-store",
15
- "content-type": "application/json",
16
- "www-authenticate": "Bearer",
17
- },
18
- status: HTTP_UNAUTHORIZED,
19
- });
20
- export const createBearerGate = (token) => {
21
- const expected = digest(token);
22
- return (req) => {
23
- const presented = BEARER_RE.exec(req.headers.get("authorization") ?? "")?.[1];
24
- // Both sides are hashed first: the digests have one length whatever was
25
- // sent, so the comparison takes the same time for every wrong token and
26
- // tells a caller nothing about the real one, not even its length.
27
- const matches = timingSafeEqual(digest(presented ?? ""), expected);
28
- return presented !== undefined && matches ? undefined : unauthorized();
29
- };
30
- };