@sedge-hq/mail 0.0.0-stage → 0.0.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/README.md +40 -2
- package/package.json +58 -5
- package/src/account.ts +325 -0
- package/src/email.ts +278 -0
- package/src/mailbox.ts +319 -0
package/README.md
CHANGED
|
@@ -1,3 +1,41 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @sedge-hq/mail
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Email for [sedge](https://sedge.sh), the always-on agent, over IMAP and SMTP:
|
|
4
|
+
|
|
5
|
+
- **`email`**, a channel: write to sedge's address, and it answers by email, in the same thread.
|
|
6
|
+
- **`mailbox`**, a signal: each new mail wakes sedge with its sender, subject and text, and its
|
|
7
|
+
actions send, reply to, file and mark mail.
|
|
8
|
+
|
|
9
|
+
In `sedge`, say "set up email" or "tell me when Ada writes, and file newsletters away".
|
|
10
|
+
|
|
11
|
+
**Logging in.** Give the address and an app password: Gmail, iCloud, Yahoo and Fastmail make you
|
|
12
|
+
create one for mail apps, in the account's security settings. The password goes to your keychain.
|
|
13
|
+
sedge knows the servers of Gmail, iCloud, Fastmail, Yahoo, AOL, Zoho and GMX; for others, set
|
|
14
|
+
`imap` and `smtp` as `host:port`. A bridge on your machine (Proton Mail Bridge) works too.
|
|
15
|
+
Outlook.com and Microsoft 365 only let in mail apps that sign in through Microsoft, which this
|
|
16
|
+
doesn't do yet.
|
|
17
|
+
|
|
18
|
+
**The channel.** Give sedge an address of its own, or share yours through an `alias` such as
|
|
19
|
+
`you+sedge@gmail.com`, so only mail to the alias reaches it and the rest of your mailbox is left
|
|
20
|
+
alone. You pair by emailing the code from the invite. Since anyone can put your address in `From`,
|
|
21
|
+
it then only reads mail your mail server found your own domain vouched for (DMARC, or a DKIM
|
|
22
|
+
signature of your domain); anything else gets no answer, and the connection's status says why.
|
|
23
|
+
Questions come with numbered choices, answered with the number or the word. Auto-replies are
|
|
24
|
+
ignored, so an out-of-office can't start a loop.
|
|
25
|
+
|
|
26
|
+
**The signal.** It watches a folder (`INBOX` by default), only looking: mail stays unread. It
|
|
27
|
+
starts with what arrives after you connect it. Set `attachments` to keep them for the agent. Its
|
|
28
|
+
details are `from`, `name`, `to`, `cc`, `subject`, `date`, `messageId`, `text` and `attachments`,
|
|
29
|
+
for conditions like `when: from = boss@work.com`. Its actions:
|
|
30
|
+
|
|
31
|
+
| Action | What it does |
|
|
32
|
+
| ------- | --------------------------------------------------------------- |
|
|
33
|
+
| `send` | Send a mail. |
|
|
34
|
+
| `reply` | Reply to a mail, to its sender or (`all`) everyone on it. |
|
|
35
|
+
| `move` | Move a mail to `archive`, `trash`, `junk`, or a folder by name. |
|
|
36
|
+
| `mark` | Mark a mail read or unread, flagged or not. |
|
|
37
|
+
|
|
38
|
+
They go through your permissions, like any action. Mail is outside content: anyone can write to
|
|
39
|
+
you, so what it says is handed to the agent as data, not instructions.
|
|
40
|
+
|
|
41
|
+
[Channels and signals](https://github.com/sedge-hq/sedge/blob/main/docs/channels-and-signals.md) · MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@sedge-hq/mail",
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "Email for sedge: write to it by email, and wake it when mail arrives.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"email",
|
|
7
|
+
"imap",
|
|
8
|
+
"mail",
|
|
9
|
+
"sedge",
|
|
10
|
+
"sedge-kit",
|
|
11
|
+
"smtp"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://sedge.sh",
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/sedge-hq/sedge.git",
|
|
18
|
+
"directory": "packages/mail"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"src",
|
|
22
|
+
"!src/**/*.test.ts"
|
|
23
|
+
],
|
|
24
|
+
"type": "module",
|
|
25
|
+
"exports": {
|
|
26
|
+
".": "./src/email.ts",
|
|
27
|
+
"./mailbox": "./src/mailbox.ts"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"typecheck": "tsc --noEmit",
|
|
34
|
+
"test": "bun --bun vitest run --passWithNoTests"
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@sedge-hq/kit": "0.4.0",
|
|
38
|
+
"imapflow": "2.12.2",
|
|
39
|
+
"mailparser": "3.15.1",
|
|
40
|
+
"nodemailer": "10.6.2"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@sedge-hq/config": "0.0.0",
|
|
44
|
+
"@types/bun": "1.4.5",
|
|
45
|
+
"@types/mailparser": "3.9.0",
|
|
46
|
+
"@types/nodemailer": "8.0.2",
|
|
47
|
+
"@types/smtp-server": "3.5.13",
|
|
48
|
+
"hoodiecrow-imap": "3.3.1",
|
|
49
|
+
"smtp-server": "3.21.8",
|
|
50
|
+
"typescript": "7.0.2",
|
|
51
|
+
"vitest": "5.1.2"
|
|
52
|
+
},
|
|
53
|
+
"sedge": {
|
|
54
|
+
"plugins": [
|
|
55
|
+
"./src/email.ts",
|
|
56
|
+
"./src/mailbox.ts"
|
|
57
|
+
]
|
|
58
|
+
}
|
|
59
|
+
}
|
package/src/account.ts
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { field, secret } from '@sedge-hq/kit';
|
|
2
|
+
import { ImapFlow } from 'imapflow';
|
|
3
|
+
import { simpleParser, type AddressObject, type ParsedMail } from 'mailparser';
|
|
4
|
+
import nodemailer from 'nodemailer';
|
|
5
|
+
|
|
6
|
+
/** The settings every kind in this package shares: which account, and how to reach it. */
|
|
7
|
+
export const ACCOUNT = {
|
|
8
|
+
address: field.text('The email address sedge logs in as.'),
|
|
9
|
+
password: secret(
|
|
10
|
+
'Its password. Gmail, iCloud, Yahoo and Fastmail want an app password, made in the account’s security settings, not your usual one.',
|
|
11
|
+
),
|
|
12
|
+
imap: field.optional(
|
|
13
|
+
field.text(
|
|
14
|
+
'The IMAP server as host:port, when sedge doesn’t know your provider. Default: from the address (Gmail, iCloud, Fastmail, Yahoo, AOL, Zoho, GMX).',
|
|
15
|
+
),
|
|
16
|
+
),
|
|
17
|
+
smtp: field.optional(
|
|
18
|
+
field.text('The SMTP server as host:port, for sending. Default: from the address.'),
|
|
19
|
+
),
|
|
20
|
+
username: field.optional(field.text('The login name, when it isn’t the address.')),
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export interface AccountSettings {
|
|
24
|
+
readonly address: string;
|
|
25
|
+
readonly password: string;
|
|
26
|
+
readonly imap?: string | undefined;
|
|
27
|
+
readonly smtp?: string | undefined;
|
|
28
|
+
readonly username?: string | undefined;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const GMAIL = { imap: 'imap.gmail.com:993', smtp: 'smtp.gmail.com:465' };
|
|
32
|
+
const ICLOUD = { imap: 'imap.mail.me.com:993', smtp: 'smtp.mail.me.com:587' };
|
|
33
|
+
const FASTMAIL = { imap: 'imap.fastmail.com:993', smtp: 'smtp.fastmail.com:465' };
|
|
34
|
+
|
|
35
|
+
/** Servers of providers that let a mail client log in with an (app) password. */
|
|
36
|
+
const PROVIDERS: Record<string, { readonly imap: string; readonly smtp: string }> = {
|
|
37
|
+
'gmail.com': GMAIL,
|
|
38
|
+
'googlemail.com': GMAIL,
|
|
39
|
+
'icloud.com': ICLOUD,
|
|
40
|
+
'me.com': ICLOUD,
|
|
41
|
+
'mac.com': ICLOUD,
|
|
42
|
+
'fastmail.com': FASTMAIL,
|
|
43
|
+
'fastmail.fm': FASTMAIL,
|
|
44
|
+
'yahoo.com': { imap: 'imap.mail.yahoo.com:993', smtp: 'smtp.mail.yahoo.com:465' },
|
|
45
|
+
'aol.com': { imap: 'imap.aol.com:993', smtp: 'smtp.aol.com:465' },
|
|
46
|
+
'zoho.com': { imap: 'imap.zoho.com:993', smtp: 'smtp.zoho.com:465' },
|
|
47
|
+
'gmx.com': { imap: 'imap.gmx.com:993', smtp: 'mail.gmx.com:465' },
|
|
48
|
+
'gmx.net': { imap: 'imap.gmx.net:993', smtp: 'mail.gmx.net:465' },
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export interface Server {
|
|
52
|
+
readonly host: string;
|
|
53
|
+
readonly port: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const domainOf = (address: string) => address.slice(address.lastIndexOf('@') + 1).toLowerCase();
|
|
57
|
+
|
|
58
|
+
const parseServer = (text: string, port: number): Server => {
|
|
59
|
+
const match = /^\[?([^\]]+?)\]?(?::(\d+))?$/.exec(text.trim());
|
|
60
|
+
if (!match) throw new Error(`"${text}" isn't a server: give it as host or host:port.`);
|
|
61
|
+
return { host: match[1]!, port: match[2] ? Number(match[2]) : port };
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/** The server to use: the one set, or the provider's for the address. */
|
|
65
|
+
export const serverFor = (settings: AccountSettings, protocol: 'imap' | 'smtp'): Server => {
|
|
66
|
+
const set = settings[protocol];
|
|
67
|
+
const fallback = protocol === 'imap' ? 993 : 465;
|
|
68
|
+
if (set) return parseServer(set, fallback);
|
|
69
|
+
const known = PROVIDERS[domainOf(settings.address)];
|
|
70
|
+
if (!known)
|
|
71
|
+
throw new Error(
|
|
72
|
+
`sedge doesn't know the mail servers for ${domainOf(settings.address)}: set ${protocol} as host:port.`,
|
|
73
|
+
);
|
|
74
|
+
return parseServer(known[protocol], fallback);
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/** A server on this machine (a bridge like Proton's, or a test server) may use its own certificate. */
|
|
78
|
+
const isLocal = (host: string) => host === 'localhost' || host === '::1' || host.startsWith('127.');
|
|
79
|
+
|
|
80
|
+
/** An IMAP client. TLS on 993; elsewhere it must upgrade with STARTTLS, unless it's on this machine. */
|
|
81
|
+
export const imapClient = (settings: AccountSettings) => {
|
|
82
|
+
const { host, port } = serverFor(settings, 'imap');
|
|
83
|
+
const local = isLocal(host);
|
|
84
|
+
return new ImapFlow({
|
|
85
|
+
host,
|
|
86
|
+
port,
|
|
87
|
+
secure: port === 993,
|
|
88
|
+
...(port !== 993 && !local ? { doSTARTTLS: true } : {}),
|
|
89
|
+
...(local ? { tls: { rejectUnauthorized: false } } : {}),
|
|
90
|
+
auth: { user: settings.username ?? settings.address, pass: settings.password },
|
|
91
|
+
logger: false,
|
|
92
|
+
// Starts listening for new mail (IDLE) after a second of quiet, not imapflow's 15.
|
|
93
|
+
autoIdleDelay: 1000,
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/** A connection for sending. TLS on 465; elsewhere STARTTLS is required, unless it's on this machine. */
|
|
98
|
+
export const smtpTransport = (settings: AccountSettings) => {
|
|
99
|
+
const { host, port } = serverFor(settings, 'smtp');
|
|
100
|
+
const local = isLocal(host);
|
|
101
|
+
return nodemailer.createTransport({
|
|
102
|
+
host,
|
|
103
|
+
port,
|
|
104
|
+
secure: port === 465,
|
|
105
|
+
requireTLS: port !== 465 && !local,
|
|
106
|
+
...(local ? { tls: { rejectUnauthorized: false } } : {}),
|
|
107
|
+
auth: { user: settings.username ?? settings.address, pass: settings.password },
|
|
108
|
+
});
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
// ── Reading mail ───────────────────────────────────────────────────────────────────────────────
|
|
112
|
+
|
|
113
|
+
export const parse = (source: Buffer | Uint8Array) => simpleParser(Buffer.from(source));
|
|
114
|
+
|
|
115
|
+
const addresses = (field: AddressObject | ReadonlyArray<AddressObject> | undefined) =>
|
|
116
|
+
(field === undefined ? [] : Array.isArray(field) ? field : [field as AddressObject])
|
|
117
|
+
.flatMap((object) => object.value)
|
|
118
|
+
.flatMap((entry) => (entry.address ? [entry.address.toLowerCase()] : []));
|
|
119
|
+
|
|
120
|
+
/** Who it's from, lowercase. */
|
|
121
|
+
export const senderOf = (mail: ParsedMail) => addresses(mail.from)[0];
|
|
122
|
+
|
|
123
|
+
/** Everyone it was sent to (To, Cc and the envelope's Delivered-To), lowercase. */
|
|
124
|
+
export const recipientsOf = (mail: ParsedMail) => {
|
|
125
|
+
const delivered = mail.headerLines
|
|
126
|
+
.filter((line) => ['delivered-to', 'x-original-to'].includes(line.key))
|
|
127
|
+
.map((line) =>
|
|
128
|
+
line.line
|
|
129
|
+
.slice(line.line.indexOf(':') + 1)
|
|
130
|
+
.trim()
|
|
131
|
+
.toLowerCase(),
|
|
132
|
+
);
|
|
133
|
+
return [...addresses(mail.to), ...addresses(mail.cc), ...delivered];
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
/** `"Name" <address>` as people read it. */
|
|
137
|
+
export const display = (field: AddressObject | ReadonlyArray<AddressObject> | undefined) =>
|
|
138
|
+
(field === undefined ? [] : Array.isArray(field) ? field : [field as AddressObject])
|
|
139
|
+
.flatMap((object) => object.value)
|
|
140
|
+
.map((entry) =>
|
|
141
|
+
entry.name ? `${entry.name} <${entry.address ?? ''}>` : (entry.address ?? ''),
|
|
142
|
+
)
|
|
143
|
+
.join(', ');
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Sent by a program rather than a person (an auto-reply, a bounce, sedge itself): answering it
|
|
147
|
+
* could loop. RFC 3834's `Auto-Submitted`, and the older `Precedence` and `X-Autoreply`.
|
|
148
|
+
*/
|
|
149
|
+
export const isAutomatic = (mail: ParsedMail) => {
|
|
150
|
+
const header = (name: string) => {
|
|
151
|
+
const value = mail.headers.get(name);
|
|
152
|
+
return typeof value === 'string' ? value.trim().toLowerCase() : '';
|
|
153
|
+
};
|
|
154
|
+
const submitted = header('auto-submitted');
|
|
155
|
+
return (
|
|
156
|
+
(submitted !== '' && submitted !== 'no') ||
|
|
157
|
+
['bulk', 'junk', 'auto_reply'].includes(header('precedence')) ||
|
|
158
|
+
mail.headers.has('x-autoreply')
|
|
159
|
+
);
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
/** What the sender wrote themselves: the reply without the earlier message quoted below it. */
|
|
163
|
+
export const ownWords = (text: string) => {
|
|
164
|
+
const lines = text.replace(/\r\n?/g, '\n').split('\n');
|
|
165
|
+
const quoteFrom = (i: number) =>
|
|
166
|
+
lines.slice(i).every((line) => line.startsWith('>') || line.trim() === '');
|
|
167
|
+
for (let i = 0; i < lines.length; i++) {
|
|
168
|
+
const line = lines[i]!.trim();
|
|
169
|
+
// "On Mon, 1 Dec 2026 at 09:00, sedge <…> wrote:", which clients sometimes wrap in two.
|
|
170
|
+
const attribution = /^On\b.*\bwrote:$/.test(line)
|
|
171
|
+
? 1
|
|
172
|
+
: /^On\b/.test(line) && /\bwrote:$/.test(lines[i + 1]?.trim() ?? '')
|
|
173
|
+
? 2
|
|
174
|
+
: 0;
|
|
175
|
+
if (attribution > 0 && quoteFrom(i + attribution))
|
|
176
|
+
return lines.slice(0, i).join('\n').trim();
|
|
177
|
+
if (line.startsWith('>') && quoteFrom(i)) return lines.slice(0, i).join('\n').trim();
|
|
178
|
+
}
|
|
179
|
+
return text.trim();
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
// ── Is it really from them? ────────────────────────────────────────────────────────────────────
|
|
183
|
+
|
|
184
|
+
interface Results {
|
|
185
|
+
readonly authserv: string;
|
|
186
|
+
readonly methods: ReadonlyArray<{
|
|
187
|
+
readonly method: string;
|
|
188
|
+
readonly result: string;
|
|
189
|
+
readonly props: Readonly<Record<string, string>>;
|
|
190
|
+
}>;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** One `Authentication-Results` header (RFC 8601), with its comments taken out. */
|
|
194
|
+
export const parseResults = (value: string): Results | undefined => {
|
|
195
|
+
let text = value.replace(/\r?\n[ \t]+/g, ' ');
|
|
196
|
+
// Comments can nest: (google.com: domain of … (more)).
|
|
197
|
+
for (let before = ''; before !== text;) {
|
|
198
|
+
before = text;
|
|
199
|
+
text = text.replace(/\([^()]*\)/g, ' ');
|
|
200
|
+
}
|
|
201
|
+
const [id, ...rest] = text.split(';').map((part) => part.trim());
|
|
202
|
+
const authserv = id?.split(/\s+/)[0]?.toLowerCase();
|
|
203
|
+
if (!authserv) return undefined;
|
|
204
|
+
const methods = rest.flatMap((part) => {
|
|
205
|
+
const [head, ...props] = part.split(/\s+/);
|
|
206
|
+
const match = /^([\w.-]+)(?:\/[\d]+)?=([\w-]+)$/.exec(head ?? '');
|
|
207
|
+
if (!match) return [];
|
|
208
|
+
return [
|
|
209
|
+
{
|
|
210
|
+
method: match[1]!.toLowerCase(),
|
|
211
|
+
result: match[2]!.toLowerCase(),
|
|
212
|
+
props: Object.fromEntries(
|
|
213
|
+
props.flatMap((prop) => {
|
|
214
|
+
const eq = prop.indexOf('=');
|
|
215
|
+
return eq > 0
|
|
216
|
+
? [
|
|
217
|
+
[
|
|
218
|
+
prop.slice(0, eq).toLowerCase(),
|
|
219
|
+
prop.slice(eq + 1).replace(/^"|"$/g, ''),
|
|
220
|
+
],
|
|
221
|
+
]
|
|
222
|
+
: [];
|
|
223
|
+
}),
|
|
224
|
+
),
|
|
225
|
+
},
|
|
226
|
+
];
|
|
227
|
+
});
|
|
228
|
+
return { authserv, methods };
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
/** `Authentication-Results` headers, top first: the receiving server adds its own on top. */
|
|
232
|
+
export const resultsOf = (mail: ParsedMail) =>
|
|
233
|
+
mail.headerLines
|
|
234
|
+
.filter((line) => line.key === 'authentication-results')
|
|
235
|
+
.flatMap((line) => {
|
|
236
|
+
const parsed = parseResults(line.line.slice(line.line.indexOf(':') + 1));
|
|
237
|
+
return parsed ? [parsed] : [];
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
/** Relaxed alignment (DMARC's): one domain is the other or under it. */
|
|
241
|
+
const aligned = (a: string | undefined, b: string) => {
|
|
242
|
+
const x = (a ?? '').replace(/^@/, '').replace(/^.*@/, '').toLowerCase();
|
|
243
|
+
return x !== '' && (x === b || x.endsWith(`.${b}`) || b.endsWith(`.${x}`));
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
export type Verdict =
|
|
247
|
+
| { readonly genuine: true; readonly authservs: ReadonlyArray<string> }
|
|
248
|
+
| { readonly genuine: false; readonly why: string };
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Whether the sender's own domain vouched for this mail, going by what the user's mail server
|
|
252
|
+
* found when it arrived. `From` alone can be forged by anyone, so a channel only believes mail
|
|
253
|
+
* its server says passed DMARC, or DKIM signed by the sender's domain.
|
|
254
|
+
*
|
|
255
|
+
* `trusted` are the servers (authserv-ids) seen on the pairing mail. Their topmost results are
|
|
256
|
+
* read, and anything below (a sender can add headers of their own) is ignored. Without `trusted`
|
|
257
|
+
* (pairing itself), every result on the mail is read; it carries the code only the user has.
|
|
258
|
+
*/
|
|
259
|
+
export const verify = (mail: ParsedMail, trusted?: ReadonlyArray<string>): Verdict => {
|
|
260
|
+
const all = resultsOf(mail);
|
|
261
|
+
const sender = senderOf(mail);
|
|
262
|
+
if (!sender) return { genuine: false, why: 'it has no sender' };
|
|
263
|
+
if (all.length === 0)
|
|
264
|
+
return {
|
|
265
|
+
genuine: false,
|
|
266
|
+
why: "the mail server didn't say whether it is genuine (no Authentication-Results)",
|
|
267
|
+
};
|
|
268
|
+
const domain = domainOf(sender);
|
|
269
|
+
let results: ReadonlyArray<Results>;
|
|
270
|
+
if (trusted) {
|
|
271
|
+
if (!trusted.includes(all[0]!.authserv))
|
|
272
|
+
return { genuine: false, why: `it wasn't checked by ${trusted.join(' or ')}` };
|
|
273
|
+
const seen = new Set<string>();
|
|
274
|
+
results = all.filter(
|
|
275
|
+
(r) => trusted.includes(r.authserv) && !seen.has(r.authserv) && seen.add(r.authserv),
|
|
276
|
+
);
|
|
277
|
+
} else {
|
|
278
|
+
results = all;
|
|
279
|
+
}
|
|
280
|
+
const methods = results.flatMap((r) => r.methods);
|
|
281
|
+
const failed = methods.find(
|
|
282
|
+
(m) =>
|
|
283
|
+
(m.method === 'dmarc' && ['fail', 'quarantine', 'reject'].includes(m.result)) ||
|
|
284
|
+
(m.method === 'dkim' &&
|
|
285
|
+
m.result === 'fail' &&
|
|
286
|
+
aligned(m.props['header.d'] ?? m.props['header.i'], domain)) ||
|
|
287
|
+
(m.method === 'spf' && m.result === 'fail'),
|
|
288
|
+
);
|
|
289
|
+
if (failed) return { genuine: false, why: `${failed.method}=${failed.result}` };
|
|
290
|
+
const passed = methods.some(
|
|
291
|
+
(m) =>
|
|
292
|
+
m.result === 'pass' &&
|
|
293
|
+
((m.method === 'dmarc' &&
|
|
294
|
+
(m.props['header.from'] === undefined ||
|
|
295
|
+
aligned(m.props['header.from'], domain))) ||
|
|
296
|
+
(m.method === 'dkim' &&
|
|
297
|
+
aligned(m.props['header.d'] ?? m.props['header.i'], domain))),
|
|
298
|
+
);
|
|
299
|
+
return passed
|
|
300
|
+
? { genuine: true, authservs: [...new Set(results.map((r) => r.authserv))] }
|
|
301
|
+
: { genuine: false, why: `${domain} didn't vouch for it (no DMARC or DKIM pass)` };
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
/** A subject line from a reply's first line, without Markdown. */
|
|
305
|
+
export const subjectFrom = (text: string) => {
|
|
306
|
+
const first =
|
|
307
|
+
text
|
|
308
|
+
.split('\n')
|
|
309
|
+
.map((line) =>
|
|
310
|
+
line
|
|
311
|
+
.replace(/^[#>*\-\s]+/, '')
|
|
312
|
+
.replace(/[*_`~]/g, '')
|
|
313
|
+
.trim(),
|
|
314
|
+
)
|
|
315
|
+
.find((line) => line !== '') ?? '';
|
|
316
|
+
return first.length > 70 ? `${first.slice(0, 69).trimEnd()}…` : first || 'From sedge';
|
|
317
|
+
};
|
|
318
|
+
|
|
319
|
+
/** `Re: …`, once. */
|
|
320
|
+
export const reSubject = (subject: string | undefined) =>
|
|
321
|
+
/^re:/i.test(subject ?? '') ? subject! : `Re: ${subject ?? ''}`.trimEnd();
|
|
322
|
+
|
|
323
|
+
/** Cuts text to `max` characters, saying so. */
|
|
324
|
+
export const clip = (text: string, max: number) =>
|
|
325
|
+
text.length > max ? `${text.slice(0, max)}\n… (${text.length - max} more characters)` : text;
|
package/src/email.ts
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { defineChannel, field, type ReceivedFile, type Reply } from '@sedge-hq/kit';
|
|
2
|
+
import type { ImapFlow } from 'imapflow';
|
|
3
|
+
import type { ParsedMail } from 'mailparser';
|
|
4
|
+
import { basename } from 'node:path';
|
|
5
|
+
import {
|
|
6
|
+
ACCOUNT,
|
|
7
|
+
imapClient,
|
|
8
|
+
isAutomatic,
|
|
9
|
+
ownWords,
|
|
10
|
+
parse,
|
|
11
|
+
recipientsOf,
|
|
12
|
+
reSubject,
|
|
13
|
+
senderOf,
|
|
14
|
+
smtpTransport,
|
|
15
|
+
subjectFrom,
|
|
16
|
+
verify,
|
|
17
|
+
} from './account';
|
|
18
|
+
|
|
19
|
+
/** A reply continues the conversation it answers when that's this recent; otherwise it starts one. */
|
|
20
|
+
const THREAD_FOR = 3 * 24 * 60 * 60 * 1000;
|
|
21
|
+
/** Looks for mail now and then even if the server's push (IDLE) went quiet. */
|
|
22
|
+
const POLL = 5 * 60 * 1000;
|
|
23
|
+
|
|
24
|
+
interface Thread {
|
|
25
|
+
readonly id: string;
|
|
26
|
+
readonly references: ReadonlyArray<string>;
|
|
27
|
+
readonly subject: string;
|
|
28
|
+
readonly at: number;
|
|
29
|
+
}
|
|
30
|
+
type Choices = ReadonlyArray<{ readonly label: string; readonly value: string }>;
|
|
31
|
+
|
|
32
|
+
/** The choice a reply picks: its number, label or value, alone on the first line. */
|
|
33
|
+
export const pickOf = (words: string, choices: Choices) => {
|
|
34
|
+
const first = (words.split('\n')[0] ?? '').trim().replace(/[.)]$/, '').toLowerCase();
|
|
35
|
+
if (first === '') return undefined;
|
|
36
|
+
const n = Number(first);
|
|
37
|
+
if (Number.isInteger(n) && n >= 1 && n <= choices.length) return choices[n - 1];
|
|
38
|
+
return choices.find(
|
|
39
|
+
(choice) => choice.label.toLowerCase() === first || choice.value.toLowerCase() === first,
|
|
40
|
+
);
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Email as a sedge channel: write to sedge's address, and it answers by email. Give it an
|
|
45
|
+
* account of its own (a new address), or share yours through an alias such as you+sedge@gmail.com,
|
|
46
|
+
* so only mail sent to the alias reaches it.
|
|
47
|
+
*
|
|
48
|
+
* It only reads mail from addresses paired through an invite (an email with the code only your
|
|
49
|
+
* screen shows), and only mail their own domain vouched for: since anyone can put any address in
|
|
50
|
+
* `From`, mail that didn't pass DMARC or DKIM, by what your mail server found, gets no answer.
|
|
51
|
+
*/
|
|
52
|
+
export default defineChannel({
|
|
53
|
+
name: 'email',
|
|
54
|
+
summary: 'email: write to sedge, and it answers by email',
|
|
55
|
+
settings: {
|
|
56
|
+
...ACCOUNT,
|
|
57
|
+
alias: field.optional(
|
|
58
|
+
field.text(
|
|
59
|
+
'Only mail sent to this address reaches sedge, and its replies come from it: like you+sedge@gmail.com, so it can share your own mailbox.',
|
|
60
|
+
),
|
|
61
|
+
),
|
|
62
|
+
},
|
|
63
|
+
connect: async (settings, kit) => {
|
|
64
|
+
const me = (settings.alias ?? settings.address).toLowerCase();
|
|
65
|
+
const smtp = smtpTransport(settings);
|
|
66
|
+
const client: ImapFlow = imapClient(settings);
|
|
67
|
+
await client.connect();
|
|
68
|
+
const box = await client.mailboxOpen('INBOX');
|
|
69
|
+
|
|
70
|
+
// Paired addresses, each with the servers that vouched for its pairing mail.
|
|
71
|
+
const paired = new Map<string, ReadonlyArray<string>>(
|
|
72
|
+
Object.entries(
|
|
73
|
+
JSON.parse((await kit.memo.get('paired')) ?? '{}') as Record<
|
|
74
|
+
string,
|
|
75
|
+
ReadonlyArray<string>
|
|
76
|
+
>,
|
|
77
|
+
),
|
|
78
|
+
);
|
|
79
|
+
let home = (await kit.memo.get('home')) ?? paired.keys().next().value;
|
|
80
|
+
const showStatus = (problem?: string) =>
|
|
81
|
+
kit.status(
|
|
82
|
+
problem ??
|
|
83
|
+
(paired.size > 0 ? `${me} · paired` : `${me} · email the pairing code to pair`),
|
|
84
|
+
);
|
|
85
|
+
showStatus();
|
|
86
|
+
|
|
87
|
+
// Where it got to: mail already there when it first connected isn't for it.
|
|
88
|
+
type Seen = { readonly validity: string; readonly uid: number };
|
|
89
|
+
const stored = JSON.parse((await kit.memo.get('seen')) ?? 'null') as Seen | null;
|
|
90
|
+
let seen: Seen =
|
|
91
|
+
stored && stored.validity === String(box.uidValidity)
|
|
92
|
+
? stored
|
|
93
|
+
: { validity: String(box.uidValidity), uid: (box.uidNext ?? 1) - 1 };
|
|
94
|
+
await kit.memo.set('seen', JSON.stringify(seen));
|
|
95
|
+
|
|
96
|
+
const threadKey = (address: string) => `thread:${address}`;
|
|
97
|
+
const choicesKey = (address: string) => `choices:${address}`;
|
|
98
|
+
|
|
99
|
+
const send = async (to: string, reply: Reply, inReplyTo?: Thread) => {
|
|
100
|
+
const thread =
|
|
101
|
+
inReplyTo ??
|
|
102
|
+
(JSON.parse((await kit.memo.get(threadKey(to))) ?? 'null') as Thread | null) ??
|
|
103
|
+
undefined;
|
|
104
|
+
const current = thread && Date.now() - thread.at < THREAD_FOR ? thread : undefined;
|
|
105
|
+
const choices = reply.choices ?? [];
|
|
106
|
+
const text =
|
|
107
|
+
choices.length > 0
|
|
108
|
+
? `${reply.text}\n\nReply with one of:\n${choices.map((c, i) => `${i + 1}. ${c.label}`).join('\n')}`
|
|
109
|
+
: reply.text;
|
|
110
|
+
await smtp.sendMail({
|
|
111
|
+
from: me,
|
|
112
|
+
to,
|
|
113
|
+
subject: current ? reSubject(current.subject) : subjectFrom(reply.text),
|
|
114
|
+
text,
|
|
115
|
+
...(current
|
|
116
|
+
? { inReplyTo: current.id, references: [...current.references, current.id] }
|
|
117
|
+
: {}),
|
|
118
|
+
attachments: (reply.files ?? []).map((file) => ({
|
|
119
|
+
path: file.path,
|
|
120
|
+
filename: basename(file.path),
|
|
121
|
+
})),
|
|
122
|
+
// Marks it as sent by a program, so auto-replies to it don't loop back.
|
|
123
|
+
headers: { 'Auto-Submitted': current ? 'auto-replied' : 'auto-generated' },
|
|
124
|
+
});
|
|
125
|
+
await kit.memo.set(choicesKey(to), JSON.stringify(choices));
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const filesOf = async (mail: ParsedMail) => {
|
|
129
|
+
const files: Array<ReceivedFile> = [];
|
|
130
|
+
for (const attachment of mail.attachments) {
|
|
131
|
+
// Pictures a message's own layout shows (a signature's logo) aren't sent files.
|
|
132
|
+
if (attachment.related) continue;
|
|
133
|
+
const name = attachment.filename ?? 'attachment';
|
|
134
|
+
files.push({
|
|
135
|
+
path: await kit.save(name, new Uint8Array(attachment.content)),
|
|
136
|
+
name,
|
|
137
|
+
type: attachment.contentType,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
return files;
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
/** Hands the mail to sedge if it's for it; true when it took it (so it's marked read). */
|
|
144
|
+
const handle = async (mail: ParsedMail): Promise<boolean> => {
|
|
145
|
+
const from = senderOf(mail);
|
|
146
|
+
if (!from || from === me || isAutomatic(mail)) return false;
|
|
147
|
+
if (settings.alias && !recipientsOf(mail).includes(me)) return false;
|
|
148
|
+
const words = ownWords(mail.text ?? '');
|
|
149
|
+
const thread: Thread = {
|
|
150
|
+
id: mail.messageId ?? '',
|
|
151
|
+
references: [mail.references ?? []].flat(),
|
|
152
|
+
subject: mail.subject ?? '',
|
|
153
|
+
at: Date.now(),
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
if (!paired.has(from)) {
|
|
157
|
+
const code = /\bpair\s+(\S+)/i.exec(`${mail.subject ?? ''}\n${words}`)?.[1];
|
|
158
|
+
if (!code) return false;
|
|
159
|
+
const verdict = verify(mail);
|
|
160
|
+
if (!verdict.genuine) {
|
|
161
|
+
showStatus(`a pairing email from ${from} wasn't verified: ${verdict.why}`);
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
if (!(await kit.claim(code, from))) return false;
|
|
165
|
+
paired.set(from, verdict.authservs);
|
|
166
|
+
home = from;
|
|
167
|
+
await kit.memo.set('paired', JSON.stringify(Object.fromEntries(paired)));
|
|
168
|
+
await kit.memo.set('home', from);
|
|
169
|
+
await kit.memo.set(threadKey(from), JSON.stringify(thread));
|
|
170
|
+
await send(from, { text: "Paired. I'm sedge; write to me here any time." }, thread);
|
|
171
|
+
showStatus();
|
|
172
|
+
return true;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const verdict = verify(mail, paired.get(from));
|
|
176
|
+
if (!verdict.genuine) {
|
|
177
|
+
showStatus(`ignored an email from ${from} that wasn't verified: ${verdict.why}`);
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
home = from;
|
|
181
|
+
await kit.memo.set('home', from);
|
|
182
|
+
if (mail.messageId) await kit.memo.set(threadKey(from), JSON.stringify(thread));
|
|
183
|
+
|
|
184
|
+
const offered = JSON.parse((await kit.memo.get(choicesKey(from))) ?? '[]') as Choices;
|
|
185
|
+
const picked = offered.length > 0 ? pickOf(words, offered) : undefined;
|
|
186
|
+
if (picked) {
|
|
187
|
+
await kit.memo.set(choicesKey(from), '[]');
|
|
188
|
+
await kit.receive({
|
|
189
|
+
type: 'picked',
|
|
190
|
+
from,
|
|
191
|
+
value: picked.value,
|
|
192
|
+
...(mail.messageId ? { key: mail.messageId } : {}),
|
|
193
|
+
});
|
|
194
|
+
return true;
|
|
195
|
+
}
|
|
196
|
+
const files = await filesOf(mail);
|
|
197
|
+
// The subject says what it's about when the body doesn't (a forwarded mail, a photo).
|
|
198
|
+
const text =
|
|
199
|
+
words !== '' && !/^re:/i.test(mail.subject ?? '') && mail.subject
|
|
200
|
+
? `${mail.subject}\n\n${words}`
|
|
201
|
+
: words || (mail.subject ?? '');
|
|
202
|
+
if (text === '' && files.length === 0) return true;
|
|
203
|
+
await kit.receive({
|
|
204
|
+
type: 'message',
|
|
205
|
+
from,
|
|
206
|
+
text,
|
|
207
|
+
...(mail.messageId ? { key: mail.messageId } : {}),
|
|
208
|
+
...(files.length > 0 ? { files } : {}),
|
|
209
|
+
});
|
|
210
|
+
return true;
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
// One look at a time: new mail, oldest first, each marked read once it's handled.
|
|
214
|
+
let looking = Promise.resolve();
|
|
215
|
+
const look = () =>
|
|
216
|
+
(looking = looking.then(async () => {
|
|
217
|
+
// Strict servers refuse `*` in an empty folder.
|
|
218
|
+
const mailbox = client.mailbox;
|
|
219
|
+
if (!mailbox || mailbox.exists === 0) return;
|
|
220
|
+
const fresh = await client.fetchAll(
|
|
221
|
+
`${seen.uid + 1}:*`,
|
|
222
|
+
{ uid: true, source: true },
|
|
223
|
+
{ uid: true },
|
|
224
|
+
);
|
|
225
|
+
for (const message of fresh.sort((a, b) => a.uid - b.uid)) {
|
|
226
|
+
// `n:*` also answers with the newest message when nothing is newer than n.
|
|
227
|
+
if (message.uid <= seen.uid || !message.source) continue;
|
|
228
|
+
const mail = await parse(message.source);
|
|
229
|
+
const took = await handle(mail).catch((error: unknown) => {
|
|
230
|
+
kit.status(
|
|
231
|
+
`couldn't handle an email: ${error instanceof Error ? error.message : String(error)}`,
|
|
232
|
+
);
|
|
233
|
+
return false;
|
|
234
|
+
});
|
|
235
|
+
// Only its own mail: in a shared mailbox, the rest stays as it was.
|
|
236
|
+
if (took)
|
|
237
|
+
await client.messageFlagsAdd(String(message.uid), ['\\Seen'], {
|
|
238
|
+
uid: true,
|
|
239
|
+
});
|
|
240
|
+
seen = { ...seen, uid: message.uid };
|
|
241
|
+
await kit.memo.set('seen', JSON.stringify(seen));
|
|
242
|
+
}
|
|
243
|
+
}));
|
|
244
|
+
|
|
245
|
+
return {
|
|
246
|
+
listen: () =>
|
|
247
|
+
new Promise<void>((resolve, reject) => {
|
|
248
|
+
const fail = (error: unknown) => {
|
|
249
|
+
clearInterval(timer);
|
|
250
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
251
|
+
};
|
|
252
|
+
const poke = () => void look().catch(fail);
|
|
253
|
+
const timer = setInterval(poke, POLL);
|
|
254
|
+
client.on('exists', poke);
|
|
255
|
+
client.on('error', fail);
|
|
256
|
+
client.on('close', () => {
|
|
257
|
+
clearInterval(timer);
|
|
258
|
+
if (kit.signal.aborted) resolve();
|
|
259
|
+
else reject(new Error('the mail server closed the connection'));
|
|
260
|
+
});
|
|
261
|
+
kit.signal.addEventListener('abort', () => client.close(), { once: true });
|
|
262
|
+
poke();
|
|
263
|
+
}),
|
|
264
|
+
invite: (code) =>
|
|
265
|
+
`Email ${me} with the subject "pair ${code}" (mailto:${me}?subject=pair%20${code})`,
|
|
266
|
+
deliver: async (reply, to) => {
|
|
267
|
+
const address = to ?? home;
|
|
268
|
+
if (!address || paired.size === 0)
|
|
269
|
+
throw new Error('Email is not paired yet: email the pairing code first.');
|
|
270
|
+
await send(address, reply);
|
|
271
|
+
},
|
|
272
|
+
close: async () => {
|
|
273
|
+
client.close();
|
|
274
|
+
smtp.close();
|
|
275
|
+
},
|
|
276
|
+
};
|
|
277
|
+
},
|
|
278
|
+
});
|
package/src/mailbox.ts
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
import { defineSignal, field, type Happening, type ReceivedFile } from '@sedge-hq/kit';
|
|
2
|
+
import type { ImapFlow } from 'imapflow';
|
|
3
|
+
import type { ParsedMail } from 'mailparser';
|
|
4
|
+
import {
|
|
5
|
+
ACCOUNT,
|
|
6
|
+
type AccountSettings,
|
|
7
|
+
clip,
|
|
8
|
+
display,
|
|
9
|
+
imapClient,
|
|
10
|
+
parse,
|
|
11
|
+
reSubject,
|
|
12
|
+
senderOf,
|
|
13
|
+
smtpTransport,
|
|
14
|
+
} from './account';
|
|
15
|
+
|
|
16
|
+
/** How much of a mail's text the agent gets. */
|
|
17
|
+
const KEEP = 20_000;
|
|
18
|
+
const POLL = 5 * 60 * 1000;
|
|
19
|
+
|
|
20
|
+
/** A new mail, as the agent and `when` conditions read it. */
|
|
21
|
+
export const happeningOf = async (
|
|
22
|
+
mail: ParsedMail,
|
|
23
|
+
key: string,
|
|
24
|
+
files: ReadonlyArray<ReceivedFile> = [],
|
|
25
|
+
): Promise<Happening> => ({
|
|
26
|
+
text: `Mail from ${display(mail.from) || 'someone'}: ${mail.subject ?? '(no subject)'}`,
|
|
27
|
+
key: mail.messageId ?? key,
|
|
28
|
+
details: {
|
|
29
|
+
from: senderOf(mail) ?? '',
|
|
30
|
+
name: mail.from?.value[0]?.name ?? '',
|
|
31
|
+
to: display(mail.to),
|
|
32
|
+
...(mail.cc ? { cc: display(mail.cc) } : {}),
|
|
33
|
+
subject: mail.subject ?? '',
|
|
34
|
+
date: (mail.date ?? new Date()).toISOString(),
|
|
35
|
+
...(mail.messageId ? { messageId: mail.messageId } : {}),
|
|
36
|
+
text: clip((mail.text ?? '').trim(), KEEP),
|
|
37
|
+
...(mail.attachments.length > 0
|
|
38
|
+
? {
|
|
39
|
+
attachments: mail.attachments
|
|
40
|
+
.filter((a) => !a.related)
|
|
41
|
+
.map((a) => ({
|
|
42
|
+
name: a.filename ?? 'attachment',
|
|
43
|
+
type: a.contentType,
|
|
44
|
+
size: a.size,
|
|
45
|
+
})),
|
|
46
|
+
}
|
|
47
|
+
: {}),
|
|
48
|
+
},
|
|
49
|
+
...(files.length > 0 ? { files } : {}),
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
/** Opens the folder on a short connection of its own, does `act`, and logs out. */
|
|
53
|
+
const withFolder = async <A>(
|
|
54
|
+
settings: AccountSettings,
|
|
55
|
+
folder: string,
|
|
56
|
+
act: (client: ImapFlow) => Promise<A>,
|
|
57
|
+
): Promise<A> => {
|
|
58
|
+
const client = imapClient(settings);
|
|
59
|
+
await client.connect();
|
|
60
|
+
try {
|
|
61
|
+
await client.mailboxOpen(folder);
|
|
62
|
+
return await act(client);
|
|
63
|
+
} finally {
|
|
64
|
+
await client.logout().catch(() => client.close());
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/** The UID of the message with this Message-ID in the open folder. */
|
|
69
|
+
const find = async (client: ImapFlow, messageId: string) => {
|
|
70
|
+
const uids = await client.search({ header: { 'message-id': messageId } }, { uid: true });
|
|
71
|
+
const uid = Array.isArray(uids) ? uids[0] : undefined;
|
|
72
|
+
if (uid === undefined) throw new Error(`No message ${messageId} in this folder.`);
|
|
73
|
+
return uid;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
/** "archive", "trash", "junk" and "sent" mean the account's own folders for them. */
|
|
77
|
+
const SPECIAL: Record<string, ReadonlyArray<string>> = {
|
|
78
|
+
archive: ['\\Archive', '\\All'],
|
|
79
|
+
trash: ['\\Trash'],
|
|
80
|
+
junk: ['\\Junk'],
|
|
81
|
+
spam: ['\\Junk'],
|
|
82
|
+
sent: ['\\Sent'],
|
|
83
|
+
};
|
|
84
|
+
const folderFor = async (client: ImapFlow, name: string) => {
|
|
85
|
+
const uses = SPECIAL[name.toLowerCase()];
|
|
86
|
+
if (!uses) return name;
|
|
87
|
+
const found = (await client.list()).find(
|
|
88
|
+
(box) => box.specialUse && uses.includes(box.specialUse),
|
|
89
|
+
);
|
|
90
|
+
// A mailbox without the special folder: the name as given (many servers call it Archive).
|
|
91
|
+
return found?.path ?? name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const folderSetting = (settings: { folder?: string | undefined }) => settings.folder ?? 'INBOX';
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* A mailbox as a sedge signal: each new mail wakes the agent with who sent it, its subject and its
|
|
98
|
+
* text, and its actions send, reply, file and mark mail. It only reads (it never marks mail read
|
|
99
|
+
* by looking), and it starts with what arrives after it connects.
|
|
100
|
+
*
|
|
101
|
+
* Mail is outside content: anyone can write to you, so it's handed to the agent as data, and what
|
|
102
|
+
* it does about a mail goes through your permissions like any other signal.
|
|
103
|
+
*/
|
|
104
|
+
export default defineSignal({
|
|
105
|
+
name: 'mailbox',
|
|
106
|
+
summary: 'new mail in your mailbox, and sending, replying to and filing mail',
|
|
107
|
+
settings: {
|
|
108
|
+
...ACCOUNT,
|
|
109
|
+
folder: field.optional(field.text('The folder to watch. Default: INBOX.')),
|
|
110
|
+
attachments: field.optional(
|
|
111
|
+
field.flag('Keep attachments, so the agent can open them. Default: off.'),
|
|
112
|
+
),
|
|
113
|
+
},
|
|
114
|
+
actions: {
|
|
115
|
+
send: {
|
|
116
|
+
description:
|
|
117
|
+
'Send an email from this mailbox. `text` is the body, plain text (Markdown reads fine).',
|
|
118
|
+
input: {
|
|
119
|
+
to: field.list('Who to send it to: email addresses.'),
|
|
120
|
+
subject: field.text('The subject.'),
|
|
121
|
+
text: field.text('The body.'),
|
|
122
|
+
cc: field.optional(field.list('Who to copy, if anyone.')),
|
|
123
|
+
},
|
|
124
|
+
run: async ({ to, subject, text, cc }, settings) => {
|
|
125
|
+
const smtp = smtpTransport(settings);
|
|
126
|
+
try {
|
|
127
|
+
await smtp.sendMail({
|
|
128
|
+
from: settings.address,
|
|
129
|
+
to: [...to],
|
|
130
|
+
...(cc?.length ? { cc: [...cc] } : {}),
|
|
131
|
+
subject,
|
|
132
|
+
text,
|
|
133
|
+
});
|
|
134
|
+
} finally {
|
|
135
|
+
smtp.close();
|
|
136
|
+
}
|
|
137
|
+
return `Sent "${subject}" to ${[...to, ...(cc ?? [])].join(', ')}.`;
|
|
138
|
+
},
|
|
139
|
+
},
|
|
140
|
+
reply: {
|
|
141
|
+
description:
|
|
142
|
+
'Reply to a mail in the watched folder, by its messageId (from the event). Goes to its sender, or to everyone on it with `all`.',
|
|
143
|
+
input: {
|
|
144
|
+
messageId: field.text('The mail’s messageId.'),
|
|
145
|
+
text: field.text('The reply.'),
|
|
146
|
+
all: field.optional(field.flag('Reply to everyone on it, not only the sender.')),
|
|
147
|
+
},
|
|
148
|
+
run: async ({ messageId, text, all }, settings) => {
|
|
149
|
+
const original = await withFolder(
|
|
150
|
+
settings,
|
|
151
|
+
folderSetting(settings),
|
|
152
|
+
async (client) => {
|
|
153
|
+
const uid = await find(client, messageId);
|
|
154
|
+
const message = await client.fetchOne(
|
|
155
|
+
String(uid),
|
|
156
|
+
{ source: true },
|
|
157
|
+
{ uid: true },
|
|
158
|
+
);
|
|
159
|
+
if (!message || !message.source)
|
|
160
|
+
throw new Error(`Couldn't read ${messageId}.`);
|
|
161
|
+
return parse(message.source);
|
|
162
|
+
},
|
|
163
|
+
);
|
|
164
|
+
const me = settings.address.toLowerCase();
|
|
165
|
+
const replyTo = original.replyTo ?? original.from;
|
|
166
|
+
const list = (value: typeof original.to) =>
|
|
167
|
+
(value === undefined ? [] : [value].flat())
|
|
168
|
+
.flatMap((object) => object.value)
|
|
169
|
+
.flatMap((entry) => (entry.address ? [entry.address] : []));
|
|
170
|
+
const to = list(replyTo);
|
|
171
|
+
const cc = all
|
|
172
|
+
? [...list(original.to), ...list(original.cc)].filter(
|
|
173
|
+
(address) => address.toLowerCase() !== me && !to.includes(address),
|
|
174
|
+
)
|
|
175
|
+
: [];
|
|
176
|
+
if (to.length === 0) throw new Error(`${messageId} has no sender to reply to.`);
|
|
177
|
+
const smtp = smtpTransport(settings);
|
|
178
|
+
try {
|
|
179
|
+
await smtp.sendMail({
|
|
180
|
+
from: settings.address,
|
|
181
|
+
to,
|
|
182
|
+
...(cc.length > 0 ? { cc } : {}),
|
|
183
|
+
subject: reSubject(original.subject),
|
|
184
|
+
text,
|
|
185
|
+
inReplyTo: messageId,
|
|
186
|
+
references: [[original.references ?? []].flat(), messageId].flat(),
|
|
187
|
+
});
|
|
188
|
+
} finally {
|
|
189
|
+
smtp.close();
|
|
190
|
+
}
|
|
191
|
+
return `Replied to ${[...to, ...cc].join(', ')}.`;
|
|
192
|
+
},
|
|
193
|
+
},
|
|
194
|
+
move: {
|
|
195
|
+
description:
|
|
196
|
+
'Move a mail out of the watched folder, by its messageId: to "archive", "trash", "junk", or a folder by name.',
|
|
197
|
+
input: {
|
|
198
|
+
messageId: field.text('The mail’s messageId.'),
|
|
199
|
+
folder: field.text('archive, trash, junk, or a folder’s name.'),
|
|
200
|
+
},
|
|
201
|
+
run: async ({ messageId, folder }, settings) =>
|
|
202
|
+
withFolder(settings, folderSetting(settings), async (client) => {
|
|
203
|
+
const uid = await find(client, messageId);
|
|
204
|
+
const target = await folderFor(client, folder);
|
|
205
|
+
if (!(await client.messageMove(String(uid), target, { uid: true })))
|
|
206
|
+
throw new Error(`The server didn't move it to ${target}.`);
|
|
207
|
+
return `Moved it to ${target}.`;
|
|
208
|
+
}),
|
|
209
|
+
},
|
|
210
|
+
mark: {
|
|
211
|
+
description:
|
|
212
|
+
'Mark a mail in the watched folder, by its messageId: read or unread, flagged or not.',
|
|
213
|
+
input: {
|
|
214
|
+
messageId: field.text('The mail’s messageId.'),
|
|
215
|
+
read: field.optional(field.flag('true marks it read, false unread.')),
|
|
216
|
+
flagged: field.optional(
|
|
217
|
+
field.flag('true flags (stars) it, false takes the flag off.'),
|
|
218
|
+
),
|
|
219
|
+
},
|
|
220
|
+
run: async ({ messageId, read, flagged }, settings) =>
|
|
221
|
+
withFolder(settings, folderSetting(settings), async (client) => {
|
|
222
|
+
const uid = String(await find(client, messageId));
|
|
223
|
+
const done: Array<string> = [];
|
|
224
|
+
for (const [flag, on, words] of [
|
|
225
|
+
['\\Seen', read, ['read', 'unread']],
|
|
226
|
+
['\\Flagged', flagged, ['flagged', 'unflagged']],
|
|
227
|
+
] as const) {
|
|
228
|
+
if (on === undefined) continue;
|
|
229
|
+
if (on) await client.messageFlagsAdd(uid, [flag], { uid: true });
|
|
230
|
+
else await client.messageFlagsRemove(uid, [flag], { uid: true });
|
|
231
|
+
done.push(on ? words[0] : words[1]);
|
|
232
|
+
}
|
|
233
|
+
return done.length > 0
|
|
234
|
+
? `Marked it ${done.join(' and ')}.`
|
|
235
|
+
: 'Nothing to change.';
|
|
236
|
+
}),
|
|
237
|
+
},
|
|
238
|
+
},
|
|
239
|
+
watch: async function* (settings, kit) {
|
|
240
|
+
const folder = folderSetting(settings);
|
|
241
|
+
const client = imapClient(settings);
|
|
242
|
+
await client.connect();
|
|
243
|
+
// Read-only (EXAMINE): looking never marks anything read.
|
|
244
|
+
const box = await client.mailboxOpen(folder, { readOnly: true });
|
|
245
|
+
kit.status(`${settings.address} · ${folder}`);
|
|
246
|
+
|
|
247
|
+
type Seen = { readonly validity: string; readonly uid: number };
|
|
248
|
+
const stored = JSON.parse((await kit.memo.get('seen')) ?? 'null') as Seen | null;
|
|
249
|
+
let seen: Seen =
|
|
250
|
+
stored && stored.validity === String(box.uidValidity)
|
|
251
|
+
? stored
|
|
252
|
+
: { validity: String(box.uidValidity), uid: (box.uidNext ?? 1) - 1 };
|
|
253
|
+
await kit.memo.set('seen', JSON.stringify(seen));
|
|
254
|
+
|
|
255
|
+
// Wakes the loop below when the server says mail arrived, it's time to look anyway, or it closed.
|
|
256
|
+
let wake: (() => void) | undefined;
|
|
257
|
+
let pending = true;
|
|
258
|
+
let closed: Error | undefined;
|
|
259
|
+
const poke = () => {
|
|
260
|
+
pending = true;
|
|
261
|
+
wake?.();
|
|
262
|
+
};
|
|
263
|
+
client.on('exists', poke);
|
|
264
|
+
client.on('error', (error: Error) => {
|
|
265
|
+
closed = error;
|
|
266
|
+
poke();
|
|
267
|
+
});
|
|
268
|
+
client.on('close', () => {
|
|
269
|
+
closed ??= new Error('the mail server closed the connection');
|
|
270
|
+
poke();
|
|
271
|
+
});
|
|
272
|
+
const timer = setInterval(poke, POLL);
|
|
273
|
+
const stop = () => {
|
|
274
|
+
clearInterval(timer);
|
|
275
|
+
client.close();
|
|
276
|
+
poke();
|
|
277
|
+
};
|
|
278
|
+
kit.signal.addEventListener('abort', stop, { once: true });
|
|
279
|
+
try {
|
|
280
|
+
while (!kit.signal.aborted) {
|
|
281
|
+
if (!pending) await new Promise<void>((resolve) => (wake = resolve));
|
|
282
|
+
pending = false;
|
|
283
|
+
if (kit.signal.aborted) break;
|
|
284
|
+
if (closed) throw closed;
|
|
285
|
+
// Strict servers refuse `*` in an empty folder.
|
|
286
|
+
const mailbox = client.mailbox;
|
|
287
|
+
if (!mailbox || mailbox.exists === 0) continue;
|
|
288
|
+
const fresh = await client.fetchAll(
|
|
289
|
+
`${seen.uid + 1}:*`,
|
|
290
|
+
{ uid: true, source: true },
|
|
291
|
+
{ uid: true },
|
|
292
|
+
);
|
|
293
|
+
for (const message of fresh.sort((a, b) => a.uid - b.uid)) {
|
|
294
|
+
if (message.uid <= seen.uid || !message.source) continue;
|
|
295
|
+
const mail = await parse(message.source);
|
|
296
|
+
const files: Array<ReceivedFile> = [];
|
|
297
|
+
if (settings.attachments) {
|
|
298
|
+
for (const attachment of mail.attachments) {
|
|
299
|
+
if (attachment.related) continue;
|
|
300
|
+
const name = attachment.filename ?? 'attachment';
|
|
301
|
+
files.push({
|
|
302
|
+
path: await kit.save(name, new Uint8Array(attachment.content)),
|
|
303
|
+
name,
|
|
304
|
+
type: attachment.contentType,
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
yield await happeningOf(mail, `${seen.validity}:${message.uid}`, files);
|
|
309
|
+
seen = { ...seen, uid: message.uid };
|
|
310
|
+
await kit.memo.set('seen', JSON.stringify(seen));
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
} finally {
|
|
314
|
+
kit.signal.removeEventListener('abort', stop);
|
|
315
|
+
clearInterval(timer);
|
|
316
|
+
client.close();
|
|
317
|
+
}
|
|
318
|
+
},
|
|
319
|
+
});
|