@wtfalch/email 0.20.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,318 @@
1
+ import { MailError } from "./errors.js";
2
+ const MARKER = '# wtfalch-mail-rules v1 ';
3
+ const OPERATION = 'mail rules';
4
+ function invalid(message) {
5
+ throw new MailError(message, { type: 'invalidArguments', operation: OPERATION });
6
+ }
7
+ /** Control characters (tab excepted) cannot sit inside a quoted Sieve string
8
+ * on one line, and have no use in a header match, a folder or an address. */
9
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: that is the point
10
+ const CONTROL = /[\u0000-\u0008\u000a-\u001f\u007f]/;
11
+ function text(value, what) {
12
+ if (typeof value !== 'string' || value.length === 0)
13
+ invalid(`${what} must be a non-empty string`);
14
+ if (CONTROL.test(value))
15
+ invalid(`${what} must not contain control characters`);
16
+ return value;
17
+ }
18
+ /** RFC 5228 §2.4.2: inside a quoted string only `\` and `"` are special. */
19
+ function quote(value) {
20
+ return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
21
+ }
22
+ const KEYWORD = /^[^\s(){%*"\\\]]{1,255}$/;
23
+ const ADDRESS = /^[^\s@"<>\\]+@[^\s@"<>\\]+$/;
24
+ const FIELDS = ['from', 'to', 'cc', 'subject'];
25
+ function checkCondition(value) {
26
+ const item = value;
27
+ if (typeof item !== 'object' || item === null)
28
+ invalid('a condition must be an object');
29
+ if (item.kind === 'hasAttachment' || item.kind === 'listId')
30
+ return { kind: item.kind };
31
+ if (typeof item.kind === 'string' && FIELDS.includes(item.kind)) {
32
+ return {
33
+ kind: item.kind,
34
+ contains: text(item.contains, `${item.kind} contains`),
35
+ };
36
+ }
37
+ return invalid(`unknown condition ${JSON.stringify(item.kind)}`);
38
+ }
39
+ function checkAction(value) {
40
+ const item = value;
41
+ if (typeof item !== 'object' || item === null)
42
+ invalid('an action must be an object');
43
+ switch (item.kind) {
44
+ case 'markRead':
45
+ case 'stop':
46
+ return { kind: item.kind };
47
+ case 'moveTo':
48
+ return { kind: 'moveTo', mailbox: text(item.mailbox, 'the mailbox to move to') };
49
+ case 'addKeyword': {
50
+ const keyword = text(item.keyword, 'the keyword');
51
+ if (!KEYWORD.test(keyword))
52
+ invalid(`${JSON.stringify(keyword)} is not a valid keyword`);
53
+ return { kind: 'addKeyword', keyword };
54
+ }
55
+ case 'forwardTo': {
56
+ const address = text(item.address, 'the address to forward to');
57
+ if (!ADDRESS.test(address))
58
+ invalid(`${JSON.stringify(address)} is not an email address`);
59
+ return { kind: 'forwardTo', address };
60
+ }
61
+ default:
62
+ return invalid(`unknown action ${JSON.stringify(item.kind)}`);
63
+ }
64
+ }
65
+ function checkRules(value) {
66
+ if (!Array.isArray(value))
67
+ invalid('rules must be an array');
68
+ return value.map((raw) => {
69
+ const rule = raw;
70
+ if (typeof rule !== 'object' || rule === null)
71
+ invalid('a rule must be an object');
72
+ if (typeof rule.id !== 'string' || rule.id.length === 0)
73
+ invalid('a rule needs an id');
74
+ if (typeof rule.name !== 'string')
75
+ invalid('a rule needs a name');
76
+ if (typeof rule.enabled !== 'boolean')
77
+ invalid('a rule needs enabled to be true or false');
78
+ if (rule.match !== 'all' && rule.match !== 'any')
79
+ invalid('match must be "all" or "any"');
80
+ if (!Array.isArray(rule.conditions) || rule.conditions.length === 0) {
81
+ invalid('a rule needs at least one condition');
82
+ }
83
+ if (!Array.isArray(rule.actions) || rule.actions.length === 0) {
84
+ invalid('a rule needs at least one action');
85
+ }
86
+ return {
87
+ id: rule.id,
88
+ name: rule.name,
89
+ enabled: rule.enabled,
90
+ match: rule.match,
91
+ conditions: rule.conditions.map(checkCondition),
92
+ actions: rule.actions.map(checkAction),
93
+ };
94
+ });
95
+ }
96
+ function test(condition) {
97
+ switch (condition.kind) {
98
+ case 'listId':
99
+ return 'exists "list-id"';
100
+ case 'hasAttachment':
101
+ // Sieve has no attachment test; a multipart/mixed message is the usual stand-in.
102
+ return 'header :contains "content-type" "multipart/mixed"';
103
+ default:
104
+ return `header :contains ${quote(condition.kind)} ${quote(condition.contains)}`;
105
+ }
106
+ }
107
+ /** Flags first, so they ride along on whichever `fileinto` follows, then the
108
+ * rest in the order the caller gave. */
109
+ function commands(actions) {
110
+ const needs = new Set();
111
+ const flags = [];
112
+ const rest = [];
113
+ for (const action of actions) {
114
+ switch (action.kind) {
115
+ case 'markRead':
116
+ needs.add('imap4flags');
117
+ flags.push('addflag "\\\\Seen";');
118
+ break;
119
+ case 'addKeyword':
120
+ needs.add('imap4flags');
121
+ flags.push(`addflag ${quote(action.keyword)};`);
122
+ break;
123
+ case 'moveTo':
124
+ needs.add('fileinto').add('mailbox');
125
+ rest.push(`fileinto :create ${quote(action.mailbox)};`);
126
+ break;
127
+ case 'forwardTo':
128
+ needs.add('copy');
129
+ rest.push(`redirect :copy ${quote(action.address)};`);
130
+ break;
131
+ case 'stop':
132
+ rest.push('stop;');
133
+ break;
134
+ }
135
+ }
136
+ return { lines: [...flags, ...rest], needs: [...needs] };
137
+ }
138
+ const REQUIRE_ORDER = ['fileinto', 'mailbox', 'imap4flags', 'copy'];
139
+ /**
140
+ * Sieve source for `rules`, first enabled rule first.
141
+ *
142
+ * Throws a `MailError` of type `invalidArguments` for a rule with no
143
+ * condition or action, an empty value, a value with a control character, a
144
+ * keyword with a character IMAP forbids, or a forward address that is not
145
+ * `name@host`. Every value is written as a quoted string with `\` and `"`
146
+ * escaped, so no value can end the string early.
147
+ */
148
+ export function rulesToSieve(rules) {
149
+ return combineScript(rules, null);
150
+ }
151
+ function compile(checked) {
152
+ const blocks = [];
153
+ const needs = new Set();
154
+ for (const rule of checked) {
155
+ if (!rule.enabled)
156
+ continue;
157
+ const { lines, needs: used } = commands(rule.actions);
158
+ for (const name of used)
159
+ needs.add(name);
160
+ const tests = rule.conditions.map(test);
161
+ const head = tests.length === 1
162
+ ? `if ${tests[0]} {`
163
+ : `if ${rule.match === 'all' ? 'allof' : 'anyof'}(${tests.join(', ')}) {`;
164
+ blocks.push([head, ...lines.map((line) => ` ${line}`), '}'].join('\n'));
165
+ }
166
+ return { blocks, needs };
167
+ }
168
+ const VACATION_MARKER = '# wtfalch-vacation v1 ';
169
+ const ISO_DAY = /^\d{4}-\d{2}-\d{2}(?:$|[T ])/;
170
+ function nullableText(value, what, lineBreaks) {
171
+ if (value === null)
172
+ return null;
173
+ if (typeof value !== 'string')
174
+ return invalid(`${what} must be a string or null`);
175
+ const probe = lineBreaks ? value.replace(/[\r\n]/g, '') : value;
176
+ if (CONTROL.test(probe))
177
+ invalid(`${what} must not contain control characters`);
178
+ return value;
179
+ }
180
+ function checkDate(value, what) {
181
+ if (value === null)
182
+ return null;
183
+ if (typeof value !== 'string' || !ISO_DAY.test(value)) {
184
+ return invalid(`${what} must be an ISO date string or null`);
185
+ }
186
+ return value;
187
+ }
188
+ function checkVacation(value) {
189
+ const item = value;
190
+ if (typeof item !== 'object' || item === null)
191
+ invalid('the vacation must be an object');
192
+ if (typeof item.isEnabled !== 'boolean')
193
+ invalid('the vacation needs isEnabled to be true or false');
194
+ const audience = item.audience;
195
+ if (audience !== 'anyone' && audience !== 'company' && audience !== 'nobody') {
196
+ invalid('audience must be "anyone", "company" or "nobody"');
197
+ }
198
+ const domain = nullableText(item.domain, 'the domain', false);
199
+ if (audience === 'company' && item.isEnabled && (domain === null || domain.length === 0)) {
200
+ invalid('a company reply needs a domain');
201
+ }
202
+ return {
203
+ isEnabled: item.isEnabled,
204
+ audience,
205
+ domain,
206
+ fromDate: checkDate(item.fromDate, 'fromDate'),
207
+ toDate: checkDate(item.toDate, 'toDate'),
208
+ subject: nullableText(item.subject, 'the subject', false),
209
+ textBody: nullableText(item.textBody, 'the text', true),
210
+ htmlBody: nullableText(item.htmlBody, 'the html', true),
211
+ };
212
+ }
213
+ function vacationBlock(vacation) {
214
+ if (!vacation.isEnabled || vacation.audience === 'nobody')
215
+ return null;
216
+ const body = (vacation.textBody ?? '').replace(/\r\n|\r|\n/g, '\r\n');
217
+ const subject = vacation.subject === null ? '' : ` :subject ${quote(vacation.subject)}`;
218
+ const command = `vacation :days 1${subject} ${quote(body)};`;
219
+ const tests = [];
220
+ if (vacation.fromDate !== null) {
221
+ tests.push(`currentdate :value "ge" "date" ${quote(vacation.fromDate.slice(0, 10))}`);
222
+ }
223
+ if (vacation.toDate !== null) {
224
+ tests.push(`currentdate :value "le" "date" ${quote(vacation.toDate.slice(0, 10))}`);
225
+ }
226
+ if (vacation.audience === 'company') {
227
+ tests.push(`address :domain :is "from" ${quote(vacation.domain ?? '')}`);
228
+ }
229
+ if (tests.length === 0)
230
+ return command;
231
+ const head = tests.length === 1 ? `if ${tests[0]} {` : `if allof(${tests.join(', ')}) {`;
232
+ return `${head}\n ${command}\n}`;
233
+ }
234
+ /**
235
+ * One Sieve script holding the rules section and a marked vacation section.
236
+ * `rules` null leaves the rules section out; `vacation` null leaves the
237
+ * vacation section out; `combineScript(rules, null)` is `rulesToSieve(rules)`
238
+ * byte for byte, and `combineScript(null, null)` is `''`.
239
+ *
240
+ * Throws `invalidArguments` for a bad rule or a bad vacation value: a subject
241
+ * with a control character, or a text with one other than line breaks (which
242
+ * are written as CRLF).
243
+ */
244
+ export function combineScript(rules, vacation) {
245
+ const checked = rules === null ? null : checkRules(rules);
246
+ const section = vacation === null ? null : checkVacation(vacation);
247
+ const { blocks, needs } = compile(checked ?? []);
248
+ const block = section === null ? null : vacationBlock(section);
249
+ if (block !== null)
250
+ needs.add('vacation');
251
+ if (section !== null && (section.fromDate !== null || section.toDate !== null)) {
252
+ needs.add('date').add('relational');
253
+ }
254
+ const required = [...REQUIRE_ORDER, 'vacation', 'date', 'relational'].filter((name) => needs.has(name));
255
+ const parts = [];
256
+ if (checked !== null)
257
+ parts.push(`${MARKER}${JSON.stringify(checked)}`);
258
+ if (required.length > 0)
259
+ parts.push(`require [${required.map(quote).join(', ')}];`);
260
+ parts.push(...blocks);
261
+ if (section !== null) {
262
+ parts.push(`${VACATION_MARKER}${JSON.stringify(section)}`);
263
+ if (block !== null)
264
+ parts.push(block);
265
+ }
266
+ return parts.length === 0 ? '' : `${parts.join('\n')}\n`;
267
+ }
268
+ function parseMarker(line, marker, check) {
269
+ try {
270
+ return check(JSON.parse(line.slice(marker.length)));
271
+ }
272
+ catch (error) {
273
+ if (error instanceof MailError || error instanceof SyntaxError)
274
+ return null;
275
+ throw error;
276
+ }
277
+ }
278
+ /**
279
+ * The rules and vacation a script was combined from. Each part is rebuilt
280
+ * from its marker JSON alone and the whole script must equal the result;
281
+ * `null` for a hand-written or edited script. An empty string is
282
+ * `{ rules: null, vacation: null }`.
283
+ */
284
+ export function splitScript(script) {
285
+ if (script === '')
286
+ return { rules: null, vacation: null };
287
+ const lines = script.split('\n');
288
+ let rules = null;
289
+ if (lines[0]?.startsWith(MARKER)) {
290
+ rules = parseMarker(lines[0], MARKER, checkRules);
291
+ if (rules === null)
292
+ return null;
293
+ }
294
+ if (combineScript(rules, null) === script)
295
+ return rules === null ? null : { rules, vacation: null };
296
+ for (const line of lines) {
297
+ if (!line.startsWith(VACATION_MARKER))
298
+ continue;
299
+ const vacation = parseMarker(line, VACATION_MARKER, checkVacation);
300
+ if (vacation !== null && combineScript(rules, vacation) === script)
301
+ return { rules, vacation };
302
+ }
303
+ return null;
304
+ }
305
+ /** True for an empty script and for one this module wrote unchanged; a caller
306
+ * refuses to write over a script for which this is false. */
307
+ export function isOurScript(text) {
308
+ return splitScript(text) !== null;
309
+ }
310
+ /**
311
+ * The rules a script was generated from, or `null` when `script` is not one
312
+ * {@link rulesToSieve} wrote unchanged: no marker, a marker that does not
313
+ * parse as rules, or a body that differs from what the generator writes for
314
+ * them.
315
+ */
316
+ export function sieveToRules(script) {
317
+ return splitScript(script)?.rules ?? null;
318
+ }
@@ -1,5 +1,5 @@
1
1
  import { type MailClient } from './client.ts';
2
- import type { Draft, EmailAddress, MailIdentity, MailboxNode, Queued, Sent } from './types.ts';
2
+ import type { Draft, EmailAddress, MailIdentity, MailboxNode, Queued, Sent, Submission, SubmissionState } from './types.ts';
3
3
  /**
4
4
  * The JMAP `Email` object a draft becomes. Exported so the shape can be
5
5
  * asserted without a server.
@@ -147,3 +147,22 @@ export declare function cancel(client: MailClient, sent: Pick<Sent, 'submissionI
147
147
  * `12:00:00Z`.
148
148
  */
149
149
  export declare function queued(client: MailClient): Promise<Queued[]>;
150
+ /**
151
+ * Sent mail with its delivery state, newest `sendAt` first.
152
+ *
153
+ * JMAP's `EmailSubmission` carries no subject, recipients, sent time or
154
+ * failure text: `subject` and `to` come from one `Email/get`, `failure` from
155
+ * the recipient's `deliveryStatus.smtpReply`, and `sentAt` is `sendAt` once
156
+ * the hold has passed. One query per needed `undoStatus`, each filtered on it
157
+ * for the reason given above `queued()`.
158
+ */
159
+ export declare function submissions(client: MailClient, options?: {
160
+ states?: SubmissionState[];
161
+ limit?: number;
162
+ }): Promise<Submission[]>;
163
+ /**
164
+ * Send a message that is already in Sent again, as a new submission with the
165
+ * identity whose address matches the message's From. Nothing is filed: no
166
+ * `onSuccessUpdateEmail`, so the message keeps its mailbox and keywords.
167
+ */
168
+ export declare function resend(client: MailClient, submission: Pick<Submission, 'emailId'>): Promise<Sent>;
@@ -461,3 +461,128 @@ export async function queued(client) {
461
461
  .sort((a, b) => Date.parse(a.sendAt) - Date.parse(b.sendAt));
462
462
  });
463
463
  }
464
+ const SUBMISSION_LIMIT = 100;
465
+ const UNDO_FOR_STATE = {
466
+ scheduled: 'pending',
467
+ sending: 'final',
468
+ delivered: 'final',
469
+ failed: 'final',
470
+ canceled: 'canceled',
471
+ };
472
+ function submissionState(record) {
473
+ if (record.undoStatus === 'canceled')
474
+ return { state: 'canceled', failure: null };
475
+ if (record.undoStatus === 'pending')
476
+ return { state: 'scheduled', failure: null };
477
+ const entries = Object.values(record.deliveryStatus ?? {});
478
+ const refused = entries.find((entry) => entry.delivered === 'no');
479
+ if (refused) {
480
+ return { state: 'failed', failure: refused.smtpReply || 'the server refused delivery' };
481
+ }
482
+ if (entries.length === 0 || entries.some((entry) => entry.delivered !== 'yes')) {
483
+ return { state: 'sending', failure: null };
484
+ }
485
+ return { state: 'delivered', failure: null };
486
+ }
487
+ /**
488
+ * Sent mail with its delivery state, newest `sendAt` first.
489
+ *
490
+ * JMAP's `EmailSubmission` carries no subject, recipients, sent time or
491
+ * failure text: `subject` and `to` come from one `Email/get`, `failure` from
492
+ * the recipient's `deliveryStatus.smtpReply`, and `sentAt` is `sendAt` once
493
+ * the hold has passed. One query per needed `undoStatus`, each filtered on it
494
+ * for the reason given above `queued()`.
495
+ */
496
+ export async function submissions(client, options = {}) {
497
+ const limit = options.limit ?? SUBMISSION_LIMIT;
498
+ if (!Number.isInteger(limit) || limit < 0) {
499
+ throw new MailError('limit must be a non-negative integer', {
500
+ type: 'invalidArguments',
501
+ operation: 'submissions',
502
+ });
503
+ }
504
+ const wanted = options.states ? new Set(options.states) : null;
505
+ const undoStatuses = [
506
+ ...new Set((wanted ? [...wanted] : Object.keys(UNDO_FOR_STATE)).map((state) => UNDO_FOR_STATE[state])),
507
+ ];
508
+ const { jam, accountId } = await client.connect();
509
+ return guard('submissions', async () => {
510
+ const lists = await Promise.all(undoStatuses.map(async (undoStatus) => {
511
+ const [results] = await jam.requestMany((t) => {
512
+ const query = t.EmailSubmission.query({
513
+ accountId,
514
+ filter: { undoStatus },
515
+ });
516
+ const got = t.EmailSubmission.get({ accountId, ids: query.$ref('/ids') });
517
+ return { query, got };
518
+ }, JAM_FETCH);
519
+ return results.got.list;
520
+ }));
521
+ const rows = lists
522
+ .flat()
523
+ .map((record) => ({ record, ...submissionState(record) }))
524
+ .filter((row) => !wanted || wanted.has(row.state))
525
+ .sort((a, b) => Date.parse(b.record.sendAt) - Date.parse(a.record.sendAt))
526
+ .slice(0, limit);
527
+ if (rows.length === 0)
528
+ return [];
529
+ const emailIds = [...new Set(rows.map((row) => row.record.emailId))];
530
+ const [fetched] = await jam.api.Email.get({ accountId, ids: emailIds, properties: ['subject', 'to', 'from'] }, JAM_FETCH);
531
+ const emails = new Map(fetched.list.map((email) => [email.id, email]));
532
+ return rows.map(({ record, state, failure }) => {
533
+ const email = emails.get(record.emailId);
534
+ return {
535
+ submissionId: record.id,
536
+ emailId: record.emailId,
537
+ threadId: record.threadId,
538
+ sendAt: record.sendAt,
539
+ sentAt: state === 'scheduled' || state === 'canceled' ? null : record.sendAt,
540
+ to: email?.to ?? [],
541
+ subject: email?.subject ?? '',
542
+ state,
543
+ failure,
544
+ };
545
+ });
546
+ });
547
+ }
548
+ /**
549
+ * Send a message that is already in Sent again, as a new submission with the
550
+ * identity whose address matches the message's From. Nothing is filed: no
551
+ * `onSuccessUpdateEmail`, so the message keeps its mailbox and keywords.
552
+ */
553
+ export async function resend(client, submission) {
554
+ const { jam, accountId } = await client.connect();
555
+ const { emailId } = submission;
556
+ return guard('resend', async () => {
557
+ const [got] = await jam.api.Email.get({ accountId, ids: [emailId], properties: ['from', 'threadId'] }, JAM_FETCH);
558
+ const email = got.list[0];
559
+ if (!email) {
560
+ throw new MailError(`no message ${emailId} to send again`, {
561
+ type: 'notFound',
562
+ operation: 'resend',
563
+ });
564
+ }
565
+ const address = email.from?.[0]?.email.toLowerCase();
566
+ const identity = (await identities(client)).find((one) => one.email.toLowerCase() === address);
567
+ if (!identity) {
568
+ throw new MailError(`no identity matches the From address of message ${emailId}`, {
569
+ type: 'notFound',
570
+ operation: 'resend',
571
+ });
572
+ }
573
+ const [submitted] = await jam.api.EmailSubmission.set({
574
+ accountId,
575
+ create: { submission: { identityId: identity.id, emailId } },
576
+ }, { using: ['urn:ietf:params:jmap:mail'], ...JAM_FETCH });
577
+ const created = submitted.created?.submission;
578
+ if (!created)
579
+ failed('submission', submitted.notCreated);
580
+ return {
581
+ submissionId: created.id,
582
+ emailId,
583
+ threadId: email.threadId,
584
+ undoStatus: created.undoStatus,
585
+ sendAt: created.sendAt,
586
+ };
587
+ });
588
+ }
@@ -289,6 +289,9 @@ export type Queued = {
289
289
  * fields left to the server's own defaults. */
290
290
  export type VacationResponse = {
291
291
  isEnabled: boolean;
292
+ /** Who gets the reply: anyone, senders in the account's own domain, or
293
+ * nobody (the dates and text are kept, no reply is sent). */
294
+ audience: 'anyone' | 'company' | 'nobody';
292
295
  /** The response starts here, or immediately when `null`. ISO 8601 UTC. */
293
296
  fromDate: string | null;
294
297
  /** The response ends here, or never when `null`. ISO 8601 UTC. */
@@ -338,3 +341,19 @@ export type MailSort = {
338
341
  property: 'receivedAt' | 'sentAt' | 'size' | 'subject' | 'from' | 'to';
339
342
  isAscending?: boolean;
340
343
  };
344
+ export type SubmissionState = 'scheduled' | 'sending' | 'delivered' | 'failed' | 'canceled';
345
+ /** One row of `submissions()`: a sent message and where its delivery stands. */
346
+ export type Submission = {
347
+ submissionId: string;
348
+ emailId: string;
349
+ threadId: string;
350
+ sendAt: string;
351
+ /** `sendAt` once the hold has passed (JMAP has no separate sent time);
352
+ * `null` while `scheduled` or once `canceled`. */
353
+ sentAt: string | null;
354
+ to: readonly EmailAddress[];
355
+ subject: string;
356
+ state: SubmissionState;
357
+ /** The first refusing recipient's `smtpReply`, only when `failed`. */
358
+ failure: string | null;
359
+ };
@@ -15,6 +15,10 @@ export type VacationResponseOptions = {
15
15
  subject?: string | null;
16
16
  textBody?: string | null;
17
17
  htmlBody?: string | null;
18
+ /** Who gets the reply: `anyone`, `company` (senders in the account's own
19
+ * domain) or `nobody` (dates and text kept, no reply). `undefined` leaves
20
+ * it as stored; a new away reply starts at `anyone`. */
21
+ audience?: 'anyone' | 'company' | 'nobody';
18
22
  };
19
23
  /**
20
24
  * Set the vacation response: whether it is on, its window, and its message.
@@ -1,5 +1,8 @@
1
- import { JAM_FETCH } from "./client.js";
1
+ import { JAM_FETCH, SIEVE_CAPABILITY } from "./client.js";
2
2
  import { MailError, guard } from "./errors.js";
3
+ import { identities } from "./identities.js";
4
+ import { combineScript, splitScript } from "./rules.js";
5
+ import { activateSieveScript, saveSieveScript, sieveScriptText, sieveScripts } from "./sieve.js";
3
6
  /**
4
7
  * The vacation auto-reply: RFC 8621 §8's `VacationResponse`, over the
5
8
  * `urn:ietf:params:jmap:vacationresponse` capability.
@@ -20,9 +23,12 @@ import { MailError, guard } from "./errors.js";
20
23
  * by hand; a plain `VacationResponse/get` or `/set` names itself.
21
24
  */
22
25
  const SINGLETON = 'singleton';
26
+ const SCRIPT_NAME = 'wtfalch-mail';
27
+ const AUDIENCES = ['anyone', 'company', 'nobody'];
23
28
  function fromRaw(raw) {
24
29
  return {
25
30
  isEnabled: raw.isEnabled,
31
+ audience: 'anyone',
26
32
  fromDate: raw.fromDate ?? null,
27
33
  toDate: raw.toDate ?? null,
28
34
  subject: raw.subject ?? null,
@@ -30,9 +36,8 @@ function fromRaw(raw) {
30
36
  htmlBody: raw.htmlBody ?? null,
31
37
  };
32
38
  }
33
- /** The account's vacation response as it stands now. */
34
- export async function vacationResponse(client) {
35
- const { jam, accountId } = await client.connect();
39
+ async function readJmap(connection) {
40
+ const { jam, accountId } = connection;
36
41
  return guard('vacation response', async () => {
37
42
  const [result] = await jam.api.VacationResponse.get({ accountId }, JAM_FETCH);
38
43
  const found = result.list[0];
@@ -45,6 +50,41 @@ export async function vacationResponse(client) {
45
50
  return fromRaw(found);
46
51
  });
47
52
  }
53
+ function hasSieve(connection) {
54
+ return connection.doc.capabilities?.[SIEVE_CAPABILITY] !== undefined;
55
+ }
56
+ /** The script the away reply lives in -- the active one, else (for a write)
57
+ * an inactive one named `wtfalch-mail` -- and what it was built from;
58
+ * `split` is null for a hand-written one. */
59
+ async function activeScript(client, orNamed = false) {
60
+ const scripts = await sieveScripts(client);
61
+ const active = scripts.find((script) => script.isActive) ?? null;
62
+ const target = active ?? (orNamed ? scripts.find((s) => s.name === SCRIPT_NAME) : undefined);
63
+ if (!target)
64
+ return { target: null, active, split: { rules: null, vacation: null } };
65
+ const split = splitScript(await sieveScriptText(client, target.id));
66
+ return { target, active, split };
67
+ }
68
+ /** The account's vacation response as it stands now. */
69
+ export async function vacationResponse(client) {
70
+ const connection = await client.connect();
71
+ if (hasSieve(connection)) {
72
+ const { split } = await activeScript(client);
73
+ const section = split?.vacation;
74
+ if (section) {
75
+ return {
76
+ isEnabled: section.isEnabled,
77
+ audience: section.audience,
78
+ fromDate: section.fromDate,
79
+ toDate: section.toDate,
80
+ subject: section.subject,
81
+ textBody: section.textBody,
82
+ htmlBody: section.htmlBody,
83
+ };
84
+ }
85
+ }
86
+ return readJmap(connection);
87
+ }
48
88
  /**
49
89
  * Set the vacation response: whether it is on, its window, and its message.
50
90
  *
@@ -56,13 +96,81 @@ export async function vacationResponse(client) {
56
96
  * responder back on does not need to resupply them.
57
97
  */
58
98
  export async function setVacationResponse(client, options) {
59
- const { jam, accountId } = await client.connect();
60
- const { isEnabled, ...rest } = options;
61
- const patch = { isEnabled };
62
- for (const [key, value] of Object.entries(rest)) {
63
- if (value !== undefined)
64
- patch[key] = value;
99
+ const { audience } = options;
100
+ if (audience !== undefined && !AUDIENCES.includes(audience)) {
101
+ throw new MailError('audience must be "anyone", "company" or "nobody"', {
102
+ type: 'invalidArguments',
103
+ operation: 'set vacation response',
104
+ });
105
+ }
106
+ const connection = await client.connect();
107
+ const { isEnabled, audience: _audience, ...rest } = options;
108
+ const jmapPatch = (fields) => updateJmap(connection, fields);
109
+ if (!hasSieve(connection)) {
110
+ if (audience === 'company' || audience === 'nobody') {
111
+ throw new MailError('this server has no sieve support, so the away reply is for anyone', {
112
+ type: 'unsupported',
113
+ operation: 'set vacation response',
114
+ });
115
+ }
116
+ const patch = { isEnabled };
117
+ for (const [key, value] of Object.entries(rest)) {
118
+ if (value !== undefined)
119
+ patch[key] = value;
120
+ }
121
+ return jmapPatch(patch);
122
+ }
123
+ const { target, active, split } = await activeScript(client, true);
124
+ if (split === null) {
125
+ if (isEnabled) {
126
+ throw new MailError('the active sieve script was not written by this app; not replacing it', {
127
+ type: 'conflict',
128
+ operation: 'set vacation response',
129
+ });
130
+ }
131
+ return jmapPatch({ isEnabled: false });
132
+ }
133
+ const stored = split.vacation ?? {
134
+ ...(await readJmap(connection)),
135
+ domain: null,
136
+ };
137
+ const next = {
138
+ isEnabled,
139
+ audience: audience ?? stored.audience,
140
+ domain: stored.domain,
141
+ fromDate: rest.fromDate !== undefined ? rest.fromDate : stored.fromDate,
142
+ toDate: rest.toDate !== undefined ? rest.toDate : stored.toDate,
143
+ subject: rest.subject !== undefined ? rest.subject : stored.subject,
144
+ textBody: rest.textBody !== undefined ? rest.textBody : stored.textBody,
145
+ htmlBody: rest.htmlBody !== undefined ? rest.htmlBody : stored.htmlBody,
146
+ };
147
+ if (next.audience === 'company' &&
148
+ isEnabled &&
149
+ (audience === 'company' || next.domain === null)) {
150
+ const [first] = await identities(client);
151
+ if (!first) {
152
+ throw new MailError('the account has no identity to take the company domain from', {
153
+ type: 'notFound',
154
+ operation: 'set vacation response',
155
+ });
156
+ }
157
+ next.domain = first.email.slice(first.email.lastIndexOf('@') + 1);
65
158
  }
159
+ const text = combineScript(split.rules, next);
160
+ const saved = await saveSieveScript(client, target?.name ?? SCRIPT_NAME, text, target ? { scriptId: target.id } : {});
161
+ if (!active)
162
+ await activateSieveScript(client, saved.id);
163
+ return jmapPatch({
164
+ isEnabled: false,
165
+ fromDate: next.fromDate,
166
+ toDate: next.toDate,
167
+ subject: next.subject,
168
+ textBody: next.textBody,
169
+ htmlBody: next.htmlBody,
170
+ });
171
+ }
172
+ async function updateJmap(connection, patch) {
173
+ const { jam, accountId } = connection;
66
174
  return guard('set vacation response', async () => {
67
175
  const [result] = await jam.api.VacationResponse.set({ accountId, update: { [SINGLETON]: patch } }, JAM_FETCH);
68
176
  const notUpdated = result.notUpdated;