loopzero-gateway-email 0.0.0-stage → 0.1.1
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 +331 -0
- package/LICENSE +201 -0
- package/README.md +39 -2
- package/dist/index.cjs +896 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +277 -0
- package/dist/index.d.ts +277 -0
- package/dist/index.js +886 -0
- package/dist/index.js.map +1 -0
- package/package.json +80 -3
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { EmailMessageEvent, BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent } from 'loopzero-gateway';
|
|
2
|
+
export type { EmailMessageEvent };
|
|
3
|
+
|
|
4
|
+
/** Where the adapter has read up to: the next UID to dispatch, within one UIDVALIDITY. */
|
|
5
|
+
interface EmailCursor {
|
|
6
|
+
readonly uidValidity: number;
|
|
7
|
+
readonly uid: number;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Persistence seam for the cursor (#348). Without one the cursor lives in memory for the life of
|
|
11
|
+
* the adapter, so a process restart takes a fresh baseline and mail that arrived while it was
|
|
12
|
+
* down is not dispatched.
|
|
13
|
+
*/
|
|
14
|
+
interface EmailCursorStore {
|
|
15
|
+
load(): EmailCursor | undefined | Promise<EmailCursor | undefined>;
|
|
16
|
+
save(cursor: EmailCursor): void | Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
/** Adapter options. */
|
|
19
|
+
interface EmailAdapterOptions {
|
|
20
|
+
/** Email address the bot listens on (also the From: of outbound). */
|
|
21
|
+
readonly address: string;
|
|
22
|
+
/**
|
|
23
|
+
* The mailbox password for the email account, or an app-specific password where required.
|
|
24
|
+
*
|
|
25
|
+
* @platform-term IMAP and SMTP both call this a **password**. Note the divergence: `nodemailer`
|
|
26
|
+
* names its field `pass`, and this one is `password` — ours, not theirs.
|
|
27
|
+
* @issued-at The mail provider's account settings; most require an app password rather than the
|
|
28
|
+
* login password when two-factor authentication is on.
|
|
29
|
+
*/
|
|
30
|
+
readonly password: string;
|
|
31
|
+
/** IMAP server (e.g., "imap.gmail.com"). */
|
|
32
|
+
readonly imapHost: string;
|
|
33
|
+
/** IMAP port. Default 993 (SSL). */
|
|
34
|
+
readonly imapPort?: number;
|
|
35
|
+
/** SMTP server (e.g., "smtp.gmail.com"). */
|
|
36
|
+
readonly smtpHost: string;
|
|
37
|
+
/** SMTP port. Default 587 (STARTTLS). */
|
|
38
|
+
readonly smtpPort?: number;
|
|
39
|
+
/** Display name for outbound From: (defaults to address local-part). */
|
|
40
|
+
readonly fromName?: string;
|
|
41
|
+
/** Allowlist of sender addresses (case-insensitive). Default: open (D333). */
|
|
42
|
+
readonly allowedSenders?: readonly string[];
|
|
43
|
+
/** Allow automated senders (noreply, postmaster, bounce). Default: false (D332). */
|
|
44
|
+
readonly allowAutomated?: boolean;
|
|
45
|
+
/** Polling interval in ms when IMAP IDLE is unavailable. Default 15000. */
|
|
46
|
+
readonly pollIntervalMs?: number;
|
|
47
|
+
/** Max body chars before truncation (EC-2). Default 50000 (~12k tokens). */
|
|
48
|
+
readonly maxBodyChars?: number;
|
|
49
|
+
/**
|
|
50
|
+
* Persist the `{uidValidity, uid}` cursor. A first connect with no cursor (or a changed
|
|
51
|
+
* UIDVALIDITY) baselines at the mailbox's UIDNEXT and dispatches nothing older.
|
|
52
|
+
*/
|
|
53
|
+
readonly cursorStore?: EmailCursorStore;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* `EmailAdapter` — Email platform adapter for `loopzero-gateway`
|
|
58
|
+
* (Adoption Roadmap v1.4 #4; ADRs D327-D339).
|
|
59
|
+
*
|
|
60
|
+
* Stack: nodemailer (SMTP) + imapflow (IMAP IDLE) + mailparser (RFC 5322).
|
|
61
|
+
* Inbound: IMAP IDLE preferred (D328), 15s poll fallback.
|
|
62
|
+
* Outbound: SMTP via nodemailer + threading reciprocity (D337).
|
|
63
|
+
*
|
|
64
|
+
* @public
|
|
65
|
+
*/
|
|
66
|
+
|
|
67
|
+
declare class EmailAdapter extends BasePlatformAdapter {
|
|
68
|
+
readonly platform: "email";
|
|
69
|
+
private readonly options;
|
|
70
|
+
private readonly seenUids;
|
|
71
|
+
/** UIDs finished with in this batch, awaiting one `\Seen` command (#11). */
|
|
72
|
+
private readonly pendingSeen;
|
|
73
|
+
private readonly threadStore;
|
|
74
|
+
private imap;
|
|
75
|
+
private smtp;
|
|
76
|
+
private handler?;
|
|
77
|
+
private connected;
|
|
78
|
+
private dispatchQueue;
|
|
79
|
+
private pollTimer;
|
|
80
|
+
/** Set by `disconnect()`: a lost connection is then not reopened. */
|
|
81
|
+
private stopping;
|
|
82
|
+
private reconnectTimer;
|
|
83
|
+
private readonly reconnectBackoff;
|
|
84
|
+
/** In-memory cursor (#348); mirrored to `options.cursorStore` when one is given. */
|
|
85
|
+
private cursor;
|
|
86
|
+
constructor(opts: EmailAdapterOptions);
|
|
87
|
+
connect(): Promise<boolean>;
|
|
88
|
+
/** A fresh IMAP client, watched for loss of its connection. */
|
|
89
|
+
private _newImapClient;
|
|
90
|
+
/**
|
|
91
|
+
* Open IMAP, keep or take the cursor, and start watching: IDLE when the server has it, a poll
|
|
92
|
+
* otherwise. Used by `connect()` and by every reconnect, so a reconnect resumes from the cursor
|
|
93
|
+
* and dispatches what arrived while the connection was down.
|
|
94
|
+
*/
|
|
95
|
+
private _openImap;
|
|
96
|
+
/**
|
|
97
|
+
* The IMAP connection dropped (a reset, a timeout, the server going away). The adapter stays
|
|
98
|
+
* connected from its caller's view and opens a new IMAP connection with growing delays until
|
|
99
|
+
* one succeeds or `disconnect()` is called. Without this a dropped link ended inbound mail for
|
|
100
|
+
* the life of the process while `connect()` had answered true.
|
|
101
|
+
*/
|
|
102
|
+
private _imapLost;
|
|
103
|
+
private _scheduleReconnect;
|
|
104
|
+
private _reconnectImap;
|
|
105
|
+
private _stopPolling;
|
|
106
|
+
disconnect(): Promise<void>;
|
|
107
|
+
sendMessage(out: OutboundMessage): Promise<SendResult>;
|
|
108
|
+
private sendText;
|
|
109
|
+
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
110
|
+
/**
|
|
111
|
+
* Load the cursor, and baseline it at the mailbox's UIDNEXT when there is none or its
|
|
112
|
+
* UIDVALIDITY no longer matches (the UIDs it counted are gone). Existing mail is not dispatched.
|
|
113
|
+
*/
|
|
114
|
+
private _establishCursor;
|
|
115
|
+
private _advanceCursor;
|
|
116
|
+
/**
|
|
117
|
+
* EC-4: serialize concurrent IDLE dispatches so seen-check is atomic.
|
|
118
|
+
* Fire-and-forget: never throws; errors logged.
|
|
119
|
+
*/
|
|
120
|
+
private _dispatchInbound;
|
|
121
|
+
private _dispatchInboundInner;
|
|
122
|
+
/**
|
|
123
|
+
* Flush the batch to the server. Never throws — a mailbox we cannot flag is
|
|
124
|
+
* not worth dropping mail over; those UIDs simply come back on the next drain.
|
|
125
|
+
*/
|
|
126
|
+
private _flushSeen;
|
|
127
|
+
private _dispatchOrDrop;
|
|
128
|
+
get _threadStoreSize(): number;
|
|
129
|
+
/**
|
|
130
|
+
* Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
|
|
131
|
+
*
|
|
132
|
+
* One line over `runHandler`, which owns the containment: a handler is user code, its throw is
|
|
133
|
+
* named as the handler's failure rather than the platform's, and delivery continues.
|
|
134
|
+
*/
|
|
135
|
+
deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* One configuration field, shaped like the core's `ChannelConfigField` (typed locally so a published
|
|
140
|
+
* `.d.ts` never names a core type an older peer release lacks), and its constructor.
|
|
141
|
+
*/
|
|
142
|
+
interface ConfigField {
|
|
143
|
+
readonly key: string;
|
|
144
|
+
readonly required: boolean;
|
|
145
|
+
readonly secret: boolean;
|
|
146
|
+
readonly description: string;
|
|
147
|
+
readonly env?: string;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* `emailChannel` — the email channel described as data.
|
|
152
|
+
*
|
|
153
|
+
* Typed locally on purpose: the object is structurally a `ChannelDescriptor`, and the integration
|
|
154
|
+
* package's typecheck is where a drift between the two fails. The package has no error class of
|
|
155
|
+
* its own, so a refused value throws the core `GatewayConfigurationError` tagged `gateway-email`.
|
|
156
|
+
*/
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The email channel: the adapter polls IMAP itself, so it needs no webhook route. A From header is
|
|
160
|
+
* written by the sender, so `sender.id` is not authenticated.
|
|
161
|
+
*
|
|
162
|
+
* `create` validates each value and throws `GatewayConfigurationError` (`invalid_config`) naming
|
|
163
|
+
* the key; it makes no network call.
|
|
164
|
+
*
|
|
165
|
+
* @public
|
|
166
|
+
*/
|
|
167
|
+
declare const emailChannel: {
|
|
168
|
+
platform: "email";
|
|
169
|
+
transport: "socket";
|
|
170
|
+
senderIdentity: {
|
|
171
|
+
unauthenticated: string;
|
|
172
|
+
};
|
|
173
|
+
config: readonly ConfigField[];
|
|
174
|
+
create(config: Readonly<Record<string, unknown>>): EmailAdapter;
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Per-error → canonical `SendResult.error` mapping for email IMAP/SMTP failures.
|
|
179
|
+
*
|
|
180
|
+
* Tolerates plain `Error` without `.code`/`.responseCode` (EC-7 pattern from Teams).
|
|
181
|
+
*
|
|
182
|
+
* @internal
|
|
183
|
+
*/
|
|
184
|
+
interface ErrorPayload {
|
|
185
|
+
code: "auth_failed" | "rate_limit" | "invalid_request" | "server_error" | "not_connected" | "empty_text" | "timeout" | "unknown";
|
|
186
|
+
message: string;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Map anything thrown by SMTP or IMAP into the canonical `{ code, message }` payload.
|
|
190
|
+
*
|
|
191
|
+
* Total by construction: `null`, `undefined`, a string and an unrecognised object each map to an
|
|
192
|
+
* `unknown`-coded payload rather than propagating.
|
|
193
|
+
*/
|
|
194
|
+
declare function mapEmailError(err: unknown): ErrorPayload;
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Inbound filters: automated-sender (D332) + allowed-sender allowlist (D333 + EC-3).
|
|
198
|
+
*
|
|
199
|
+
* @internal
|
|
200
|
+
*/
|
|
201
|
+
/**
|
|
202
|
+
* EC-3: extract pure email address from a string that may include display
|
|
203
|
+
* name + brackets (`"Alice" <alice@example.com>`). Normalizes to lowercase.
|
|
204
|
+
*/
|
|
205
|
+
declare function extractAddr(s: string): string;
|
|
206
|
+
/**
|
|
207
|
+
* D332: automated-sender filter. Returns `true` if the message should be
|
|
208
|
+
* DROPPED (sender is automated / bot-loop risk).
|
|
209
|
+
*/
|
|
210
|
+
declare function isAutomatedSender(fromAddress: string, headers: Map<string, string>): boolean;
|
|
211
|
+
/**
|
|
212
|
+
* D333 + EC-3: allowed-sender allowlist.
|
|
213
|
+
*
|
|
214
|
+
* - `undefined` allowlist → OPEN (all allowed).
|
|
215
|
+
* - Empty array → CLOSED (none allowed). Intentional distinction from undefined.
|
|
216
|
+
* - Both sides normalized via `extractAddr` so `"Alice <alice@x>"` matches `alice@x`.
|
|
217
|
+
*/
|
|
218
|
+
declare function isAllowedSender(fromAddress: string, allowedSenders?: readonly string[]): boolean;
|
|
219
|
+
|
|
220
|
+
/** Options for {@link normalizeEmail}. */
|
|
221
|
+
interface NormalizeOptions {
|
|
222
|
+
readonly botAddress: string;
|
|
223
|
+
/** EC-2: cap body length. Default 50000. */
|
|
224
|
+
readonly maxBodyChars?: number;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Parse raw RFC 5322 bytes into an `EmailMessageEvent`.
|
|
228
|
+
*
|
|
229
|
+
* The body is capped at `maxBodyChars` (50000 by default) because an inbound mail can carry
|
|
230
|
+
* megabytes of quoted history, and everything downstream — hooks, the handler, the model — pays for
|
|
231
|
+
* every character of it.
|
|
232
|
+
*/
|
|
233
|
+
declare function normalizeEmail(rawBuffer: Buffer | string, opts: NormalizeOptions): Promise<EmailMessageEvent>;
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Bounded `Set<number>` of dispatched IMAP UIDs (ADR D331).
|
|
237
|
+
*
|
|
238
|
+
* Caps at 5000 entries; trims to 4000 (drops oldest 1000) on overflow.
|
|
239
|
+
* Same pattern as the Teams ConversationReferenceStore / WhatsApp Web bridge
|
|
240
|
+
* — bounded memory in long-running bots.
|
|
241
|
+
*
|
|
242
|
+
* @internal
|
|
243
|
+
*/
|
|
244
|
+
declare class SeenUidSet {
|
|
245
|
+
private set;
|
|
246
|
+
static readonly MAX_SIZE = 5000;
|
|
247
|
+
static readonly TRIM_TO = 4000;
|
|
248
|
+
has(uid: number): boolean;
|
|
249
|
+
add(uid: number): void;
|
|
250
|
+
private trim;
|
|
251
|
+
get size(): number;
|
|
252
|
+
clear(): void;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** What a reply needs in order to land in the same mail thread as the message it answers. */
|
|
256
|
+
interface ThreadContext {
|
|
257
|
+
readonly subject: string;
|
|
258
|
+
readonly references: readonly string[];
|
|
259
|
+
readonly lastMessageId: string;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* In-memory map from conversation id to the headers a threaded reply needs.
|
|
263
|
+
*
|
|
264
|
+
* Bounded at `MAX_SIZE` entries and evicted oldest-first: a long-running bot would otherwise retain
|
|
265
|
+
* every thread it ever saw. State is per-process and deliberately not persisted — a restart loses
|
|
266
|
+
* threading, which degrades a reply to a new thread rather than losing the reply.
|
|
267
|
+
*/
|
|
268
|
+
declare class ThreadStore {
|
|
269
|
+
private readonly map;
|
|
270
|
+
static readonly MAX_SIZE = 1000;
|
|
271
|
+
recordFromInbound(event: EmailMessageEvent): void;
|
|
272
|
+
lookup(topicId: string): ThreadContext | undefined;
|
|
273
|
+
get size(): number;
|
|
274
|
+
clear(): void;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export { EmailAdapter, type EmailAdapterOptions, type EmailCursor, type EmailCursorStore, type NormalizeOptions, SeenUidSet, type ThreadContext, ThreadStore, emailChannel, extractAddr, isAllowedSender, isAutomatedSender, mapEmailError, normalizeEmail };
|