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