@wtfalch/email 0.14.0 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,22 +1,30 @@
1
1
  # @wtfalch/email
2
2
 
3
- The estate's mail, in two entries with **no code in common**:
3
+ The estate's mail, in three entries with **no code in common**:
4
4
 
5
5
  @wtfalch/email/mailbox reading and writing messages (RFC 8620/8621)
6
- @wtfalch/email/postmaster administering the server (Stalwart's `x:` extension)
6
+ @wtfalch/email/imip proposing and declining a time (RFC 5546/6047)
7
+ @wtfalch/email/postmaster administering the server (Stalwart's `x:` extension)
7
8
 
8
9
  They share a subject, a scope and a repository, and nothing else. There is
9
10
  deliberately no root entry: an entry named for a seam that does not exist is
10
11
  worse than no entry at all.
11
12
 
12
13
  `/mailbox` is for the person who has an address — inbox, threads, compose —
13
- running in their browser as them, able to touch only their own mail.
14
- `/postmaster` is for whoever runs the server — who gets a mailbox, what name
15
- is on it, who holds a key — running server-side with an administrator
16
- credential, and never touching the contents of anybody's messages.
14
+ running in their browser as them, able to touch only their own mail. `/imip`
15
+ composes and parses the scheduling messages `/mailbox` sends and receives as
16
+ ordinary mail, behind its own entry so the calendar parser it needs never
17
+ rides along with a plain inbox. `/postmaster` is for whoever runs the server —
18
+ who gets a mailbox, what name is on it, who holds a key — running server-side
19
+ with an administrator credential, and never touching the contents of
20
+ anybody's messages.
17
21
 
18
- The post office holds the analogy: one is the letters, the other is the
19
- pigeonholes.
22
+ The post office holds the analogy: one is the letters, one is what's inside a
23
+ particular kind of envelope, the other is the pigeonholes.
24
+
25
+ ## Status
26
+
27
+ Published: yes, v0.15.1, 2026-09-28.
20
28
 
21
29
  ---
22
30
 
@@ -111,11 +119,47 @@ use, and stamps it `$snoozed:<unix seconds>`. JMAP has no snooze, so nothing
111
119
  brings it back on its own: the host runs `wakeSnoozed(client, now)` on a
112
120
  timer, and each thread whose time has come goes back to the Inbox, unread.
113
121
 
122
+ `vacationResponse` reads the account's out-of-office responder and
123
+ `setVacationResponse` sets it — RFC 8621 §8's `VacationResponse`, over the
124
+ `urn:ietf:params:jmap:vacationresponse` capability Stalwart advertises. It is
125
+ a singleton, never created or destroyed, so a set is always an update; a field
126
+ left out of the call keeps whatever the server already has, and `null` clears
127
+ it. `clearVacationResponse` is the shorthand for turning it off — `isEnabled:
128
+ false` — without touching the dates or the message, so switching it back on
129
+ does not need them resupplied.
130
+
131
+ ```ts
132
+ await setVacationResponse(client, {
133
+ isEnabled: true,
134
+ fromDate: '2026-09-28T00:00:00Z',
135
+ toDate: '2026-10-05T00:00:00Z',
136
+ subject: 'Out sick',
137
+ textBody: 'I am out sick until October 5th.',
138
+ });
139
+ // …later
140
+ await clearVacationResponse(client);
141
+ ```
142
+
114
143
  Note that a stock Stalwart account has **no Archive mailbox** — it creates
115
144
  Inbox, Drafts, Sent Items, Junk Mail and Deleted Items — so `moveToRole(…,
116
145
  'archive')` throws there rather than doing nothing, and a caller should offer
117
146
  the action only where `findRole(tree, 'archive')` finds one.
118
147
 
148
+ **Per-account filtering rules are Sieve, over the same JMAP endpoint** — RFC
149
+ 9661, `urn:ietf:params:jmap:sieve`. `sieveScripts` lists every script on the
150
+ account (`name`, `isActive`, `blobId`); `sieveScriptText` reads one's source.
151
+ `saveSieveScript(client, name, text)` creates a script from `text`, or
152
+ replaces one's content when given `{ scriptId }`, uploading it as a blob the
153
+ same way `attach` uploads a file. `validateSieveScript` compiles `text` on
154
+ the server without saving it, for a check before committing. Exactly one
155
+ script is active per account: `activateSieveScript(client, id)` makes it the
156
+ one that runs, and `deactivateSieveScripts` turns filtering off entirely.
157
+ `deleteSieveScript` is refused while its target is the active script — the
158
+ server's own guard, deactivate first. Nothing here parses a rule into
159
+ conditions and actions: Stalwart's `SieveScript` object is a name, an active
160
+ flag and a blob holding real Sieve source, so a caller past "one sender,
161
+ one folder" owns generating that source itself.
162
+
119
163
  ### The React
120
164
 
121
165
  `@wtfalch/email/mailbox/react` draws it, on `@wtfalch/design` >=0.16.0.
@@ -236,6 +280,15 @@ specifiers, which only compiles under `allowImportingTsExtensions`; nothing of
236
280
  it reaches this package's public types, so a consumer does not inherit the
237
281
  flag.
238
282
 
283
+ **`jmap-jam` already knows `VacationResponse` needs its own capability.** It
284
+ derives a request's `using` from the method names being sent, against a
285
+ built-in table that maps `VacationResponse` to
286
+ `urn:ietf:params:jmap:vacationresponse` the same way it maps `Mailbox` to mail
287
+ and `EmailSubmission` to submission (confirmed against the installed
288
+ `jmap-jam@0.13.6`). So `vacationResponse`/`setVacationResponse` need no `using`
289
+ override — unlike `send`/`cancel`, whose implicit `Email/set` runs under a
290
+ method name the request never states.
291
+
239
292
  **Per-mailbox sharing is real, and it is the plain `Mailbox` object, not a
240
293
  separate capability.** `shareWith`/`myRights` are confirmed on the schema at
241
294
  `stalwartlabs/stalwart` tag `v0.16.20`
@@ -247,6 +300,94 @@ object's ACL suite, `tests/src/jmap/contacts/acl.rs`, which shares the same
247
300
  the way `instance-one.json`'s fixture is: nothing in this package wrote a
248
301
  `shareWith` grant before now.
249
302
 
303
+ **`jmap-jam` does not know Sieve at all**, so `sieve.ts` is the one place in
304
+ this package that calls `jam.request` directly rather than `jam.api`, adding
305
+ `urn:ietf:params:jmap:sieve` to `using` by hand — the same thing `send()`
306
+ already does for the mail capability. Confirmed against
307
+ `stalwartlabs/stalwart` at `main`, `02503015580abd6706923d34e9d8e501e76f8634`:
308
+ `SieveScript/get|set|query|validate` under that capability
309
+ (`crates/jmap-proto/src/request/method.rs:146-149,284-287`), the object as
310
+ `{id, name, blobId, isActive}` with no structured rule shape
311
+ (`crates/jmap-proto/src/object/sieve.rs:19-24`), and activation as the
312
+ non-standard `onSuccessActivateScript`/`onSuccessDeactivateScript` set
313
+ arguments (`set.rs:371-391`). **`onSuccessActivateScript` silently does
314
+ nothing for an id the account does not have** — Stalwart clears it rather
315
+ than refusing (`set.rs:96-101`) — so `activateSieveScript` pairs it with a
316
+ no-op `update` on the same id, whose own `notFound` is what actually
317
+ surfaces a bad id.
318
+
319
+ ## @wtfalch/email/imip
320
+
321
+ An attendee proposing a new time for a meeting, and an organizer declining
322
+ that proposal — RFC 5546's `COUNTER` and `DECLINECOUNTER`, sent and read as
323
+ ordinary mail (RFC 6047). Everything server-side — accepting a counter, or
324
+ sending the `REQUEST`/`REPLY`/`CANCEL` methods around it — is the mail
325
+ server's own iTIP engine; this is compose and parse for the two methods
326
+ nothing else here speaks for.
327
+
328
+ ```ts
329
+ import { counter, declineCounter, parseImip, imipOf } from '@wtfalch/email/imip';
330
+ import { send } from '@wtfalch/email/mailbox';
331
+
332
+ const proposal = counter({
333
+ uid: event.uid,
334
+ sequence: event.sequence, // echoed, never incremented
335
+ summary: event.summary,
336
+ organizer: { email: 'ada@example.com', name: 'Ada Lovelace' },
337
+ attendee: { email: 'charles@example.com', name: 'Charles Babbage' },
338
+ start: newStart,
339
+ end: newEnd,
340
+ comment: 'Could we push this an hour later?',
341
+ });
342
+
343
+ await send(client, { ...draft, calendar: proposal }); // Draft.calendar, mailbox/types.ts
344
+
345
+ // On the organizer's side, reading a received message back:
346
+ const imip = await imipOf(client, message); // null if it carries neither method
347
+ if (imip?.method === 'COUNTER') { … }
348
+ ```
349
+
350
+ **Plain fields in, a typed union out.** `counter`/`declineCounter` take an
351
+ object of primitives and return `{ method, ics }`; `parseImip` is a pure
352
+ function from that `ics` text back to a typed `Imip`, or `null` for any other
353
+ method or for text it cannot make sense of — it never throws, since it reads
354
+ mail nobody here wrote. Neither this entry nor `@wtfalch/email/mailbox` takes
355
+ a dependency on `@wtfalch/calendar` or any other calendar model.
356
+
357
+ **`ical.js` never reaches `@wtfalch/email/mailbox`.** It is a real dependency
358
+ of this package, but only `src/imip/**` imports it, so reading or sending
359
+ ordinary mail never pays for a calendar parser. `imipOf` finds the calendar
360
+ part in a `Message`'s `attachments` — RFC 8621 §4.1.4 puts a `text/calendar`
361
+ part there whether it sits inline in a `multipart/alternative` or as a true
362
+ attachment, since it is never `text/plain` or `text/html` — downloads it with
363
+ `downloadAttachment`, and hands the bytes to `parseImip`.
364
+
365
+ **Compose writes UTC times, which is why it never needs a `VTIMEZONE`** (RFC
366
+ 5546 requires one only when a property uses `TZID`). Parse accepts UTC, a
367
+ `TZID` resolved against the message's own embedded `VTIMEZONE` — how
368
+ Outlook's Windows zone names (`Pacific Standard Time`, never an IANA
369
+ identifier) arrive, and `ical.js` resolves one with no registration needed,
370
+ by walking up to the `VCALENDAR` and matching the embedded component — and a
371
+ floating time, which is read as UTC deterministically rather than through
372
+ `ical.js`'s own default of the machine's local zone.
373
+
374
+ **The `method=` parameter rides in the JMAP body part's own `type` string.**
375
+ Stalwart's `Email/set` writes whatever that string holds onto the wire
376
+ unparsed rather than validating it as a bare media type, so
377
+ `text/calendar; method=COUNTER` survives to the `Content-Type` header exactly
378
+ as given — confirmed against `stalwartlabs/stalwart` at commit
379
+ `0250301` (`crates/jmap/src/email/set.rs:325-327,439-467,515-562`) and
380
+ mail-builder's `ContentType::write_header` at the `v1.0.0` commit Stalwart's
381
+ `Cargo.lock` pins (`0e87ce2`, `src/headers/content_type.rs:49-63`). An
382
+ explicit `header:Content-Type` property is not the alternative it looks like:
383
+ Stalwart does not enforce RFC 8621 §4.6's rule against setting the same
384
+ header field twice, so combining it with `type` would silently emit two
385
+ `Content-Type` headers rather than one.
386
+
387
+ **Outlook and Google never send `DECLINECOUNTER`.** Nothing here waits on one
388
+ arriving; this only composes and parses the method for the organizer side
389
+ that does emit it.
390
+
250
391
  ## @wtfalch/email/postmaster
251
392
 
252
393
  Administer a [Stalwart](https://stalw.art) mail server: its domain, its
@@ -428,3 +569,182 @@ closed maps them instead: `wtfalch-manage`'s database refuses any action
428
569
  outside its authorisation package's set, so its writer puts each back on the
429
570
  core event it already recorded these under, and signs the row with the
430
571
  principal it resolved rather than the one the event echoes.
572
+
573
+ ## One org's mail on the shared server
574
+
575
+ `applyOrgMail` and `parkOrgMail` give foundry ([`wtfalch/email#96`](https://github.com/wtfalch/email/issues/96))
576
+ a typed, idempotent way to put one org's mail on the one shared Stalwart
577
+ instance, without a second server per org and without this package ever
578
+ calling Cloudflare itself.
579
+
580
+ ```ts
581
+ import { applyOrgMail, parkOrgMail } from '@wtfalch/email/postmaster';
582
+
583
+ const options = { apex: 'oikos.host', mailHost: 'mail.oikos.host' };
584
+
585
+ // Level 1: no domain of its own, so it lives at acme.oikos.host and must be hosted.
586
+ await applyOrgMail(client, { slug: 'acme', mode: 'hosted' }, options);
587
+
588
+ // A domain of its own, kept receiving through Google or Microsoft.
589
+ const { domain, records } = await applyOrgMail(
590
+ client,
591
+ { slug: 'acme', domain: 'acme.com', mode: 'received' },
592
+ options,
593
+ );
594
+
595
+ // Changing mode is calling it again with the new mode.
596
+ await applyOrgMail(client, { slug: 'acme', domain: 'acme.com', mode: 'hosted' }, options);
597
+
598
+ // Park stops it receiving; every mailbox and message stays.
599
+ await parkOrgMail(client, { slug: 'acme', domain: 'acme.com', mode: 'hosted' }, options);
600
+ ```
601
+
602
+ **One `Domain` per org, upserted by name.** `applyOrgMail` calls the same
603
+ `Domain` object `mailObjects`/`applyObjects` write for the instance itself,
604
+ so calling it twice with the same org leaves exactly one `Domain`, and
605
+ calling it again with a different `mode` changes only the records it
606
+ returns — never a second `Domain`. Calling it on a parked org sets
607
+ `isEnabled` back to `true`. `parkOrgMail` touches only that one field, and
608
+ never an `Account` or a message: parking keeps every mailbox.
609
+
610
+ **`certificateManagement` and `dnsManagement` are `Manual` on an org's
611
+ `Domain`.** Only `dkimManagement` stays `Automatic`, so Stalwart still mints
612
+ and rotates the signing key — this package reads it back rather than have
613
+ Stalwart publish anything to a DNS provider itself. Publishing stays
614
+ foundry's, since foundry owns Cloudflare. `applyOrgMail` re-asserts all
615
+ three — `certificateManagement`, `dnsManagement` and `dkimManagement` — on
616
+ every call, so a manual change to any of them in the web admin is reverted
617
+ the next time foundry re-applies the org's declared file.
618
+
619
+ **The management API can read back what a domain needs published.**
620
+ `x:Domain/get` computes an extra `dnsZoneFile` property — a full BIND zone,
621
+ DKIM included — confirmed against `stalwartlabs/stalwart` at commit
622
+ `0250301` (`crates/jmap/src/registry/get.rs:297-304` calls
623
+ `Server::build_bind_dns_records`, `crates/common/src/network/dns/records.rs:357-382`).
624
+ `applyOrgMail` derives MX and SPF itself (no round trip needed for either)
625
+ and reads only the `_domainkey` lines back out of that zone file for DKIM.
626
+ **The DKIM record can be empty on the very first `applyOrgMail`**: Stalwart
627
+ mints the key on a background task queued by the same write
628
+ (`crates/jmap/src/registry/mapping/domain.rs:102-133`), not inside it. A
629
+ caller that needs the key right away calls `applyOrgMail` again a moment
630
+ later — free beyond the extra read, since the `Domain` is already there.
631
+
632
+ **What each mode returns.** `hosted` gets an `MX` record at `mailHost` plus
633
+ a `TXT` SPF record of `v=spf1 mx -all`, matching how Stalwart's own zone
634
+ generation composes SPF for a domain it holds the MX for. `received` gets no
635
+ `MX` at all — the org's existing one, at Google or Microsoft, is not this
636
+ package's to touch — and a `TXT` SPF record of `v=spf1
637
+ include:<mailHost> -all` for the org to merge into what it already
638
+ publishes.
639
+
640
+ **Level 1 is the slug on the shared apex, and freezes there.** An org with
641
+ no `domain` gets `${slug}.${apex}` (foundry#7: "Level 1 gets
642
+ `@acme.oikos.host`") and its `mode` must be `hosted` — there is nowhere
643
+ else for a level-1 org's mail to be `received` at. `applyOrgMail` and
644
+ `parkOrgMail` both refuse a slug or a domain that is not a lowercase DNS
645
+ label before making a request.
646
+
647
+ **Stalwart tenants are out of scope here.** Every org's mail lives in the
648
+ one shared instance regardless of level; Agora's own org scoping is the
649
+ boundary between them, not a Stalwart tenant. Moving an org's old mail in
650
+ from Google or Microsoft — [`wtfalch/email#108`](https://github.com/wtfalch/email/issues/108) — is `mailCopyPlan`, below.
651
+
652
+ ## Copying an org's old mail with Vandelay
653
+
654
+ Stalwart ships its own migration tool, [`stalwartlabs/vandelay`](https://github.com/stalwartlabs/vandelay):
655
+ a JMAP importer-exporter that reads a source account (IMAP, JMAP, Exchange,
656
+ Google Takeout, …) into a local SQLite archive, then pushes that archive
657
+ into a target JMAP account. `mailCopyPlan` decides the exact Vandelay
658
+ command lines foundry runs per account — it never spawns Vandelay itself,
659
+ never touches a network, and never carries a real credential.
660
+
661
+ ```ts
662
+ import { mailCopyPlan } from '@wtfalch/email/postmaster';
663
+
664
+ const plan = mailCopyPlan({
665
+ provider: 'google', // or 'microsoft'
666
+ accounts: [{ source: 'alice@acme.com', targetAccountId: 'a1' }],
667
+ stalwartUrl: 'https://mail.wtfalch.dev',
668
+ archiveDir: '/var/lib/mail-copy/acme',
669
+ });
670
+
671
+ // plan.accounts[0].importArgv: ['import', 'imap', '--url', 'imaps://imap.gmail.com',
672
+ // '--auth-bearer', '--auth-user=alice@acme.com', '--', '/var/lib/mail-copy/acme/alice%40acme.com.sqlite']
673
+ // plan.accounts[0].exportArgv: ['export', '--url', 'https://mail.wtfalch.dev',
674
+ // '--auth-bearer', '--account-id=a1', '--', '/var/lib/mail-copy/acme/alice%40acme.com.sqlite']
675
+ // plan.accounts[0].importEnv / .exportEnv: [{ name: 'VANDELAY_TOKEN', purpose: '…' }] — a
676
+ // variable NAME, never a value.
677
+ ```
678
+
679
+ The archive filename is the account's address, percent-encoded — never collapsed to a
680
+ lossy `_`, so two different addresses (`alice+bob@acme.com`, `alice_bob@acme.com`) can
681
+ never land on the same file. `mailCopyPlan` also refuses a plan where two accounts would
682
+ still collide (e.g. two spellings that case-fold to the same address). A target id or
683
+ name, or `archiveDir`, is free to start with `-`: the account selector uses `--flag=value`
684
+ and a literal `--` always precedes the archive path, so Vandelay's own arg parser (clap)
685
+ never mistakes either for another flag.
686
+
687
+ **Both providers go through `import imap`, not a provider-specific
688
+ importer.** Vandelay's IMAP importer authenticates with XOAUTH2
689
+ (`--auth-bearer` + `--auth-user`) and imports mail only — the same argv
690
+ shape for Google and Microsoft. Microsoft also has `import exchange-graph`,
691
+ but it is one of the two importers Vandelay's own docs call experimental,
692
+ and its non-interactive path still needs a token minted outside Vandelay
693
+ with no built-in client-credentials flow, so switching to it buys nothing.
694
+
695
+ **No secret ever lands in argv.** Every Vandelay flag that carries a secret
696
+ (`--auth-password`, `--auth-bearer`, …) takes an optional inline value;
697
+ passed bare, as this plan always does, Vandelay resolves it from a
698
+ same-named environment variable and finally an interactive prompt — never a
699
+ file. `importEnv`/`exportEnv` name that variable, `VANDELAY_TOKEN`, and
700
+ never carry a value themselves — the type has no field for one.
701
+
702
+ **The import token and the export token are the same variable name, at
703
+ different moments.** A bare `--auth-bearer` always reads `$VANDELAY_TOKEN`,
704
+ whether it is authenticating to the source or to Stalwart. Import and
705
+ export are two separate process launches, so this is only safe if the
706
+ caller sets `VANDELAY_TOKEN` to the source token before running `importArgv`
707
+ and to the Stalwart credential before running `exportArgv`, and never
708
+ merges the two into one shared environment.
709
+
710
+ **Rerunning is safe.** Vandelay's import and export are both convergent: a
711
+ rerun picks up an interrupted transfer or new mail since the last snapshot,
712
+ and export is upsert-only, never recreating or duplicating a message
713
+ already on the Stalwart account. `mailCopyPlan` never sets `--prune`, so a
714
+ plan built here can never delete anything on the target. It is also a pure
715
+ function: the same input returns the same plan, byte for byte.
716
+
717
+ **Vandelay never checks that the export credential may write into
718
+ `targetAccountId`/`targetAccountName` — Stalwart does.** Vandelay resolves
719
+ `--account-id`/`--account-name` and uses it as-is, with no authorization
720
+ check of its own. Stalwart's JMAP dispatcher is the actual gate: writing
721
+ into that account's mail requires the export credential to either be a
722
+ member of it (its own account, a group it belongs to, or the Stalwart
723
+ `impersonate` permission outright) or hold ACL/shared access to that
724
+ account's `Email` collection specifically. `impersonate` is already a
725
+ permission this package's own API keys can hold, and is the practical
726
+ choice for one migration credential that writes into many different
727
+ accounts, rather than pre-arranging a per-account ACL share for each one.
728
+
729
+ ### Admin setup
730
+
731
+ **Google Workspace.** Create a service account with domain-wide delegation
732
+ and authorize it for the scope `https://www.googleapis.com/auth/gmail.imap_admin`
733
+ ([developers.google.com/workspace/gmail/imap/xoauth2-protocol](https://developers.google.com/workspace/gmail/imap/xoauth2-protocol)) —
734
+ this is the scope built for exactly this case, reading any user's mailbox
735
+ over IMAP without that user's own consent. IMAP downloads are capped at
736
+ 2,500 MB per account per day
737
+ ([support.google.com/a/answer/1071518](https://support.google.com/a/answer/1071518)),
738
+ so a large mailbox needs several days of reruns to finish; that is exactly
739
+ the rerun `mailCopyPlan`'s convergent export supports.
740
+
741
+ **Microsoft 365.** Register an Entra app, grant it the Exchange
742
+ `IMAP.AccessAsApp` application permission, get tenant admin consent, then
743
+ register the app's service principal in Exchange with the `New-ServicePrincipal`
744
+ cmdlet and grant it the target mailboxes with `Add-MailboxPermission`
745
+ ([learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth](https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth)) —
746
+ this is the client-credentials, non-interactive path the same page
747
+ documents for IMAP. The alternative is a Graph `Mail.Read` application
748
+ permission instead, which is what `import exchange-graph` would need; this
749
+ package uses the IMAP path instead (see above), so `IMAP.AccessAsApp` is
750
+ the one this plan's admin setup actually needs.
@@ -0,0 +1,5 @@
1
+ import type { CalendarPart, CounterInput, DeclineCounterInput } from './types.ts';
2
+ /** Propose a new time for an event. */
3
+ export declare function counter(input: CounterInput): CalendarPart;
4
+ /** Decline a `counter()` an attendee sent. */
5
+ export declare function declineCounter(input: DeclineCounterInput): CalendarPart;
@@ -0,0 +1,84 @@
1
+ import ICAL from 'ical.js';
2
+ /** Identifies this package's own iTIP messages in a `PRODID`, RFC 5545
3
+ * §3.7.3's required format. Nothing reads it back; it is for whoever is
4
+ * staring at raw MIME wondering where a `.ics` came from. */
5
+ const PRODID = '-//wtfalch/email//imip 1.0//EN';
6
+ /** A `Date` as an RFC 5545 UTC time -- `...Z`, never a `TZID`. Compose only
7
+ * ever writes UTC (see the module doc on why that needs no `VTIMEZONE`),
8
+ * so every date this module writes goes through here. */
9
+ function utc(date) {
10
+ return ICAL.Time.fromJSDate(date, true);
11
+ }
12
+ /** `ORGANIZER`/`ATTENDEE`: a `mailto:` URI, with `CN` set only when a name
13
+ * was given -- an empty `CN=""` is worse than none at all. */
14
+ function setPerson(vevent, name, person) {
15
+ const property = vevent.updatePropertyWithValue(name, `mailto:${person.email}`);
16
+ if (person.name)
17
+ property.setParameter('cn', person.name);
18
+ }
19
+ /** The properties every `COUNTER` and `DECLINECOUNTER` carries (RFC 5546
20
+ * §3.2.7/§3.2.8's required tables, minus what each stops there): `UID` and
21
+ * `SEQUENCE` echoed, `DTSTAMP` stamped now, both people, and the two
22
+ * optional properties neither method treats differently. */
23
+ function baseEvent(input) {
24
+ const vevent = new ICAL.Component('vevent');
25
+ vevent.updatePropertyWithValue('uid', input.uid);
26
+ vevent.updatePropertyWithValue('sequence', input.sequence);
27
+ vevent.updatePropertyWithValue('dtstamp', utc(new Date()));
28
+ setPerson(vevent, 'organizer', input.organizer);
29
+ setPerson(vevent, 'attendee', input.attendee);
30
+ if (input.recurrenceId)
31
+ vevent.updatePropertyWithValue('recurrence-id', utc(input.recurrenceId));
32
+ if (input.comment)
33
+ vevent.updatePropertyWithValue('comment', input.comment);
34
+ return vevent;
35
+ }
36
+ /**
37
+ * `vcalendar.toString()`, with `ical.js`'s line folding corrected.
38
+ *
39
+ * `ICAL.foldLength` (documented default `75`, `ical.js`'s own module
40
+ * setting) caps each folded line's *content* at that many UTF-8 bytes and
41
+ * then prepends the continuation's one leading space on top of that --
42
+ * so a folded line can come out 76 bytes, one over RFC 5545 §3.1's 75-octet
43
+ * limit, which counts that leading space as part of the line. Budgeting one
44
+ * byte less than `ical.js` does accounts for the space it does not.
45
+ *
46
+ * Restored in a `finally`, synchronously, with no `await` between the set
47
+ * and the `toString()` that reads it -- `foldLength` lives on the `ICAL`
48
+ * module object shared by every importer of `ical.js` in the process, and
49
+ * this package is not the only thing that could be one, so the mutation
50
+ * must not be observable outside this single, uninterrupted call.
51
+ */
52
+ function serialize(vcalendar) {
53
+ const foldLength = ICAL.foldLength;
54
+ ICAL.foldLength = foldLength - 1;
55
+ try {
56
+ return vcalendar.toString();
57
+ }
58
+ finally {
59
+ ICAL.foldLength = foldLength;
60
+ }
61
+ }
62
+ /** Wraps one `VEVENT` in the `VCALENDAR` every iTIP message needs: RFC 5546
63
+ * §3.2 requires `METHOD`, and RFC 5545 §3.7.3/§3.7.4 requires `PRODID` and
64
+ * `VERSION`. */
65
+ function calendar(method, vevent) {
66
+ const vcalendar = new ICAL.Component('vcalendar');
67
+ vcalendar.updatePropertyWithValue('prodid', PRODID);
68
+ vcalendar.updatePropertyWithValue('version', '2.0');
69
+ vcalendar.updatePropertyWithValue('method', method);
70
+ vcalendar.addSubcomponent(vevent);
71
+ return { method, ics: serialize(vcalendar) };
72
+ }
73
+ /** Propose a new time for an event. */
74
+ export function counter(input) {
75
+ const vevent = baseEvent(input);
76
+ vevent.updatePropertyWithValue('summary', input.summary);
77
+ vevent.updatePropertyWithValue('dtstart', utc(input.start));
78
+ vevent.updatePropertyWithValue('dtend', utc(input.end));
79
+ return calendar('COUNTER', vevent);
80
+ }
81
+ /** Decline a `counter()` an attendee sent. */
82
+ export function declineCounter(input) {
83
+ return calendar('DECLINECOUNTER', baseEvent(input));
84
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `@wtfalch/email/imip` -- compose and parse `COUNTER` and `DECLINECOUNTER`
3
+ * over iMIP (RFC 5546/6047).
4
+ *
5
+ * A new time an attendee proposes, and an organizer's refusal of one, both as
6
+ * ordinary mail: `counter`/`declineCounter` build the `text/calendar` part
7
+ * `draftToEmail` (`@wtfalch/email/mailbox`) sends inline, and `parseImip`/
8
+ * `imipOf` read one back out of a received message. `ical.js` lives entirely
9
+ * behind this entry -- `@wtfalch/email/mailbox` never imports it, so reading
10
+ * or sending ordinary mail never pays for a calendar parser.
11
+ */
12
+ export { counter, declineCounter } from './compose.ts';
13
+ export { imipOf } from './lookup.ts';
14
+ export { parseImip } from './parse.ts';
15
+ export type { CalendarPart, CounterInput, DeclineCounterInput, Imip, ImipPerson } from './types.ts';
@@ -0,0 +1,14 @@
1
+ /**
2
+ * `@wtfalch/email/imip` -- compose and parse `COUNTER` and `DECLINECOUNTER`
3
+ * over iMIP (RFC 5546/6047).
4
+ *
5
+ * A new time an attendee proposes, and an organizer's refusal of one, both as
6
+ * ordinary mail: `counter`/`declineCounter` build the `text/calendar` part
7
+ * `draftToEmail` (`@wtfalch/email/mailbox`) sends inline, and `parseImip`/
8
+ * `imipOf` read one back out of a received message. `ical.js` lives entirely
9
+ * behind this entry -- `@wtfalch/email/mailbox` never imports it, so reading
10
+ * or sending ordinary mail never pays for a calendar parser.
11
+ */
12
+ export { counter, declineCounter } from "./compose.js";
13
+ export { imipOf } from "./lookup.js";
14
+ export { parseImip } from "./parse.js";
@@ -0,0 +1,21 @@
1
+ import type { MailClient } from '../mailbox/client.ts';
2
+ import type { Message } from '../mailbox/types.ts';
3
+ import type { Imip } from './types.ts';
4
+ /**
5
+ * The iTIP message a received `Message` carries, or `null` when it has none.
6
+ *
7
+ * **Reads `attachments`, not `bodyStructure`.** RFC 8621 §4.1.4 puts every
8
+ * non-multipart part that is not `textBody`/`htmlBody` in `attachments` --
9
+ * `text/calendar` never qualifies for either list, so JMAP lists a calendar
10
+ * part there whether it arrived inline in a `multipart/alternative` (what
11
+ * `draftToEmail` sends, and what #99 found every vendor sends) or as a true
12
+ * attachment. `downloadAttachment` fetches its bytes, since a `Message`
13
+ * carries only the part's metadata, and `parseImip` reads the method out of
14
+ * the iCalendar body itself -- never the MIME `Content-Type`, which is
15
+ * stripped of `method=` by the time it reaches here (see the PR).
16
+ *
17
+ * A network failure downloading the part throws, the same `MailError`
18
+ * `downloadAttachment` always throws; only a missing calendar part or one
19
+ * `parseImip` cannot make sense of answers `null`.
20
+ */
21
+ export declare function imipOf(client: MailClient, message: Message): Promise<Imip | null>;
@@ -0,0 +1,26 @@
1
+ import { downloadAttachment } from "../mailbox/download.js";
2
+ import { parseImip } from "./parse.js";
3
+ /**
4
+ * The iTIP message a received `Message` carries, or `null` when it has none.
5
+ *
6
+ * **Reads `attachments`, not `bodyStructure`.** RFC 8621 §4.1.4 puts every
7
+ * non-multipart part that is not `textBody`/`htmlBody` in `attachments` --
8
+ * `text/calendar` never qualifies for either list, so JMAP lists a calendar
9
+ * part there whether it arrived inline in a `multipart/alternative` (what
10
+ * `draftToEmail` sends, and what #99 found every vendor sends) or as a true
11
+ * attachment. `downloadAttachment` fetches its bytes, since a `Message`
12
+ * carries only the part's metadata, and `parseImip` reads the method out of
13
+ * the iCalendar body itself -- never the MIME `Content-Type`, which is
14
+ * stripped of `method=` by the time it reaches here (see the PR).
15
+ *
16
+ * A network failure downloading the part throws, the same `MailError`
17
+ * `downloadAttachment` always throws; only a missing calendar part or one
18
+ * `parseImip` cannot make sense of answers `null`.
19
+ */
20
+ export async function imipOf(client, message) {
21
+ const part = message.attachments.find((attachment) => attachment.type.toLowerCase() === 'text/calendar');
22
+ if (!part)
23
+ return null;
24
+ const blob = await downloadAttachment(client, part);
25
+ return parseImip(await blob.text());
26
+ }
@@ -0,0 +1,11 @@
1
+ import type { Imip } from './types.ts';
2
+ /**
3
+ * Read an iTIP `COUNTER` or `DECLINECOUNTER` out of its `VCALENDAR` text.
4
+ *
5
+ * **Never throws.** Malformed text, a `VCALENDAR` with no `VEVENT`, an
6
+ * event missing a property this module requires, or any other method --
7
+ * `REQUEST`, `REPLY`, `CANCEL`, all of them the server's own iTIP engine
8
+ * owns (#97) -- all answer `null` rather than raise, since this reads mail
9
+ * nobody here wrote.
10
+ */
11
+ export declare function parseImip(ics: string): Imip | null;