npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@wtfalch/email

v0.28.0

Published

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.

Readme

@wtfalch/email

The estate's mail, in three entries with no code in common:

@wtfalch/email/mailbox      reading and writing messages   (RFC 8620/8621)
@wtfalch/email/imip         proposing and declining a time  (RFC 5546/6047)
@wtfalch/email/postmaster   administering the server        (Stalwart's `x:` extension)

They share a subject, a scope and a repository, and nothing else. There is deliberately no root entry: an entry named for a seam that does not exist is worse than no entry at all.

/mailbox is for the person who has an address — inbox, threads, compose — running in their browser as them, able to touch only their own mail. /imip composes and parses the scheduling messages /mailbox sends and receives as ordinary mail, behind its own entry so the calendar parser it needs never rides along with a plain inbox. /postmaster is for whoever runs the server — who gets a mailbox, what name is on it, who holds a key — running server-side with an administrator credential, and never touching the contents of anybody's messages.

The post office holds the analogy: one is the letters, one is what's inside a particular kind of envelope, the other is the pigeonholes.

Status

Published: yes, v0.15.1, 2026-09-28.


@wtfalch/email/mailbox

Read and write mail over JMAP: session, mailbox tree, threads, bodies and attachments, search, identities, submission and push. RFC 8620 and 8621, over jmap-jam, so it is not tied to Stalwart the way its neighbour is.

import { MailClient, mailboxes, findRole, listThreads, thread } from '@wtfalch/email/mailbox';

const client = new MailClient({
  sessionUrl: 'https://email.example.com/.well-known/jmap',
  bearerToken: accessToken,   // the signed-in person's, from the issuer
});

const tree = await mailboxes(client);
const page = await listThreads(client, findRole(tree, 'inbox').id, { limit: 50 });

A login usually reaches more than one mailbox. client.accounts() lists them, the person's own first: a shared mailbox such as hr@ is an ordinary account the server puts in the same session with isPersonal: false, because the account is a member of it. A client stays on the account it was built with, so opening another one is new MailClient({ …, accountId }) with the id from that list — which is what keeps one client's cached session honest.

One folder can also be shared on its own, finer than a whole account: shareMailbox(client, mailboxId, accountId, rights) grants another account some of RFC 8621 §2's ten rights (mayReadItems, mayAddItems, …) on that one mailbox, and unshareMailbox takes them back. Both patch Mailbox/set at shareWith/<accountId> rather than sending the whole shareWith map, so granting or revoking one account's access never touches another's, and needs no read first. findPrincipals(client, query) turns an email address or a name into the colleague's accountId and display name (JMAP principals, same domain as the login only; an empty list is nobody, two entries is a choice), and lookupPrincipal returns the one match or null, or throws ambiguous. sharedPeople(client, mailboxId) goes the other way: for one folder it lists each account in shareWith with the person's name, email and rights, sorted by name, in one Principal/query and one Principal/get. An account the directory cannot name comes back with its account id as name and email. mailboxes() returns each node's own myRights (what the signed-in login may do there) and shareWith (who else can, and with what), both always present, every right explicit — RFC 8621 requires myRights, and the wire has been seen to fill in every unrequested right on shareWith as false too, which buildTree also does for a caller-built value that leaves some out.

A page of threads is one round trip: the query, the newest message per thread, the threads' member ids and the members are four method calls chained by JMAP result reference in a single request.

Delta sync, for a follower that has to notice new or moved mail without holding a full JMAP client of its own — the gap Activity's mail source had to work around by writing one. emailChanges(client, { sinceState }) and mailboxChanges(client, { sinceState }) are RFC 8620 §5.2's /changes: { oldState, newState, hasMoreChanges, created, updated, destroyed }, id lists only. Watch both — a thread moving folders changes Mailbox, not Email membership, so a follower that only watches Email never notices a move. emailHeaders(client, ids) reads created/updated back as a header-only projection (id, threadId, mailboxIds, from, subject, preview, receivedAt, inReplyTo, keywords) that never fetches a body or an attachment. When the server can no longer diff from sinceState, both changes calls throw a MailError typed cannotCalculateChanges — isCannotCalculateChanges(error) tells a caller apart from any other failure, so it knows to resync (list what it wants fresh, and start delta sync again from the state that read returns) rather than retry. Works the same with a service credential for someone else's account (MailClientOptions.accountId plus a bearer or app-password credential the caller holds, not the signed-in session's own) — Activity's calendar source already does this for calendars.

replyDraft and forwardDraft are pure — give them a message and they compute the recipients, the subject prefix, the In-Reply-To and References chain and the quoted body, with no client and no network, so a composer can call them on every keystroke. send creates the draft, submits it, and files it in Sent; a delay in seconds holds it there first, and cancel unsends it while undoStatus is still 'pending' — the only honest sign the window is still open, since a server not set up for held delivery answers 'final' regardless. queued lists everything still held, soonest first, for a "scheduled" view that survives a reload: it filters its query on undoStatus rather than reading the field off an unfiltered one, since that filter is what makes the server recheck each submission against the mail queue and demote one that already went, instead of answering a stale 'pending'. Every row it returns is safe to hand straight to cancel. submissions lists the account's sent mail newest first, each with a state (scheduled, sending, delivered, failed, canceled) read from undoStatus and the server's deliveryStatus, plus the email's subject and to; options.states and options.limit (default 100) narrow it, and a failed row carries the recipient's smtpReply as failure. resend sends a message that is already in Sent again, with the identity matching its From, and files nothing. saveDraft stores a draft in Drafts so it outlives the compose sheet, and given the id it returned last time, replaces that draft instead of adding one (messages are immutable, so the id changes each save). send(…, { draftId }) sends and removes the saved draft. Both refuse an id that is not a $draft, since replacing is a destroy. attach uploads a file and gives back what a draft carries; the upload is refused before any of it is sent when the file is over the session's maxSizeUpload, which client.session() reports alongside maxSizeAttachmentsPerEmail.

setRead, setFlagged, moveThread, moveToRole and removeFromMailbox change mail rather than read it, and every one of them takes a thread. RFC 8621 has no Thread/set — a thread is derived from its messages — so each resolves the members and patches all of them in one Email/set, because a conversation half-archived or half-read is not a thing anybody asked for. They resolve when the server has accepted the change; nothing here is optimistic, since the count is the one number people trust.

await setRead(client, threadId, true);
await moveToRole(client, threadId, 'archive', { mailboxes: tree });

setLabel puts a label on a thread without moving it: the keyword $label:<name>, lowercased, since keywords are case-insensitive. A name a keyword cannot hold (a space, any of (){]%*"\) is refused, not rewritten. ThreadSummary.labels carries the labels on any message in the thread. listLabels reads the newest 500 messages (scan to change it), because JMAP can search for a keyword but cannot list them.

snoozeThread moves a thread into a top-level Snoozed mailbox, made on first use, and stamps it $snoozed:<unix seconds>. JMAP has no snooze, so nothing brings it back on its own: the host runs wakeSnoozed(client, now) on a timer, and each thread whose time has come goes back to the Inbox, unread.

vacationResponse reads the account's out-of-office responder and setVacationResponse sets it — RFC 8621 §8's VacationResponse, over the urn:ietf:params:jmap:vacationresponse capability Stalwart advertises. It is a singleton, never created or destroyed, so a set is always an update; a field left out of the call keeps whatever the server already has, and null clears it. clearVacationResponse is the shorthand for turning it off — isEnabled: false — without touching the dates or the message, so switching it back on does not need them resupplied.

The reply has an audience: 'anyone' (default), 'company' (senders in the account's own domain, taken from the first identity) or 'nobody' (dates and text kept, no reply). With the sieve capability the away reply is the vacation section of the account's one active script, next to the mail rules, and the server's own VacationResponse is kept isEnabled: false so it never replies twice; a hand-written active script refuses an enabling write (conflict) but can still be turned off. Without the capability only 'anyone' works and the JMAP object is used as before.

await setVacationResponse(client, {
  isEnabled: true,
  fromDate: '2026-09-28T00:00:00Z',
  toDate: '2026-10-05T00:00:00Z',
  subject: 'Out sick',
  textBody: 'I am out sick until October 5th.',
});
// …later
await clearVacationResponse(client);

Note that a stock Stalwart account has no Archive mailbox — it creates Inbox, Drafts, Sent Items, Junk Mail and Deleted Items — so moveToRole(…, 'archive') throws there rather than doing nothing, and a caller should offer the action only where findRole(tree, 'archive') finds one.

Per-account filtering rules are Sieve, over the same JMAP endpoint — RFC 9661, urn:ietf:params:jmap:sieve. sieveScripts lists every script on the account (name, isActive, blobId); sieveScriptText reads one's source. saveSieveScript(client, name, text) creates a script from text, or replaces one's content when given { scriptId }, uploading it as a blob the same way attach uploads a file. validateSieveScript compiles text on the server without saving it, for a check before committing. Exactly one script is active per account: activateSieveScript(client, id) makes it the one that runs, and deactivateSieveScripts turns filtering off entirely. deleteSieveScript is refused while its target is the active script — the server's own guard, deactivate first. Stalwart's SieveScript is only a name, an active flag and a blob of Sieve source, so rules live in this package: rulesToSieve(rules) writes Sieve for a list of MailRules (from/to/cc/subject contains, has attachment, list-id present; move to a folder, add a keyword, mark read, forward a copy, stop), and sieveToRules(script) reads back only a script that function wrote, using a marker line at the top, and gives null for a hand-written or edited one. Every value is quoted and escaped, so it cannot end its string early.

The React

@wtfalch/email/mailbox/react draws it, on @wtfalch/design ^0.30.0.

Breaking: the floor moved from ^0.28.0 to ^0.30.0. 0.30.0 ships a rewritten Toggle -- a busy state drawn as an opacity pulse and a new spring on the knob, keyed to the new --dur-spring token -- and this package follows the same rule PR #126 set: the peer tracks the design minor this package actually builds and tests against, never a range wide enough to claim an untested one. No estate host runs design 0.30 yet -- Archon peers 0.29.0, Agora's app resolves 0.28.0 -- so a host on an older design must upgrade @wtfalch/design to 0.30.x before taking this @wtfalch/email release; installing this range against an older design is a peer conflict, not a silent downgrade.

Mail is the whole client — mailboxes, list, message, composer, search, a toolbar, and a command palette on Cmd-K — and the only piece that holds state or fetches. MailboxTree, ThreadList, ThreadView and Composer take their data as props and know nothing about a client, so an application with its own layout takes the four and skips the shell. HtmlBody, which ThreadView draws a message's HTML with, is exported on its own too. Import @wtfalch/email/mailbox/mail.css after the design stylesheet.

Three layouts, and the middle one is not decoration. Three panes above 1150px, an icon rail and two panes above 860px, one pane at a time below it. That last is why usePanes is a hook and not a media query: at one column the list and the message are the same space, so which of them is showing is state the shell has to hold.

The keyboard is the point. Arrows and j/k move through the list, which is a single tab stop rather than fifty; c writes, r/a/f answer, e/#/u/s file, / searches and ? lists them all. They are ignored while a field has focus, or c could never be typed into a subject.

Opening a conversation marks it read, which is what opening means — and only when there is something unread in it, because a set that changes nothing still moves the account's state and wakes every other client's push connection.

A file is on the draft only once it has uploaded. Attach opens the file picker, and a file dropped anywhere on the composer is taken too. Until its upload lands it sits in the list with a spinner and Send waits, because a message that went while a file was on its way arrives without it. One that failed says why and can be tried again; one over the server's limits is refused before a byte is sent. Either stays in the list, and Send keeps waiting, until it is retried or removed. Composer takes the upload as an onAttach prop, since it holds no client, and Mail supplies attach.

HTML is drawn in a frame it cannot climb out of. Mail arrives from strangers, and a client that injects their markup into its own document is one script tag from being read by them. So HtmlBody never does. Three walls, each of which holds if the other two fall:

  • A sandboxed frame. A srcdoc iframe with no allow-scripts, no allow-forms and no allow-top-navigation: nothing in it runs, submits or replaces the page. Links open a tab of their own. It has allow-same-origin, deliberately, so the view can size the frame to the message; that is safe only because nothing in it can run, and FRAME_SANDBOX is pinned by a test that fails if allow-scripts joins it.
  • A content policy of its own. default-src 'none', inline styles and nothing else, form-action and base-uri closed, no fonts, and images from data: only.
  • A sanitiser. An allowlist of elements and attributes, walked over an inert DOMParser document, for what the other two do not stop — a <meta> refresh, a <base>, a ping, a relative address that would fetch from this application. CSS is read back through the CSSOM rather than matched with a pattern, so u\72l( is caught as the url( it is.

Remote images wait to be asked for. An image on the sender's server tells the sender the message was opened, when and from where, so they are withheld and the reader is told how many, with a button that shows them for that message. Inline cid: pictures are part of the message and are drawn — fetched through fetchInline, behind the same credential as everything else.

Plain text first, where there is a choice. A message with both bodies is shown as its text, with the formatted version a button away. HTML is drawn on white in either theme, because it was written for white.

A srcdoc frame inherits the embedding page's content policy as well as carrying its own, so a host whose policy has no style-src 'unsafe-inline' will draw mail unstyled, and one whose img-src has no data: will draw it without pictures.

Mailboxes are drawn in reading order, not the server's. Stalwart gives all five sortOrder: 0, so the tie-break by name puts Deleted Items first and Inbox third. mailboxes() still reports what the server said.

A mail server's admin API with no server

@wtfalch/email/postmaster/fake is the management API in memory, for development builds and for tests of code that calls the postmaster functions.

const { instance, dispose } = fakePostmaster();   // one domain, one administrator
await createMailbox(instance, { local: 'ada', domainId, apex, external: true });
const view = await loadOverview(instance, null);  // the real functions, over the real client
dispose();

It answers at the transport, like the mailbox fake, so the real StalwartClient runs unchanged. One suite, postmasterContract in src/postmaster/contract.ts, takes any target and runs against the fake in pnpm check; the release run points it at a real server. Behaviour the fake had to guess is marked unverified against Stalwart in its source.

How the fakes are kept true

A fake can drift from the server it stands in for, so the same two suites (postmasterContract and mailboxContract) run against both. Every pnpm check runs them against the fakes. Before a release, and on a manual run of the CI workflow, they run against a real Stalwart 0.16.20 in a container. Where the real server answered differently, the fake was changed to match. Two differences are known and kept: the admin fake answers notFound for every missing id, where Stalwart ignores an id it cannot parse (the client never makes ids), and the mailbox fake's Sieve check knows a subset of the commands and does not check require (see src/mailbox/fake/mailbox.ts).

To run them against a server of your own, on a machine with Docker, curl, jq and openssl:

packages/email/scripts/stalwart-up.sh     # prints the STALWART_* variables as export lines
pnpm --filter @wtfalch/email test:real    # with those variables set

The script starts a throwaway container named stalwart and makes one account in it. It pins 0.16.20 on purpose: Stalwart 1.x renamed fields this client sends.

What it knows that the RFCs do not

RFC 8621 §7.5's onSuccessUpdateEmail collides. The server returns the implicit Email/set under the same method call id as the EmailSubmission/set that triggered it, so a client reading a multi-call response into a map by id loses the submission's own result. jmap-jam does exactly that, so send submits through the single-call path — and creates the draft in a separate request, which also leaves a failed send in Drafts rather than losing it.

The event source is authenticated, and the browser EventSource cannot send a header. push reads the stream with fetch and parses the server-sent events itself.

Session URLs are templates that need encoding. RFC 8620 §6.2 requires it, and jmap-jam's expander does not: an attachment called Q3 report (final).pdf otherwise builds a URL addressing the wrong thing.

Stalwart sends null, not an omitted property, for an absent header or display name. src/mailbox/fixtures/instance-one.json is recorded from a live 0.16.20 instance and pins it.

Message.senderAuthenticated reads the Authentication-Results header Stalwart's inbound DATA handling stamps on accepted mail, merging its DKIM/DKIM2, SPF, IPREV and DMARC checks into one header (crates/smtp/src/inbound/data.rs, stalwartlabs/stalwart, gated on a config toggle, dc.add_auth_results, this package has not confirmed is on for any real deployment), in the wire format stalwartlabs/mail-auth's AuthenticationResults HeaderWriter builds (src/auth_results.rs). thread() reads every instance with RFC 8621 §4.1.3's header:Authentication-Results:asRaw:all, confirmed as a generic EmailProperty::Header case (crates/jmap/src/email/get.rs) rather than a hand-picked header list, and mailbox/auth-results.ts derives true from a DKIM signature whose header.d=/header.i= domain exactly matches the message's from[0] domain, or a dmarc=pass. Fails closed: a sender can write its own Authentication-Results header, and the server hostname is public, so a matching authserv-id alone proves nothing. Stalwart prepends its own header (add_auth_results, on by default) and never strips incoming ones, so only the topmost instance is read. senderAuthenticated is always false unless the caller passes { trustedAuthServId } (the instance's Stalwart hostname), and then only if the first instance carries that authserv-id (case-insensitive); later instances are never read. Setting the option asserts the receiving server prepends its own header on every message; if it does not, leave it unset. Not confirmed: which hostname a real instance uses.

jmap-jam is kept internal. It ships raw TypeScript with .ts import specifiers, which only compiles under allowImportingTsExtensions; nothing of it reaches this package's public types, so a consumer does not inherit the flag.

jmap-jam already knows VacationResponse needs its own capability. It derives a request's using from the method names being sent, against a built-in table that maps VacationResponse to urn:ietf:params:jmap:vacationresponse the same way it maps Mailbox to mail and EmailSubmission to submission (confirmed against the installed [email protected]). So vacationResponse/setVacationResponse need no using override — unlike send/cancel, whose implicit Email/set runs under a method name the request never states.

Per-mailbox sharing is real, and it is the plain Mailbox object, not a separate capability. shareWith/myRights are confirmed on the schema at stalwartlabs/stalwart tag v0.16.20 (crates/jmap-proto/src/object/mailbox.rs:31-53) and exercised end to end — grant, partial patch, revoke, and the server's own fill-in of every unrequested right as false on read-back — by the sibling AddressBook object's ACL suite, tests/src/jmap/contacts/acl.rs, which shares the same shareWith/myRights machinery. Not yet confirmed against a live instance the way instance-one.json's fixture is: nothing in this package wrote a shareWith grant before now.

jmap-jam does not know Sieve at all, so sieve.ts is the one place in this package that calls jam.request directly rather than jam.api, adding urn:ietf:params:jmap:sieve to using by hand — the same thing send() already does for the mail capability. Confirmed against stalwartlabs/stalwart at main, 02503015580abd6706923d34e9d8e501e76f8634: SieveScript/get|set|query|validate under that capability (crates/jmap-proto/src/request/method.rs:146-149,284-287), the object as {id, name, blobId, isActive} with no structured rule shape (crates/jmap-proto/src/object/sieve.rs:19-24), and activation as the non-standard onSuccessActivateScript/onSuccessDeactivateScript set arguments (set.rs:371-391). onSuccessActivateScript silently does nothing for an id the account does not have — Stalwart clears it rather than refusing (set.rs:96-101) — so activateSieveScript pairs it with a no-op update on the same id, whose own notFound is what actually surfaces a bad id.

@wtfalch/email/imip

An attendee proposing a new time for a meeting, and an organizer declining that proposal — RFC 5546's COUNTER and DECLINECOUNTER, sent and read as ordinary mail (RFC 6047). Everything server-side — accepting a counter, or sending the REQUEST/REPLY/CANCEL methods around it — is the mail server's own iTIP engine; this is compose and parse for the two methods nothing else here speaks for.

import { counter, declineCounter, parseImip, imipOf } from '@wtfalch/email/imip';
import { send } from '@wtfalch/email/mailbox';

const proposal = counter({
  uid: event.uid,
  sequence: event.sequence,       // echoed, never incremented
  summary: event.summary,
  organizer: { email: '[email protected]', name: 'Ada Lovelace' },
  attendee: { email: '[email protected]', name: 'Charles Babbage' },
  start: newStart,
  end: newEnd,
  comment: 'Could we push this an hour later?',
});

await send(client, { ...draft, calendar: proposal });   // Draft.calendar, mailbox/types.ts

// On the organizer's side, reading a received message back:
const imip = await imipOf(client, message);              // null if it carries neither method
if (imip?.method === 'COUNTER') { … }

Plain fields in, a typed union out. counter/declineCounter take an object of primitives and return { method, ics }; parseImip is a pure function from that ics text back to a typed Imip, or null for any other method or for text it cannot make sense of — it never throws, since it reads mail nobody here wrote. Neither this entry nor @wtfalch/email/mailbox takes a dependency on @wtfalch/calendar or any other calendar model.

ical.js never reaches @wtfalch/email/mailbox. It is a real dependency of this package, but only src/imip/** imports it, so reading or sending ordinary mail never pays for a calendar parser. imipOf finds the calendar part in a Message's attachments — RFC 8621 §4.1.4 puts a text/calendar part there whether it sits inline in a multipart/alternative or as a true attachment, since it is never text/plain or text/html — downloads it with downloadAttachment, and hands the bytes to parseImip.

Compose writes UTC times, which is why it never needs a VTIMEZONE (RFC 5546 requires one only when a property uses TZID). Parse accepts UTC, a TZID resolved against the message's own embedded VTIMEZONE — how Outlook's Windows zone names (Pacific Standard Time, never an IANA identifier) arrive, and ical.js resolves one with no registration needed, by walking up to the VCALENDAR and matching the embedded component — and a floating time, which is read as UTC deterministically rather than through ical.js's own default of the machine's local zone.

The method= parameter rides in the JMAP body part's own type string. Stalwart's Email/set writes whatever that string holds onto the wire unparsed rather than validating it as a bare media type, so text/calendar; method=COUNTER survives to the Content-Type header exactly as given — confirmed against stalwartlabs/stalwart at commit 0250301 (crates/jmap/src/email/set.rs:325-327,439-467,515-562) and mail-builder's ContentType::write_header at the v1.0.0 commit Stalwart's Cargo.lock pins (0e87ce2, src/headers/content_type.rs:49-63). An explicit header:Content-Type property is not the alternative it looks like: Stalwart does not enforce RFC 8621 §4.6's rule against setting the same header field twice, so combining it with type would silently emit two Content-Type headers rather than one.

Outlook and Google never send DECLINECOUNTER. Nothing here waits on one arriving; this only composes and parses the method for the organizer side that does emit it.

@wtfalch/email/postmaster

Administer a Stalwart mail server: its domain, its mailboxes, their aliases, their app passwords and their quotas, over the JMAP management API.

This is not a JMAP mail client. It speaks the urn:stalwart:jmap management extension — x:Account, x:Domain, x:ApiKey and their neighbours — which is a different surface from RFC 8620 and 8621 entirely.

The credential is why this entry must never reach a browser. /mailbox runs in a browser holding the signed-in person's token. This runs on a server holding an administrative one. A minted key can be scoped — that is what DASHBOARD_PERMISSIONS is for — but nothing obliges a caller to hand this entry a scoped one, and an account password or an 'inherit' key is as powerful as the account itself.

Neither a package boundary nor an entry name enforces that: bundlers follow imports. What does is the browser condition in the exports map, which resolves this entry to a module that throws with an explanatory message. It was server-only for one commit, which was wrong — that throws in any environment without React's react-server condition, plain Node included, so it blocked pnpm bootstrap and mail:sync, which are exactly the callers this entry is Node-safe for. The browser condition tells the illegitimate caller from the legitimate one; server-only could not.

import { openInstance, overview } from '@wtfalch/email/postmaster';   // pure Node
import { DomainCard, Mailboxes, People } from '@wtfalch/email/postmaster/react';

The first entry has no React in it, so a provisioning script can use it. The components are server components except the two interactive leaves, and they take data and already-bound actions: nothing here fetches, gates or decides. The consuming app reads the instance, asks its own authorisation, binds its own Server Actions and passes the results in — the division @wtfalch/threads draws, and what keeps a package free of anybody's session.

openInstance refuses with a reason, not a sentence. It throws InstanceRefused, whose reason is 'not-https' or 'account-missing'. Branch on that. Both refusals were once a plain Error, so consumers told them apart by matching words in the message, and rewording a sentence here quietly changed which error a dashboard showed.

try {
  openInstance({ url, secret, user });
} catch (e) {
  if (e instanceof InstanceRefused && e.reason === 'account-missing') …
}

@wtfalch/design is an optional peer dependency, needed only for /react.

What it knows that the docs do not

Every one of these was established against a live 0.16.20 instance, and each cost an afternoon.

An API key authenticates as Authorization: Bearer, never Basic. The same secret sent as Basic is refused with 401 whatever username accompanies it — the account name, the local part, the key itself, none. authFor picks the scheme from the secret's own shape, since a key is API_-prefixed.

An API key is scoped with the sys* permission names. permissions takes {'@type': 'Replace', permissions: {…}}, a Set, so {sysDomainGet: true}. The names live in enums.Permission, and the management ones read sys<Object><Verb>. An earlier round of sixty guessed names accepted only authenticate and impersonate, which is what made a scoped key look impossible; the guesses were wrong, not the feature.

createApiKey therefore mints a scoped key by default. DASHBOARD_PERMISSIONS is the set verified on 0.16.20: authenticate plus sysAccountQuery, sysAccountGet, sysAccountCreate, sysAccountUpdate, sysDomainQuery, sysDomainGet, sysSystemSettingsGet, sysMtaExtensionsGet, sysMtaExtensionsUpdate and sysActionCreate. It serves every /email page, and it is forbidden on Email/query for every account on the instance — including its own, so the key administers mail and cannot read any. Pass 'inherit' for a key as powerful as the account; prefer not to.

sysActionCreate is the widest of these: Stalwart has one permission for every action, so the key that can reload settings can also pause the mail queue. It is there because a changed setting does nothing until a ReloadSettings action runs. A key minted before a name joined the set does not gain it; mint a new one.

ROOM_PERMISSIONS is DASHBOARD_PERMISSIONS plus one more, sysAccountDestroy, for a caller that removes meeting rooms; mint with createApiKey(description, ROOM_PERMISSIONS).

A server that is not holding mail says nothing. With MtaExtensions.futureRelease unset, Stalwart sends a held submission at once and reports it as held. Provisioning sets it (FUTURE_RELEASE, 30 days); an instance provisioned before it did stays off. holdLimit(instance) returns the limit, or null when the server will not hold at all, and enableHolding(instance) sets it and reloads.

An API key can never create a credential. It authenticates, and both x:ApiKey/set and x:AppPassword/set answer forbidden whatever permissions it holds, so a key cannot mint its own successor. Rotating one needs the account's password or app password. On a domain with an external directory the account password stops being verified locally as well, which leaves an app password the only credential that can still write — and the admin UI will not add one from the account form, answering "Secondary credentials cannot be set directly". Provision the replacement before revoking the one in use.

A List<T> write replaces the whole list. Adding one alias means sending back every alias that survives. A read-modify-write that drops an entry does not fail; it deletes somebody's alias, or every app password on their phone. withAlias, withoutAlias, withoutAppPassword and withoutAllAppPasswords exist so that arithmetic is decided by a unit test rather than at the end of a request.

Disabling a person's sign-in does not stop their mail by itself. IMAP and SMTP authenticate against the account's own credentials and never consult the issuer, so an app password minted before a person is disabled keeps working after. revokeAllAppPasswords drops every AppPassword credential on an account at once — the Password and any ApiKey entries survive untouched — for the moment a person must be shut out of mail immediately, alongside whatever disables their sign-in. Same self-protection as revokeAppPassword: refused on the account this app itself signs in as.

A shared mailbox is a Group account. hr@ that a team reads together is an ordinary account whose @type is Group: same delivery, same aliases, no password, because nobody ever signs in as it. Who reads it is written on the people — an account's memberGroupIds names the groups it belongs to, and the server turns each one into a second account on that person's own JMAP session, which is how /mailbox's client.accounts() sees it. createGroupMailbox makes one, addToGroup and removeFromGroup say who reads it, and withMembership/withoutMembership do the arithmetic. A membership map is a set on the wire ({"<id>": true}) and is replaced whole, exactly like a List<T>. addToGroup refuses a group id that turns out to be a person's own mailbox: the server would store that happily and it would give nobody access to anything.

There is no conditional write. JMAP's answer to the above is ifInState, and these objects do not offer it: x:Account/get returns accountId, list and notFound with no state token, and x:Account/set rejects an ifInState argument outright as notRequest. So two overlapping writes to one mailbox still lose one, and what apply.ts does instead is notice: it re-reads afterwards and names anything the caller never touched that has gone.

Wire shapes are not what the docs show. A List<T> is a map keyed by index ({"0": …}), a Map<T> is {"value": true}, a SecretKey from the environment is {"@type":"EnvironmentVariable","variableName":"…"}, and singletons are addressed with the id singleton. An administrator's roles is {'@type': 'Admin'}. usedDiskQuota is a plain byte count; quotas is an object whose key for a set quota has never been observed, so overview() reports no limit rather than inventing a number.

Refusals

The write helpers refuse rather than doing something surprising: an alias given as a whole address (it would become an address at [email protected]@example.com), a duplicate (an unreachable second entry), revoking an account Password or an ApiKey through a call meant for app passwords, and creating a mailbox on a domain that keeps its own passwords, which needs a first password shown once and so points at a terminal tool instead.

The audit

createMailbox, createGroupMailbox, addToGroup, removeFromGroup, addAlias, removeAlias, revokeAppPassword, revokeAllAppPasswords, enableHolding, retryQueuedMessage and purgeQueuedMessage take an optional last argument, a PostmasterAudit: a write the host bound to its own ledger, the principal it resolved for this request, and the request id its log uses. Without one, nothing changes.

const applied = await addAlias(instance, { accountId, name, domainId, apex }, {
  write: (event) => ledger.record(event),     // the host's, bound to `mail`
  actor: { id: principal.id, display: principal.display },
  requestId,
});

A write records what happened, after the server has answered. The event carries the before/after pair the write computed — which alias, on which mailbox; which app password, by its description — so a host does not reassemble it from Applied. It is never a secret: target.id is an address or a credential id.

A refused write records nothing. It throws before write is called, and recording the attempt is the caller's, since only the caller knows who was refused and why. Nor can the two be atomic — one is a mail server, the other is the host's database — so a crash between them loses the row, and the request id is what joins it back to a log line.

The names are mail.*, declared in POSTMASTER_AUDIT_EVENTS so a host can merge them into its ledger's vocabulary. A host whose vocabulary is closed maps them instead: wtfalch-manage's database refuses any action outside its authorisation package's set, so its writer puts each back on the core event it already recorded these under, and signs the row with the principal it resolved rather than the one the event echoes.

One org's mail on the shared server

applyOrgMail and parkOrgMail give foundry (wtfalch/email#96) a typed, idempotent way to put one org's mail on the one shared Stalwart instance, without a second server per org and without this package ever calling Cloudflare itself.

import { applyOrgMail, parkOrgMail } from '@wtfalch/email/postmaster';

const options = { apex: 'oikos.host', mailHost: 'mail.oikos.host' };

// Level 1: no domain of its own, so it lives at acme.oikos.host and must be hosted.
await applyOrgMail(client, { slug: 'acme', mode: 'hosted' }, options);

// A domain of its own, kept receiving through Google or Microsoft.
const { domain, records } = await applyOrgMail(
  client,
  { slug: 'acme', domain: 'acme.com', mode: 'received' },
  options,
);

// Changing mode is calling it again with the new mode.
await applyOrgMail(client, { slug: 'acme', domain: 'acme.com', mode: 'hosted' }, options);

// Park stops it receiving; every mailbox and message stays.
await parkOrgMail(client, { slug: 'acme', domain: 'acme.com', mode: 'hosted' }, options);

One Lettermint relay per org. applyOrgRelay(client, { slug, domain, secret }) upserts an MtaRoute named lettermint-<slug> (smtp.lettermint.co, port 465, implicit TLS, user lettermint, the token as a Value secret) and rebuilds MtaOutboundStrategy.route so mail from domain leaves through it and every other sender is delivered direct (route 'mx'). The expression always starts with the rule that delivers a recipient on a hosted domain to its mailbox (route 'local'), whoever the sender is. removeOrgRelay(client, { slug }) deletes the route and rebuilds; a missing route removes nothing and only repairs an outdated expression. hasOrgRelay(client, { slug }) is true when the route holds a secret, so a caller knows whether it needs a fresh token. The domain is kept in the route's description, and the expression is rebuilt from the routes that exist, never patched. applyObjects rebuilds it the same way, so re-applying the instance plan keeps every org's route. Relay changes are not locked: two callers at once can drop one org's entry until the next change, so run them one at a time.

One Domain per org, upserted by name. applyOrgMail calls the same Domain object mailObjects/applyObjects write for the instance itself, so calling it twice with the same org leaves exactly one Domain, and calling it again with a different mode changes only the records it returns — never a second Domain. Calling it on a parked org sets isEnabled back to true. parkOrgMail touches only that one field, and never an Account or a message: parking keeps every mailbox.

certificateManagement and dnsManagement are Manual on an org's Domain. Only dkimManagement stays Automatic, so Stalwart still mints and rotates the signing key — this package reads it back rather than have Stalwart publish anything to a DNS provider itself. Publishing stays foundry's, since foundry owns Cloudflare. applyOrgMail re-asserts all three — certificateManagement, dnsManagement and dkimManagement — on every call, so a manual change to any of them in the web admin is reverted the next time foundry re-applies the org's declared file.

The management API can read back what a domain needs published. x:Domain/get computes an extra dnsZoneFile property — a full BIND zone, DKIM included — confirmed against stalwartlabs/stalwart at commit 0250301 (crates/jmap/src/registry/get.rs:297-304 calls Server::build_bind_dns_records, crates/common/src/network/dns/records.rs:357-382). applyOrgMail derives MX and SPF itself (no round trip needed for either) and reads only the _domainkey lines back out of that zone file for DKIM. The DKIM record can be empty on the very first applyOrgMail: Stalwart mints the key on a background task queued by the same write (crates/jmap/src/registry/mapping/domain.rs:102-133), not inside it. A caller that needs the key right away calls applyOrgMail again a moment later — free beyond the extra read, since the Domain is already there.

What each mode returns. hosted gets an MX record at mailHost plus a TXT SPF record of v=spf1 mx -all, matching how Stalwart's own zone generation composes SPF for a domain it holds the MX for. received gets no MX at all — the org's existing one, at Google or Microsoft, is not this package's to touch — and a TXT SPF record of v=spf1 include:<mailHost> -all for the org to merge into what it already publishes.

Level 1 is the slug on the shared apex, and freezes there. An org with no domain gets ${slug}.${apex} (foundry#7: "Level 1 gets @acme.oikos.host") and its mode must be hosted — there is nowhere else for a level-1 org's mail to be received at. applyOrgMail and parkOrgMail both refuse a slug or a domain that is not a lowercase DNS label before making a request.

Stalwart tenants are out of scope here. Every org's mail lives in the one shared instance regardless of level; Agora's own org scoping is the boundary between them, not a Stalwart tenant. Moving an org's old mail in from Google or Microsoft — wtfalch/email#108 — is mailCopyPlan, below.

Importing an uploaded Google Takeout archive

For a person whose mailbox is over Google's daily download cap, mailTakeoutPlan decides the Vandelay commands that import an uploaded Takeout .mbox into one Stalwart account (import takeout, then the same export step as mailCopyPlan; the export credential is only named in exportEnv, never in argv). It refuses, with MailCopyPlanRefused, a path that is not an absolute .mbox under uploadDir in its own directory, a size over TAKEOUT_MAX_BYTES (50 GiB), and a target naming both id and name or neither. Vandelay scans the mbox's whole directory, so keep one upload per directory.

How it differs from the IMAP route (mailCopyPlan):

  • Labels differ. IMAP folders become mailboxes. Takeout carries Gmail labels in X-Gmail-Labels: each label becomes a mailbox of that name (Archived → Archive), Inbox/Sent/Drafts/Trash/Spam/Archive get the matching Stalwart roles, Starred/Important/Opened become the $flagged/$important/$seen keywords, and Category … labels are dropped. A message with several labels sits in several mailboxes.
  • The final pass is still IMAP. A Takeout is a snapshot at export time; mail that arrived since is picked up by running the mailCopyPlan import afterwards.

Copying an org's old mail with Vandelay

Stalwart ships its own migration tool, stalwartlabs/vandelay: a JMAP importer-exporter that reads a source account (IMAP, JMAP, Exchange, Google Takeout, …) into a local SQLite archive, then pushes that archive into a target JMAP account. mailCopyPlan decides the exact Vandelay command lines foundry runs per account — it never spawns Vandelay itself, never touches a network, and never carries a real credential.

import { mailCopyPlan } from '@wtfalch/email/postmaster';

const plan = mailCopyPlan({
  provider: 'google', // or 'microsoft'
  accounts: [{ source: '[email protected]', targetAccountId: 'a1' }],
  stalwartUrl: 'https://mail.companyincluded.com',
  archiveDir: '/var/lib/mail-copy/acme',
});

// plan.accounts[0].importArgv: ['import', 'imap', '--url', 'imaps://imap.gmail.com',
//   '--auth-bearer', '[email protected]', '--', '/var/lib/mail-copy/acme/alice%40acme.com.sqlite']
// plan.accounts[0].exportArgv: ['export', '--url', 'https://mail.companyincluded.com',
//   '--auth-bearer', '--account-id=a1', '--', '/var/lib/mail-copy/acme/alice%40acme.com.sqlite']
// plan.accounts[0].importEnv / .exportEnv: [{ name: 'VANDELAY_TOKEN', purpose: '…' }] — a
// variable NAME, never a value.

The archive filename is the account's address, percent-encoded — never collapsed to a lossy _, so two different addresses ([email protected], [email protected]) can never land on the same file. mailCopyPlan also refuses a plan where two accounts would still collide (e.g. two spellings that case-fold to the same address). A target id or name, or archiveDir, is free to start with -: the account selector uses --flag=value and a literal -- always precedes the archive path, so Vandelay's own arg parser (clap) never mistakes either for another flag.

Both providers go through import imap, not a provider-specific importer. Vandelay's IMAP importer authenticates with XOAUTH2 (--auth-bearer + --auth-user) and imports mail only — the same argv shape for Google and Microsoft. Microsoft also has import exchange-graph, but it is one of the two importers Vandelay's own docs call experimental, and its non-interactive path still needs a token minted outside Vandelay with no built-in client-credentials flow, so switching to it buys nothing.

No secret ever lands in argv. Every Vandelay flag that carries a secret (--auth-password, --auth-bearer, …) takes an optional inline value; passed bare, as this plan always does, Vandelay resolves it from a same-named environment variable and finally an interactive prompt — never a file. importEnv/exportEnv name that variable, VANDELAY_TOKEN, and never carry a value themselves — the type has no field for one.

The import token and the export token are the same variable name, at different moments. A bare --auth-bearer always reads $VANDELAY_TOKEN, whether it is authenticating to the source or to Stalwart. Import and export are two separate process launches, so this is only safe if the caller sets VANDELAY_TOKEN to the source token before running importArgv and to the Stalwart credential before running exportArgv, and never merges the two into one shared environment.

Rerunning is safe. Vandelay's import and export are both convergent: a rerun picks up an interrupted transfer or new mail since the last snapshot, and export is upsert-only, never recreating or duplicating a message already on the Stalwart account. mailCopyPlan never sets --prune, so a plan built here can never delete anything on the target. It is also a pure function: the same input returns the same plan, byte for byte.

Vandelay never checks that the export credential may write into targetAccountId/targetAccountName — Stalwart does. Vandelay resolves --account-id/--account-name and uses it as-is, with no authorization check of its own. Stalwart's JMAP dispatcher is the actual gate: writing into that account's mail requires the export credential to either be a member of it (its own account, a group it belongs to, or the Stalwart impersonate permission outright) or hold ACL/shared access to that account's Email collection specifically. impersonate is already a permission this package's own API keys can hold, and is the practical choice for one migration credential that writes into many different accounts, rather than pre-arranging a per-account ACL share for each one.

Admin setup

Google Workspace. Create a service account with domain-wide delegation and authorize it for the scope https://www.googleapis.com/auth/gmail.imap_admin (developers.google.com/workspace/gmail/imap/xoauth2-protocol) — this is the scope built for exactly this case, reading any user's mailbox over IMAP without that user's own consent. IMAP downloads are capped at 2,500 MB per account per day (support.google.com/a/answer/1071518), so a large mailbox needs several days of reruns to finish; that is exactly the rerun mailCopyPlan's convergent export supports.

Microsoft 365. Register an Entra app, grant it the Exchange IMAP.AccessAsApp application permission, get tenant admin consent, then register the app's service principal in Exchange with the New-ServicePrincipal cmdlet and grant it the target mailboxes with Add-MailboxPermission (learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth) — this is the client-credentials, non-interactive path the same page documents for IMAP. The alternative is a Graph Mail.Read application permission instead, which is what import exchange-graph would need; this package uses the IMAP path instead (see above), so IMAP.AccessAsApp is the one this plan's admin setup actually needs.

Backing up and restoring one org's mail

Every org's mail lives in the one shared Stalwart instance, scoped only by Domain — so there is no per-org database or container for a company-wide backup (archon#132) to snapshot the way it can a company's own Postgres. accountsOnDomain, orgMailBackupPlan and orgMailRestorePlan (wtfalch/email#139) pull one org's mail out of the shared instance's own store instead, and plan it back into a — possibly different — shared instance later.

import {
  accountsOnDomain,
  orgMailBackupPlan,
  orgMailRestorePlan,
} from '@wtfalch/email/postmaster';

// 1. Which accounts does this org have, on the instance being backed up?
const accounts = await accountsOnDomain(client, 'acme.com');

// 2. The Vandelay commands that pull each one's mail into a local archive.
const backup = orgMailBackupPlan({
  accounts,
  stalwartUrl: 'https://mail.companyincluded.com',
  archiveDir: '/var/lib/mail-backup/acme',
});

// 3. Later, possibly on a different instance: resolve the same addresses to
//    that instance's own account ids (re-provisioning the org there first,
//    then accountsOnDomain again, gives exactly this), and push the
//    archives back in.
const restore = orgMailRestorePlan({
  accounts: [{ address: '[email protected]', targetAccountId: 'b1' }],
  stalwartUrl: 'https://mail.companyincluded.com',
  archiveDir: '/var/lib/mail-backup/acme',
});

This is mail-copy.ts's mirror image, not a new mechanism. Vandelay already speaks JMAP on both sides, so a backup is import jmap reading this org's own account off the shared instance — the source is the instance itself, not Google or Microsoft — and a restore is the same export mailCopyPlan already uses, into a target account on whichever instance the restore runs against. Confirmed against stalwartlabs/vandelay at commit 486a3847121732fc46c2433de0e0ed50bbcb5825 (main, 2026-10-04): Source::Jmap(Box<JmapImportArgs>) at src/cli.rs:58, JmapImportArgs at src/cli.rs:131-174, requiring exactly one of auth_basic/auth_bearer and one of account_id/account_name — the same two ArgGroups ExportArgs carries. A bare --auth-bearer resolves $VANDELAY_TOKEN on both sides, exactly as it already does for mailCopyPlan.

Backup and restore take independent account lists, unlike mailCopyPlan's single bundled plan. A migration's target account is known at plan time; a backup's eventual restore target is not — it may be a different instance that does not exist yet, resolved only once a restore actually runs. The one thing the two plans share is each account's address, which is what the archive filename is derived from: the file a backup writes is the file its later restore reads.

Domain-level settings are not part of this plan. An org's Domain and relay are already fully reconstructed by calling applyOrgMail/applyOrgRelay again with the org's own declared config — a restore's first step, and nothing new to export.

accountsOnDomain scopes by Domain, the same exact lookup applyOrgMail uses, and returns an empty list rather than refusing for a domain this instance has never heard of — the same "no-op, not a refusal" parkOrgMail already gives that case.