@wtfalch/email 0.20.0 → 0.21.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 +13 -5
- package/dist/mailbox/fake/index.d.ts +2 -2
- package/dist/mailbox/fake/index.js +1 -1
- package/dist/mailbox/fake/mailbox.d.ts +11 -0
- package/dist/mailbox/fake/mailbox.js +49 -0
- package/dist/mailbox/index.d.ts +4 -0
- package/dist/mailbox/index.js +2 -0
- package/dist/mailbox/principals.d.ts +48 -0
- package/dist/mailbox/principals.js +111 -0
- package/dist/mailbox/rules.d.ts +66 -0
- package/dist/mailbox/rules.js +191 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -60,7 +60,11 @@ some of RFC 8621 §2's ten rights (`mayReadItems`, `mayAddItems`, …) on that o
|
|
|
60
60
|
mailbox, and `unshareMailbox` takes them back. Both patch `Mailbox/set` at
|
|
61
61
|
`shareWith/<accountId>` rather than sending the whole `shareWith` map, so
|
|
62
62
|
granting or revoking one account's access never touches another's, and needs
|
|
63
|
-
no read first. `
|
|
63
|
+
no read first. `findPrincipals(client, query)` turns an email address or a
|
|
64
|
+
name into the colleague's `accountId` and display name (JMAP principals, same
|
|
65
|
+
domain as the login only; an empty list is nobody, two entries is a choice),
|
|
66
|
+
and `lookupPrincipal` returns the one match or `null`, or throws `ambiguous`.
|
|
67
|
+
`mailboxes()` returns each node's own `myRights` (what the
|
|
64
68
|
signed-in login may do there) and `shareWith` (who else can, and with what),
|
|
65
69
|
both always present, every right explicit — RFC 8621 requires `myRights`, and
|
|
66
70
|
the wire has been seen to fill in every unrequested right on `shareWith` as
|
|
@@ -174,10 +178,14 @@ the server without saving it, for a check before committing. Exactly one
|
|
|
174
178
|
script is active per account: `activateSieveScript(client, id)` makes it the
|
|
175
179
|
one that runs, and `deactivateSieveScripts` turns filtering off entirely.
|
|
176
180
|
`deleteSieveScript` is refused while its target is the active script — the
|
|
177
|
-
server's own guard, deactivate first.
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
+
server's own guard, deactivate first. Stalwart's `SieveScript` is
|
|
182
|
+
only a name, an active flag and a blob of Sieve source, so rules live in
|
|
183
|
+
this package: `rulesToSieve(rules)` writes Sieve for a list of `MailRule`s
|
|
184
|
+
(from/to/cc/subject contains, has attachment, list-id present; move to a
|
|
185
|
+
folder, add a keyword, mark read, forward a copy, stop), and
|
|
186
|
+
`sieveToRules(script)` reads back only a script that function wrote, using a
|
|
187
|
+
marker line at the top, and gives `null` for a hand-written or edited one.
|
|
188
|
+
Every value is quoted and escaped, so it cannot end its string early.
|
|
181
189
|
|
|
182
190
|
### The React
|
|
183
191
|
|
|
@@ -10,10 +10,10 @@
|
|
|
10
10
|
* ```
|
|
11
11
|
*/
|
|
12
12
|
import { MailClient } from '../client.ts';
|
|
13
|
-
import { FakeMailbox, type FakeOptions, type SeedMessage, type SeedThread } from './mailbox.ts';
|
|
13
|
+
import { FakeMailbox, type FakeOptions, type SeedMessage, type SeedPrincipal, type SeedThread } from './mailbox.ts';
|
|
14
14
|
import { SAMPLE } from './sample.ts';
|
|
15
15
|
export { FakeMailbox };
|
|
16
|
-
export type { FakeOptions, SeedMessage, SeedThread };
|
|
16
|
+
export type { FakeOptions, SeedMessage, SeedPrincipal, SeedThread };
|
|
17
17
|
export { SAMPLE };
|
|
18
18
|
export type FakeMail = {
|
|
19
19
|
/** A real `MailClient`. Everything this package exports works against it
|
|
@@ -44,6 +44,17 @@ export type FakeOptions = {
|
|
|
44
44
|
latency?: number;
|
|
45
45
|
/** The session's `maxSizeUpload`. Stalwart's own default when not given. */
|
|
46
46
|
maxSizeUpload?: number;
|
|
47
|
+
/** The directory `Principal/query` searches: colleagues with a mail
|
|
48
|
+
* account of their own. Empty when not given. */
|
|
49
|
+
principals?: SeedPrincipal[];
|
|
50
|
+
};
|
|
51
|
+
export type SeedPrincipal = {
|
|
52
|
+
id: string;
|
|
53
|
+
name: string;
|
|
54
|
+
email: string;
|
|
55
|
+
/** The account a share would be granted to. Empty: no mail account. */
|
|
56
|
+
accountId: string;
|
|
57
|
+
type?: string;
|
|
47
58
|
};
|
|
48
59
|
export declare class FakeMailbox {
|
|
49
60
|
#private;
|
|
@@ -98,6 +98,7 @@ export class FakeMailbox {
|
|
|
98
98
|
/** `SieveScript` objects: `{id, name, blobId}` triples, `isActive` derived
|
|
99
99
|
* from `#activeSieveScriptId` -- the same shape `SieveProperty` has on the
|
|
100
100
|
* real server (`jmap-proto/src/object/sieve.rs:19-24`). */
|
|
101
|
+
#principals;
|
|
101
102
|
#sieveScripts = [];
|
|
102
103
|
#activeSieveScriptId = null;
|
|
103
104
|
constructor(options = {}) {
|
|
@@ -105,6 +106,7 @@ export class FakeMailbox {
|
|
|
105
106
|
this.#now = options.now ?? new Date('2026-09-07T12:00:00Z');
|
|
106
107
|
this.#latency = options.latency ?? 0;
|
|
107
108
|
this.#maxSizeUpload = options.maxSizeUpload ?? STALWART_MAX_SIZE;
|
|
109
|
+
this.#principals = options.principals ?? [];
|
|
108
110
|
this.#boxes = MAILBOXES.map((box) => ({
|
|
109
111
|
id: box.id,
|
|
110
112
|
name: box.name,
|
|
@@ -242,6 +244,7 @@ export class FakeMailbox {
|
|
|
242
244
|
'urn:ietf:params:jmap:submission': {},
|
|
243
245
|
'urn:ietf:params:jmap:vacationresponse': {},
|
|
244
246
|
'urn:ietf:params:jmap:sieve': {},
|
|
247
|
+
'urn:ietf:params:jmap:principals': {},
|
|
245
248
|
},
|
|
246
249
|
accounts: {
|
|
247
250
|
[ACCOUNT]: {
|
|
@@ -799,6 +802,52 @@ export class FakeMailbox {
|
|
|
799
802
|
notFound: ids.filter((id) => !this.#submissionState.has(id)),
|
|
800
803
|
};
|
|
801
804
|
}
|
|
805
|
+
case 'Principal/query': {
|
|
806
|
+
const filter = (args.filter ?? {});
|
|
807
|
+
const email = filter.email?.toLowerCase();
|
|
808
|
+
const text = filter.text?.toLowerCase();
|
|
809
|
+
const ids = this.#principals
|
|
810
|
+
.filter((one) => email !== undefined
|
|
811
|
+
? one.email.toLowerCase().includes(email)
|
|
812
|
+
: text === undefined ||
|
|
813
|
+
one.name.toLowerCase().includes(text) ||
|
|
814
|
+
one.email.toLowerCase().includes(text))
|
|
815
|
+
.map((one) => one.id);
|
|
816
|
+
return {
|
|
817
|
+
accountId: ACCOUNT,
|
|
818
|
+
queryState: 'principal1',
|
|
819
|
+
canCalculateChanges: false,
|
|
820
|
+
position: 0,
|
|
821
|
+
ids: ids.slice(0, typeof args.limit === 'number' ? args.limit : ids.length),
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
case 'Principal/get': {
|
|
825
|
+
const ids = (args.ids ?? null);
|
|
826
|
+
const list = this.#principals
|
|
827
|
+
.filter((one) => ids === null || ids.includes(one.id))
|
|
828
|
+
.map((one) => ({
|
|
829
|
+
id: one.id,
|
|
830
|
+
type: one.type ?? 'individual',
|
|
831
|
+
name: one.name,
|
|
832
|
+
email: one.email,
|
|
833
|
+
accounts: one.accountId
|
|
834
|
+
? {
|
|
835
|
+
[one.accountId]: {
|
|
836
|
+
name: one.email,
|
|
837
|
+
isPersonal: true,
|
|
838
|
+
isReadOnly: false,
|
|
839
|
+
accountCapabilities: { 'urn:ietf:params:jmap:mail': {} },
|
|
840
|
+
},
|
|
841
|
+
}
|
|
842
|
+
: {},
|
|
843
|
+
}));
|
|
844
|
+
return {
|
|
845
|
+
accountId: ACCOUNT,
|
|
846
|
+
state: 'principal1',
|
|
847
|
+
list,
|
|
848
|
+
notFound: (ids ?? []).filter((id) => !this.#principals.some((one) => one.id === id)),
|
|
849
|
+
};
|
|
850
|
+
}
|
|
802
851
|
case 'SieveScript/get': {
|
|
803
852
|
const ids = (args.ids ?? null);
|
|
804
853
|
const found = ids
|
package/dist/mailbox/index.d.ts
CHANGED
|
@@ -38,5 +38,9 @@ export { push } from './push.ts';
|
|
|
38
38
|
export type { PushHandle, PushOptions } from './push.ts';
|
|
39
39
|
export { activateSieveScript, deactivateSieveScripts, deleteSieveScript, saveSieveScript, sieveScriptText, sieveScripts, validateSieveScript, } from './sieve.ts';
|
|
40
40
|
export type { SavedSieveScript, SaveSieveScriptOptions, SieveScriptSummary } from './sieve.ts';
|
|
41
|
+
export { findPrincipals, lookupPrincipal } from './principals.ts';
|
|
42
|
+
export type { PrincipalMatch } from './principals.ts';
|
|
43
|
+
export { rulesToSieve, sieveToRules } from './rules.ts';
|
|
44
|
+
export type { MailRule, MailRuleAction, MailRuleCondition } from './rules.ts';
|
|
41
45
|
export { expandTemplate } from './uri.ts';
|
|
42
46
|
export type { Attachment, ChangedState, Draft, DraftAttachment, EmailAddress, MailAccount, MailFilter, MailIdentity, MailSession, MailSort, MailboxNode, MailboxRight, MailboxRights, MailboxRole, Message, Queued, Sent, ThreadDetail, ThreadPage, ThreadSummary, VacationResponse, } from './types.ts';
|
package/dist/mailbox/index.js
CHANGED
|
@@ -22,4 +22,6 @@ export { labelKeyword, listLabels, moveThread, moveToRole, removeFromMailbox, se
|
|
|
22
22
|
export { DEFAULT_MAX_DOWNLOAD_BYTES, downloadAttachment } from "./download.js";
|
|
23
23
|
export { push } from "./push.js";
|
|
24
24
|
export { activateSieveScript, deactivateSieveScripts, deleteSieveScript, saveSieveScript, sieveScriptText, sieveScripts, validateSieveScript, } from "./sieve.js";
|
|
25
|
+
export { findPrincipals, lookupPrincipal } from "./principals.js";
|
|
26
|
+
export { rulesToSieve, sieveToRules } from "./rules.js";
|
|
25
27
|
export { expandTemplate } from "./uri.js";
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { type MailClient } from './client.ts';
|
|
2
|
+
/**
|
|
3
|
+
* Colleague lookup for sharing: the JMAP Principals capability
|
|
4
|
+
* (`urn:ietf:params:jmap:principals`, RFC 9670), `Principal/query` then
|
|
5
|
+
* `Principal/get`.
|
|
6
|
+
*
|
|
7
|
+
* {@link shareMailbox} keys a grant by account id, which nobody types. This
|
|
8
|
+
* turns an email address or a name into that id. `jmap-jam` does not know the
|
|
9
|
+
* capability, so the calls go through `jam.request` with `using` set by hand,
|
|
10
|
+
* the same way `sieve.ts` does.
|
|
11
|
+
*
|
|
12
|
+
* Only principals on the current login's own domain (the part of the session
|
|
13
|
+
* `username` after `@`) are returned, so a lookup cannot name someone outside
|
|
14
|
+
* the organisation.
|
|
15
|
+
*/
|
|
16
|
+
export declare const PRINCIPALS_CAPABILITY = "urn:ietf:params:jmap:principals";
|
|
17
|
+
export type PrincipalMatch = {
|
|
18
|
+
principalId: string;
|
|
19
|
+
/** The account to pass to {@link shareMailbox} as `accountId`. */
|
|
20
|
+
accountId: string;
|
|
21
|
+
name: string;
|
|
22
|
+
email: string;
|
|
23
|
+
/** `individual`, `group` and so on, as the server names it. */
|
|
24
|
+
type: string;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Who on this login's domain matches `query`.
|
|
28
|
+
*
|
|
29
|
+
* A query with an `@` is matched against the email address, anything else
|
|
30
|
+
* against name and email together. The server decides what "matches" means
|
|
31
|
+
* (Stalwart: a case-insensitive substring), so a short query can return
|
|
32
|
+
* several people: an empty list is "nobody", two or more is for the caller to
|
|
33
|
+
* choose between. A principal with no mail account is left out, since there is
|
|
34
|
+
* nothing to share with.
|
|
35
|
+
*
|
|
36
|
+
* Throws `invalidArguments` for a blank query and `unknownCapability` when the
|
|
37
|
+
* server does not offer principals.
|
|
38
|
+
*/
|
|
39
|
+
export declare function findPrincipals(client: MailClient, query: string): Promise<readonly PrincipalMatch[]>;
|
|
40
|
+
/**
|
|
41
|
+
* The one colleague `query` means, or `null` for nobody.
|
|
42
|
+
*
|
|
43
|
+
* An email address that matches exactly (ignoring case) wins over a longer
|
|
44
|
+
* address that merely contains it. Otherwise two or more matches throw
|
|
45
|
+
* `ambiguous`, with the choices in the message; use {@link findPrincipals}
|
|
46
|
+
* to let a person pick.
|
|
47
|
+
*/
|
|
48
|
+
export declare function lookupPrincipal(client: MailClient, query: string): Promise<PrincipalMatch | null>;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { JAM_FETCH, MAIL_CAPABILITY } from "./client.js";
|
|
2
|
+
import { MailError, guard } from "./errors.js";
|
|
3
|
+
/**
|
|
4
|
+
* Colleague lookup for sharing: the JMAP Principals capability
|
|
5
|
+
* (`urn:ietf:params:jmap:principals`, RFC 9670), `Principal/query` then
|
|
6
|
+
* `Principal/get`.
|
|
7
|
+
*
|
|
8
|
+
* {@link shareMailbox} keys a grant by account id, which nobody types. This
|
|
9
|
+
* turns an email address or a name into that id. `jmap-jam` does not know the
|
|
10
|
+
* capability, so the calls go through `jam.request` with `using` set by hand,
|
|
11
|
+
* the same way `sieve.ts` does.
|
|
12
|
+
*
|
|
13
|
+
* Only principals on the current login's own domain (the part of the session
|
|
14
|
+
* `username` after `@`) are returned, so a lookup cannot name someone outside
|
|
15
|
+
* the organisation.
|
|
16
|
+
*/
|
|
17
|
+
export const PRINCIPALS_CAPABILITY = 'urn:ietf:params:jmap:principals';
|
|
18
|
+
const OPTIONS = { using: [PRINCIPALS_CAPABILITY], ...JAM_FETCH };
|
|
19
|
+
const LIMIT = 10;
|
|
20
|
+
/** The mail account of a principal, the personal one if it has several. */
|
|
21
|
+
function mailAccountId(principal) {
|
|
22
|
+
const mail = Object.entries(principal.accounts ?? {}).filter(([, account]) => account.accountCapabilities?.[MAIL_CAPABILITY] !== undefined);
|
|
23
|
+
const [first] = [...mail].sort(([, a], [, b]) => Number(b.isPersonal === true) - Number(a.isPersonal === true));
|
|
24
|
+
return first ? first[0] : null;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Who on this login's domain matches `query`.
|
|
28
|
+
*
|
|
29
|
+
* A query with an `@` is matched against the email address, anything else
|
|
30
|
+
* against name and email together. The server decides what "matches" means
|
|
31
|
+
* (Stalwart: a case-insensitive substring), so a short query can return
|
|
32
|
+
* several people: an empty list is "nobody", two or more is for the caller to
|
|
33
|
+
* choose between. A principal with no mail account is left out, since there is
|
|
34
|
+
* nothing to share with.
|
|
35
|
+
*
|
|
36
|
+
* Throws `invalidArguments` for a blank query and `unknownCapability` when the
|
|
37
|
+
* server does not offer principals.
|
|
38
|
+
*/
|
|
39
|
+
export async function findPrincipals(client, query) {
|
|
40
|
+
const needle = query.trim();
|
|
41
|
+
if (!needle) {
|
|
42
|
+
throw new MailError('a colleague lookup needs an email address or a name', {
|
|
43
|
+
type: 'invalidArguments',
|
|
44
|
+
operation: 'find principals',
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
const { jam, doc, accountId } = await client.connect();
|
|
48
|
+
if (!doc.capabilities?.[PRINCIPALS_CAPABILITY]) {
|
|
49
|
+
throw new MailError('the server does not offer principals, so it cannot look up colleagues', {
|
|
50
|
+
type: 'unknownCapability',
|
|
51
|
+
operation: 'find principals',
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
const domain = doc.username.includes('@')
|
|
55
|
+
? doc.username.slice(doc.username.lastIndexOf('@') + 1).toLowerCase()
|
|
56
|
+
: '';
|
|
57
|
+
if (!domain) {
|
|
58
|
+
throw new MailError('the login has no email domain to look colleagues up in', {
|
|
59
|
+
type: 'invalidArguments',
|
|
60
|
+
operation: 'find principals',
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
return guard('find principals', async () => {
|
|
64
|
+
const filter = needle.includes('@') ? { email: needle } : { text: needle };
|
|
65
|
+
const [found] = await jam.request(['Principal/query', { accountId, filter, limit: LIMIT }], OPTIONS);
|
|
66
|
+
const ids = (found.ids ?? []).slice(0, LIMIT);
|
|
67
|
+
if (ids.length === 0)
|
|
68
|
+
return [];
|
|
69
|
+
const [got] = await jam.request([
|
|
70
|
+
'Principal/get',
|
|
71
|
+
{ accountId, ids, properties: ['id', 'type', 'name', 'email', 'accounts'] },
|
|
72
|
+
], OPTIONS);
|
|
73
|
+
const matches = [];
|
|
74
|
+
for (const principal of got.list ?? []) {
|
|
75
|
+
const email = principal.email;
|
|
76
|
+
// No `@` means lastIndexOf is -1 and the whole string would be compared.
|
|
77
|
+
if (!email?.includes('@'))
|
|
78
|
+
continue;
|
|
79
|
+
if (email.slice(email.lastIndexOf('@') + 1).toLowerCase() !== domain)
|
|
80
|
+
continue;
|
|
81
|
+
const account = mailAccountId(principal);
|
|
82
|
+
if (!account)
|
|
83
|
+
continue;
|
|
84
|
+
matches.push({
|
|
85
|
+
principalId: principal.id,
|
|
86
|
+
accountId: account,
|
|
87
|
+
name: principal.name ?? email,
|
|
88
|
+
email,
|
|
89
|
+
type: principal.type ?? 'individual',
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
return matches;
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* The one colleague `query` means, or `null` for nobody.
|
|
97
|
+
*
|
|
98
|
+
* An email address that matches exactly (ignoring case) wins over a longer
|
|
99
|
+
* address that merely contains it. Otherwise two or more matches throw
|
|
100
|
+
* `ambiguous`, with the choices in the message; use {@link findPrincipals}
|
|
101
|
+
* to let a person pick.
|
|
102
|
+
*/
|
|
103
|
+
export async function lookupPrincipal(client, query) {
|
|
104
|
+
const matches = await findPrincipals(client, query);
|
|
105
|
+
const exact = matches.filter((match) => match.email.toLowerCase() === query.trim().toLowerCase());
|
|
106
|
+
const pool = exact.length === 1 ? exact : matches;
|
|
107
|
+
if (pool.length > 1) {
|
|
108
|
+
throw new MailError(`${pool.length} colleagues match ${JSON.stringify(query.trim())}: ${pool.map((match) => match.email).join(', ')}`, { type: 'ambiguous', operation: 'lookup principal' });
|
|
109
|
+
}
|
|
110
|
+
return pool[0] ?? null;
|
|
111
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small rule model that compiles to Sieve (RFC 5228, with `fileinto`
|
|
3
|
+
* `:create` from RFC 5490, `imap4flags` from RFC 5232 and `copy` from RFC
|
|
4
|
+
* 3894), so a UI can offer "if the sender contains X, move it to Y" without
|
|
5
|
+
* writing Sieve by hand.
|
|
6
|
+
*
|
|
7
|
+
* Only scripts this module wrote are read back. {@link rulesToSieve} puts a
|
|
8
|
+
* marker line at the top that carries the rules as JSON, and
|
|
9
|
+
* {@link sieveToRules} accepts a script only when the marker parses and the
|
|
10
|
+
* script body is exactly what the generator writes for those rules. A
|
|
11
|
+
* hand-written script, or a generated one someone edited, gives `null` and
|
|
12
|
+
* is left alone.
|
|
13
|
+
*
|
|
14
|
+
* The result goes through {@link saveSieveScript} and
|
|
15
|
+
* {@link validateSieveScript} like any other script text.
|
|
16
|
+
*/
|
|
17
|
+
export type MailRuleCondition = {
|
|
18
|
+
kind: 'from' | 'to' | 'cc' | 'subject';
|
|
19
|
+
contains: string;
|
|
20
|
+
} | {
|
|
21
|
+
kind: 'hasAttachment';
|
|
22
|
+
} | {
|
|
23
|
+
kind: 'listId';
|
|
24
|
+
};
|
|
25
|
+
export type MailRuleAction = {
|
|
26
|
+
kind: 'moveTo';
|
|
27
|
+
mailbox: string;
|
|
28
|
+
} | {
|
|
29
|
+
kind: 'addKeyword';
|
|
30
|
+
keyword: string;
|
|
31
|
+
} | {
|
|
32
|
+
kind: 'markRead';
|
|
33
|
+
} | {
|
|
34
|
+
kind: 'forwardTo';
|
|
35
|
+
address: string;
|
|
36
|
+
} | {
|
|
37
|
+
kind: 'stop';
|
|
38
|
+
};
|
|
39
|
+
export type MailRule = {
|
|
40
|
+
/** The caller's own id, kept through a round trip. */
|
|
41
|
+
id: string;
|
|
42
|
+
name: string;
|
|
43
|
+
/** A disabled rule stays in the marker but writes no Sieve. */
|
|
44
|
+
enabled: boolean;
|
|
45
|
+
/** `all`: every condition must hold. `any`: one is enough. */
|
|
46
|
+
match: 'all' | 'any';
|
|
47
|
+
conditions: readonly MailRuleCondition[];
|
|
48
|
+
actions: readonly MailRuleAction[];
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Sieve source for `rules`, first enabled rule first.
|
|
52
|
+
*
|
|
53
|
+
* Throws a `MailError` of type `invalidArguments` for a rule with no
|
|
54
|
+
* condition or action, an empty value, a value with a control character, a
|
|
55
|
+
* keyword with a character IMAP forbids, or a forward address that is not
|
|
56
|
+
* `name@host`. Every value is written as a quoted string with `\` and `"`
|
|
57
|
+
* escaped, so no value can end the string early.
|
|
58
|
+
*/
|
|
59
|
+
export declare function rulesToSieve(rules: readonly MailRule[]): string;
|
|
60
|
+
/**
|
|
61
|
+
* The rules a script was generated from, or `null` when `script` is not one
|
|
62
|
+
* {@link rulesToSieve} wrote unchanged: no marker, a marker that does not
|
|
63
|
+
* parse as rules, or a body that differs from what the generator writes for
|
|
64
|
+
* them.
|
|
65
|
+
*/
|
|
66
|
+
export declare function sieveToRules(script: string): MailRule[] | null;
|
|
@@ -0,0 +1,191 @@
|
|
|
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
|
+
const checked = checkRules(rules);
|
|
150
|
+
const blocks = [];
|
|
151
|
+
const needs = new Set();
|
|
152
|
+
for (const rule of checked) {
|
|
153
|
+
if (!rule.enabled)
|
|
154
|
+
continue;
|
|
155
|
+
const { lines, needs: used } = commands(rule.actions);
|
|
156
|
+
for (const name of used)
|
|
157
|
+
needs.add(name);
|
|
158
|
+
const tests = rule.conditions.map(test);
|
|
159
|
+
const head = tests.length === 1
|
|
160
|
+
? `if ${tests[0]} {`
|
|
161
|
+
: `if ${rule.match === 'all' ? 'allof' : 'anyof'}(${tests.join(', ')}) {`;
|
|
162
|
+
blocks.push([head, ...lines.map((line) => ` ${line}`), '}'].join('\n'));
|
|
163
|
+
}
|
|
164
|
+
const required = REQUIRE_ORDER.filter((name) => needs.has(name));
|
|
165
|
+
const parts = [`${MARKER}${JSON.stringify(checked)}`];
|
|
166
|
+
if (required.length > 0)
|
|
167
|
+
parts.push(`require [${required.map(quote).join(', ')}];`);
|
|
168
|
+
parts.push(...blocks);
|
|
169
|
+
return `${parts.join('\n')}\n`;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* The rules a script was generated from, or `null` when `script` is not one
|
|
173
|
+
* {@link rulesToSieve} wrote unchanged: no marker, a marker that does not
|
|
174
|
+
* parse as rules, or a body that differs from what the generator writes for
|
|
175
|
+
* them.
|
|
176
|
+
*/
|
|
177
|
+
export function sieveToRules(script) {
|
|
178
|
+
const first = script.split('\n', 1)[0] ?? '';
|
|
179
|
+
if (!first.startsWith(MARKER))
|
|
180
|
+
return null;
|
|
181
|
+
let rules;
|
|
182
|
+
try {
|
|
183
|
+
rules = checkRules(JSON.parse(first.slice(MARKER.length)));
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
if (error instanceof MailError || error instanceof SyntaxError)
|
|
187
|
+
return null;
|
|
188
|
+
throw error;
|
|
189
|
+
}
|
|
190
|
+
return rulesToSieve(rules) === script ? rules : null;
|
|
191
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wtfalch/email",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.21.0",
|
|
4
4
|
"description": "The wtfalch estate: reading a mailbox over JMAP, administering the Stalwart server it lives on, and iTIP scheduling over iMIP. Three entries with no code in common.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|