imap-mcp 1.2.0 → 1.4.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.
@@ -0,0 +1,276 @@
1
+ // Ported from langmail-mcp (MIT, same author): src/tools/one-click-post.ts.
2
+ //
3
+ // The one outward HTTP request on the MCP surface: an RFC 8058 one-click
4
+ // unsubscribe POST to a URL the *sender* wrote. The sender also controls that
5
+ // host's DNS, so the address check runs inside the connection's own DNS
6
+ // lookup — the IP that is checked is the IP that is dialled, and a rebinding
7
+ // answer between a check and a connect cannot slip through. Every redirect
8
+ // hop is a new request through the same guard, and must be https too.
9
+ import { lookup as dnsLookup } from "node:dns";
10
+ import https from "node:https";
11
+ import { BlockList, isIP } from "node:net";
12
+ // Ranges a sender-supplied URL must never reach: this host, the private
13
+ // network, the cloud metadata endpoint, and every reserved or translated
14
+ // range that can lead back into them.
15
+ const BLOCKED = new BlockList();
16
+ for (const [net, prefix] of [
17
+ ["0.0.0.0", 8],
18
+ ["10.0.0.0", 8],
19
+ ["100.64.0.0", 10],
20
+ ["127.0.0.0", 8],
21
+ ["169.254.0.0", 16],
22
+ ["172.16.0.0", 12],
23
+ ["192.0.0.0", 24],
24
+ ["192.0.2.0", 24],
25
+ ["192.168.0.0", 16],
26
+ ["198.18.0.0", 15],
27
+ ["198.51.100.0", 24],
28
+ ["203.0.113.0", 24],
29
+ ["224.0.0.0", 4],
30
+ ["240.0.0.0", 4],
31
+ ]) {
32
+ BLOCKED.addSubnet(net, prefix, "ipv4");
33
+ }
34
+ for (const [net, prefix] of [
35
+ ["::", 96],
36
+ // IPv4-mapped (::ffff:0:0/96) is deliberately absent: BlockList checks
37
+ // every IPv4 address against it too, which would block them all. Mapped
38
+ // addresses are checked against the IPv4 rules instead (isBlockedAddress,
39
+ // and BlockList's own folding for the hex form). This entry is SIIT
40
+ // (RFC 2765 IPv4-translated), a different prefix.
41
+ ["::ffff:0:0:0", 96],
42
+ ["2001::", 32],
43
+ ["64:ff9b:1::", 48],
44
+ ["::1", 128],
45
+ ["64:ff9b::", 96],
46
+ ["100::", 64],
47
+ ["2001:db8::", 32],
48
+ ["2002::", 16],
49
+ ["fc00::", 7],
50
+ ["fe80::", 10],
51
+ ["fec0::", 10],
52
+ ["ff00::", 8],
53
+ ]) {
54
+ BLOCKED.addSubnet(net, prefix, "ipv6");
55
+ }
56
+ const BRACKETS_RE = /^\[|\]$/gu;
57
+ const IPV4_MAPPED_RE = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/iu;
58
+ export const isBlockedAddress = (address) => {
59
+ const mapped = IPV4_MAPPED_RE.exec(address)?.[1];
60
+ if (mapped) {
61
+ return BLOCKED.check(mapped, "ipv4");
62
+ }
63
+ const family = isIP(address);
64
+ if (family === 0) {
65
+ return true;
66
+ }
67
+ return BLOCKED.check(address, family === 4 ? "ipv4" : "ipv6");
68
+ };
69
+ export class BlockedAddressError extends Error {
70
+ constructor(host) {
71
+ super(`${host} resolves to a private or internal address`);
72
+ this.name = "BlockedAddressError";
73
+ }
74
+ }
75
+ const systemResolve = (host) => new Promise((resolve, reject) => {
76
+ dnsLookup(host, { all: true }, (err, addresses) => err ? reject(err) : resolve(addresses));
77
+ });
78
+ // A `lookup` for https.request that refuses the whole connection when any
79
+ // address the name resolves to is internal: a name with one public and one
80
+ // private record could otherwise be dialled on the private one.
81
+ export const guardedLookup = (resolve) => (host, opts, cb) => {
82
+ resolve(host)
83
+ .then((addresses) => {
84
+ if (addresses.length === 0 ||
85
+ addresses.some((a) => isBlockedAddress(a.address))) {
86
+ cb(new BlockedAddressError(host));
87
+ return;
88
+ }
89
+ if (typeof opts === "object" && opts?.all) {
90
+ cb(null, addresses);
91
+ return;
92
+ }
93
+ const [first] = addresses;
94
+ cb(null, first?.address, first?.family);
95
+ })
96
+ .catch((err) => cb(err instanceof Error ? err : new Error(String(err))));
97
+ };
98
+ const TIMEOUT_MS = 10_000;
99
+ const MAX_BODY_BYTES = 16_384;
100
+ const ONE_CLICK_BODY = "List-Unsubscribe=One-Click";
101
+ // One request, nothing followed. The whole hop — connect, TLS, headers and
102
+ // body — has one hard deadline (the socket `timeout` alone only fires on an
103
+ // idle socket, so a trickling sender could hold the call forever), and the
104
+ // body is cut off at a cap: a sender's endpoint has no business sending more
105
+ // than a confirmation page.
106
+ export const makeSendHop = (resolve = systemResolve) => (url, method) => new Promise((resolvePromise, rejectPromise) => {
107
+ // Settle once: the body cap destroys the response, which can still emit
108
+ // `end` or `error` afterwards, and the deadline must not outlive the hop.
109
+ let settled = false;
110
+ const settle = (fn) => {
111
+ if (!settled) {
112
+ settled = true;
113
+ clearTimeout(deadline);
114
+ fn();
115
+ }
116
+ };
117
+ const reject = (err) => settle(() => rejectPromise(err));
118
+ const req = https.request(url, {
119
+ headers: {
120
+ "user-agent": "Langmail-Unsubscribe/1.0",
121
+ ...(method === "POST"
122
+ ? {
123
+ "content-length": String(ONE_CLICK_BODY.length),
124
+ "content-type": "application/x-www-form-urlencoded",
125
+ }
126
+ : {}),
127
+ },
128
+ lookup: guardedLookup(resolve),
129
+ method,
130
+ }, (res) => {
131
+ const chunks = [];
132
+ let size = 0;
133
+ const finish = () => settle(() => resolvePromise({
134
+ body: Buffer.concat(chunks)
135
+ .subarray(0, MAX_BODY_BYTES)
136
+ .toString("utf8"),
137
+ location: typeof res.headers.location === "string"
138
+ ? res.headers.location
139
+ : null,
140
+ status: res.statusCode ?? 0,
141
+ }));
142
+ res.on("data", (chunk) => {
143
+ chunks.push(chunk);
144
+ size += chunk.length;
145
+ if (size >= MAX_BODY_BYTES) {
146
+ finish();
147
+ res.destroy();
148
+ }
149
+ });
150
+ res.on("end", finish);
151
+ res.on("error", reject);
152
+ });
153
+ const deadline = setTimeout(() => req.destroy(hopTimeoutError()), TIMEOUT_MS);
154
+ req.on("error", reject);
155
+ req.end(method === "POST" ? ONE_CLICK_BODY : undefined);
156
+ });
157
+ // The cause that marks a hop that got no answer in time.
158
+ const HOP_TIMEOUT = Symbol("hop timeout");
159
+ const hopTimeoutError = () => new Error(`no answer within ${TIMEOUT_MS / 1000} seconds`, {
160
+ cause: HOP_TIMEOUT,
161
+ });
162
+ // A short, generic reason for a failed request. The raw message can carry the
163
+ // address and port that was dialled, which the sender must not learn back
164
+ // through the agent.
165
+ const failureReason = (err) => {
166
+ if (err instanceof Error && err.cause === HOP_TIMEOUT) {
167
+ return err.message;
168
+ }
169
+ const code = err?.code;
170
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") {
171
+ return "the host name does not resolve";
172
+ }
173
+ if (code === "ECONNREFUSED" ||
174
+ code === "ECONNRESET" ||
175
+ code === "EHOSTUNREACH" ||
176
+ code === "ENETUNREACH") {
177
+ return "the connection failed";
178
+ }
179
+ if (typeof code === "string" &&
180
+ (code.includes("CERT") ||
181
+ code.startsWith("ERR_TLS") ||
182
+ code.includes("SSL"))) {
183
+ return "the TLS handshake failed";
184
+ }
185
+ return "the request failed";
186
+ };
187
+ const MAX_REDIRECTS = 3;
188
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
189
+ const isBlockedError = (err) => err instanceof BlockedAddressError ||
190
+ (err instanceof Error && err.name === "BlockedAddressError");
191
+ // One hop: the https check, then the request, with a thrown error turned into
192
+ // an outcome. A HopResponse means "go on".
193
+ const runHop = async (current, hop, method, sendHop) => {
194
+ let target;
195
+ try {
196
+ target = new URL(current);
197
+ }
198
+ catch {
199
+ return { kind: "refused", reason: "the link is not a valid URL" };
200
+ }
201
+ if (target.protocol !== "https:") {
202
+ return {
203
+ kind: "refused",
204
+ reason: hop === 0
205
+ ? "the link is not https"
206
+ : `the sender redirected to a non-https address (${target.protocol})`,
207
+ };
208
+ }
209
+ // An IP literal never goes through `lookup` (Node and Bun skip DNS for
210
+ // it), so the guard has to check it here.
211
+ const literal = target.hostname.replace(BRACKETS_RE, "");
212
+ if (isIP(literal) !== 0 && isBlockedAddress(literal)) {
213
+ return {
214
+ kind: "refused",
215
+ reason: new BlockedAddressError(target.hostname).message,
216
+ };
217
+ }
218
+ try {
219
+ return { res: await sendHop(target.href, method), target };
220
+ }
221
+ catch (err) {
222
+ if (isBlockedError(err)) {
223
+ return { kind: "refused", reason: err.message };
224
+ }
225
+ return { kind: "failed", reachedSender: false, reason: failureReason(err) };
226
+ }
227
+ };
228
+ // POST `List-Unsubscribe=One-Click` to the URL, following at most three
229
+ // redirects. 307/308 repeat the POST (the RFC 7231 rule); 301/302/303 turn
230
+ // into a GET, as browsers do. Every hop must be https and pass the guard.
231
+ export const postOneClick = async (url, sendHop) => {
232
+ let current = url;
233
+ let method = "POST";
234
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
235
+ const step = await runHop(current, hop, method, sendHop);
236
+ if ("kind" in step) {
237
+ // Past the first hop the POST already reached the sender: a refused or
238
+ // failed redirect does not mean nothing was sent.
239
+ if (hop > 0 && step.kind !== "response") {
240
+ const reason = step.kind === "refused"
241
+ ? `${step.reason}, so the redirect was not followed`
242
+ : step.reason;
243
+ return { kind: "failed", reachedSender: true, reason };
244
+ }
245
+ return step;
246
+ }
247
+ const { res, target } = step;
248
+ if (!(REDIRECT_STATUSES.has(res.status) && res.location)) {
249
+ return {
250
+ body: res.body,
251
+ host: target.host,
252
+ kind: "response",
253
+ redirected: hop > 0,
254
+ status: res.status,
255
+ };
256
+ }
257
+ try {
258
+ current = new URL(res.location, target).href;
259
+ }
260
+ catch {
261
+ return {
262
+ kind: "failed",
263
+ reachedSender: true,
264
+ reason: "the sender redirected to an invalid address",
265
+ };
266
+ }
267
+ if (res.status !== 307 && res.status !== 308) {
268
+ method = "GET";
269
+ }
270
+ }
271
+ return {
272
+ kind: "failed",
273
+ reachedSender: true,
274
+ reason: `the sender redirected more than ${MAX_REDIRECTS} times`,
275
+ };
276
+ };
@@ -0,0 +1,219 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import { BlockedAddressError, guardedLookup, isBlockedAddress, makeSendHop, postOneClick, } from "./one-click-post.js";
3
+ describe("isBlockedAddress", () => {
4
+ test.each([
5
+ "127.0.0.1",
6
+ "10.1.2.3",
7
+ "172.20.0.1",
8
+ "192.168.1.1",
9
+ "169.254.169.254",
10
+ "100.64.0.1",
11
+ "0.0.0.0",
12
+ "::1",
13
+ "::",
14
+ "fe80::1",
15
+ "fd00::1",
16
+ "::ffff:127.0.0.1",
17
+ "::ffff:10.0.0.1",
18
+ "64:ff9b::a00:1",
19
+ "64:ff9b:1::1",
20
+ "::7f00:1",
21
+ "::ffff:7f00:1",
22
+ "::ffff:a9fe:a9fe",
23
+ "2001:0:4136::1",
24
+ "2002:a00:1::1",
25
+ "not-an-ip",
26
+ ])("blocks %s", (address) => {
27
+ expect(isBlockedAddress(address)).toBe(true);
28
+ });
29
+ test.each([
30
+ "93.184.215.14",
31
+ "1.1.1.1",
32
+ "2606:4700:4700::1111",
33
+ "::ffff:1.1.1.1",
34
+ ])("allows %s", (address) => {
35
+ expect(isBlockedAddress(address)).toBe(false);
36
+ });
37
+ });
38
+ describe("guardedLookup", () => {
39
+ const run = (addresses, all) => new Promise((resolve) => {
40
+ guardedLookup(() => Promise.resolve(addresses))("news.example.com", { all }, (err, result) => resolve({ err, result }));
41
+ });
42
+ test("refuses a name with any internal address, even beside a public one", async () => {
43
+ const { err } = await run([
44
+ { address: "93.184.215.14", family: 4 },
45
+ { address: "10.0.0.5", family: 4 },
46
+ ], true);
47
+ expect(err).toBeInstanceOf(BlockedAddressError);
48
+ });
49
+ test("hands public addresses through in the shape asked for", async () => {
50
+ const addresses = [{ address: "93.184.215.14", family: 4 }];
51
+ expect((await run(addresses, true)).result).toEqual(addresses);
52
+ expect((await run(addresses, false)).result).toBe("93.184.215.14");
53
+ });
54
+ });
55
+ describe("makeSendHop", () => {
56
+ test("a host that resolves to loopback is refused before any connection", async () => {
57
+ const hop = makeSendHop(() => Promise.resolve([{ address: "127.0.0.1", family: 4 }]));
58
+ expect(await postOneClick("https://rebind.example.com/u", hop)).toEqual({
59
+ kind: "refused",
60
+ reason: "rebind.example.com resolves to a private or internal address",
61
+ });
62
+ });
63
+ });
64
+ const scripted = (responses) => {
65
+ const calls = [];
66
+ const hop = (url, method) => {
67
+ calls.push([url, method]);
68
+ const r = responses[url];
69
+ if (!r) {
70
+ return Promise.reject(new Error(`unexpected ${url}`));
71
+ }
72
+ return r instanceof Error ? Promise.reject(r) : Promise.resolve(r);
73
+ };
74
+ return { calls, hop };
75
+ };
76
+ describe("postOneClick", () => {
77
+ test("POSTs once and returns the response", async () => {
78
+ const { calls, hop } = scripted({
79
+ "https://news.example.com/u": { body: "ok", location: null, status: 202 },
80
+ });
81
+ expect(await postOneClick("https://news.example.com/u", hop)).toEqual({
82
+ body: "ok",
83
+ host: "news.example.com",
84
+ kind: "response",
85
+ redirected: false,
86
+ status: 202,
87
+ });
88
+ expect(calls).toEqual([["https://news.example.com/u", "POST"]]);
89
+ });
90
+ test("refuses a non-https link without calling it", async () => {
91
+ const { calls, hop } = scripted({});
92
+ expect(await postOneClick("http://news.example.com/u", hop)).toEqual({
93
+ kind: "refused",
94
+ reason: "the link is not https",
95
+ });
96
+ expect(calls).toEqual([]);
97
+ });
98
+ test("307 repeats the POST, 302 turns into a GET", async () => {
99
+ const { calls, hop } = scripted({
100
+ "https://a.example.com/u": {
101
+ body: "",
102
+ location: "https://b.example.com/u",
103
+ status: 307,
104
+ },
105
+ "https://b.example.com/u": { body: "", location: "/done", status: 302 },
106
+ "https://b.example.com/done": {
107
+ body: "Bye",
108
+ location: null,
109
+ status: 200,
110
+ },
111
+ });
112
+ const out = await postOneClick("https://a.example.com/u", hop);
113
+ expect(out).toMatchObject({
114
+ host: "b.example.com",
115
+ kind: "response",
116
+ redirected: true,
117
+ status: 200,
118
+ });
119
+ expect(calls).toEqual([
120
+ ["https://a.example.com/u", "POST"],
121
+ ["https://b.example.com/u", "POST"],
122
+ ["https://b.example.com/done", "GET"],
123
+ ]);
124
+ });
125
+ test("a redirect to http is not followed, and the sender already has the request", async () => {
126
+ const { hop } = scripted({
127
+ "https://a.example.com/u": {
128
+ body: "",
129
+ location: "http://a.example.com/u",
130
+ status: 301,
131
+ },
132
+ });
133
+ expect(await postOneClick("https://a.example.com/u", hop)).toEqual({
134
+ kind: "failed",
135
+ reachedSender: true,
136
+ reason: "the sender redirected to a non-https address (http:), so the redirect was not followed",
137
+ });
138
+ });
139
+ test("a redirect into an internal address is not followed, and the sender already has the request", async () => {
140
+ const { hop } = scripted({
141
+ "https://a.example.com/u": {
142
+ body: "",
143
+ location: "https://internal.example.com/x",
144
+ status: 307,
145
+ },
146
+ "https://internal.example.com/x": new BlockedAddressError("internal.example.com"),
147
+ });
148
+ expect(await postOneClick("https://a.example.com/u", hop)).toEqual({
149
+ kind: "failed",
150
+ reachedSender: true,
151
+ reason: "internal.example.com resolves to a private or internal address, so the redirect was not followed",
152
+ });
153
+ });
154
+ test("a network error is reported as failed", async () => {
155
+ const err = Object.assign(new Error("connect ECONNREFUSED 10.0.0.5:6379"), {
156
+ code: "ECONNREFUSED",
157
+ });
158
+ const { hop } = scripted({ "https://a.example.com/u": err });
159
+ // The dialled address and port stay out of the result.
160
+ expect(await postOneClick("https://a.example.com/u", hop)).toEqual({
161
+ kind: "failed",
162
+ reachedSender: false,
163
+ reason: "the connection failed",
164
+ });
165
+ });
166
+ test.each([
167
+ "https://127.0.0.1/u",
168
+ "https://169.254.169.254/latest",
169
+ "https://[::1]/u",
170
+ "https://[::ffff:127.0.0.1]/u",
171
+ "https://2130706433/u",
172
+ ])("refuses the IP literal %s without calling it", async (url) => {
173
+ const { calls, hop } = scripted({});
174
+ const out = await postOneClick(url, hop);
175
+ expect(out.kind).toBe("refused");
176
+ expect(calls).toEqual([]);
177
+ });
178
+ test("a redirect to an internal IP literal is not followed", async () => {
179
+ const { calls, hop } = scripted({
180
+ "https://a.example.com/u": {
181
+ body: "",
182
+ location: "https://10.0.0.5/x",
183
+ status: 307,
184
+ },
185
+ });
186
+ expect(await postOneClick("https://a.example.com/u", hop)).toMatchObject({
187
+ kind: "failed",
188
+ reachedSender: true,
189
+ });
190
+ expect(calls).toHaveLength(1);
191
+ });
192
+ test("a malformed Location is a failure, not a throw", async () => {
193
+ const { hop } = scripted({
194
+ "https://a.example.com/u": {
195
+ body: "",
196
+ location: "https://[bad",
197
+ status: 302,
198
+ },
199
+ });
200
+ expect(await postOneClick("https://a.example.com/u", hop)).toEqual({
201
+ kind: "failed",
202
+ reachedSender: true,
203
+ reason: "the sender redirected to an invalid address",
204
+ });
205
+ });
206
+ test("stops after three redirects", async () => {
207
+ const { hop } = scripted({
208
+ "https://a.example.com/1": { body: "", location: "/2", status: 307 },
209
+ "https://a.example.com/2": { body: "", location: "/3", status: 307 },
210
+ "https://a.example.com/3": { body: "", location: "/4", status: 307 },
211
+ "https://a.example.com/4": { body: "", location: "/5", status: 307 },
212
+ });
213
+ expect(await postOneClick("https://a.example.com/1", hop)).toEqual({
214
+ kind: "failed",
215
+ reachedSender: true,
216
+ reason: "the sender redirected more than 3 times",
217
+ });
218
+ });
219
+ });
@@ -3,13 +3,11 @@
3
3
  // self-hosted search_emails; the differences are in the description.
4
4
  import { createHash } from "node:crypto";
5
5
  import { z } from "zod/v4";
6
- import { attachmentsOf, errorResult, folderLabel, formatAddresses, formatAttachmentLine, formatDate, messageFlags, messageId, messageTags, READ_ONLY, resolveMailbox, searchUids, uidRanges, examine, SAFETY_LINE, selectableFolders, sortFolderLabels, textResult, TODO_KEYWORD, withClient, } from "./imap.js";
6
+ import { errorResult, folderLabel, messageId, READ_ONLY, renderHits, resolveMailbox, searchUids, uidRanges, examine, SAFETY_LINE, selectableFolders, textResult, TODO_KEYWORD, withClient, } from "./imap.js";
7
7
  // The largest page a caller can ask for.
8
8
  const MAX_LIMIT = 100;
9
9
  // Only the first terms of a long query are searched.
10
10
  const MAX_QUERY_TERMS = 10;
11
- // Attachments listed per hit; get_email lists them all.
12
- const LIST_ATTACHMENT_LIMIT = 5;
13
11
  const QUERY_DESCRIPTION = 'Free-text search over subject, body, and addresses (IMAP SEARCH TEXT: every header counts, and most servers match a term anywhere inside a word, so "art" finds "party"). Terms are OR\'d — a message matches if it contains ANY term. Messages containing every term come first, then the rest ranked by how many terms they contain, across all pages (each hit shows matched: X/N terms). Wrap a phrase in double quotes to match only messages holding those words next to each other, in that order. Narrow with from/after/before/read/starred/todo, not by adding terms; only the first 10 terms are used.';
14
12
  export const searchEmailsShape = {
15
13
  after: z.iso
@@ -120,6 +118,7 @@ export const searchFingerprint = (args) => createHash("sha256")
120
118
  .slice(0, 10);
121
119
  const BAD_CURSOR_MESSAGE = "cursor is not one search_emails printed. Nothing was searched. Pass the cursor exactly as the result printed it, or leave cursor out to start from the newest match.";
122
120
  const OTHER_SEARCH_MESSAGE = "cursor belongs to a search with other filters. Nothing was searched. Pass it with the same query and filters as the search that printed it, or leave cursor out to start this search from the newest match.";
121
+ // --- searching ------------------------------------------------------------------
123
122
  const DAY_MS = 24 * 60 * 60 * 1000;
124
123
  /**
125
124
  * The filters every SEARCH of this call shares. IMAP SINCE and BEFORE
@@ -227,52 +226,6 @@ function nextCursor(search, page, previous) {
227
226
  seen: [...new Set([...carried, ...page.filter(sameKey).map((h) => h.id)])],
228
227
  };
229
228
  }
230
- /** Fetches the page's details folder by folder and renders each hit. */
231
- async function renderPage(client, page, termCount) {
232
- const byPath = new Map();
233
- for (const hit of page) {
234
- byPath.set(hit.path, [...(byPath.get(hit.path) ?? []), hit]);
235
- }
236
- const lines = new Map();
237
- for (const [path, hits] of byPath) {
238
- await client.mailboxOpen(path, { readOnly: true });
239
- const byUid = new Map(hits.map((h) => [h.uid, h]));
240
- for await (const msg of client.fetch(uidRanges([...byUid.keys()]), { uid: true, envelope: true, flags: true, bodyStructure: true }, { uid: true })) {
241
- const hit = byUid.get(msg.uid);
242
- if (!hit)
243
- continue;
244
- const out = [
245
- `${msg.envelope?.subject || "(no subject)"}`,
246
- ` id: ${hit.id}`,
247
- ` from: ${formatAddresses(msg.envelope?.from) || "(unknown sender)"}`,
248
- ` date: ${formatDate(hit.date)}`,
249
- ` folders: ${sortFolderLabels(hit.folders).join(", ")}`,
250
- ];
251
- const tags = messageTags(msg.flags);
252
- if (tags.length > 0)
253
- out.push(` tags: ${tags.join(", ")}`);
254
- const flags = messageFlags(msg.flags);
255
- if (flags.length > 0)
256
- out.push(` flags: ${flags.join(", ")}`);
257
- const attachments = attachmentsOf(msg.bodyStructure).filter((a) => !a.inline);
258
- if (attachments.length > 0) {
259
- out.push(" attachments:", ...attachments
260
- .slice(0, LIST_ATTACHMENT_LIMIT)
261
- .map((a, i) => ` ${formatAttachmentLine(i + 1, a)}`));
262
- if (attachments.length > LIST_ATTACHMENT_LIMIT) {
263
- out.push(` … +${attachments.length - LIST_ATTACHMENT_LIMIT} more (see get_email)`);
264
- }
265
- }
266
- if (termCount > 1)
267
- out.push(` matched: ${hit.rank}/${termCount} terms`);
268
- lines.set(hit.id, out.join("\n"));
269
- }
270
- }
271
- return page.flatMap((h, i) => {
272
- const line = lines.get(h.id);
273
- return line ? [`${i + 1}. ${line}`] : [];
274
- });
275
- }
276
229
  function matchHeader(opts) {
277
230
  const { continued, cursor, limit, shown, total } = opts;
278
231
  const noun = continued ? "remaining message(s)" : "message(s)";
@@ -315,7 +268,7 @@ export async function searchEmails(createClient, args) {
315
268
  : "No messages matched.");
316
269
  }
317
270
  const page = remaining.slice(0, args.limit);
318
- const lines = await renderPage(client, page, terms.length);
271
+ const lines = await renderHits(client, page, { termCount: terms.length });
319
272
  const next = remaining.length > page.length
320
273
  ? encodeCursor(nextCursor(search, page, cursor))
321
274
  : undefined;