@wtfalch/email 0.14.0 → 0.15.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,206 @@
1
+ import { MailWriteRefused } from './writes.js';
2
+ /** A lowercase DNS label: RFC 1035, minus the wire's own length limit — this
3
+ * refuses on shape, not on how long a name can get. */
4
+ const DNS_LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
5
+ function assertLabel(what, value) {
6
+ if (!DNS_LABEL.test(value)) {
7
+ throw new MailWriteRefused(`${what} "${value}" must be a lowercase DNS label`);
8
+ }
9
+ }
10
+ function assertDomain(value) {
11
+ const labels = value.split('.');
12
+ if (labels.length < 2 || labels.some((label) => !DNS_LABEL.test(label))) {
13
+ throw new MailWriteRefused(`"${value}" is not a valid lowercase domain name`);
14
+ }
15
+ }
16
+ /**
17
+ * The `Domain` name this org's mail lives on. Refuses before any request: an
18
+ * org with no domain of its own is level 1, and foundry#7's "Level 1 gets
19
+ * `@acme.wtfalch.dev`" fixes both what the name is and that it can only ever
20
+ * be `hosted` — a level-1 org has nowhere else for mail to be `received` at.
21
+ */
22
+ function resolveDomain(org, options) {
23
+ assertLabel('an org slug', org.slug);
24
+ if (!org.domain) {
25
+ if (org.mode !== 'hosted') {
26
+ throw new MailWriteRefused(`${org.slug} has no domain of its own, so it is level 1 on ${options.apex} and its mode must be "hosted"; "received" needs a domain elsewhere to keep receiving mail`);
27
+ }
28
+ return `${org.slug}.${options.apex}`;
29
+ }
30
+ assertDomain(org.domain);
31
+ return org.domain;
32
+ }
33
+ /**
34
+ * MX and SPF, fully derivable from `apex`/`mailHost` with no round trip.
35
+ *
36
+ * `hosted`: Stalwart holds the MX, so SPF's `mx` mechanism resolves to it
37
+ * exactly the way Stalwart's own `build_dns_records` composes it for a
38
+ * self-hosted MX (`DnsRecordType::Spf`, `records.rs:74-95`: `"v=spf1 mx
39
+ * -all"`).
40
+ *
41
+ * `received`: the MX stays with Google or Microsoft, so `mx` would
42
+ * authorise *their* servers, not Stalwart's dual-delivery sender. The org's
43
+ * own SPF record needs an explicit `include:` of the shared mail host
44
+ * instead, and no MX record is returned at all — foundry must not touch the
45
+ * existing one.
46
+ */
47
+ function mxAndSpf(domain, mode, options) {
48
+ if (mode === 'hosted') {
49
+ return [
50
+ { type: 'MX', name: domain, value: options.mailHost, priority: 10 },
51
+ { type: 'TXT', name: domain, value: 'v=spf1 mx -all' },
52
+ ];
53
+ }
54
+ return [{ type: 'TXT', name: domain, value: `v=spf1 include:${options.mailHost} -all` }];
55
+ }
56
+ function unescapeTxt(s) {
57
+ return s.replace(/\\"/g, '"').replace(/\\\\/g, '\\');
58
+ }
59
+ function stripTrailingDot(name) {
60
+ return name.endsWith('.') ? name.slice(0, -1) : name;
61
+ }
62
+ /**
63
+ * The `_domainkey` TXT records inside a `dnsZoneFile` BIND zone, as
64
+ * `x:Domain/get` returns it. Every other record type in the zone (MX, SPF,
65
+ * DMARC, TLS-RPT, CAA, autoconfig, …) is derived instead of read back, so
66
+ * this reads only the lines whose name contains `._domainkey.`.
67
+ *
68
+ * Handles both shapes `BindSerializer::serialize` emits
69
+ * (`stalwartlabs/dns-update`'s `src/bind.rs:44-56`, commit
70
+ * `40e94d85bdbdeeb3a13d4ac8e84a33de5baa6b49`): a short value on one line
71
+ * (`name IN TXT "value"`), and a value over 255 bytes — every RSA DKIM key
72
+ * — split into a parenthesized block of quoted chunks that this
73
+ * reassembles in order.
74
+ */
75
+ export function dkimRecordsFromZoneFile(zoneFile) {
76
+ const records = [];
77
+ const lines = zoneFile.split('\n');
78
+ for (let i = 0; i < lines.length; i++) {
79
+ const line = lines[i] ?? '';
80
+ const single = /^(\S+)\s+IN\s+TXT\s+"((?:[^"\\]|\\.)*)"\s*$/.exec(line);
81
+ if (single) {
82
+ const [, name, value] = single;
83
+ if (name?.includes('._domainkey.')) {
84
+ records.push({
85
+ type: 'TXT',
86
+ name: stripTrailingDot(name),
87
+ value: unescapeTxt(value ?? ''),
88
+ });
89
+ }
90
+ continue;
91
+ }
92
+ const blockStart = /^(\S+)\s+IN\s+TXT\s+\($/.exec(line);
93
+ if (blockStart) {
94
+ const name = blockStart[1] ?? '';
95
+ const chunks = [];
96
+ let j = i + 1;
97
+ while (j < lines.length && lines[j]?.trim() !== ')') {
98
+ const chunk = /^\s*"((?:[^"\\]|\\.)*)"\s*$/.exec(lines[j] ?? '');
99
+ if (chunk?.[1] !== undefined)
100
+ chunks.push(unescapeTxt(chunk[1]));
101
+ j++;
102
+ }
103
+ if (name.includes('._domainkey.')) {
104
+ records.push({ type: 'TXT', name: stripTrailingDot(name), value: chunks.join('') });
105
+ }
106
+ i = j;
107
+ }
108
+ }
109
+ return records;
110
+ }
111
+ /** The `Domain` value this module writes: `isEnabled` and the three
112
+ * management blocks. `name` travels alongside so a caller can spread this
113
+ * straight into a create, and is excluded from the patch an update sends
114
+ * (the same immutable-match-property rule `applyObjects` follows). */
115
+ function domainValue(domain) {
116
+ return {
117
+ name: domain,
118
+ isEnabled: true,
119
+ certificateManagement: { '@type': 'Manual' },
120
+ dnsManagement: { '@type': 'Manual' },
121
+ dkimManagement: { '@type': 'Automatic' },
122
+ };
123
+ }
124
+ /**
125
+ * The org's `Domain`, found by an exact, server-side filter on `name` —
126
+ * never by listing and scanning every `Domain` on the instance.
127
+ *
128
+ * `client.list` (and so `client.upsert`, which is built on it) calls
129
+ * `x:Domain/query` with no filter at all, which Stalwart caps at
130
+ * `query_max_results` (5000 by default) and never pages past
131
+ * (`crates/jmap/src/registry/query.rs:241-250`,
132
+ * `crates/registry/src/schema/structs_impl.rs:23113` for the default, both
133
+ * at `02503015580abd6706923d34e9d8e501e76f8634`). An instance with more
134
+ * `Domain`s than that would put some past the first page, where a lookup
135
+ * built on `list`/`upsert` would miss an existing one and create a second
136
+ * `Domain` with the same name — this is why `applyOrgMail`/`parkOrgMail` use
137
+ * this filtered lookup instead of `client.upsert`.
138
+ *
139
+ * `ObjectType::Domain`'s `name` index is declared `IndexSchemaType::Unique`
140
+ * / `IndexSchemaValueType::Keyword`
141
+ * (`crates/registry/src/schema/properties_impl.rs:3489-3493`), and a
142
+ * `Keyword` index accepts an exact-match filter
143
+ * (`crates/jmap/src/registry/query.rs:190-193`), sent as a flat
144
+ * `filter: {"name": "…"}` object — a bare property name in the filter is
145
+ * `RegistryFilterOperator::Equal` (`crates/jmap-proto/src/object/registry.rs:123-135`),
146
+ * and a single-key filter object needs no `operator`/`conditions` wrapper
147
+ * (`crates/jmap-proto/src/method/query.rs:214-260`). That filter is
148
+ * evaluated server-side and matches at most one `Domain` — `name` is
149
+ * unique — so it is correct regardless of how many Domains the instance
150
+ * holds or which page this one would fall on.
151
+ */
152
+ async function findDomain(client, domain) {
153
+ const { ids } = await client.call('x:Domain/query', {
154
+ filter: { name: domain },
155
+ });
156
+ const id = ids?.[0];
157
+ if (!id)
158
+ return undefined;
159
+ const [wire] = await client.get('Domain', [id]);
160
+ return wire;
161
+ }
162
+ /**
163
+ * Give an org mail, change its mode, or re-enable a parked one — all the
164
+ * same call. Idempotent: the `Domain` is upserted by `name`, so calling this
165
+ * twice with the same org leaves exactly one `Domain`, and calling it again
166
+ * with a different `mode` changes only the records this returns, never a
167
+ * second `Domain`.
168
+ *
169
+ * Returns the DNS records foundry must publish. This never calls Cloudflare
170
+ * itself — that stays foundry's, by the campaign's non-goals.
171
+ */
172
+ export async function applyOrgMail(client, org, options) {
173
+ const domain = resolveDomain(org, options);
174
+ const value = domainValue(domain);
175
+ const patch = Object.fromEntries(Object.entries(value).filter(([k]) => k !== 'name'));
176
+ const existing = await findDomain(client, domain);
177
+ let id;
178
+ if (existing) {
179
+ await client.update('Domain', existing.id, patch);
180
+ id = existing.id;
181
+ }
182
+ else {
183
+ id = await client.create('Domain', value);
184
+ }
185
+ const [wire] = await client.get('Domain', [id]);
186
+ const records = [
187
+ ...mxAndSpf(domain, org.mode, options),
188
+ ...dkimRecordsFromZoneFile(wire?.dnsZoneFile ?? ''),
189
+ ];
190
+ return { domain, records };
191
+ }
192
+ /**
193
+ * Stop a domain receiving, keeping every mailbox and message — foundry#7's
194
+ * "park keeps mail, never deletes it". Touches only the `Domain`'s
195
+ * `isEnabled`; no `Account`, no message, ever.
196
+ *
197
+ * A no-op, not a refusal, for an org this instance has never heard of or one
198
+ * already parked: neither sends a request.
199
+ */
200
+ export async function parkOrgMail(client, org, options) {
201
+ const domain = resolveDomain(org, options);
202
+ const existing = await findDomain(client, domain);
203
+ if (!existing || existing.isEnabled === false)
204
+ return;
205
+ await client.update('Domain', existing.id, { isEnabled: false });
206
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@wtfalch/email",
3
- "version": "0.14.0",
4
- "description": "The wtfalch estate: reading a mailbox over JMAP, and administering the Stalwart server it lives on. Two entries with no code in common.",
3
+ "version": "0.15.0",
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",
7
7
  "repository": {
@@ -22,6 +22,10 @@
22
22
  "default": "./dist/mailbox/fake/index.js"
23
23
  },
24
24
  "./mailbox/mail.css": "./dist/mailbox/mail.css",
25
+ "./imip": {
26
+ "types": "./dist/imip/index.d.ts",
27
+ "default": "./dist/imip/index.js"
28
+ },
25
29
  "./postmaster": {
26
30
  "browser": "./dist/postmaster/browser-refusal.js",
27
31
  "types": "./dist/postmaster/index.d.ts",
@@ -75,8 +79,9 @@
75
79
  "engines": {
76
80
  "node": ">=22.0.0"
77
81
  },
78
- "keywords": ["jmap", "email", "mail", "stalwart", "rfc8621"],
82
+ "keywords": ["jmap", "email", "mail", "stalwart", "rfc8621", "itip", "imip", "icalendar"],
79
83
  "dependencies": {
84
+ "ical.js": "2.2.1",
80
85
  "jmap-jam": "^0.13.6"
81
86
  }
82
87
  }