loopzero-gateway-email 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +325 -0
- package/LICENSE +201 -0
- package/README.md +39 -2
- package/dist/index.cjs +799 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +255 -0
- package/dist/index.d.ts +255 -0
- package/dist/index.js +789 -0
- package/dist/index.js.map +1 -0
- package/package.json +80 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,789 @@
|
|
|
1
|
+
import { channelConfigReaders, BasePlatformAdapter } from 'loopzero-gateway';
|
|
2
|
+
import { ImapFlow } from 'imapflow';
|
|
3
|
+
import { simpleParser } from 'mailparser';
|
|
4
|
+
import { createTransport } from 'nodemailer';
|
|
5
|
+
|
|
6
|
+
// src/adapter.ts
|
|
7
|
+
|
|
8
|
+
// src/errors.ts
|
|
9
|
+
var NETWORK_ERR_RE = /ECONN|ENOTFOUND|ETIMEDOUT|EHOSTUNREACH|EAI_AGAIN|fetch failed/i;
|
|
10
|
+
function mapEmailError(err) {
|
|
11
|
+
if (err === null || err === void 0) {
|
|
12
|
+
return { code: "unknown", message: "Unknown error" };
|
|
13
|
+
}
|
|
14
|
+
if (typeof err === "string") {
|
|
15
|
+
return { code: "unknown", message: err };
|
|
16
|
+
}
|
|
17
|
+
const e = err;
|
|
18
|
+
const code = e.code ?? "";
|
|
19
|
+
const respCode = typeof e.responseCode === "number" ? e.responseCode : void 0;
|
|
20
|
+
const message = typeof e.message === "string" && e.message.length > 0 ? e.message : String(err);
|
|
21
|
+
if (code === "EAUTH" || code === "EAUTHENTICATION") {
|
|
22
|
+
return { code: "auth_failed", message };
|
|
23
|
+
}
|
|
24
|
+
if (code === "EENVELOPE" && /550/.test(message)) {
|
|
25
|
+
return { code: "invalid_request", message };
|
|
26
|
+
}
|
|
27
|
+
if (code === "ECONNECTION" || code === "ESOCKET" || code === "ETLS") {
|
|
28
|
+
return { code: "server_error", message };
|
|
29
|
+
}
|
|
30
|
+
if (code === "ETIMEDOUT") {
|
|
31
|
+
return { code: "timeout", message };
|
|
32
|
+
}
|
|
33
|
+
if (respCode !== void 0) {
|
|
34
|
+
if (respCode === 535 || respCode === 530) return { code: "auth_failed", message };
|
|
35
|
+
if (respCode === 421 || respCode === 451 || respCode === 452)
|
|
36
|
+
return { code: "rate_limit", message };
|
|
37
|
+
if (respCode === 550 || respCode === 551 || respCode === 553)
|
|
38
|
+
return { code: "invalid_request", message };
|
|
39
|
+
if (respCode >= 500) return { code: "server_error", message };
|
|
40
|
+
if (respCode >= 400) return { code: "rate_limit", message };
|
|
41
|
+
}
|
|
42
|
+
if (e.name === "IMAP_AUTH_FAILED" || /auth/i.test(message)) {
|
|
43
|
+
return { code: "auth_failed", message };
|
|
44
|
+
}
|
|
45
|
+
if (NETWORK_ERR_RE.test(message)) return { code: "server_error", message };
|
|
46
|
+
return { code: "unknown", message };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// src/filters.ts
|
|
50
|
+
var NOREPLY_RE = /^(noreply|no-reply|no_reply|donotreply|do-not-reply|mailer-daemon|postmaster|bounce|notifications)@/i;
|
|
51
|
+
function extractAddr(s) {
|
|
52
|
+
const m = s.match(/<([^>]+)>/);
|
|
53
|
+
return (m?.[1] ?? s).toLowerCase().trim();
|
|
54
|
+
}
|
|
55
|
+
function isAutomatedSender(fromAddress, headers) {
|
|
56
|
+
if (NOREPLY_RE.test(fromAddress)) return true;
|
|
57
|
+
const lowered = /* @__PURE__ */ new Map();
|
|
58
|
+
for (const [k, v] of headers) lowered.set(k.toLowerCase(), v);
|
|
59
|
+
const autoSubmitted = lowered.get("auto-submitted");
|
|
60
|
+
if (typeof autoSubmitted === "string" && /auto-generated|auto-replied/i.test(autoSubmitted)) {
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
const precedence = lowered.get("precedence");
|
|
64
|
+
if (typeof precedence === "string" && /bulk|list/i.test(precedence)) {
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
const xAuto = lowered.get("x-auto-response-suppress");
|
|
68
|
+
if (typeof xAuto === "string" && /all/i.test(xAuto)) {
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
function isAllowedSender(fromAddress, allowedSenders) {
|
|
74
|
+
if (allowedSenders === void 0) return true;
|
|
75
|
+
const norm = extractAddr(fromAddress);
|
|
76
|
+
return allowedSenders.some((s) => extractAddr(s) === norm);
|
|
77
|
+
}
|
|
78
|
+
var ImapClient = class {
|
|
79
|
+
constructor(config) {
|
|
80
|
+
this.config = config;
|
|
81
|
+
}
|
|
82
|
+
config;
|
|
83
|
+
client;
|
|
84
|
+
idleAbort;
|
|
85
|
+
async connect() {
|
|
86
|
+
this.client = new ImapFlow({
|
|
87
|
+
host: this.config.host,
|
|
88
|
+
port: this.config.port,
|
|
89
|
+
secure: this.config.secure,
|
|
90
|
+
auth: this.config.auth,
|
|
91
|
+
logger: false
|
|
92
|
+
});
|
|
93
|
+
await this.client.connect();
|
|
94
|
+
await this.client.mailboxOpen("INBOX");
|
|
95
|
+
}
|
|
96
|
+
// eslint-disable-next-line @typescript-eslint/require-await
|
|
97
|
+
async mailboxStatus() {
|
|
98
|
+
const box = this.client?.mailbox;
|
|
99
|
+
if (box === void 0 || box === false) throw new Error("no mailbox open");
|
|
100
|
+
return { uidValidity: Number(box.uidValidity), uidNext: box.uidNext };
|
|
101
|
+
}
|
|
102
|
+
supportsIdle() {
|
|
103
|
+
if (this.client === void 0) return false;
|
|
104
|
+
const caps = this.client.capabilities;
|
|
105
|
+
return caps?.has?.("IDLE") ?? false;
|
|
106
|
+
}
|
|
107
|
+
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: shape-mapping function — imapflow can hand headers as Map OR Buffer depending on protocol path; this is the single normalization site.
|
|
108
|
+
async fetchUnseen(sinceUid) {
|
|
109
|
+
if (this.client === void 0) return [];
|
|
110
|
+
const out = [];
|
|
111
|
+
const query = sinceUid === void 0 ? { seen: false } : { seen: false, uid: `${sinceUid}:*` };
|
|
112
|
+
for await (const raw of this.client.fetch(query, {
|
|
113
|
+
uid: true,
|
|
114
|
+
source: true,
|
|
115
|
+
headers: true
|
|
116
|
+
})) {
|
|
117
|
+
const msg = raw;
|
|
118
|
+
const headers = /* @__PURE__ */ new Map();
|
|
119
|
+
const h = msg.headers;
|
|
120
|
+
if (h instanceof Map) {
|
|
121
|
+
for (const [k, v] of h) {
|
|
122
|
+
headers.set(String(k), Array.isArray(v) ? v[0] ?? "" : v);
|
|
123
|
+
}
|
|
124
|
+
} else if (h instanceof Buffer) {
|
|
125
|
+
for (const line of h.toString("utf8").split(/\r?\n/)) {
|
|
126
|
+
const idx = line.indexOf(":");
|
|
127
|
+
if (idx > 0)
|
|
128
|
+
headers.set(line.slice(0, idx).trim().toLowerCase(), line.slice(idx + 1).trim());
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (msg.uid !== void 0 && msg.source !== void 0) {
|
|
132
|
+
out.push({
|
|
133
|
+
uid: msg.uid,
|
|
134
|
+
source: msg.source,
|
|
135
|
+
headers
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
async markSeen(uids) {
|
|
142
|
+
if (this.client === void 0 || uids.length === 0) return;
|
|
143
|
+
await this.client.messageFlagsAdd({ uid: uids.join(",") }, ["\\Seen"], { uid: true });
|
|
144
|
+
}
|
|
145
|
+
async startIdle(onExists) {
|
|
146
|
+
if (this.client === void 0) return;
|
|
147
|
+
this.idleAbort = new AbortController();
|
|
148
|
+
const c = this.client;
|
|
149
|
+
c.on("exists", () => {
|
|
150
|
+
onExists();
|
|
151
|
+
});
|
|
152
|
+
void c.idle().catch(() => {
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
async stopIdle() {
|
|
156
|
+
if (this.idleAbort !== void 0) {
|
|
157
|
+
this.idleAbort.abort();
|
|
158
|
+
this.idleAbort = void 0;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
async disconnect() {
|
|
162
|
+
await this.stopIdle();
|
|
163
|
+
if (this.client !== void 0) {
|
|
164
|
+
try {
|
|
165
|
+
await this.client.logout();
|
|
166
|
+
} catch {
|
|
167
|
+
}
|
|
168
|
+
this.client = void 0;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
var DEFAULT_MAX_BODY = 5e4;
|
|
173
|
+
function stripBraces(id) {
|
|
174
|
+
if (id === void 0 || id.length === 0) return void 0;
|
|
175
|
+
return id.replace(/^<|>$/g, "");
|
|
176
|
+
}
|
|
177
|
+
function normalizeRefs(refs) {
|
|
178
|
+
if (refs === void 0) return void 0;
|
|
179
|
+
const arr = Array.isArray(refs) ? refs : refs.split(/\s+/).filter((s) => s.length > 0);
|
|
180
|
+
const cleaned = arr.map((r) => stripBraces(r)).filter((r) => r !== void 0);
|
|
181
|
+
return cleaned.length > 0 ? cleaned : void 0;
|
|
182
|
+
}
|
|
183
|
+
function addressesFrom(obj) {
|
|
184
|
+
if (obj === void 0) return [];
|
|
185
|
+
if (Array.isArray(obj)) {
|
|
186
|
+
const out = [];
|
|
187
|
+
for (const o of obj) out.push(...o.value ?? []);
|
|
188
|
+
return out;
|
|
189
|
+
}
|
|
190
|
+
return Array.from(obj.value ?? []);
|
|
191
|
+
}
|
|
192
|
+
async function normalizeEmail(rawBuffer, opts) {
|
|
193
|
+
const parsed = await simpleParser(rawBuffer);
|
|
194
|
+
const messageId = stripBraces(parsed.messageId) ?? "unknown";
|
|
195
|
+
const inReplyTo = stripBraces(parsed.inReplyTo);
|
|
196
|
+
const references = normalizeRefs(parsed.references);
|
|
197
|
+
const fromEntries = addressesFrom(parsed.from);
|
|
198
|
+
const fromAddress = (fromEntries[0]?.address ?? "anonymous").toLowerCase().trim();
|
|
199
|
+
const trimmedName = fromEntries[0]?.name?.trim();
|
|
200
|
+
const fromName = trimmedName !== void 0 && trimmedName.length > 0 ? trimmedName : void 0;
|
|
201
|
+
const botAddrLc = opts.botAddress.toLowerCase().trim();
|
|
202
|
+
const recipients = [];
|
|
203
|
+
for (const entry of [
|
|
204
|
+
...addressesFrom(parsed.to),
|
|
205
|
+
...addressesFrom(parsed.cc)
|
|
206
|
+
]) {
|
|
207
|
+
const addr = entry.address?.toLowerCase().trim();
|
|
208
|
+
if (addr !== void 0 && addr.length > 0 && addr !== botAddrLc) {
|
|
209
|
+
recipients.push(addr);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
const subject = parsed.subject ?? "(no subject)";
|
|
213
|
+
const rawText = parsed.text ?? "";
|
|
214
|
+
const maxChars = opts.maxBodyChars ?? DEFAULT_MAX_BODY;
|
|
215
|
+
const text = rawText.length > maxChars ? `${rawText.slice(0, maxChars)}
|
|
216
|
+
|
|
217
|
+
[truncated \u2014 full body in event.email.raw]` : rawText;
|
|
218
|
+
const receivedAt = parsed.date instanceof Date ? parsed.date.getTime() : Date.now();
|
|
219
|
+
const attachmentCount = Array.isArray(parsed.attachments) ? parsed.attachments.length : 0;
|
|
220
|
+
const emailMeta = {
|
|
221
|
+
messageId,
|
|
222
|
+
...inReplyTo !== void 0 ? { inReplyTo } : {},
|
|
223
|
+
...references !== void 0 ? { references } : {},
|
|
224
|
+
subject,
|
|
225
|
+
fromAddress,
|
|
226
|
+
...fromName !== void 0 ? { fromName } : {},
|
|
227
|
+
recipients,
|
|
228
|
+
attachmentCount,
|
|
229
|
+
raw: parsed
|
|
230
|
+
};
|
|
231
|
+
return {
|
|
232
|
+
id: messageId,
|
|
233
|
+
platform: "email",
|
|
234
|
+
sender: {
|
|
235
|
+
id: fromAddress,
|
|
236
|
+
...fromName !== void 0 ? { displayName: fromName } : {}
|
|
237
|
+
},
|
|
238
|
+
channel: { id: fromAddress, type: "dm", topicId: messageId },
|
|
239
|
+
text,
|
|
240
|
+
receivedAt,
|
|
241
|
+
email: emailMeta
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// src/refuse-attachments.ts
|
|
246
|
+
function refuseAttachments(out) {
|
|
247
|
+
if (out.attachments == null || out.attachments.length === 0) return void 0;
|
|
248
|
+
return {
|
|
249
|
+
ok: false,
|
|
250
|
+
error: { code: "attachments_unsupported", message: "email adapter cannot send attachments" }
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// src/seen-uids.ts
|
|
255
|
+
var SeenUidSet = class _SeenUidSet {
|
|
256
|
+
set = /* @__PURE__ */ new Set();
|
|
257
|
+
static MAX_SIZE = 5e3;
|
|
258
|
+
static TRIM_TO = 4e3;
|
|
259
|
+
has(uid) {
|
|
260
|
+
return this.set.has(uid);
|
|
261
|
+
}
|
|
262
|
+
add(uid) {
|
|
263
|
+
if (this.set.size >= _SeenUidSet.MAX_SIZE) this.trim();
|
|
264
|
+
this.set.add(uid);
|
|
265
|
+
}
|
|
266
|
+
trim() {
|
|
267
|
+
const target = _SeenUidSet.TRIM_TO;
|
|
268
|
+
const toDrop = this.set.size - target;
|
|
269
|
+
if (toDrop <= 0) return;
|
|
270
|
+
let i = 0;
|
|
271
|
+
for (const key of this.set) {
|
|
272
|
+
if (i >= toDrop) break;
|
|
273
|
+
this.set.delete(key);
|
|
274
|
+
i++;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
get size() {
|
|
278
|
+
return this.set.size;
|
|
279
|
+
}
|
|
280
|
+
clear() {
|
|
281
|
+
this.set.clear();
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
var SmtpClient = class {
|
|
285
|
+
constructor(config) {
|
|
286
|
+
this.config = config;
|
|
287
|
+
}
|
|
288
|
+
config;
|
|
289
|
+
transporter;
|
|
290
|
+
getTransporter() {
|
|
291
|
+
if (this.transporter === void 0) {
|
|
292
|
+
this.transporter = createTransport({
|
|
293
|
+
host: this.config.host,
|
|
294
|
+
port: this.config.port,
|
|
295
|
+
secure: this.config.secure,
|
|
296
|
+
auth: this.config.auth
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
return this.transporter;
|
|
300
|
+
}
|
|
301
|
+
async verify() {
|
|
302
|
+
return this.getTransporter().verify();
|
|
303
|
+
}
|
|
304
|
+
async send(opts) {
|
|
305
|
+
const mail = {
|
|
306
|
+
from: opts.from,
|
|
307
|
+
to: opts.to,
|
|
308
|
+
subject: opts.subject,
|
|
309
|
+
text: opts.text
|
|
310
|
+
};
|
|
311
|
+
if (opts.html !== void 0) {
|
|
312
|
+
mail.html = opts.html;
|
|
313
|
+
}
|
|
314
|
+
if (opts.inReplyTo !== void 0) {
|
|
315
|
+
mail.inReplyTo = `<${opts.inReplyTo}>`;
|
|
316
|
+
}
|
|
317
|
+
if (opts.references !== void 0 && opts.references.length > 0) {
|
|
318
|
+
mail.references = opts.references.map((r) => `<${r}>`);
|
|
319
|
+
}
|
|
320
|
+
const info = await this.getTransporter().sendMail(mail);
|
|
321
|
+
const raw = (info.messageId ?? "").replace(/^<|>$/g, "");
|
|
322
|
+
return raw;
|
|
323
|
+
}
|
|
324
|
+
async close() {
|
|
325
|
+
if (this.transporter !== void 0) {
|
|
326
|
+
this.transporter.close();
|
|
327
|
+
this.transporter = void 0;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
};
|
|
331
|
+
|
|
332
|
+
// src/thread-store.ts
|
|
333
|
+
var ThreadStore = class _ThreadStore {
|
|
334
|
+
map = /* @__PURE__ */ new Map();
|
|
335
|
+
static MAX_SIZE = 1e3;
|
|
336
|
+
recordFromInbound(event) {
|
|
337
|
+
const ctx = {
|
|
338
|
+
subject: event.email.subject,
|
|
339
|
+
references: event.email.references ?? [],
|
|
340
|
+
lastMessageId: event.email.messageId
|
|
341
|
+
};
|
|
342
|
+
if (this.map.size >= _ThreadStore.MAX_SIZE && !this.map.has(event.email.messageId)) {
|
|
343
|
+
const firstKey = this.map.keys().next().value;
|
|
344
|
+
if (firstKey !== void 0) this.map.delete(firstKey);
|
|
345
|
+
}
|
|
346
|
+
this.map.delete(event.email.messageId);
|
|
347
|
+
this.map.set(event.email.messageId, ctx);
|
|
348
|
+
}
|
|
349
|
+
lookup(topicId) {
|
|
350
|
+
return this.map.get(topicId);
|
|
351
|
+
}
|
|
352
|
+
get size() {
|
|
353
|
+
return this.map.size;
|
|
354
|
+
}
|
|
355
|
+
clear() {
|
|
356
|
+
this.map.clear();
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
// src/adapter.ts
|
|
361
|
+
var DEFAULT_POLL_INTERVAL_MS = 15e3;
|
|
362
|
+
function reportDrainFailure(err) {
|
|
363
|
+
console.error("[email] drain failed:", err instanceof Error ? err.message : err);
|
|
364
|
+
}
|
|
365
|
+
function htmlPartFor(text, format) {
|
|
366
|
+
if (format === "html") return text;
|
|
367
|
+
const escaped = text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
368
|
+
return `<pre>${escaped}</pre>`;
|
|
369
|
+
}
|
|
370
|
+
var EmailAdapter = class extends BasePlatformAdapter {
|
|
371
|
+
platform = "email";
|
|
372
|
+
options;
|
|
373
|
+
seenUids = new SeenUidSet();
|
|
374
|
+
/** UIDs finished with in this batch, awaiting one `\Seen` command (#11). */
|
|
375
|
+
pendingSeen = /* @__PURE__ */ new Set();
|
|
376
|
+
threadStore = new ThreadStore();
|
|
377
|
+
imap;
|
|
378
|
+
smtp;
|
|
379
|
+
handler;
|
|
380
|
+
connected = false;
|
|
381
|
+
// EC-4: serialize concurrent _dispatchInbound calls.
|
|
382
|
+
dispatchQueue = Promise.resolve();
|
|
383
|
+
pollTimer;
|
|
384
|
+
/** In-memory cursor (#348); mirrored to `options.cursorStore` when one is given. */
|
|
385
|
+
cursor;
|
|
386
|
+
constructor(opts) {
|
|
387
|
+
super();
|
|
388
|
+
for (const k of ["address", "password", "imapHost", "smtpHost"]) {
|
|
389
|
+
const v = opts[k];
|
|
390
|
+
if (typeof v !== "string" || v.length === 0) {
|
|
391
|
+
throw new TypeError(`EmailAdapter: ${k} is required and must be a non-empty string`);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
this.options = opts;
|
|
395
|
+
}
|
|
396
|
+
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: connect orchestrates factory-vs-real, verify(), connect(), IDLE-vs-poll choice, and rollback-on-throw — a linear single-transaction sequence; splitting hurts the disconnect-on-failure invariant.
|
|
397
|
+
async connect() {
|
|
398
|
+
if (this.connected) return true;
|
|
399
|
+
try {
|
|
400
|
+
const imapFactory = this.options.__imapFactory;
|
|
401
|
+
const smtpFactory = this.options.__smtpFactory;
|
|
402
|
+
this.imap = imapFactory !== void 0 ? imapFactory({
|
|
403
|
+
host: this.options.imapHost,
|
|
404
|
+
port: this.options.imapPort ?? 993,
|
|
405
|
+
secure: true,
|
|
406
|
+
auth: { user: this.options.address, pass: this.options.password }
|
|
407
|
+
}) : new ImapClient({
|
|
408
|
+
host: this.options.imapHost,
|
|
409
|
+
port: this.options.imapPort ?? 993,
|
|
410
|
+
secure: true,
|
|
411
|
+
auth: { user: this.options.address, pass: this.options.password }
|
|
412
|
+
});
|
|
413
|
+
this.smtp = smtpFactory !== void 0 ? smtpFactory({
|
|
414
|
+
host: this.options.smtpHost,
|
|
415
|
+
port: this.options.smtpPort ?? 587,
|
|
416
|
+
secure: (this.options.smtpPort ?? 587) === 465,
|
|
417
|
+
auth: { user: this.options.address, pass: this.options.password }
|
|
418
|
+
}) : new SmtpClient({
|
|
419
|
+
host: this.options.smtpHost,
|
|
420
|
+
port: this.options.smtpPort ?? 587,
|
|
421
|
+
secure: (this.options.smtpPort ?? 587) === 465,
|
|
422
|
+
auth: { user: this.options.address, pass: this.options.password }
|
|
423
|
+
});
|
|
424
|
+
await this.smtp.verify();
|
|
425
|
+
await this.imap.connect();
|
|
426
|
+
await this._establishCursor(this.imap);
|
|
427
|
+
if (this.imap.supportsIdle()) {
|
|
428
|
+
await this.imap.startIdle(() => {
|
|
429
|
+
void this._drainUnseen().catch(reportDrainFailure);
|
|
430
|
+
});
|
|
431
|
+
void this._drainUnseen().catch(reportDrainFailure);
|
|
432
|
+
} else {
|
|
433
|
+
const intervalMs = this.options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
434
|
+
this.pollTimer = setInterval(() => {
|
|
435
|
+
void this._drainUnseen().catch(reportDrainFailure);
|
|
436
|
+
}, intervalMs);
|
|
437
|
+
}
|
|
438
|
+
this.connected = true;
|
|
439
|
+
return true;
|
|
440
|
+
} catch (err) {
|
|
441
|
+
console.error("[email] connect failed:", err instanceof Error ? err.message : err);
|
|
442
|
+
await this.disconnect().catch(() => {
|
|
443
|
+
});
|
|
444
|
+
return false;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
async disconnect() {
|
|
448
|
+
if (this.pollTimer !== void 0) {
|
|
449
|
+
clearInterval(this.pollTimer);
|
|
450
|
+
this.pollTimer = void 0;
|
|
451
|
+
}
|
|
452
|
+
if (this.imap !== void 0) {
|
|
453
|
+
await this.imap.disconnect().catch(() => {
|
|
454
|
+
});
|
|
455
|
+
this.imap = void 0;
|
|
456
|
+
}
|
|
457
|
+
if (this.smtp !== void 0) {
|
|
458
|
+
await this.smtp.close().catch(() => {
|
|
459
|
+
});
|
|
460
|
+
this.smtp = void 0;
|
|
461
|
+
}
|
|
462
|
+
this.connected = false;
|
|
463
|
+
this.handler = void 0;
|
|
464
|
+
this.seenUids.clear();
|
|
465
|
+
this.threadStore.clear();
|
|
466
|
+
}
|
|
467
|
+
async sendMessage(out) {
|
|
468
|
+
return refuseAttachments(out) ?? this.sendText(out);
|
|
469
|
+
}
|
|
470
|
+
async sendText(out) {
|
|
471
|
+
if (out.text.length === 0) {
|
|
472
|
+
return { ok: false, error: { code: "empty_text", message: "Empty text rejected." } };
|
|
473
|
+
}
|
|
474
|
+
if (!this.connected || this.smtp === void 0) {
|
|
475
|
+
return {
|
|
476
|
+
ok: false,
|
|
477
|
+
error: { code: "not_connected", message: "EmailAdapter not connected." }
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
const to = out.channel.id;
|
|
481
|
+
const topicId = out.channel.topicId;
|
|
482
|
+
const context = topicId !== void 0 ? this.threadStore.lookup(topicId) : void 0;
|
|
483
|
+
const { subject, inReplyTo, references } = replyHeaders(context);
|
|
484
|
+
const from = this.options.fromName !== void 0 ? { name: this.options.fromName, address: this.options.address } : this.options.address;
|
|
485
|
+
try {
|
|
486
|
+
const base = {
|
|
487
|
+
from,
|
|
488
|
+
to,
|
|
489
|
+
subject,
|
|
490
|
+
text: out.text,
|
|
491
|
+
...inReplyTo !== void 0 ? { inReplyTo } : {},
|
|
492
|
+
...references !== void 0 ? { references } : {}
|
|
493
|
+
};
|
|
494
|
+
const html = out.format === "markdown" || out.format === "html" ? htmlPartFor(out.text, out.format) : void 0;
|
|
495
|
+
const messageId = await sendWithTextFallback(this.smtp, base, html);
|
|
496
|
+
return { ok: true, messageId };
|
|
497
|
+
} catch (err) {
|
|
498
|
+
return { ok: false, error: mapEmailError(err) };
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
onInbound(handler) {
|
|
502
|
+
this.handler = handler;
|
|
503
|
+
return () => {
|
|
504
|
+
if (this.handler === handler) this.handler = void 0;
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Load the cursor, and baseline it at the mailbox's UIDNEXT when there is none or its
|
|
509
|
+
* UIDVALIDITY no longer matches (the UIDs it counted are gone). Existing mail is not dispatched.
|
|
510
|
+
*/
|
|
511
|
+
async _establishCursor(imap) {
|
|
512
|
+
const store = this.options.cursorStore;
|
|
513
|
+
const status = await imap.mailboxStatus();
|
|
514
|
+
const known = this.cursor ?? await store?.load();
|
|
515
|
+
if (known !== void 0 && known.uidValidity === status.uidValidity) {
|
|
516
|
+
this.cursor = known;
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
this.cursor = { uidValidity: status.uidValidity, uid: status.uidNext };
|
|
520
|
+
await store?.save(this.cursor);
|
|
521
|
+
}
|
|
522
|
+
/** @internal — drain UNSEEN past the cursor once and dispatch each. */
|
|
523
|
+
async _drainUnseen() {
|
|
524
|
+
if (this.imap === void 0 || this.cursor === void 0) return;
|
|
525
|
+
const since = this.cursor.uid;
|
|
526
|
+
let messages = [];
|
|
527
|
+
try {
|
|
528
|
+
messages = await this.imap.fetchUnseen(since);
|
|
529
|
+
} catch (err) {
|
|
530
|
+
console.error("[email] fetchUnseen failed:", err instanceof Error ? err.message : err);
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
messages = messages.filter((m) => m.uid >= since);
|
|
534
|
+
for (const msg of messages) {
|
|
535
|
+
this._dispatchInbound(msg.uid, msg.source, msg.headers);
|
|
536
|
+
}
|
|
537
|
+
await this._advanceCursor(messages);
|
|
538
|
+
this.dispatchQueue = this.dispatchQueue.then(() => this._flushSeen());
|
|
539
|
+
}
|
|
540
|
+
async _advanceCursor(messages) {
|
|
541
|
+
if (this.cursor === void 0 || messages.length === 0) return;
|
|
542
|
+
const next = Math.max(...messages.map((m) => m.uid)) + 1;
|
|
543
|
+
if (next <= this.cursor.uid) return;
|
|
544
|
+
this.cursor = { uidValidity: this.cursor.uidValidity, uid: next };
|
|
545
|
+
try {
|
|
546
|
+
await this.options.cursorStore?.save(this.cursor);
|
|
547
|
+
} catch (err) {
|
|
548
|
+
console.error("[email] could not save cursor:", err instanceof Error ? err.message : err);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.
|
|
553
|
+
* Fire-and-forget: never throws; errors logged.
|
|
554
|
+
*/
|
|
555
|
+
_dispatchInbound(uid, rawBuffer, headers) {
|
|
556
|
+
this.dispatchQueue = this.dispatchQueue.then(
|
|
557
|
+
() => this._dispatchInboundInner(uid, rawBuffer, headers).catch(
|
|
558
|
+
(err) => console.error("[email] dispatch error:", err instanceof Error ? err.message : err)
|
|
559
|
+
)
|
|
560
|
+
);
|
|
561
|
+
return this.dispatchQueue;
|
|
562
|
+
}
|
|
563
|
+
async _dispatchInboundInner(uid, rawBuffer, headers) {
|
|
564
|
+
if (this.seenUids.has(uid)) return;
|
|
565
|
+
this.seenUids.add(uid);
|
|
566
|
+
try {
|
|
567
|
+
await this._dispatchOrDrop(uid, rawBuffer, headers);
|
|
568
|
+
} finally {
|
|
569
|
+
this.pendingSeen.add(uid);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Flush the batch to the server. Never throws — a mailbox we cannot flag is
|
|
574
|
+
* not worth dropping mail over; those UIDs simply come back on the next drain.
|
|
575
|
+
*/
|
|
576
|
+
async _flushSeen() {
|
|
577
|
+
if (this.imap === void 0 || this.pendingSeen.size === 0) return;
|
|
578
|
+
const uids = [...this.pendingSeen];
|
|
579
|
+
this.pendingSeen.clear();
|
|
580
|
+
try {
|
|
581
|
+
await this.imap.markSeen(uids);
|
|
582
|
+
} catch (err) {
|
|
583
|
+
console.error(
|
|
584
|
+
`[email] could not flag ${uids.length} message(s) \\Seen (they will be re-delivered):`,
|
|
585
|
+
err instanceof Error ? err.message : err
|
|
586
|
+
);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
async _dispatchOrDrop(uid, rawBuffer, headers) {
|
|
590
|
+
const event = await normalizeEmail(rawBuffer, {
|
|
591
|
+
botAddress: this.options.address,
|
|
592
|
+
...this.options.maxBodyChars !== void 0 ? { maxBodyChars: this.options.maxBodyChars } : {}
|
|
593
|
+
});
|
|
594
|
+
if (event.email.fromAddress === this.options.address.toLowerCase()) {
|
|
595
|
+
console.warn(`[email] dropped own-address loopback (uid=${uid})`);
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
if (this.options.allowAutomated !== true && isAutomatedSender(event.email.fromAddress, headers)) {
|
|
599
|
+
console.warn(`[email] dropped automated sender: ${event.email.fromAddress}`);
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
if (!isAllowedSender(event.email.fromAddress, this.options.allowedSenders)) {
|
|
603
|
+
console.warn(`[email] sender not in allowlist: ${event.email.fromAddress}`);
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
this.threadStore.recordFromInbound(event);
|
|
607
|
+
if (this.handler !== void 0) await this.handler(event);
|
|
608
|
+
}
|
|
609
|
+
/** Test seams. @internal */
|
|
610
|
+
get _seenUidsSize() {
|
|
611
|
+
return this.seenUids.size;
|
|
612
|
+
}
|
|
613
|
+
get _threadStoreSize() {
|
|
614
|
+
return this.threadStore.size;
|
|
615
|
+
}
|
|
616
|
+
/** Test seam — wait for queued dispatches to drain. @internal */
|
|
617
|
+
async _drainDispatchQueue() {
|
|
618
|
+
await this.dispatchQueue;
|
|
619
|
+
}
|
|
620
|
+
/** Test seam — drain IMAP UNSEEN now + flush dispatch queue. @internal */
|
|
621
|
+
async _drainNow() {
|
|
622
|
+
await this._drainUnseen();
|
|
623
|
+
await this.dispatchQueue;
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
|
|
627
|
+
*
|
|
628
|
+
* One line over `runHandler`, which owns the containment: a handler is user code, its throw is
|
|
629
|
+
* named as the handler's failure rather than the platform's, and delivery continues.
|
|
630
|
+
*/
|
|
631
|
+
async deliver(event) {
|
|
632
|
+
return this.runHandler(this.handler, event);
|
|
633
|
+
}
|
|
634
|
+
};
|
|
635
|
+
function replyHeaders(context) {
|
|
636
|
+
if (context === void 0) return { subject: "Message from agent" };
|
|
637
|
+
return {
|
|
638
|
+
subject: context.subject.startsWith("Re:") ? context.subject : `Re: ${context.subject}`,
|
|
639
|
+
inReplyTo: context.lastMessageId,
|
|
640
|
+
// EC-6: dedup the chain.
|
|
641
|
+
references: Array.from(/* @__PURE__ */ new Set([...context.references, context.lastMessageId]))
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
async function sendWithTextFallback(smtp, base, html) {
|
|
645
|
+
try {
|
|
646
|
+
return await smtp.send(html === void 0 ? base : { ...base, html });
|
|
647
|
+
} catch (err) {
|
|
648
|
+
if (html === void 0) throw err;
|
|
649
|
+
process.stderr.write(
|
|
650
|
+
"[gateway-email] the server rejected the html part; retrying with text only\n"
|
|
651
|
+
);
|
|
652
|
+
return smtp.send(base);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
// ../../shared/channel-config-field.ts
|
|
657
|
+
var field = (key, env, description, { required = true, secret = false } = {}) => ({ key, required, secret, env, description });
|
|
658
|
+
|
|
659
|
+
// ../../shared/env-value-readers.ts
|
|
660
|
+
function readEnvNumber(invalid2, config, key) {
|
|
661
|
+
const value = config[key];
|
|
662
|
+
if (value === void 0) return void 0;
|
|
663
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
664
|
+
if (typeof value === "string" && /^[0-9]+$/.test(value.trim())) {
|
|
665
|
+
const parsed = Number(value.trim());
|
|
666
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
667
|
+
}
|
|
668
|
+
throw invalid2(key, "a number or a digit string");
|
|
669
|
+
}
|
|
670
|
+
function readEnvBoolean(invalid2, config, key) {
|
|
671
|
+
const value = config[key];
|
|
672
|
+
if (value === void 0) return void 0;
|
|
673
|
+
if (value === true || value === "true") return true;
|
|
674
|
+
if (value === false || value === "false") return false;
|
|
675
|
+
throw invalid2(key, 'a boolean or the string "true" or "false"');
|
|
676
|
+
}
|
|
677
|
+
function envValueReaders(invalid2) {
|
|
678
|
+
return {
|
|
679
|
+
number: (config, key) => readEnvNumber(invalid2, config, key),
|
|
680
|
+
boolean: (config, key) => readEnvBoolean(invalid2, config, key)
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// src/channel.ts
|
|
685
|
+
var readers = channelConfigReaders("gateway-email");
|
|
686
|
+
var { invalid } = readers;
|
|
687
|
+
var isAbsent = (value) => value === void 0;
|
|
688
|
+
var read = {
|
|
689
|
+
...envValueReaders(invalid),
|
|
690
|
+
string: readers.requiredString,
|
|
691
|
+
optionalString: (config, key) => config[key] === void 0 ? void 0 : readers.requiredString(config, key),
|
|
692
|
+
list(config, key) {
|
|
693
|
+
const value = config[key];
|
|
694
|
+
if (value === void 0) return void 0;
|
|
695
|
+
if (typeof value === "string") {
|
|
696
|
+
return value.split(",").map((item) => item.trim()).filter((item) => item.length > 0);
|
|
697
|
+
}
|
|
698
|
+
if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value;
|
|
699
|
+
throw invalid(key, "an array of strings or a comma-separated string");
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
function readCursorStore(config) {
|
|
703
|
+
const value = config.cursorStore;
|
|
704
|
+
if (isAbsent(value)) return void 0;
|
|
705
|
+
const store = value;
|
|
706
|
+
if (typeof value !== "object" || typeof store?.load !== "function" || typeof store.save !== "function") {
|
|
707
|
+
throw invalid("cursorStore", "an object with load and save functions");
|
|
708
|
+
}
|
|
709
|
+
return value;
|
|
710
|
+
}
|
|
711
|
+
var CONFIG = [
|
|
712
|
+
field(
|
|
713
|
+
"address",
|
|
714
|
+
"EMAIL_ADDRESS",
|
|
715
|
+
"Email address the bot listens on; also the From address of outbound mail."
|
|
716
|
+
),
|
|
717
|
+
field("password", "EMAIL_PASSWORD", "Password or app password for the IMAP and SMTP login.", {
|
|
718
|
+
secret: true
|
|
719
|
+
}),
|
|
720
|
+
field("imapHost", "EMAIL_IMAP_HOST", "IMAP server host name."),
|
|
721
|
+
field("imapPort", "EMAIL_IMAP_PORT", "IMAP server port.", { required: false }),
|
|
722
|
+
field("smtpHost", "EMAIL_SMTP_HOST", "SMTP server host name."),
|
|
723
|
+
field("smtpPort", "EMAIL_SMTP_PORT", "SMTP server port.", { required: false }),
|
|
724
|
+
field("fromName", "EMAIL_FROM_NAME", "Display name for outbound mail.", { required: false }),
|
|
725
|
+
field(
|
|
726
|
+
"allowedSenders",
|
|
727
|
+
"EMAIL_ALLOWED_SENDERS",
|
|
728
|
+
"Sender addresses allowed through, as a list or comma-separated string.",
|
|
729
|
+
{ required: false }
|
|
730
|
+
),
|
|
731
|
+
field(
|
|
732
|
+
"allowAutomated",
|
|
733
|
+
"EMAIL_ALLOW_AUTOMATED",
|
|
734
|
+
"When true, automated senders (no-reply, bulk mail) are not filtered out.",
|
|
735
|
+
{ required: false }
|
|
736
|
+
),
|
|
737
|
+
field("pollIntervalMs", "EMAIL_POLL_INTERVAL_MS", "Milliseconds between mailbox polls.", {
|
|
738
|
+
required: false
|
|
739
|
+
}),
|
|
740
|
+
field("maxBodyChars", "EMAIL_MAX_BODY_CHARS", "Longest inbound body kept, in characters.", {
|
|
741
|
+
required: false
|
|
742
|
+
}),
|
|
743
|
+
{
|
|
744
|
+
key: "cursorStore",
|
|
745
|
+
required: false,
|
|
746
|
+
secret: false,
|
|
747
|
+
description: "Programmatic store that persists the IMAP cursor; no env binding."
|
|
748
|
+
}
|
|
749
|
+
];
|
|
750
|
+
var emailChannel = {
|
|
751
|
+
platform: "email",
|
|
752
|
+
transport: "socket",
|
|
753
|
+
senderIdentity: {
|
|
754
|
+
unauthenticated: "an email From header is written by the sender and can be forged"
|
|
755
|
+
},
|
|
756
|
+
config: CONFIG,
|
|
757
|
+
create(config) {
|
|
758
|
+
const address = read.string(config, "address");
|
|
759
|
+
const password = read.string(config, "password");
|
|
760
|
+
const imapHost = read.string(config, "imapHost");
|
|
761
|
+
const smtpHost = read.string(config, "smtpHost");
|
|
762
|
+
const imapPort = read.number(config, "imapPort");
|
|
763
|
+
const smtpPort = read.number(config, "smtpPort");
|
|
764
|
+
const fromName = read.optionalString(config, "fromName");
|
|
765
|
+
const allowedSenders = read.list(config, "allowedSenders");
|
|
766
|
+
const allowAutomated = read.boolean(config, "allowAutomated");
|
|
767
|
+
const pollIntervalMs = read.number(config, "pollIntervalMs");
|
|
768
|
+
const maxBodyChars = read.number(config, "maxBodyChars");
|
|
769
|
+
const cursorStore = readCursorStore(config);
|
|
770
|
+
return new EmailAdapter({
|
|
771
|
+
address,
|
|
772
|
+
password,
|
|
773
|
+
imapHost,
|
|
774
|
+
smtpHost,
|
|
775
|
+
...imapPort === void 0 ? {} : { imapPort },
|
|
776
|
+
...smtpPort === void 0 ? {} : { smtpPort },
|
|
777
|
+
...fromName === void 0 ? {} : { fromName },
|
|
778
|
+
...allowedSenders === void 0 ? {} : { allowedSenders },
|
|
779
|
+
...allowAutomated === void 0 ? {} : { allowAutomated },
|
|
780
|
+
...pollIntervalMs === void 0 ? {} : { pollIntervalMs },
|
|
781
|
+
...maxBodyChars === void 0 ? {} : { maxBodyChars },
|
|
782
|
+
...cursorStore === void 0 ? {} : { cursorStore }
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
};
|
|
786
|
+
|
|
787
|
+
export { EmailAdapter, SeenUidSet, ThreadStore, emailChannel, extractAddr, isAllowedSender, isAutomatedSender, mapEmailError, normalizeEmail };
|
|
788
|
+
//# sourceMappingURL=index.js.map
|
|
789
|
+
//# sourceMappingURL=index.js.map
|