Compare commits

..
Author SHA1 Message Date
LINUXexpert.org fa10563ed0 Merge pull request #55 from LINUXexpert-org/settings-server-side
Keep settings with the account, not the browser
2026-08-26 08:24:03 -07:00
jcoffey-dev b7e0fc0c7d Keep settings with the account, not the browser
Every setting lived in localStorage, so none of them travelled between
devices. The sharpest edge is the default identity: with none set the
address that sorts first wins, so mail goes out from an address the
recipient may not recognise -- and someone who sets it at work finds it
unset at home, with nothing to say so. Reported in #54.

They now live in a settings.json in the account's own JMAP Files, beside
the signature images already kept there. ihasmail itself stays stateless:
no volume, no database, nothing to back up separately, and the settings
are covered by whatever backs up the mail store.

localStorage stays as a cache rather than the source of truth, so the
first frame is painted from it and the file corrects it a moment later.
A private window has no cache and shows defaults for that one frame,
which is the trade for not gating the whole app on a network round trip.

Not everything should follow the account. A list-pane width picked on a
27" monitor is wrong on a laptop, and the notification toggles track a
permission the browser grants per-device, so claiming it elsewhere would
be a lie. Those stay local, written as a list of exceptions so that a
setting added later syncs by default -- which is what adding one almost
always means.

Writes are coalesced: update() fires on every frame of a splitter drag,
so a change waits 3s and the newest value wins. A tab going away flushes
first, as does signing out, so a setting changed seconds before either
is not lost.

The ihasmail folder is now hidden from the Files view, contents and all.
Hiding the folder alone would have been worse than showing it: the tree
attaches a node whose parent is missing to the root, so the signature
images would have spilled into the top level as if the user had put them
there. Those images have been visible since signatures shipped.

Requires 0.16 -- FileNode/query cannot see directories before that. On
0.15 settings stay local exactly as they were.

Verified against the mock end to end: folder create, blob upload, node
create, read back, update, re-read. Not yet exercised against the live
0.16.19.
2026-08-26 08:19:57 -07:00
LINUXexpert.org abd2269581 Merge pull request #53 from LINUXexpert-org/screenshots-refresh
Retake the screenshots on the new logo
2026-08-25 15:53:04 -07:00
jcoffey-dev 3530a0cc64 Retake the screenshots on the new logo, and refresh the README header
Every screenshot still showed the old mark in the topbar -- squashed,
with an illegible ".com" smudge under it. All seven are retaken against
the mock server at the original framing (1420x703, mobile 500x703).

The four Sieve rules in filters.jpg are not seeded by the mock, so they
are rebuilt through the rule builder to match the previous shot:
Newsletters, From the boss, Receipts, Build failures.

Date format is pinned to the locale default so the list reads "Aug 24"
as it did before, rather than the "24.08." the stored preference had
drifted to.

README: the header logo drops 180 -> 150 wide, since the mark alone is
portrait where the old artwork was landscape, and the note about the
prototype now says the logo has lost its wordmark too.
2026-08-25 15:47:50 -07:00
LINUXexpert.org ba819369f4 Merge pull request #52 from LINUXexpert-org/logo-drop-com-wordmark
Drop the .com wordmark from the logo
2026-08-25 15:34:58 -07:00
jcoffey-dev bae29e647e Drop the .com wordmark from the logo
The logo baked "ihasmail.com" into the artwork, which is the wrong
identity for a project that is not the hosted instance -- and at the
34px the topbar renders it at, the wordmark was an illegible smudge
under a squashed cat.

logo.png, icon-512.png, icon-192.png and apple-touch-icon.png are now
the mark alone. favicon-64.png, icon-maskable.png and favicon.ico
already were, and are untouched.

Cropping needed a threshold: both source files carry a band of
near-invisible pixels (alpha 1-10) roughly 40px wide down the left
side, so a plain getbbox() crop leaves the mark sitting off-centre.
The bounding box is taken at alpha > 8 instead.

The login page had no name of its own -- it relied on the wordmark --
so it gets one as text, styled like the topbar's. Its screenshot is
retaken; the rest still show the old mark in the topbar.
2026-08-25 15:32:17 -07:00
LINUXexpert.org 4a12a898d1 Update email format for reporting security issues 2026-08-25 14:31:45 -07:00
LINUXexpert.org aa13fcae7f Modify email address format in CONTRIBUTING.md
Updated email format for reporting security issues.
2026-08-25 14:31:03 -07:00
LINUXexpert.org 55721faed2 Update contact email format for reporting vulnerabilities 2026-08-25 14:29:28 -07:00
LINUXexpert.org a9dd6b3569 Add Contributor Covenant Code of Conduct
Added Contributor Covenant Code of Conduct to promote a respectful and inclusive community.
2026-08-25 14:27:34 -07:00
LINUXexpert.org 1fc24e6273 Revise SECURITY.md for clarity on support and reporting
Updated the security policy to clarify supported versions and reporting procedures for vulnerabilities.
2026-08-25 14:26:43 -07:00
LINUXexpert.org ea36270adf Create CONTRIBUTING.md 2026-08-25 14:25:11 -07:00
LINUXexpert.org b8ab46270d Merge pull request #51 from LINUXexpert-org/readme-badges-trim
Trim the badges
2026-08-25 13:54:09 -07:00
jcoffey-dev d77928426a Trim the badges to three, and credit LINUXexpert.org
Down to the licence, the Stalwart generations this has been run
against, and a LINUXexpert.org badge linking to the site. The CI, JMAP,
Node, TypeScript and no-IMAP badges are gone.

The Stalwart and LINUXexpert.org links carry target="_blank". Worth
knowing that GitHub itself will ignore it: its README sanitiser strips
target and rewrites rel to nofollow, which was checked against the
markdown API rather than assumed. The attribute still does its job
anywhere else the README is rendered, so it stays.
2026-08-25 13:52:13 -07:00
LINUXexpert.org 1514fd9e0a Merge pull request #50 from LINUXexpert-org/readme-badges
Put badges under the logo
2026-08-25 13:48:24 -07:00
LINUXexpert.org 62242493f8 Merge pull request #49 from LINUXexpert-org/agpl-source-offer
Make the AGPL's source offer point at the source being run
2026-08-25 13:47:41 -07:00
jcoffey-dev f7db2f23fa Put badges under the logo
Seven, each saying something true about this project rather than
decorating the page: CI, the licence, which Stalwart generations it has
actually been run against, the JMAP RFCs it implements, the Node floor
from engines, that both tsconfigs are strict, and the line the README
already uses to describe itself -- no IMAP, no SMTP, no database.

Every claim was checked against the repository: the CI badge is the
workflow's own, the licence matches LICENSE and package.json, the Node
version comes from engines, and strict is set in both tsconfigs. All
seven were fetched and rendered before committing, so none of them is a
broken image.

The standalone licence badge lower down goes, being now the second one
on the page.

The Stalwart badge is the one to remember: it is static, so it needs
changing when the live instance moves, exactly as the prose above it
does.
2026-08-25 13:46:32 -07:00
jcoffey-dev 4a9c0c1c55 Make the AGPL's source offer point at the source being run
Three things a licence audit turned up. None of them is a conflict --
every one of the 182 installed packages is permissive, and the relicence
was within the copyright holder's gift -- but all three are ways the
AGPL fails to stick.

The offer was hard-coded to this repository. Section 13 asks whoever
runs a modified version to offer *that* version's source, so every
deployment with a patch in it was pointing at the wrong tree, and would
have gone on doing so unless its operator noticed and edited the About
page. SOURCE_URL now sets it, alongside APP_NAME, and both the sign-in
page and About read it.

The offer was also only visible after signing in. Whoever is looking at
the sign-in form is interacting with the program over a network too, so
the footer carries it now.

And the two workspace packages declared no licence at all. Private, so
npm never minded, but anything reading the tree saw a blank where the
rest of the project says AGPL-3.0-or-later.

Checked both ways round: with SOURCE_URL set to a fork, the sign-in page
and About both point at the fork; with it unset, both fall back to this
repository.
2026-08-25 13:42:11 -07:00
LINUXexpert.org acc9df299e Merge pull request #44 from LINUXexpert-org/push-dot-and-menu-close
Close the colour menu on a pick, and make the push dot readable
2026-08-25 13:18:20 -07:00
jcoffey-dev 0dd0aed0dd Close the colour menu on a pick, and make the push dot readable
Two cosmetics.

Picking a folder colour left the menu open, which every other action in
it does not. It closes now, the way the calendar's colour menu already
did.

The live-updates indicator was an 8px flat speck in --fg-faint, near
invisible in either theme, and it had two states where the code has
three. The push client only ever said connected or not, which cannot
tell "retrying with a backoff" from "stopped": it now reports
connecting, connected or disconnected, and the retry path says
connecting rather than going dark. pushConnected stays for the callers
that only want the boolean.

The dot is 12px and raised -- a white highlight over a solid colour with
a soft halo, so one bead reads on light and dark alike without a
per-theme variant. Green connected, amber reconnecting with a slow
pulse, red disconnected. The pulse respects prefers-reduced-motion, and
the indicator is labelled for a screen reader rather than hidden from
it, since it carries real information.
2026-08-25 13:15:56 -07:00
LINUXexpert.org ca2c4544dc Merge pull request #42 from LINUXexpert-org/folder-colours-filled
Fill a coloured folder in, rather than outlining it
2026-08-25 13:07:23 -07:00
jcoffey-dev a5c971ace4 Fill a coloured folder in, rather than outlining it
A tinted outline barely registered against the sidebar. The icon is now
filled with the colour, which is what makes it findable at a glance in a
list of a dozen folders.

Two details it needed. The fill has to come from CSS, because lucide
writes fill="none" as a presentation attribute on the svg and a rule
beats one. And the strokes are drawn in --bg rather than the colour: a
solid fill in one colour swallowed the detail inside icons that have any
-- Archive lost the lid and handle of its box and became an orange blob.
Knocked out against the background they read again, in either theme,
since --bg follows the theme rather than being pinned to one.

Checked by pixels and by eye in both themes: the coloured area of the
icon went from an outline to 55% of its box, and Archive, Newsletters
and Work are all still recognisably themselves.
2026-08-25 13:04:45 -07:00
LINUXexpert.org aad599d802 Merge pull request #41 from LINUXexpert-org/folder-colours
Give a folder a colour from its right-click menu
2026-08-25 12:57:37 -07:00
jcoffey-dev 25046e85e3 Give a folder a colour from its right-click menu
Right-click a folder and pick one of the twelve colours the calendar
already uses, or clear it again. The colour tints the folder's icon; the
label keeps the sidebar's own contrast, which a dozen arbitrary colours
would not reliably give it.

Kept by mailbox id rather than by name, so a folder renamed or dragged
somewhere else keeps its colour. Stored in settings, which live in this
browser -- JMAP has nowhere on a Mailbox to put a colour, and every other
colour in the app, labels and event categories included, already works
this way. Worth knowing it does not follow you to another device.

The cascade needed care: .nav-item svg sets the colour on the icon
itself, so a colour inherited from a wrapper does nothing. Checking
getComputedStyle on the wrapper said the icon was purple while the pixels
stayed grey; the rule now targets the svg, and the check now reads the
pixels.
2026-08-25 12:54:33 -07:00
LINUXexpert.org 145abef3fe Merge pull request #40 from LINUXexpert-org/folder-drag-to-move
Move a folder by dragging it
2026-08-25 12:39:09 -07:00
jcoffey-dev e29e3b35b0 Move a folder by dragging it
Reparenting a folder meant the Folders settings page, or nothing at all.
The tree already accepted messages dropped onto a folder, so folders now
travel the same way: drag one onto another to nest it, or onto the
Folders heading to bring it back to the top level.

The heading says "Drop here for the top level" while a folder is in
flight, because an unlabelled strip of heading is not a discoverable
target. The row being dragged fades, the row under the pointer is
outlined, and only rows that would accept the drop light up.

Four drops are refused: a folder onto itself, into its own subtree,
onto the parent it already has, and any folder the server gave a role,
which is not draggable in the first place. The subtree case is the one
that matters -- it would orphan the branch -- and it checks the whole
subtree rather than the immediate children.

Whether a drop is legal has to be known during dragover, when
dataTransfer.getData is blocked, so the tree remembers what is being
dragged rather than asking the drag.

The move goes through updateMailbox, so the filter rules pointing at the
folder follow it, and the target folder is expanded afterwards so the
folder can be seen where it landed.
2026-08-25 12:36:09 -07:00
LINUXexpert.org 99382486b8 Merge pull request #39 from LINUXexpert-org/sieve-detach-only-fileinto
Take the filing action, not the whole rule
2026-08-25 12:25:41 -07:00
jcoffey-dev 9e2987f43c Take the filing action, not the whole rule
Deleting a folder removed every rule that filed into it, along with
whatever else those rules did. A rule that filed into Work, marked read
and stopped processing lost the marking and the stopping too, and
deleting a folder says nothing about whether those were still wanted.

Only the fileinto action goes now. A rule left with nothing to do is
still removed, because it has nothing to do; a rule filing into two
folders keeps the one that still exists. The toast says which happened.

Verified against the running app with two rules aimed at the same
folder, one filing only and one filing and marking read: the first was
removed, the second kept its markread, and the script stored on the
server agrees.
2026-08-25 12:23:29 -07:00
LINUXexpert.org 788eb0b0e1 Merge pull request #38 from LINUXexpert-org/relicense-agpl3
Relicense to the AGPL, version 3 or later
2026-08-25 12:18:40 -07:00
LINUXexpert.org b7f4b4e496 Merge pull request #37 from LINUXexpert-org/sieve-follows-folders
Keep filter rules pointing at the folder they were aimed at
2026-08-25 12:16:22 -07:00
jcoffey-dev 0fc4bd7a52 Relicense to the AGPL, version 3 or later
ihasmail is webmail: it is nearly always run as a network service rather
than handed to anyone as a binary, which is the case the plain GPL does
not reach. The AGPL's section 13 does — anyone running a modified
ihasmail for other people has to offer them its source.

LICENSE is the full AGPL-3.0 text from gnu.org. The SPDX identifier
changes from GPL-3.0-or-later to AGPL-3.0-or-later in package.json, the
lockfile's own entry for it, and the About screen. Old commits and tags
are left exactly as they were; this is the license from here on.
2026-08-25 12:13:41 -07:00
jcoffey-dev 56e1f4f1be Keep filter rules pointing at the folder they were aimed at
A rule files mail into a folder by path, because that is what Sieve
needs. Rename the folder and the path becomes a lie: the rule keeps
matching and stops filing, and nothing anywhere says so. Delete the
folder and the rule is aimed at nothing at all.

Renaming or moving a folder now rewrites the rules that file into it,
and deleting one takes its rules with it. Both are reported in a toast,
because rules live on the server and are otherwise invisible from the
folder list.

The reconciliation runs off one hook. Before a mailbox is changed the
folder and everything beneath it are noted with the paths they have then
-- renaming a parent rewrites the path of every child, and rules naming
those children are just as stale. Afterwards, whatever still exists is
retargeted and whatever has gone takes its rules with it.

Rules record the folder twice, as a mailboxId and as the path. The id is
the reliable half and is preferred; the path is the fallback for rules
written before the id was recorded, or by hand in the Scripts tab, and a
rule matched that way has its id filled in on the way past. Only the
script the rule editor manages is touched; a hand-written one is left
alone.

Awaited rather than fired and forgotten, so a folder operation is not
reported complete while the rules still disagree with it.
2026-08-25 12:12:30 -07:00
LINUXexpert.org a9231a335c Merge pull request #36 from LINUXexpert-org/screenshot-script-guards
Make the light screenshot actually light
2026-08-25 10:41:49 -07:00
jcoffey-dev 00868f053c Make the light screenshot actually light
The light inbox screenshot in the README was not light, and had not been
since it was first taken -- the pair showed the dark theme twice.

The app was never at fault: update() calls applyTheme() synchronously
and the CSS flips --bg to #f6f8fa as it should. The capture was.
Swapping the theme under setDeviceMetricsOverride produces a mixed
frame, the panes that re-rendered in the new theme and the rest of the
chrome still in the old one, while the DOM and computed styles insist
the whole page is light. Clicking the app's own toggle, setting the
attribute, pinning it against applyTheme with a MutationObserver,
installing that pin before the document loads, nudging the viewport and
forcing a full reflow all left the frame mixed.

Chrome launched at --window-size, with the emulation layer never
touched, renders it correctly. That is docs/screenshots-light.mjs, and
inbox-light.jpg is now genuinely light.

assertTheme() stays: without it the script wrote a dark screenshot under
a light caption and reported success, which is how this survived
unnoticed. The header says which shots are taken elsewhere and why.
2026-08-25 10:39:44 -07:00
LINUXexpert.org ea55b1b2aa Merge pull request #35 from LINUXexpert-org/readme-screenshots-refresh
Take the screenshots again, on today's build
2026-08-25 10:19:25 -07:00
jcoffey-dev a027b312c5 Take the screenshots again, on today's build
The ones in the README were captured on 23 August, before the 2.0 QA
work: no drag handles on the filter rules, none of the calendar or
Sieve fixes, and the read-receipt line in the composer missing.

Same sizes as before, 1420x703 and 500x703 for the phone, so the table
lays out unchanged. The filters shot now carries four rules that say
something -- list-id, sender, subject, a wildcard match, each filing
somewhere different -- instead of four blank ones, and the calendar is
in the month view its caption has always claimed. A contact is open in
the contacts shot rather than an empty "select a contact".

The script that took them is committed alongside, so the next person
does not have to work out how to drive the mock: headless Chrome over
CDP, which is also how the viewport comes out at exactly the size the
old images used.
2026-08-25 10:16:14 -07:00
LINUXexpert.org db6afb72ff Merge pull request #34 from LINUXexpert-org/scheduled-send-verified-live
Record that a hold really does hold, on the live server
2026-08-25 09:30:21 -07:00
jcoffey-dev 047a0029bf Record that a hold really does hold, on the live server
Scheduled send had only ever been exercised against the mock, and the
one thing that could not be taken on trust was whether the MTA honours
the hold at all: with futureRelease off it takes the HOLDUNTIL, drops
the hold and sends at once, saying nothing.

With the setting turned on at 30d, a submission ten minutes out came
back pending, sendAt equal to the time asked for, queued at the MTA.

The capability stays worthless as evidence — it advertised
maxDelayedSend: 2592000 and FUTURERELEASE throughout, including while
the setting was off. Noted, because it is the obvious thing to check and
it lies.

Still mock-only, and now said so precisely: the Scheduled folder
reconciling on the way in, and a hold expiring into a delivery.
2026-08-25 09:22:58 -07:00
LINUXexpert.org b0be465e50 Merge pull request #33 from LINUXexpert-org/calendar-vocabulary-into-main
Bring the stranded calendar work into main
2026-08-25 09:08:18 -07:00
jcoffey-dev fe9285062c Merge remote-tracking branch 'origin/calendar-recurring-warning' into calendar-vocabulary-into-main 2026-08-25 09:05:48 -07:00
LINUXexpert.org 9a2f355a4a Merge pull request #32 from LINUXexpert-org/sieve-rule-drag-reorder
Let a filter rule be dragged into place
2026-08-25 08:53:39 -07:00
jcoffey-dev 4740ca46eb Let a filter rule be dragged into place
Twenty-five rules and two buttons that move one place at a time meant a
rule pushed to the wrong end cost ten clicks to bring back. It can now
be dragged.

A grip on the left of each card arms the drag, so the switch, the name
and the buttons still take a plain click, and the up and down buttons
stay for the keyboard. The card being dragged fades; the one under the
pointer draws a line on the edge the rule would land on, top half or
bottom.

The guard against dropping a rule onto itself reads a ref rather than
state: dragstart and the first dragover can arrive in the same frame,
and a stale read there drew a drop line on the card being dragged. Found
by driving the real thing in a browser, and covered by a test that fires
the two events back to back.
2026-08-25 08:51:28 -07:00
LINUXexpert.org c04bc7a31b Merge pull request #31 from LINUXexpert-org/calendar-stalwart-vocabulary
Say it in the words Stalwart 0.16 answers to
2026-08-25 08:42:25 -07:00
jcoffey-dev 377e3aba2a Record that RSVP and the edit path hold up too
Adding a participant by patch had failed earlier, which left a question
over RSVP, since that patches participants/{key}/participationStatus.
It works, comment and all, and so does adding guests to an event that
had none and clearing them again with null.

The patch has to name the base event: a synthetic id is refused with
"Updating synthetic ids is not yet supported", which is exactly why rsvp
resolves baseEventId first. Worth writing down before someone simplifies
that line away.
2026-08-25 08:39:40 -07:00
jcoffey-dev 27dbc8ac41 Record that the invitation reached a real guest and came back
The store side was proven earlier; the sending side had only been
reasoned about. An invitation went to an external Gmail address from the
live 0.16.19: it arrived as an invite card, the decline came back, and
Stalwart applied it to the event — needs-action to declined, sequence 1.
Cancelling notified the guest as well.
2026-08-25 08:31:47 -07:00
jcoffey-dev cc073693f4 Say it in the words Stalwart 0.16 answers to
Guests added to an event vanished on save and no invitation was ever
sent. Not a guard in the editor, and nothing the server complained
about: ihasmail addresses a participant the way RFC 8984 does, with
sendTo and email, and Stalwart 0.16 keeps that address under
calendarAddress. Handed the RFC's spelling it stores the event, drops
the entire participant map, and reports success. Six shapes were tried
against a live 0.16.19, down to sendTo and roles alone; all six were
dropped, and patching a participant onto an existing event fails
outright with "Patch operation failed".

The same disagreement runs through two more properties. The organizer is
organizerCalendarAddress, not replyTo. A recurrence is a single
recurrenceRule, not a recurrenceRules array — and that one Stalwart
refuses honestly, with invalidProperties, so no recurring event could be
created at all and existing ones showed no repeat.

So writes now use Stalwart's names and reads accept either, since a
mailbox may hold events written by other clients. The mock now refuses
what the real server refuses and drops what it drops: advertising the
RFC spelling is exactly how this reached a live server unnoticed, the
same way the capability-placement bug did.

Verified against 0.16.19: participants, organizer and rule all survive a
create, an update and a re-read, with the roles kept as sent.

Fixes #26
Fixes #30
2026-08-25 08:26:34 -07:00
jcoffey-dev a9ff405135 Ask the recurrenceId, which is the part that survives expansion
Rules alone were still wrong, in the other direction. A live 0.16.19 was
asked to expand a real weekly series: the occurrences come back carrying
no rule at all — only the master has one — and Stalwart spells that
master's rule "recurrenceRule", singular, not the RFC 8984 array ihasmail
looks for. So a genuine occurrence would have read as a one-off, and the
delete dialog would have offered to delete "this event" while deleting
the series.

What an occurrence does carry is a recurrenceId, which a one-off never
has. Master by its rule under either name, occurrence by its
recurrenceId. The tests carry the shapes the live server returned.
2026-08-25 08:18:38 -07:00
jcoffey-dev 65443a235a Ask only the recurrence rules, the live server settles it
A probe against the live 0.16.19 says a one-off event comes back from an
expanded query as id "eaaaaai" with baseEventId "i" — an instance id of
its own, and a base that is a different event. The clause that treated a
differing base as an occurrence of a series would therefore have gone on
calling every event recurring, which was the bug.

So recurrence rules alone decide it. What that gives up is an expanded
instance that arrives without its rules attached; whether Stalwart does
that is still to be checked against a real series.
2026-08-25 08:12:06 -07:00
LINUXexpert.org 0cbebed645 Merge pull request #29 from LINUXexpert-org/sieve-custom-header-operator
Give a hand-typed header its own box
2026-08-25 07:58:37 -07:00
jcoffey-dev 16dd867707 Give a hand-typed header its own box
Picking "Other header…" in the filter dialog took the comparator away.
The condition row has three columns — field, comparator, value — and the
box for the header name was rendered into the comparator's, so the
comparator disappeared along with any way to change it. Whatever it had
been when you switched, contains, was what the rule got: matching a
header exactly, or on a regex, could not be expressed at all.

The header name now has a column of its own and the comparator keeps
its, on a row that widens to hold both.

Fixes #23
2026-08-25 07:56:01 -07:00
LINUXexpert.org 9a7f37b540 Merge pull request #28 from LINUXexpert-org/calendar-recurring-warning
Stop calling every event a series
2026-08-25 07:53:00 -07:00
LINUXexpert.org 9a8c7516d7 Merge pull request #27 from LINUXexpert-org/sieve-rule-order-on-edit
Keep an edited filter rule where it was
2026-08-25 07:52:32 -07:00
jcoffey-dev 6170fc3944 Stop calling every event a series
A one-time event opened for editing said "this is a recurring event —
changes apply to the whole series", and deleting one offered to delete
all occurrences of an event that has exactly one.

Three places asked whether an event had a baseEventId and took that for
recurrence. It isn't: the calendar loads its range with expandRecurrences,
and Stalwart puts a baseEventId on everything it returns that way, a
one-off pointing at itself included. The mock never sets the field at
all, which is why this only showed up against a real server.

They now share isRecurring(), which asks about recurrence rules, and
treats a base that is some other event as an occurrence of a series too
— so an expanded instance that travels without its rules is still
described honestly on the way to being deleted.

Fixes #25
2026-08-25 07:01:23 -07:00
jcoffey-dev ee998eff46 Keep an edited filter rule where it was
Renaming or editing a Sieve rule moved it to the bottom of the list, and
in Sieve the order is the order the rules run in, so mail started being
filed by a different rule than before. Putting it back took a click per
place moved.

Two things did it. saveAndApply always appended the rule it was given —
right for a rule created from a message, wrong for one being edited. And
the "Also apply to existing messages" tick defaulted to on wherever it
was offered, so every edit in Settings went down that path, including a
plain rename.

The rule now keeps its seat: a shared upsertRule replaces by id in place
and only appends what is genuinely new. The tick defaults to on only in
"Filter messages like this…", where applying it is the point, and the
toast no longer calls an edited rule "created".

Fixes #24
2026-08-25 06:55:47 -07:00
LINUXexpert.org d4d218f078 Merge pull request #22 from LINUXexpert-org/registry-path-verified
Record that the registry path has now met a live 0.16.19
2026-08-24 23:06:14 -07:00
LINUXexpert.org e9c183f2a5 Merge branch 'main' into registry-path-verified 2026-08-24 23:04:33 -07:00
jcoffey-dev be46c0c3c9 Record that the registry path has now met a live 0.16.19
Self-service credentials work against the real server: password changes, 2FA
and app passwords, over the registry rather than the REST endpoint 0.16
removed. That also settles the generation lookup, which About and Files read
through the same helper.

Files is the one thing this does not settle. The earlier live run recorded
against 0.16.19 exercised the pre-0.16 path -- correct behaviour for what
ihasmail then believed the server to be, but not the path it takes now. Said
so, rather than letting an old confirmation stand for a different code path.
2026-08-24 23:02:58 -07:00
LINUXexpert.org 05c9bd46c2 Merge pull request #21 from LINUXexpert-org/read-receipts
Send the read receipt the sender asked for
2026-08-24 23:01:03 -07:00
jcoffey-dev d1d3041ce6 Drop S/MIME and OpenPGP from the roadmap
Not worth the cost right now. Removing it rather than leaving it sitting
there unstarted, so the list says what is actually intended.
2026-08-24 22:59:15 -07:00
jcoffey-dev b0944b2f42 Send the read receipt the sender asked for
JMAP has an extension for this -- RFC 9007's MDN/send -- and Stalwart does
not implement it, so ihasmail assembles the RFC 8098 multipart/report itself
and sends it the long way round: raw MIME uploaded as a blob, imported,
submitted. That is also why the receipt lands in Sent, which is where it
honestly belongs.

The plumbing is the easy half. A receipt tells whoever asked that the address
is live and when the message was read, to an address the sender chose, so the
refusals are the feature: nothing marked Auto-Submitted (RFC 3834, or two
servers answer each other forever), nothing carrying Precedence bulk/list/junk
or a List-Id, nothing already acknowledged, nothing that never arrived. A
receipt aimed anywhere other than the sender is offered, but says so first.
There is no "always send" setting, only ask or never.

Sending is recorded with RFC 3503's $mdnsent keyword on the original rather
than remembered locally, so a second look -- or another client entirely --
knows not to ask again. Non-ASCII parts go base64 rather than 8bit, so
nothing rests on 8BITMIME surviving every hop.

Verified against the mock end to end: the blob uploads, the receipt imports
and submits, and the original reads back marked. Not yet exercised against
the live server.
2026-08-24 22:53:06 -07:00
jcoffey-dev ca2c71e858 Merge scheduled send
Both branches turn on where Stalwart advertises a capability, so they meet
in the same two files. The mock keeps `urn:stalwart:jmap` out of the
session-level capabilities and hands it out per-account, as a real server
does, while the submission capability it grew for scheduled send lives
per-account beside it; the client keeps both accessors, one asking whether a
capability is advertised anywhere and one reading the object itself.
2026-08-24 22:24:13 -07:00
jcoffey-dev 2f8af1ce94 Look for Stalwart's capability where Stalwart advertises it
Self-service credentials, the About page and Files all keyed off
`urn:stalwart:jmap`, and all three looked for it in the session-level
`capabilities`. Stalwart has never put it there. `Session::new` builds that
list from a fixed set the capability is not part of, in any 0.16.x from
0.16.0 to 0.16.19; it is handed out per-account instead, so it arrives in
`primaryAccounts` and in each account's `accountCapabilities`.

So every real 0.16 server read as pre-0.16. Password changes, 2FA and app
passwords fell back to `POST /api/account/auth`, which 0.16 removed, and
reported that the server offers no self-service credential management. About
named the wrong generation. Files ran the pre-0.16 path, omitting `nodeType`
and listing the tree through get.

Look in all three places, on both sides. Two nearby soft spots go with it: a
transport error while probing the registry no longer downgrades a server to
the legacy path -- which would have posted the current password to an
endpoint that is not there -- and a locale request that is merely refused no
longer discards a generation the capability had already settled.

The mock advertised the capability in the session, which is why no test ever
caught this; it now advertises it where the real server does, and validates
`using` by the urn rather than by the session, as Stalwart does. Put the old
lookup back and nine tests fail.

Stalwart still publishes no version number to clients -- VERSION_PUBLIC is a
fixed "1.0.0" -- so About continues to report the generation and edition,
which are now the right ones.
2026-08-24 22:21:26 -07:00
jcoffey-dev 6127a77458 Hold a message in the server's queue until the time you asked for
Scheduled send, which the README listed as needing server support that
Stalwart has had all along. The delay cannot be asked for directly --
RFC 8621 makes `sendAt` read-only and server-derived -- so it goes on the
envelope as an RFC 4865 `HOLDUNTIL` parameter, and the server reports back
the time it settled on.

Stalwart advertises this in the *account* capability, not the session-level
one (which is empty): `maxDelayedSend` of thirty days and `FUTURERELEASE`
among its `submissionExtensions`. The composer offers scheduling only when
both are there, and never offers a time the server would refuse.

A held message goes to a Scheduled folder rather than Sent, because
`onSuccessUpdateEmail` would otherwise file it as sent the moment the
submission is created, and it has not been sent. Nothing moves it out when
the hold expires, so the folder is reconciled on the way in: released
messages to Sent, cancelled ones back to Drafts. Cancelling uses a separate
`Email/set` rather than `onSuccessUpdateEmail`, whose key Stalwart reads as
an Email id and not, as the RFC says, a submission id.

The mock grows the whole lifecycle, and learns to resolve creation
references while it is there -- it had been quietly declining to create any
submission at all, since sending names its message as `#m`. Because
Stalwart's own `futureRelease` setting defaults to off and then drops the
hold in silence, `npm run dev:mock:no-future-release` reproduces that.

Verified end to end against the mock; not yet against the live server.
2026-08-24 22:07:29 -07:00
jcoffey-dev afecc7d1dc Say which Stalwart the live instance runs, and credit the tool that moved it
The README described the deployment as 0.15.5 in four places. It has run
0.16.19 since 2026-08-25, which matters here because ihasmail supports both
generations of Stalwart and they are less alike than the version numbers
suggest: 0.16 replaced the REST management API with JMAP registry objects,
changed the shape of FileNode, split its rights up, and moved configuration
into the store.

Both backends have now met a real server of their own generation. The
registry paths for credentials and Files had only ever met the mock, and are
now exercised against the live 0.16.19: app passwords created and revoked,
password changed, 2FA switched on and off with the browser session surviving
the swap to an app password, and Files through folder creation, upload,
rename, move and delete. That closes the gap, and it was worth closing - the
0.16 half was resting on a mock we wrote ourselves, which is the arrangement
that let four bugs through on the 0.15 side.

Each known-issues entry now says which generation it was proven against
rather than implying one level of assurance across both. The account locale
is confirmed working on 0.16; on 0.15 neither method it can use was
reachable, so it had always fallen back to the browser.

Also records what did the upgrade. stalwart-migrator is a companion project,
and the 0.15 to 0.16 move is genuinely treacherous by hand - the store is
migrated in place with no way back, and Stalwart's own converter drops
settings without reporting them - so a reader running 0.15.x has a real
reason to want the link.
2026-08-24 17:38:39 -07:00
LINUXexpert.org d756d3ca68 Merge pull request #20 from LINUXexpert-org/empty-trash-batching
Empty a folder in batches the server will accept
2026-08-24 12:57:24 -07:00
jcoffey-dev f1f762c228 Empty a folder in batches the server will accept
Emptying Deleted Items back-referenced one Email/query straight into one
Email/set, so every id in the folder arrived in a single call. Stalwart
refuses the whole call over maxObjectsInSet with requestTooLarge, which
left a folder of 5192 messages impossible to empty at all.

Walk the folder a page at a time instead: the filter re-runs each pass,
so the next page is whatever is still there. A pass that destroys nothing
stops the loop and reports the server's error rather than spinning.

The same defect sat in two neighbours. Delete-forever on a large
selection sent every id in one Email/set, and mark-all-read fed up to
5000 ids into an Email/get that only echoed them back - past
maxObjectsInGet, and for no gain, since the query already returned them.
Both now page through the same ceiling, read from the session rather than
hardcoded.

The mock advertised maxObjectsInSet but never enforced it, so none of
this could fail in a test. It now rejects oversized get and set calls the
way Stalwart does.

While here, restrict emptying to Deleted Items. It was offered on Junk
too, where a permanent one-shot clear is harder to justify; Junk is now
select-all plus Delete, which takes the batched path.
2026-08-24 12:55:23 -07:00
LINUXexpert.org 232e518d55 Merge pull request #19 from LINUXexpert-org/image-proxy-pinning
Connect the image proxy to the address it checked
2026-08-24 11:52:45 -07:00
jcoffey-dev 287af22ef8 Connect the image proxy to the address it checked
The proxy resolved a hostname, refused it if any answer pointed somewhere
private, and then handed the *hostname* to fetch — which resolved it again when
the socket opened. An attacker who controls the zone answers with a public
address the first time and 127.0.0.1 the second, and the check has been walked
straight past. It is the standard way an SSRF guard gets bypassed.

Resolve once and connect to that address: a `lookup` that returns what we
already approved, on `node:http`/`node:https` rather than fetch, since fetch
gives no say in how the socket is opened. Every redirect hop is re-checked and
re-pinned. TLS is unaffected — the certificate is still validated against the
hostname, which `servername` and the Host header carry.

Pooling had to go with it: sockets are keyed by host and port, not by the
address we pinned, so a connection opened earlier would be reused and the pin
never consulted. Found by a test, not by reading it back.

Also refuse two ranges the old check let through: IPv6 multicast, and the NAT64
prefix, which is a route into IPv4 space.
2026-08-24 11:27:14 -07:00
LINUXexpert.org 409e5578a0 Merge pull request #18 from LINUXexpert-org/audit-hardening
Harden four things the security audit turned up
2026-08-24 11:12:43 -07:00
jcoffey-dev f1a2972d3a Harden four things the audit turned up
**The login rate limiter could be sidestepped.** X-Forwarded-For is a list each
hop appends to, and nginx's $proxy_add_x_forwarded_for appends ours — so a
client sending "X-Forwarded-For: 1.2.3.4" arrives as "1.2.3.4, <their real
address>". Reading the leftmost entry, as we did, handed the caller a
rate-limit key they could change per request: unlimited password guessing
against a deployment that looks correctly configured. Read from the right
instead, skip hops that are themselves trusted proxies, and believe the header
only when the peer is one (loopback and the private ranges by default,
TRUSTED_PROXIES to be explicit).

**The upload cap was a suggestion.** It read content-length, which a chunked
request simply omits. Count the bytes through a stream, as the image proxy
already does.

**App password secrets were drawn with a modulo.** 256 is not a multiple of 33,
so the first 25 characters of the alphabet came up on 8 byte values and the
last 8 on only 7. Rejection sampling instead. The test weighs the whole tail of
the alphabet rather than single characters, because a 7/8 skew is invisible
per character against the noise — and it does fail when the bias is put back.

**Upstream headers were relayed wholesale.** Anything the mail server set —
cookies, auth challenges, CORS grants — landed on our origin, where it means
something else. Allowlist what is actually wanted.
2026-08-24 11:10:15 -07:00
LINUXexpert.org 3521487f6c Merge pull request #17 from LINUXexpert-org/message-css-containment
Stop a message painting over the whole application
2026-08-24 11:07:54 -07:00
jcoffey-dev f5373c6fcd Stop a message painting over the whole application
A shadow root scopes selectors, not layout. `position:fixed` in mail CSS is
still positioned against the viewport, and the containment meant to stop that
sat inside the shadow root as `.ihm-email-root { contain: content }` — in the
same tree as the message's own <style>, which is inserted after it and simply
overrides it. Any sender could cover the entire window with markup of their
choosing, inside our own origin: a ready-made place to ask for a password.

Verified in a browser: the message rendered at exactly the viewport size with
the maximum z-index.

Moving the containment onto the shadow host does not fix it — mail CSS reaches
the host through `:host`, and an `!important` there beats an `!important` from
the app's own stylesheet, because importance reverses tree order in the
cascade. An ancestor of the host is the one thing mail CSS has no selector
for, so the control goes on .message-body. `layout` rather than `paint`: it
makes the element a containing block for fixed descendants without clipping
tall messages.

The sanitizer now also turns fixed and sticky positioning static and defangs
`:host`, as a second line that does not depend on one CSS declaration.

Checked end to end against the real stylesheet afterwards: the same message
renders 1678x112 instead of 1720x1279.
2026-08-24 11:00:10 -07:00
LINUXexpert.org c4b9741c6d Merge pull request #16 from LINUXexpert-org/legacy-mock
Teach the mock to impersonate Stalwart 0.15
2026-08-24 10:27:04 -07:00
jcoffey-dev 1aee40a169 Teach the mock to impersonate Stalwart 0.15
MOCK_STALWART=0.15 (or npm run mock:legacy) switches the mock to the
generation before the registry. It is not a cut-down mock: it reproduces the
specific ways that generation differs, and every one of them is a thing the
server does not report as an error.

  - urn:stalwart:jmap is not a capability it knows, and naming one it cannot
    parse fails the whole request rather than the one call
  - x: methods do not exist; credentials live at POST /api/account/auth
  - FileNode/query masks out containers, so it returns files and never folders
  - FileNode has no nodeType, and rights are only mayRead/mayWrite/mayShare

Both modes now also enforce the 2047-byte signature cap, and `using` is
validated in both — the gap that let the Identity capability bug in #12 ship.

This gives the legacy credential adapter its first automated coverage: it was
the least-tested code here, checked only by hand against the live server. The
new tests also pin the mock's own fidelity, so it cannot quietly drift back to
being 0.16-shaped in the places that matter.
2026-08-24 10:23:39 -07:00
LINUXexpert.org d5468277d6 Merge pull request #15 from LINUXexpert-org/signature-byte-limit
Make signatures and Files work on Stalwart before 0.16
2026-08-24 10:13:30 -07:00
jcoffey-dev 0a49c914eb Record the live Files and signature verification
Both entries had been sitting as pending QA. Everything they were waiting on
has now run against the live 0.15.5 server: oversized, non-ASCII and
inline-image signatures (with a test message reaching Gmail intact), and folder
creation, listing, upload, rename, move and delete in Files.

The Files entry now describes what actually differs before 0.16 — the query
that cannot see folders, the missing nodeType, the coarser rights — since all
three were found the hard way and none of them surfaces as an error.
2026-08-24 10:11:08 -07:00
jcoffey-dev 57ff18bb7f List Files through get, because query cannot see a folder before 0.16
Creating a folder on the live 0.15.5 server did nothing visible, with no error
and nothing after a reload. The folder was real all along: FileNode/query masks
its results with document_ids(false) — resources that are *not* containers — so
it returns files and never folders, and says nothing about the omission.

FileNode/get carries no such mask, so on those servers the whole tree comes
from a single get with ids:null instead. That also stops ensureFolder making a
fresh "ihasmail" folder on every signature save, having never been able to find
the one already there.
2026-08-24 10:05:08 -07:00
jcoffey-dev b8263aa785 Translate the older FileNode rights, so Rename and Delete work again
Deleting a file did nothing on the live 0.15.5 server, with no error: the menu
items are gated on myRights.mayDelete and myRights.mayRename, and 0.16 was the
release that split rights up. Before it a node carried mayRead, mayWrite and
mayShare, with the one mayWrite covering everything the newer release names
separately — so both items sat permanently disabled.

Widen mayWrite into the four rights the newer shape names, alongside the
nodeType normalisation, and the UI can keep reading the 0.16 vocabulary.
2026-08-24 09:56:53 -07:00
jcoffey-dev ee7542fd86 Stop sending nodeType to servers that have no such property
Uploading a file or creating a folder failed on the live 0.15.5 server with
`invalidProperties (nodeType)`. The property arrived in Stalwart 0.16; before
that a FileNode has no nodeType at all, and the create is refused outright.

Older servers tell a file from a directory a different way: the node carries
file properties or it does not. Setting blobId, size or type — even to null —
makes it a file, so a directory there is exactly parentId plus name.

0.16 is also the first release to advertise urn:stalwart:jmap and no earlier
one knows that capability, so its presence stands in for "has the newer
FileNode shape". Creates, and the property lists we ask for, are shaped from
that.

The read side needed it too: a server that never reports nodeType would have
had every folder drawn with a file icon, sorted among the files and opening as
a download. Nodes are normalised as they arrive, so everything downstream can
still just read nodeType.
2026-08-24 09:42:25 -07:00
jcoffey-dev c92a68aba1 Measure signatures in bytes, so the oversize fallback actually saves
Stalwart accepts a signature of `value.len() < 2048`, and that is Rust's len():
2047 bytes of UTF-8. Every check here counted JavaScript `.length` instead,
which is UTF-16 units and agrees only for ASCII — an accent is one unit and two
bytes, CJK three, an emoji two units and four.

That alone would let a non-Latin signature we judged to fit come back rejected.
But the fallback that is supposed to rescue an oversize signature was broken
outright, for everyone: it truncated to `budget - 1` characters and appended an
ellipsis, one character but three bytes, so the result was always 2047
characters and 2049 bytes. Every marker signature Stalwart was ever offered was
two bytes too long, ASCII included. That is why this flow has been sitting in
the README as implemented but unconfirmed — the first person to exceed 2 KB
would have hit it.

Cutting the source text and rendering afterwards, rather than slicing the
rendered string, also means a cut can no longer land inside an HTML entity, and
stepping through code points means it cannot split a surrogate pair.

The old tests used ASCII only, which is how this survived; the new ones weigh
the encoded form.
2026-08-24 09:32:39 -07:00
LINUXexpert.org 41f4cc7f8c Merge pull request #14 from LINUXexpert-org/self-service-credentials
Self-service credentials, plus the account-locale fix, server info and a theme toggle
2026-08-24 09:13:55 -07:00
jcoffey-dev c13a5375ab Finish the README pass: stale locale method, and the two new bits of UI
The Dates & times entry still named x:Account/get as where the default locale
comes from, which this branch changed. It also never mentioned the top-bar
light/dark toggle or what About now reports about the server.
2026-08-24 09:12:19 -07:00
jcoffey-dev 4025812c5d Record what the live 0.15.5 run actually verified
The REST credential path is no longer untested: password change, app passwords
and enabling and disabling 2FA were all exercised against the live server on a
real mailbox. The registry path is still mock-only.

Also correct the locale line. Both methods it can use are 0.16 ones, so on an
older server neither is reachable and the browser locale still wins — the fix
helps 0.16+ users, and the entry should not imply otherwise.
2026-08-24 09:08:43 -07:00
jcoffey-dev ad0b913efb Fix two things live testing on 0.15.5 turned up
**About said "not detected".** Generation was only worked out from the reply to
a registry method, which we never send to a server that does not advertise
urn:stalwart:jmap — every 0.16 build does, and nothing older knows the
capability at all, so its absence is already the answer. Say so, instead of
shrugging. A session with no capabilities at all stays unknown, which is a
different thing from old.

**The caret jumped out of the OTP field after one digit.** Dialog's autofocus
effect listed onClose in its dependencies, and every caller passes an inline
arrow, so each keystroke in a dialog holding state tore the effect down, set it
up again, and refocused the first field — which in the disable-2FA dialog is
the password. Keep the handler in a ref so the effect depends only on `open`.
This was a bug in the shared dialog rather than in one screen; every dialog
with more than one field had it.

The test for it fails against the old dependency array, not just passes
against the new one.
2026-08-24 09:04:16 -07:00
jcoffey-dev 337c46ebda Treat an unreadable backend probe as the older server, not an error
Stalwart before 0.16 does not know urn:stalwart:jmap, and rejects the whole
request rather than the one call when `using` names a capability it cannot
parse. The probe is only sent when the session advertises that capability, so
this should not arise — but if it ever does, throwing turns a server we can
still manage credentials on into a Security page that only shows an error.
Fall through to the endpoint those servers do have.
2026-08-24 08:41:15 -07:00
jcoffey-dev c55b54163f Read the locale where users can actually read it, and say which Stalwart answered
The account locale came from `x:Account/get`, which needs `sysAccountGet` — a
permission the built-in `user` role is not given, so the setting silently fell
back to the browser locale for exactly the people most likely to have set it.
Stalwart 0.16 carries the same field on `x:AccountSettings`, whose
`sysAccountSettingsGet` *is* part of that role. Both are now asked for in one
request and whichever answers wins, so admins and older servers keep working.

That pair of replies also says which generation we are talking to: only 0.16+
can parse the method name at all. About now reports that, plus the edition
from /api/account where the server offers it. It does not report a version
number because Stalwart does not publish one to clients — it hardcodes a
public "1.0.0" and keeps the real version to its SMTP internals — so the
screen says what was actually detected rather than inventing precision.

Also adds a light/dark toggle to the top bar, left of the settings button. The
stored setting is three-way, so the button acts on the theme actually on
screen: whichever one you see, a click gives you the other. Choosing "match
system" again stays in Settings › Appearance, where a three-way choice belongs.
2026-08-24 08:35:22 -07:00
jcoffey-dev 3621e81d0c Manage your own password, app passwords and 2FA
Settings › Security grows three working sections instead of a note telling
people to use Stalwart's own portal.

Stalwart moved this API between releases, so ihasmail speaks both: 0.16+ has
the x:AccountPassword singleton and x:AppPassword registry objects over JMAP,
while 0.15.x has the /api/account/auth REST endpoint. Which one answers the
probe is the only reliable way to tell them apart, and the result is cached
per session. The built-in `user` role already grants sysAccountPassword* and
sysAppPassword*, so no administrator setup is needed.

Two problems are worth calling out, because both would bite a user hard:

Stalwart validates the credentials already on the account when 2FA is turned
on and never checks the new secret, so an authenticator that was mistyped or
out of step would lock someone out of their mailbox at the next sign-in. We
verify a code against the new secret ourselves first (RFC 6238, tested against
the spec's vectors) and only then ask the server to store anything.

Every proxied call re-authenticates with the credential sealed into the
session, and from the moment 2FA is on Stalwart wants a fresh TOTP code with
it — which we cannot produce between requests. Turning 2FA on would therefore
sign the user out of the browser they just turned it on in. App passwords
authenticate without a second factor, so the session is moved onto one minted
for this browser, and the session cookie is re-sealed with it. The order
matters: it is minted while the old credential still works, and revoked again
if enabling then fails.

Password changes re-seal this session too and drop the others, whose sealed
copies of the old password would fail on their next call.

The mock now enforces what a real server does — current password, password
policy, a TOTP code on every request once 2FA is on, app passwords exempt —
so the whole flow is exercised in tests rather than only by hand.
2026-08-24 08:18:47 -07:00
LINUXexpert.org c4731fc8e0 Merge pull request #13 from LINUXexpert-org/identity-submission-capability
Ask for the submission capability when using identities
2026-08-24 06:37:11 -07:00
jcoffey-dev 0db2acb52b Ask for the submission capability when using identities
Identity is defined by RFC 8621 under urn:ietf:params:jmap:submission, not
under mail. ihasmail asked for mail alone, so Stalwart 0.16 rejected both
Identity/get and Identity/set with unknownMethod: no identities were ever
listed, none could be created, and sending then failed with "No sending
identity available". Older Stalwart builds accepted the calls anyway, which
is why this went unnoticed.

Also filter `using` down to the capabilities the session actually advertises.
A server must reject the entire request with unknownCapability when `using`
names something it does not implement, so one over-eager urn would take down
every call sharing the batch — including, on a server predating the submission
capability, the mailbox and message loads batched alongside an identity fetch.

Fixes #12
2026-08-24 06:31:37 -07:00
LINUXexpert.org 15d64c6320 Fix version number in known issues section
Updated known issues section with corrected version number and additional details.
2026-08-23 21:37:47 -07:00
LINUXexpert.org e87ba09d70 Merge pull request #11 from LINUXexpert-org/contact-from-message
Add contacts by right-clicking anyone named in a message
2026-08-23 15:19:19 -07:00
jcoffey-dev 54c256e69e Add contacts by right-clicking anyone named in a message
Right-clicking a sender, or any address in the message details, opens a menu
offering to add that person to the address book - plus edit them when they are
already known, write to them, or copy the address.

"Add to contacts" opens the contact editor prefilled rather than saving
silently, so the address book gets a real card that the user can complete,
not a bare email address. contactFromAddress splits the display name into
JSContact name components: "Ada Lovelace" into given and surname, "Lovelace,
Ada" unpicked, a single word as the given name, and a name that is really
just an address left off entirely.

Addresses in the details block were joined into one string, so they are now
rendered per address to be individually targetable.

ContactEditor previously ignored a prefilled name on an unsaved card - it read
name components only when the card had an id - so it now reads them either
way.
2026-08-23 14:46:38 -07:00
LINUXexpert.org 98edc18570 Merge pull request #10 from LINUXexpert-org/fix-subject-focus
Stop the composer stealing focus while the subject is typed
2026-08-23 14:17:24 -07:00
jcoffey-dev 9cdf84203b Stop the composer stealing focus while the subject is typed
The body editor was told to focus itself with

    autoFocus={d.to.length > 0 && Boolean(d.subject)}

and RichEditor ran that as an effect keyed on the prop. Typing the first
letter of a subject flipped Boolean(d.subject) false -> true, the effect fired,
and the caret jumped from the subject line into the message body.

autoFocus now means what it means on a DOM element: focus on mount. RichEditor
captures the prop in a ref and focuses once, and the composer decides where the
caret starts when it opens - recipients for a blank message, body for a reply
that already has recipients and a subject - instead of deriving it from state
that changes as the user types.

initialFocusTarget is extracted and exported so the rule is stated in one place
and tested. The regression test renders RichEditor and asserts it does not take
focus from a field being typed into; it fails against the previous effect.
2026-08-23 14:15:28 -07:00
LINUXexpert.org 24fac8204a Merge pull request #9 from LINUXexpert-org/set-error-detail
Fix sending: never send null for an empty header property
2026-08-23 14:02:32 -07:00
jcoffey-dev eadec49b4f Fix sending: never send null for an empty header property
Every message ihasmail sent set cc, bcc and replyTo to null when unused, and
inReplyTo/references likewise on a new message. Stalwart parses those
properties with try_into_address_list, which returns None for null, and the
create is rejected outright:

    if let Some(addresses) = value.try_into_address_list() { ... }
    else { response.invalid_property_create(id, header); continue 'create; }

So every send failed with "Invalid property or value.", new messages and
replies alike, regardless of attachments or signature. The mock server
accepts anything, which is why this only showed up against a real server.

Empty header properties are now omitted. On a create there is no previous
value to clear, so null was never needed - only the properties actually being
set belong in the object.

buildEmailObject is exported so the shape can be tested directly, with a
regression test that no property is ever null.
2026-08-23 13:59:33 -07:00
LINUXexpert.org 95e442b2dd Merge pull request #8 from LINUXexpert-org/remove-live-hostname
Keep the live mail host out of the repo
2026-08-23 13:57:10 -07:00
jcoffey-dev 3ec4dc44fb Keep the live mail host out of the repo
Replace the hard-coded mail.inbuxa.com with generic placeholders: the config
default and .env.example use mail.example.com, the README stops naming the QA
host, and docker-compose now requires STALWART_URL to be set rather than
defaulting to somebody's real server.

Nothing deployed depends on the old default - the running container passes
STALWART_URL explicitly.
2026-08-23 13:55:17 -07:00
jcoffey-dev 7caa847737 Say which property a JMAP SetError rejected
"Send failed: Invalid property or value." is Stalwart's description for
invalidProperties, and on its own it says nothing about what to fix. The
SetError also carries a `properties` array naming the offending fields, which
every call site was discarding.

setErrorMessage appends them, and the 35 places that surfaced a SetError -
send, save draft, mailboxes, calendars, contacts, sieve, files, signature
images, sharing - now go through it.
2026-08-23 13:51:02 -07:00
LINUXexpert.org 0b278ca3c0 Merge pull request #7 from LINUXexpert-org/message-theme-option
Let messages follow the app theme, at the user's choice
2026-08-23 13:36:38 -07:00
jcoffey-dev 860cda22ab Let messages follow the app theme, at the user's choice
Messages render on a white card in every theme. That is deliberate for mail
that styles itself, but #4 points out the case it gets wrong: a message with
no styling of its own has nothing worth preserving, and flashing white at
someone reading in the dark is a real cost.

Appearance gains a switch under the theme cards, off by default so the
current behaviour is unchanged. With it on, HTML mail that declares no
colours follows the app theme; mail that sets a background or text colour
still gets the light card it was designed for, because half-darkening someone
else's design is worse than leaving it alone. Plain-text mail already
followed the theme and is untouched by the switch.

The themed palette is expressed in the app's own custom properties, which
cross the shadow boundary, so switching theme repaints open messages without
re-rendering them, and the accent-coloured link stays consistent. The host
element takes color-scheme: inherit so form controls and scrollbars inside a
message match too.

htmlDeclaresColors covers bgcolor attributes, <font color>, and colour or
background declarations in style attributes and <style> blocks, while
ignoring near-misses like border-color and ?color= in a URL.

Closes #4
2026-08-23 13:34:24 -07:00
LINUXexpert.org ecbcd76372 Merge pull request #6 from LINUXexpert-org/default-mail-handler
Offer ihasmail as the browser's mailto: handler
2026-08-23 13:29:21 -07:00
LINUXexpert.org 4846b5515c Merge pull request #5 from LINUXexpert-org/custom-date-time-pickers
Custom date and time pickers that follow the configured format
2026-08-23 13:27:02 -07:00
jcoffey-dev b870ee1910 Offer ihasmail as the browser's mailto: handler
Settings > General gains a "Default mail app" section that calls
registerProtocolHandler so mail links anywhere in the browser open ihasmail.
The browser owns the decision and there is no API to read it back, so the UI
says what it can: it records that we asked, offers "Ask again", shows a
Remove button where unregisterProtocolHandler exists, and points at the
browser's own settings. Unsupported browsers (Safari) and insecure contexts
get an explanation instead of a dead button.

The manifest now declares protocol_handlers for mailto, which is the route by
which an *installed* app can be offered by the operating system itself; the
UI says so and links the two ideas rather than promising a system-wide
default the page cannot grant.

Mailto parsing is now one function (parseMailto in lib/address.ts) instead of
three hand-rolled copies in AppShell and MessageView. It follows RFC 6068:
recipients from the path, the to= header or both, case-insensitive headers,
"+" as space, and tolerant of malformed escapes. That fixes Cc and Bcc being
silently dropped, and draftFromMailto escapes the body so a mailto: URL from
an untrusted page reaches the composer as text rather than markup.
2026-08-23 13:21:50 -07:00
jcoffey-dev 36c19d639b Custom date and time pickers that follow the configured format
Browsers render <input type="date"> and datetime-local in their own locale and
ignore the page's, so #1 left a German user on an English browser reading
22.11.2025 everywhere but still entering dates through an mm/dd/yyyy widget.
#3 makes the case that people use the picker rather than typing, which is
where the AM/PM mistakes happen.

New DateField and DateTimeField (web/src/ui/datefield.tsx) replace all nine
native controls — event editor (all-day and timed start/end, recurrence
until), out-of-office, contact birthday, advanced search. They take and emit
the same ISO strings the native inputs did, so call sites barely changed.

Each is a text box in the configured order plus a popover: a month grid
(week start from settings, locale weekday and month names, today and the
selection marked) and, for date-times, a list of times in the configured
clock. Keyboard: arrows move by day, PageUp/PageDown by month, Home/End
across the week, Enter picks, Escape closes, ArrowDown opens; the focused day
holds DOM focus so screen readers follow, and the dialog has an accessible
name (Popover gained an ariaLabel prop).

Text entry is lenient — the configured order with any separator, unseparated
digits (221125), day and month alone, non-Latin digits, and bare ISO always;
times take 18:23, 1823, 6:23pm, 930. What will not parse reverts on blur
rather than clearing the field, and impossible dates like 31 February are
rejected instead of rolling into March.

Editable boxes stay Gregorian and Latin-digit even where display does not
(fa-IR, th-TH, ar-EG): the locale's field order and separator are kept, but a
Buddhist-era year in a text box cannot round-trip against a Gregorian grid.
Noted in the README.

The out-of-office format echo added in #2 is gone — the fields now show the
right format themselves.

Closes #3
2026-08-23 13:12:17 -07:00
LINUXexpert.org d0828d67ed Merge pull request #2 from LINUXexpert-org/locale-date-time-formats
Configurable date and time formats, defaulting to the Stalwart locale
2026-08-23 12:43:36 -07:00
jcoffey-dev be893ef482 Configurable date and time formats, defaulting to the Stalwart locale
Every user-visible date now goes through web/src/lib/datetime.ts, driven by
three settings (Settings > General > Locale):

- Language & region: automatic, or any of the 618 locales CLDR has data for,
  each named in its own language and script (web/src/lib/locales.ts, generated
  by probing Intl over the subtag space).
- Date format: automatic (locale order), 22.11.2025, 22/11/2025, 11/22/2025,
  or ISO 8601 2025-11-22.
- Time format: automatic (locale), 24-hour, or 12-hour.

Automatic takes the locale Stalwart has for the account, read best-effort at
login via x:Account/get (urn:stalwart:jmap) and passed to the client in the
session; servers without the capability, or that deny sysAccountGet to a
regular user, fall back to the browser locale. POSIX forms are normalised
(de_DE.UTF-8 -> de-DE) and script modifiers kept (sr_RS@latin -> sr-Latn-RS,
uz_UZ@cyrillic -> uz-Cyrl-UZ), while dialect/variant/currency modifiers are
dropped and a script the locale already implies is not appended.

Numerals follow the locale (22.11.2025 renders as Arabic-Indic digits under
ar-EG); ISO 8601 is the exception and pins date and clock to Latin digits so
one line never mixes digit systems.

Rewired: message list and headers, quoted reply headers, calendar (titles,
weekday and hour gutters, mini calendar, agenda, popovers, invite cards,
free/busy), contacts, files, sessions. No raw toLocale*String date calls are
left in web/src.

Native <input type="datetime-local"> pickers always follow the browser locale
and cannot be restyled by a page, so the out-of-office fields echo the entered
instant in the chosen format underneath.

Also: month-grid day labels no longer wrap when they hold a date, and the mock
server serves x:Account/get (MOCK_LOCALE, default en_US).

Closes #1
2026-08-23 12:32:11 -07:00
LINUXexpert.org 86660497b1 Update README with new server version 2026-08-23 02:12:22 -07:00
jcoffey-dev 626a48e678 Folder pane: align icons, mark-read incl. subfolders
- Move the expand chevron into a gutter left of the folder icon so folders
  with and without subfolders line up on their icon; labels share the column.
- Add "Mark all as read, incl. subfolders" to the folder context menu, with
  the affected count and a per-folder fallback for servers without filter
  operators.
- Re-measure the virtualised message list when row height changes.
- Mock: seed unread mail in a subfolder.
2026-08-23 01:34:15 -07:00
jcoffey-dev 49c06e6efe Update copyright holder to LINUXexpert.org 2026-08-23 01:25:18 -07:00
jcoffey-dev 487da2fbca Use verbatim GPL-3.0 text in LICENSE
The LICENSE file only carried the short "how to apply" notice, not the
license itself, so it wasn't a valid GPLv3 distribution and license
detection tools couldn't identify it. Replace it with the canonical
674-line GNU GPL v3 text (sha256 8ceb4b9e...), and move the project
copyright line plus the "version 3 or any later version" grant into the
README, which now matches package.json's GPL-3.0-or-later.
2026-08-23 01:15:29 -07:00
jcoffey-dev c17887e48e ihasmail 2.0: rebuild as Stalwart-first JMAP webmail
Replace the FastAPI/HTMX prototype with a Node/Hono session proxy and a
React 19/Vite SPA. Mail (conversation view, search operators, labels,
sanitised HTML, privacy image proxy, invites, undo send, templates),
calendar (month/week/day/agenda, invites, free/busy, categories,
context menus), contacts (JSContact, groups, vCard), files, Sieve filter
builder (incl. filter-from-message with retroactive apply), vacation,
identities with default + Reply-To, PWA/mobile layout, push via SSE,
in-memory mock Stalwart for dev, Docker + CI.
2026-08-23 01:07:13 -07:00
350 changed files with 4848 additions and 56653 deletions
+1 -69
View File
@@ -12,18 +12,6 @@ APP_SECRET=change-me
HOST=0.0.0.0
PORT=8080
# Serve the app from a subpath instead of the domain root, for a reverse proxy
# that maps https://example.com/mail/ here. Leave it unset for the root, which
# is what every deployment gets unless it asks otherwise. "/mail", "mail" and
# "/mail/" all mean the same thing.
#
# The prefix must reach ihasmail intact -- do not strip it in the proxy -- and
# it has to be set for the *build* as well as the run: the web bundle writes
# its own asset URLs, so a build that does not know the prefix produces an app
# that cannot load itself under one. With Docker that means
# `--build-arg BASE_PATH=/mail` alongside `-e BASE_PATH=/mail`.
# BASE_PATH=/mail
# Set to "1" when running behind a TLS-terminating reverse proxy (trusts
# X-Forwarded-* and marks cookies Secure). Set to "0" for plain-HTTP dev.
TRUST_PROXY=1
@@ -40,20 +28,8 @@ SESSION_TTL=43200
SESSION_REMEMBER_TTL=2592000
# Where to persist sessions so restarts don't log everyone out (optional).
# Leave it empty to hold sessions in memory only, which is what an immutable
# instance does -- see IMMUTABLE below.
SESSION_FILE=./data/sessions.json
# Assert that this instance is running as an immutable container: read-only
# root filesystem, no durable state of its own. It is checked rather than
# taken on trust -- the server refuses to start if SESSION_FILE is set, or if
# the filesystem it is installed on turns out to be writable. Off by default.
# Running one looks like:
# docker run --read-only --tmpfs /tmp -e IMMUTABLE=1 -e SESSION_FILE= ...
# The cost today is that a restart signs everyone out, since there is nowhere
# left to keep the sessions. Removing that cost is what the OAuth work is for.
# IMMUTABLE=1
# Upstream timeouts / limits
UPSTREAM_TIMEOUT=30000
MAX_UPLOAD_BYTES=52428800
@@ -61,12 +37,6 @@ MAX_UPLOAD_BYTES=52428800
# Remote-image privacy proxy (Gmail-style). Set to 0 to load remote images directly.
IMAGE_PROXY=1
# In-app administration, for accounts whose Stalwart role manages accounts and
# domains. 0 turns it off for everyone: no menu, and the JMAP proxy refuses
# Stalwart's registry methods beyond an account's own password, app passwords
# and settings. Stalwart's own admin interface is not affected.
ADMINISTRATION=1
# Branding
APP_NAME=ihasmail
@@ -74,42 +44,4 @@ APP_NAME=ihasmail
# asks whoever runs a modified version to offer *that* version's source -- so if
# you have patched it, point this at your own tree. Shown on the sign-in page
# and in Settings > About.
SOURCE_URL=https://github.com/Coffey-Labs/ihasmail
# ---- Settings this installation decides (all optional) ----
#
# Seed what a new account starts on, lock what nobody may change, and turn
# something on once for accounts that already exist. Setting none of these --
# the default -- behaves exactly as ihasmail always has.
#
# A file is easier once there are `changes` in it. See the shipped
# settings-policy.example.json, and mount it read-only:
#
# -v /srv/ihasmail/policy.json:/etc/ihasmail/policy.json:ro
#
# SETTINGS_POLICY_FILE=/etc/ihasmail/policy.json
#
# Or inline, which is what an immutable deployment with no volume wants. These
# are ignored entirely when SETTINGS_POLICY_FILE is set, so a file and a stray
# variable cannot half-apply between them.
#
# SETTINGS_DEFAULTS={"externalSenderBanner":true}
# SETTINGS_ENFORCED={"externalRecipientConfirm":true}
# SETTINGS_CHANGES=[{"version":"20260902084513","settings":{"externalSenderBanner":true}}]
#
# Read once at startup: editing a policy means restarting the container.
# Docs: https://docs.ihasmail.org/configure/#settings-your-installation-decides
# ---- Several Stalwart servers (optional) ----
#
# Choose the upstream by the domain someone signs in with. STALWART_URL above
# stays required and stays the default; this only adds domains that go
# elsewhere. See the shipped stalwart-servers.example.json, and mount it
# read-only:
#
# -v /srv/ihasmail/servers.json:/etc/ihasmail/servers.json:ro
#
# STALWART_SERVERS_FILE=/etc/ihasmail/servers.json
#
# An unlisted domain, or a username with no domain, goes to STALWART_URL. A
# listed domain never falls back. Read once at startup: editing means a restart.
SOURCE_URL=https://github.com/LINUXexpert-org/ihasmail
-4
View File
@@ -1,4 +0,0 @@
# Funding platforms shown behind the repository's Sponsor button.
# https://docs.github.com/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/displaying-a-sponsor-button-in-your-repository
github: jcoffey-dev
-44
View File
@@ -1,44 +0,0 @@
version: 2
updates:
# The npm entry sits at the root because that is where the single lockfile
# is: root, server and web are one npm workspace, so one entry covers all
# three. Pointing entries at server/ or web/ would find package.json files
# with no lockfile beside them and update nothing.
- package-ecosystem: npm
directory: "/"
schedule:
interval: weekly
day: tuesday
time: "09:00"
timezone: Etc/UTC
open-pull-requests-limit: 5
groups:
# Everything routine arrives as one PR a week, so the dashboard is not
# the only place these get noticed. Majors are deliberately left out of
# the group: they are migrations, not bumps -- vitest 3 to 4 is one --
# and each deserves its own PR and its own CI run.
minor-and-patch:
update-types:
- minor
- patch
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: weekly
day: tuesday
time: "09:00"
timezone: Etc/UTC
groups:
actions:
patterns:
- "*"
# The runtime and build stages both pin node:22-alpine, so this is what
# keeps the published container images off a stale base between the weekly
# releases.
- package-ecosystem: docker
directory: "/"
schedule:
interval: weekly
day: tuesday
time: "09:00"
timezone: Etc/UTC
+3 -11
View File
@@ -3,22 +3,14 @@ on:
push:
branches: [main]
pull_request:
# Lets CI be run by hand against any ref, including a specific commit.
# Without this there is no way to re-run a check that never started: a run
# GitHub queues and then orphans -- as it did to every run created during the
# Actions outage on 2026-08-26 -- can be neither rerun ("already running")
# nor cancelled ("already completed"), and the workflow has no other trigger
# to reach for. Useful too for putting a check on a commit that predates a CI
# change, without pushing an empty commit to move it.
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 26
node-version: 22
cache: npm
- run: npm ci --ignore-scripts
- run: npm run typecheck
-68
View File
@@ -1,68 +0,0 @@
# Prune old image versions from GHCR.
#
# Releases are kept forever -- they carry no assets and their generated notes
# are this project's only changelog, so deleting one destroys history that
# cannot be reconstructed for nothing saved. Images are the opposite: a
# multi-arch build a week, and the by-digest push in publish.yml leaves two
# untagged per-architecture manifests behind each time on top of the tagged
# index. Those accumulate and nobody wants fifty of them.
#
# THE FOOTGUN: the obvious tool for this -- delete-package-versions with
# `delete-only-untagged-versions` -- will happily delete the per-architecture
# manifests that a multi-arch tag points *at*, because they are untagged by
# design. Nothing appears to break: the tag still exists, and pulls simply
# start failing for one architecture. This action understands manifest lists
# and will not orphan a retained index, and `validate` re-checks every
# multi-arch manifest against the registry afterwards.
#
# Separate from publish.yml, and dispatchable on its own, so `dry_run` can show
# exactly what would be deleted without rebuilding and re-pushing an image to
# find out.
name: Prune images
on:
workflow_call:
inputs:
dry_run:
type: boolean
default: false
workflow_dispatch:
inputs:
dry_run:
description: "List what would be deleted, delete nothing"
type: boolean
default: true
jobs:
prune:
runs-on: ubuntu-latest
permissions:
packages: write
steps:
# Pinned to a commit rather than a moving major tag. This action is
# handed `packages: write` and its whole job is deletion, so a tag
# repointed at something else -- by a compromise or a mistake upstream --
# is a bad day. v1.2.2.
- uses: dataaxiom/ghcr-cleanup-action@d52806a0dc70b430571a37da1fde39733ffd640f
with:
owner: Coffey-Labs
package: ihasmail
token: ${{ secrets.GITHUB_TOKEN }}
# Ten weekly releases is roughly a quarter of history, which is more
# than enough to roll back to and far less than the year's worth that
# would otherwise pile up. Older *releases* stay either way; this
# only removes the images.
keep-n-tagged: 10
# Belt and braces on top of the action's own manifest awareness:
# `latest` is never a candidate for deletion under any counting.
exclude-tags: latest
delete-untagged: true
# Sweeps the wreckage of a half-failed run: an index whose platform
# images did not all land, and referrers whose parent is gone.
delete-partial-images: true
delete-orphaned-images: true
# Checks every remaining multi-architecture manifest still resolves
# in the registry. This is the step that would catch the footgun
# above rather than leaving a reader to discover it on `docker pull`.
validate: true
dry-run: ${{ inputs.dry_run }}
-202
View File
@@ -1,202 +0,0 @@
# Publish the container image to GHCR.
#
# The README and the docs site have told people to run
# `ghcr.io/coffey-labs/ihasmail:latest` for a long time, and nothing ever
# pushed it: `docker pull` answered `denied`, because the package did not
# exist. This is the workflow that makes those instructions true. It is also
# the prerequisite for the self-hosted app catalogues -- TrueNAS and Unraid
# both install by pulling an image and neither builds from source.
#
# FIRST RUN: a package GHCR creates for the first time is **private**, even in
# a public repository, and an anonymous `docker pull` will still answer
# `denied`. Nothing in a workflow can change that -- the visibility is set once
# by hand under the package's settings, and until it is, this looks like it
# worked while the docs stay just as wrong as before. Check with a logged-out
# pull, not with one from a machine that has credentials.
#
# Two architectures, each built on its own native runner rather than under
# QEMU. Emulated arm64 has to run `npm ci` and the Vite build through
# instruction translation, which takes tens of minutes and occasionally runs
# out of memory; `ubuntu-24.04-arm` is free for public repositories and does
# the same work at native speed. The cost is the by-digest dance below: each
# runner pushes an untagged image, and a final job joins the two digests into
# one multi-arch tag.
name: Publish image
on:
release:
types: [published]
# Callable, so release.yml can build the release it just cut. This is not a
# stylistic choice: a release created with GITHUB_TOKEN does **not** raise a
# `release` event -- GitHub refuses to let a token trigger another workflow,
# to stop a workflow looping on its own output. A scheduled job that cut a
# release and expected this file to notice would silently never publish. The
# alternatives are a personal access token kept as a secret, or calling the
# workflow directly. This is the one that needs no credential.
workflow_call:
inputs:
ref:
description: "Tag, branch or SHA to build"
required: true
type: string
tag_latest:
description: "Also move :latest to this build"
type: boolean
default: false
# Same reasoning as ci.yml's dispatch trigger: a run GitHub queues and then
# orphans can be neither rerun nor cancelled, and this workflow otherwise
# only fires on a release -- which is not something to cut twice because a
# runner died. `ref` also allows publishing an image for a tag that predates
# this workflow, which is how the first one gets built.
workflow_dispatch:
inputs:
ref:
description: "Tag, branch or SHA to build"
required: true
default: main
tag_latest:
description: "Also move :latest to this build"
type: boolean
default: false
env:
# Hardcoded rather than derived from github.repository: a registry path must
# be lowercase and the owner is spelled `Coffey-Labs`, so deriving it means
# remembering to lowercase it. This is the string the docs already name.
IMAGE: ghcr.io/coffey-labs/ihasmail
jobs:
# The version is worked out once and handed to both builds, so the two
# architectures cannot disagree about what they are. scripts/version.mjs
# reads the commit date and how the commit arrived, so it needs real history
# rather than a shallow clone.
version:
runs-on: ubuntu-latest
outputs:
version: ${{ steps.v.outputs.version }}
docker_tag: ${{ steps.v.outputs.docker_tag }}
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.ref || github.ref }}
fetch-depth: 0
- uses: actions/setup-node@v7
with:
node-version: 26
- id: v
run: |
V="$(node scripts/version.mjs)"
echo "version=$V" >> "$GITHUB_OUTPUT"
# A Docker tag may not contain '+', so build metadata becomes '-'.
# The build is still *told* the real form, which is what About and
# /api/health report.
echo "docker_tag=${V/+/-}" >> "$GITHUB_OUTPUT"
echo "version $V -> tag ${V/+/-}"
build:
needs: version
runs-on: ${{ matrix.runner }}
permissions:
contents: read
packages: write
strategy:
fail-fast: false
matrix:
include:
- platform: linux/amd64
runner: ubuntu-latest
- platform: linux/arm64
runner: ubuntu-24.04-arm
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.ref || github.ref }}
- uses: docker/setup-buildx-action@v4
- uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push by digest
id: push
uses: docker/build-push-action@v7
with:
context: .
platforms: ${{ matrix.platform }}
build-args: IHASMAIL_VERSION=${{ needs.version.outputs.version }}
# Attestations are off deliberately: they add manifests of their own
# to the index, and `imagetools create` below expects the two entries
# it pushed rather than four.
provenance: false
sbom: false
cache-from: type=gha,scope=${{ matrix.platform }}
cache-to: type=gha,mode=max,scope=${{ matrix.platform }}
outputs: type=image,name=${{ env.IMAGE }},push-by-digest=true,name-canonical=true,push=true
- name: Save the digest
run: |
mkdir -p /tmp/digests
# The prefix is stripped here and put back in the merge job, so the
# filename is the bare hash. Leaving it on produces
# `image@sha256:sha256:...` when the reference is rebuilt.
digest="${{ steps.push.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- uses: actions/upload-artifact@v7
with:
# One artifact per platform; the merge job globs them back together.
name: digest-${{ strategy.job-index }}
path: /tmp/digests/*
retention-days: 1
if-no-files-found: error
# Joins the per-architecture digests into a single tagged manifest, so
# `docker pull ghcr.io/coffey-labs/ihasmail:<tag>` resolves on both.
publish:
needs: [version, build]
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/download-artifact@v8
with:
path: /tmp/digests
pattern: digest-*
merge-multiple: true
- uses: docker/setup-buildx-action@v4
- uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Create the manifest
run: |
# Arrays rather than a string: the tags and the digest references
# have to reach docker as separate arguments, and building them by
# word-splitting an unquoted variable is the version of this that
# breaks the day a value contains a space.
tags=(-t "${IMAGE}:${{ needs.version.outputs.docker_tag }}")
# :latest follows real releases only. A prerelease that moved it
# would hand every `:latest` deployment an unfinished build, and a
# dispatch run has to ask for it on purpose.
if [ "${{ github.event_name }}" = "release" ] && [ "${{ github.event.release.prerelease }}" = "false" ]; then
tags+=(-t "${IMAGE}:latest")
elif [ "${{ inputs.tag_latest }}" = "true" ]; then
tags+=(-t "${IMAGE}:latest")
fi
refs=()
for f in /tmp/digests/*; do
refs+=("${IMAGE}@sha256:$(basename "$f")")
done
echo "tags: ${tags[*]}"
echo "refs: ${refs[*]}"
docker buildx imagetools create "${tags[@]}" "${refs[@]}"
- name: Show what landed
run: docker buildx imagetools inspect "${IMAGE}:${{ needs.version.outputs.docker_tag }}"
# Runs only after a successful publish, because that is the only moment the
# package grows. See cleanup.yml for why this is not the obvious one-liner.
prune:
needs: publish
permissions:
packages: write
uses: ./.github/workflows/cleanup.yml
-155
View File
@@ -1,155 +0,0 @@
# Cut a release once a week, but only if there is something in it.
#
# Releases had drifted 184 commits behind main, which made `:latest` describe
# a build nobody was running -- the demo, prod and anyone building from source
# were all ahead of it. Publishing on release is the right trigger only if
# releases actually happen, so this is the part that makes that true without
# anyone having to remember.
#
# It does nothing on a quiet week. A release with no commits in it is worse
# than no release: it moves `:latest` to an identical build, spends a version
# number, and mails everybody watching the repository about nothing.
name: Weekly release
on:
schedule:
# Mondays, 09:00 UTC. GitHub runs scheduled jobs on a best-effort basis and
# can delay a run by a good while when the queue is busy, so do not read
# the exact minute as a promise. Note also that GitHub disables scheduled
# workflows in a repository with no activity for 60 days -- not a concern
# while this one is being worked on weekly, but it is why a silent stop is
# worth checking for before assuming the file is broken.
- cron: "0 9 * * 1"
workflow_dispatch:
inputs:
dry_run:
description: "Work out what would be released, then stop"
type: boolean
default: false
# One at a time. Two overlapping runs would race to create the same tag, and
# the loser fails noisily for a reason that has nothing to do with the code.
concurrency:
group: weekly-release
cancel-in-progress: false
jobs:
check:
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
should_release: ${{ steps.decide.outputs.should_release }}
tag: ${{ steps.decide.outputs.tag }}
title: ${{ steps.decide.outputs.title }}
sha: ${{ steps.decide.outputs.sha }}
previous: ${{ steps.decide.outputs.previous }}
count: ${{ steps.decide.outputs.count }}
steps:
- uses: actions/checkout@v7
with:
ref: main
fetch-depth: 0
- uses: actions/setup-node@v7
with:
node-version: 26
- id: decide
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
# The newest published release, or empty on a repository that has
# never had one -- in which case everything counts as new. Drafts are
# excluded: an unpublished draft is not a release anybody has, so
# counting from it would hide commits that have never shipped.
previous="$(gh release list --limit 1 --exclude-drafts --json tagName --jq '.[0].tagName // ""')"
# A tag named by a release is normally present after a full checkout,
# but a release can outlive its tag. Falling back to the whole
# history is the safe direction to be wrong in: it over-counts, which
# cuts a release that was due anyway, where under-counting would skip
# one that was.
if [ -n "$previous" ] && git rev-parse -q --verify "refs/tags/${previous}" >/dev/null; then
count="$(git rev-list --count "${previous}..HEAD")"
else
count="$(git rev-list --count HEAD)"
fi
version="$(node scripts/version.mjs)"
# A Docker tag may not contain '+', and neither should the git tag,
# so the two always agree about what to call a build.
tag="v${version/+/-}"
title="v${version%%+*}"
sha="$(git rev-parse HEAD)"
should_release=true
reason=""
if [ "$count" -eq 0 ]; then
should_release=false
reason="no commits since ${previous}"
elif git rev-parse -q --verify "refs/tags/${tag}" >/dev/null; then
# Same commit, different week: the version is derived from the
# commit, so nothing new means the tag already exists.
should_release=false
reason="tag ${tag} already exists"
fi
{
echo "should_release=$should_release"
echo "tag=$tag"
echo "title=$title"
echo "sha=$sha"
echo "previous=$previous"
echo "count=$count"
} >> "$GITHUB_OUTPUT"
# Written to the run summary so a skipped week reads as a decision
# rather than as a workflow that quietly did nothing.
{
echo "### Weekly release"
echo
if [ "$should_release" = "true" ]; then
echo "Releasing **${tag}** — ${count} commit(s) since ${previous:-the beginning}."
else
echo "Nothing to release: ${reason}."
fi
} >> "$GITHUB_STEP_SUMMARY"
cut:
needs: check
if: needs.check.outputs.should_release == 'true' && !inputs.dry_run
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v7
with:
ref: main
fetch-depth: 0
- env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
args=(--target "${{ needs.check.outputs.sha }}"
--title "${{ needs.check.outputs.title }}"
--generate-notes)
# Bound the notes to what is actually new. Without a start tag the
# generator reaches back to whatever it decides is previous, which on
# a repository with older tag shapes is not always the last release.
if [ -n "${{ needs.check.outputs.previous }}" ]; then
args+=(--notes-start-tag "${{ needs.check.outputs.previous }}")
fi
gh release create "${{ needs.check.outputs.tag }}" "${args[@]}"
# Called rather than left to the `release` trigger on purpose: see the note
# at the top of publish.yml. A release created with GITHUB_TOKEN raises no
# event, so without this the tag would exist and no image would follow it.
publish:
needs: [check, cut]
permissions:
contents: read
packages: write
uses: ./.github/workflows/publish.yml
with:
ref: ${{ needs.check.outputs.sha }}
tag_latest: true
-1
View File
@@ -6,4 +6,3 @@ dist/
server/data/
.vite/
coverage/
-150
View File
@@ -1,150 +0,0 @@
# Upstream palette values, fetched from source (all MIT)
Fetched 2026-09-02 from the projects' own repositories, not from any
reimplementation.
## Dracula — dracula/dracula-theme, MIT
README section is titled "Color Palette (OSS)" and contains BOTH variants,
so Alucard is open source and not PRO-only.
### Dracula (dark)
Background #282a36 · Current Line #44475a · Selection #44475a
Foreground #f8f8f2 · Comment #6272a4
Cyan #8be9fd · Green #50fa7b · Orange #ffb86c · Pink #ff79c6
Purple #bd93f9 · Red #ff5555 · Yellow #f1fa8c
### Alucard (light)
Background #fffbeb · Current Line #6c664b · Selection #cfcfde
Foreground #1f1f1f · Comment #6c664b
Cyan #036a96 · Green #14710a · Orange #a34d14 · Pink #a3144d
Purple #644ac9 · Red #cb3a2a · Yellow #846e15
## Gruvbox — morhetz/gruvbox, MIT
dark0_hard #1d2021 · dark0 #282828 · dark0_soft #32302f · dark1 #3c3836
dark2 #504945 · dark3 #665c54 · dark4 #7c6f64 · gray #928374
light0_hard #f9f5d7 · light0 #fbf1c7 · light0_soft #f2e5bc · light1 #ebdbb2
light2 #d5c4a1 · light3 #bdae93 · light4 #a89984
bright: red #fb4934 green #b8bb26 yellow #fabd2f blue #83a598 purple #d3869b aqua #8ec07c orange #fe8019
neutral: red #cc241d green #98971a yellow #d79921 blue #458588 purple #b16286 aqua #689d6a orange #d65d0e
faded: red #9d0006 green #79740e yellow #b57614 blue #076678 purple #8f3f71 aqua #427b58 orange #af3a03
## Rosé Pine — rose-pine/palette, MIT (palette.json)
### main (dark)
base #191724 surface #1f1d2e overlay #26233a muted #6e6a86 subtle #908caa text #e0def4
love #eb6f92 gold #f6c177 rose #ebbcba pine #31748f foam #9ccfd8 iris #c4a7e7
### dawn (light)
base #faf4ed surface #fffaf3 overlay #f2e9e1 muted #9893a5 subtle #797593 text #464261
love #b4637a gold #ea9d34 rose #d7827e pine #286983 foam #56949f iris #907aa9
## Tokyo Night — enkia/tokyo-night-vscode-theme, MIT
### Night (dark)
bg #1a1b26 · bg_dark #16161e · fg #a9b1d6 · line numbers #363b54 · border #101014
selection #202330 · link #6183bb
accents: purple #bb9af7 · text-bright #c0caf5 · red #f7768e · cyan #0db9d7
blue #7aa2f7 · light-cyan #7dcfff · yellow #e0af68 · teal #73daca · green #9ece6a
### Day (light)
bg #e6e7ed · bg_dark #d6d8df · fg #343b59 · line numbers #9da0ab · border #c1c2c7
link #2959aa
accents: purple #65359d · red #8c4351 · cyan #006c86 · blue #2959aa
yellow #8f5e15 · teal #33635c · green #385f0d
---
Fetched 2026-09-06 from the projects' own repositories, same rule as above.
Where a project publishes fewer background tiers than ihasmail needs, the
missing one is derived and marked **derived** here rather than passed off as
upstream. Body text is lifted to 7:1 by the build script for most of these —
they target their own ~4.5:1 — and every shift is printed in the generated CSS.
## Catppuccin — catppuccin/palette, MIT (palette.json)
Cited from the palette repo rather than the hub README; it is the normative
machine-readable source.
### Mocha (dark)
base #1e1e2e · mantle #181825 · crust #11111b · surface0 #313244 · surface1 #45475a
text #cdd6f4 · subtext0 #a6adc8 · overlay1 #7f849c
mauve #cba6f7 · blue #89b4fa · red #f38ba8 · peach #fab387 · green #a6e3a1
yellow #f9e2af · pink #f5c2e7
### Latte (light)
base #eff1f5 · mantle #e6e9ef · crust #dce0e8 · surface0 #ccd0da · surface1 #bcc0cc
text #4c4f69 · subtext0 #6c6f85
mauve #8839ef · blue #1e66f5 · red #d20f39 · peach #fe640b · green #40a02b
yellow #df8e1d · pink #ea76cb
Latte publishes no tier lighter than `base`, so `base` is used as the elevated
surface and `mantle` as the page behind it.
## Solarized — altercation/solarized, MIT (README "The Values")
base03 #002b36 · base02 #073642 · base01 #586e75 · base00 #657b83
base0 #839496 · base1 #93a1a1 · base2 #eee8d5 · base3 #fdf6e3
yellow #b58900 · orange #cb4b16 · red #dc322f · magenta #d33682
violet #6c71c4 · blue #268bd2 · cyan #2aa198 · green #859900
The accents are shared by both modes by design. Two tiers are **derived**: the
sunken dark surface #001f28 (below base03) and the raised light surface
#fffdf6 (above base3), neither of which Solarized publishes, plus the two
rule colours #0d4552 and #e6dfc8.
## Everforest — sainnhe/everforest, MIT (palette.md), medium contrast
### Dark
bg_dim #232a2e · bg0 #2d353b · bg1 #343f44 · bg3 #475258
fg #d3c6aa · grey1 #859289
red #e67e80 · orange #e69875 · yellow #dbbc7f · green #a7c080 · aqua #83c092
blue #7fbbb3 · purple #d699b6
### Light
bg_dim #efebd4 · bg0 #fdf6e3 · bg3 #e6e2cc · bg5 #bdc3af
fg #5c6a72 · grey1 #939f91
red #f85552 · orange #f57d26 · yellow #dfa000 · green #8da101 · aqua #35a77c
blue #3a94c5 · purple #df69ba
Light uses bg_dim as the page and bg0 as the raised surface, so the card the
reader looks at is the colour Everforest calls its background.
## Kanagawa — rebelot/kanagawa.nvim, MIT (lua/kanagawa/colors.lua)
### Wave (dark)
sumiInk0 #16161D · sumiInk3 #1F1F28 · sumiInk4 #2A2A37 · sumiInk5 #363646
fujiWhite #DCD7BA · fujiGray #727169
crystalBlue #7E9CD8 · springBlue #7FB4CA · samuraiRed #E82424 · roninYellow #FF9E3B
springGreen #98BB6C · carpYellow #E6C384 · sakuraPink #D27E99
### Lotus (light)
lotusWhite0 #d5cea3 · lotusWhite1 #dcd5ac · lotusWhite2 #e5ddb0 · lotusWhite3 #f2ecbc
lotusInk1 #545464 · lotusGray2 #716e61
lotusViolet4 #624c83 · lotusBlue4 #4d699b · lotusRed #c84053 · lotusOrange #cc6d00
lotusGreen #6f894e · lotusYellow #77713f · lotusPink #b35b79
## Ayu — ayu-theme/ayu-colors, MIT (themes/dark.yaml, themes/light.yaml)
The YAMLs give the base palette and the surfaces as literals but express syntax
roles as references (`$palette.indigo.l2`), and the resolved files are not
committed. The two signature accents are taken from the same organisation's
MIT-licensed ayu-theme/vscode-ayu build.
### Dark
surface base #0D1017 · lift #10141C (sunk is `base -L0.1`, **derived** here as #070a0f)
ui line #1B1F29 · ui fg #5A6378 · editor fg #BFBDB6
red #F07178 · orange #FF8F40 · yellow #FFB454 · green #AAD94C · teal #95E6CB
indigo #39BAE6 · blue #59C2FF · purple #D2A6FF · accent #E6B450 (vscode-ayu)
### Light
surface sunk #EBEEF0 · base #F8F9FA · lift #FCFCFC
ui fg #828E9F · editor fg #5C6166 · rule #dfe2e5 (**derived**)
red #F07171 · orange #FA8532 · yellow #EBA400 · green #86B300 · teal #4CBF99
indigo #55B4D4 · blue #22A4E6 · purple #A37ACC · accent #F29718 (vscode-ayu)
## Primer — primer/primitives, MIT (src/tokens/base/color/{dark,light})
Named "Primer" after the design system. The colour values are MIT; "GitHub"
and the Invertocat are trademarks, and nothing here is endorsed by them.
### Dark
neutral #0D1117 #151B23 #212830 #262C36 #2A313C #2F3742 #3D444D #656C76
#9198A1 #B7BDC8 #D1D7E0 #F0F6FC · black #010409
blue #79c0ff #58a6ff · green #56d364 #3fb950 · yellow #e3b341 #d29922
red #ff7b72 · purple #d2a8ff
### Light
neutral #F6F8FA #EFF2F5 #E6EAEF #E0E6EB #DAE0E7 #D1D9E0 #C8D1DA #818B98
#59636E #454C54 #393F46 #25292E
blue #0969da #0550ae · green #1a7f37 #116329 · yellow #bf8700 #9a6700
red #cf222e · purple #8250df
+1 -1
View File
@@ -60,7 +60,7 @@ representative at an online or offline event.
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
**johnellisATlinuxDOTcom**.
.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
+1 -60
View File
@@ -16,7 +16,7 @@ By participating in this project, you agree to treat other contributors with res
### Reporting Bugs
Before opening a new issue, please search [existing issues](https://github.com/Coffey-Labs/ihasmail/issues) to see if it's already been reported. When filing a bug report, include:
Before opening a new issue, please search [existing issues](https://github.com/LINUXexpert-org/ihasmail/issues) to see if it's already been reported. When filing a bug report, include:
- A clear, descriptive title
- Steps to reproduce the issue
@@ -48,15 +48,6 @@ For larger changes, please open an issue to discuss the approach **before** subm
- Related issue number(s), if any
- Screenshots/GIFs for UI changes
- Any manual testing you performed
8. **Add translations** for any new user-visible string — see
[Translations](#translations) below — and **drive the built app** for any
change that is visible on screen, as described in
[Verifying UI work](#verifying-ui-work).
`main` is protected. A change reaches it through a pull request whose **build**
check has passed — not afterwards — and the branch cannot be force-pushed or
deleted. No approving review is required, so a PR of your own is not blocked
waiting for one.
### Code Style
@@ -65,56 +56,6 @@ waiting for one.
- Prefer clarity over cleverness — this is a mail client people rely on for their inbox.
- Comment non-obvious JMAP interactions, especially around state/`changes` handling, since JMAP's delta-sync model can be easy to get subtly wrong.
### Translations
Nine languages ship alongside English: German, Spanish, French, Dutch,
Portuguese (Brazil), Russian, Ukrainian, Simplified Chinese and Japanese, in
`web/src/locales/`. A missing key renders its English source rather than
failing, so an untranslated string is invisible until somebody reading that
language finds it.
**Any change that adds or alters a user-visible string adds work in all nine
catalogues.** Say so explicitly in the PR — how many keys, and the fallback
count before and after — and say so just as explicitly when a change adds none,
so it is never left to be inferred.
#### The catalogue key for a plural is the `other` form
`plural()` looks the entry up by `forms.other`, so a call site written as
```ts
plural(n, { one: "Deleted {n} contact", other: "Deleted {n} contacts" })
```
is keyed on **`"Deleted {n} contacts"`**. Keying the catalogue on the `one`
form type-checks, builds, passes every test, and silently falls back to English
in all nine languages. Nothing errors. The only signal is the fallback count
going up, so read it:
```sh
npm run i18n:check # literals wrapped, and catalogue health
node scripts/i18n-catalog-check.mjs # per-language: translated / used / falling back
```
Compare the "falling back to English" number against `main` before and after.
It should not rise. Do not read the percentage instead — adding keys moves the
denominator, so it can hold steady while new strings go untranslated.
Plural forms are per language, from `Intl.PluralRules`: `one`/`other` for most,
`one`/`few`/`many`/`other` for Russian and Ukrainian, `other` alone for Japanese
and Chinese. Supplying a form a language does not draw is inventing a
distinction, not being thorough.
### Verifying UI work
Store tests do not exercise the component. At least one bug in this repo's
history — a shift-click range measured inside a `setState` updater, which React
runs after the anchor ref has already moved — passed every store assertion and
failed the moment the built app was driven. If a change is visible on screen,
run it: `npm run dev:mock` (mock Stalwart, credentials printed on start), then
drive the real thing. Add a component test for what you find; there are
examples in `web/src/views/*/__tests__/`.
### Development Setup
1. Clone your fork:
+8 -62
View File
@@ -1,21 +1,5 @@
# ---- build stage ----
FROM node:26-alpine AS build
# What this build calls itself: 2.16.<PR>, worked out by whoever runs the
# build. It cannot be worked out in here -- .dockerignore keeps .git out of the
# context on purpose, and git is not installed either. `node scripts/version.mjs`
# in a checkout prints the right answer; ihasmail-deploy.sh passes it through.
# Left empty, the build falls back to the base version from package.json.
ARG IHASMAIL_VERSION=""
ENV IHASMAIL_VERSION=$IHASMAIL_VERSION
# The subpath the app will be served from, e.g. /mail. Empty -- the default --
# is the domain root and is what every deployment gets unless it asks
# otherwise. Unlike the rest of ihasmail's configuration this cannot wait for
# the process to start: the web build writes its own asset URLs into
# index.html, so a build that does not know the prefix produces a shell that
# cannot load itself under one. It is therefore a build argument here and an
# environment variable in the runtime stage, from the same value.
ARG BASE_PATH=""
ENV BASE_PATH=$BASE_PATH
FROM node:22-alpine AS build
WORKDIR /app
COPY package.json package-lock.json* ./
COPY server/package.json server/
@@ -25,59 +9,21 @@ COPY . .
RUN npm run build
# ---- runtime stage ----
FROM node:26-alpine AS runtime
# Re-declared: an ARG does not cross stages.
ARG IHASMAIL_VERSION=""
ARG BASE_PATH=""
FROM node:22-alpine AS runtime
ENV NODE_ENV=production \
HOST=0.0.0.0 \
PORT=8080 \
STATIC_DIR=/app/web/dist \
SESSION_FILE=/data/sessions.json \
IHASMAIL_VERSION=$IHASMAIL_VERSION \
BASE_PATH=$BASE_PATH
SESSION_FILE=/data/sessions.json
WORKDIR /app
COPY package.json package-lock.json* ./
COPY package.json ./
COPY server/package.json server/
# config.ts reads the version through this at startup. With IHASMAIL_VERSION
# set it never looks further; without it, it falls back to package.json rather
# than failing, since there is no git in here to ask.
COPY scripts/ ./scripts/
# Only what the server loads at runtime: hono and its Node adapter, about 4 MB.
# The build stage's tree is 132 MB of vite, TypeScript, esbuild and React that
# never executes here but shipped anyway -- and showed up in every CVE scan.
RUN npm ci --ignore-scripts --omit=dev --workspace server \
&& rm -rf /root/.npm /tmp/*
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/server/dist ./server/dist
COPY --from=build /app/web/dist ./web/dist
# /data is the only path the process may write. /app stays root-owned and
# read-only to the runtime user on purpose; the previous `chown -R /app`
# re-wrote every file and, on overlayfs, duplicated the whole tree into a
# second 173 MB layer.
RUN mkdir -p /data && chown node:node /data \
# The base image ships a package manager the server never calls. Anyone who
# gets code execution should not find one waiting for them.
&& rm -rf /usr/local/lib/node_modules /usr/local/bin/npm /usr/local/bin/npx \
/usr/local/bin/corepack /opt/yarn* /usr/local/bin/yarn /usr/local/bin/yarnpkg
RUN mkdir -p /data && chown -R node:node /data /app
USER node
# No `VOLUME ["/data"]`. It reads like documentation for where the session file
# goes, but Docker acts on it: a container started without `-v` gets an
# anonymous volume mounted there anyway, and that mount stays writable even
# under `--read-only`. So the directive quietly put a writable hole in a
# container meant to be immutable, and left an orphaned volume behind every
# time one was replaced -- while never persisting anything across a redeploy,
# since each new container got a fresh empty volume of its own. Deployments
# that want the sessions to survive say so themselves: docker-compose.yml and
# deploy.example.sh both mount a *named* volume at /data, which is unaffected.
VOLUME ["/data"]
EXPOSE 8080
# Shell form, so $BASE_PATH is expanded by the container rather than baked in
# empty at build time: the health endpoint moves with the mount.
#
# The two substitutions repeat, in sh, what scripts/basePath.mjs does in
# JavaScript -- drop a trailing slash, add a leading one -- because this runs
# before there is a Node process to ask. It is worth the duplication: an
# operator who writes BASE_PATH=mail/ gets a working server, and without this
# a healthcheck that says the working server is unhealthy and has Docker
# restart it forever.
HEALTHCHECK --interval=30s --timeout=5s CMD BP="${BASE_PATH%/}"; case "$BP" in ""|/*) ;; *) BP="/$BP";; esac; wget -qO- "http://127.0.0.1:8080$BP/api/health" || exit 1
HEALTHCHECK --interval=30s --timeout=5s CMD wget -qO- http://127.0.0.1:8080/api/health || exit 1
CMD ["node", "server/dist/index.js"]
-1680
View File
File diff suppressed because it is too large Load Diff
-104
View File
@@ -1,104 +0,0 @@
# Known issues and pending QA
What was checked, against which server, and when. For a failure you are hitting
right now, start with [Troubleshooting](https://docs.ihasmail.org/troubleshooting/);
for what is not built yet, see [ROADMAP.md](ROADMAP.md).
The live instance runs **0.16.22**, and as of **2026-08-26 there is nothing
left pending**. Most entries below were exercised against 0.16.19 on the date
they name, and the dates still say so: each upgrade since was read against the
diff rather than re-run, and nothing in those diffs touches the session
capabilities, blob, quota, submission or registry paths these entries describe.
The calendar entries carrying a 2026-08-31 date were exercised against a live
0.16.20 directly, as were the public-key entries dated 2026-09-05.
**0.16.21 was different and was re-run rather than read.** It changed four
things a client can see, one of which resolved an entry below outright. The app
was run against a real 0.16.21 with mail, calendar and contacts exercised by
hand, including editing one occurrence of a recurring series through the
interface and confirming the rest of the series stayed where it was.
**0.16.22 (2026-09-13) was tested too.** The app has been tested against it on
the live instance. Its changes a client can see are all in `CalendarEvent/get`
and `ContactCard/get`, and were read from its source before the mock was made
to follow them: `baseEventId` is `null` for an event read by its stored id,
`recurrenceRule` and `recurrenceOverrides` asked for on a synthetic id come back
`null`, `useDefaultAlerts` belongs to the reader and reads `false` until set,
and an empty `properties` list returns `id` alone. None of them contradicts an
entry below.
What remains here is not a list of unknowns but of things worth knowing — where
Stalwart departs from a spec, where a setting has to be turned on for a feature
to work, and what ihasmail deliberately does not do.
Entries keep saying what was checked and when, because this section has been
wrong before: the 0.16 registry path was once recorded as verified live when a
capability looked for in the wrong place meant it had never run at all.
Some entries record what a live **0.15.5** proved before that server was
upgraded on 2026-08-25. They are kept where the finding is about ihasmail
rather than about 0.15 — a byte cap that still applies, a flow that still
works the same way — and dropped where 0.15 was the whole subject. Support for
0.15 was removed on 2026-08-26; the last release that runs on it is tagged
[`stalwart-0.15-support`](https://github.com/Coffey-Labs/ihasmail/releases/tag/stalwart-0.15-support).
- **Administration was built from Stalwart's source, and the first live run found the one thing the source reading got wrong.** Accounts and Domains were written on 2026-09-13 against the 0.16.22 source and a mock reproducing it, deployed the same day, and exercised against the live server from an administrator's session. On that server the Accounts list did not load: `x:Account/query` answered **`unsupportedFilter - type`**. A registry filter is keyed by the property's name *as it appears on the object*, and the discriminator is `@type`, so `{"type": "User"}` names nothing the server knows and fails the whole query; `{"@type": "User"}` is accepted. The research that fed the build had listed the field as `type`, and the mock took it without complaint — which is how it shipped. Fixed in [#336](https://github.com/Coffey-Labs/ihasmail/pull/336), and the mock now refuses any filter name the real server does not index, answering the way Stalwart does. Everything else was **confirmed live (2026-09-13)**, mostly read-only, with the domain writes made on a throwaway domain created for the purpose and removed afterwards:
- **Permissions** come from `GET /api/account` in camelCase (`sysAccountGet`); an administrator's list held 641 of them and none were kebab-case, whatever the documentation shows. The menu gates on these.
- **The Basic credential ihasmail proxies with reaches the admin `x:` methods**, as it already reached the self-service ones. No separate token is involved.
- **An account reads back in the shapes the code expects**: `credentials` as `{"0": {"@type": "Password", …}}`, aliases and group memberships as objects, the disk limit under `quotas.maxDiskQuota`.
- **A new domain gets automatic DKIM straight away** — an Ed25519 and an RSA key, both `active`, with their records already in the zone file — and manual DNS and certificates.
- **`dnsZoneFile` is BIND text**, one record per line as `name IN TYPE value`, with a long TXT record split into a parenthesised run of quoted chunks. A throwaway domain's file held 18 records and 3 continuation lines; every record parsed and the panel showed 18 rows. The production domains also carry TLSA records, which show as rows like any other.
- **`x:DkimSignature/query` accepts a `domainId` filter.**
- **`catchAllAddress` wants a whole address.** A bare local part is refused with `invalidPatch`, *"Invalid email address"*.
- **A domain its keys still name cannot be destroyed**: `objectIsLinked`, with `linkedObjects` listing each as `{"object": "DkimSignature", "id": …}` and no description. Removing through the panel destroys the keys first and then the domain; both were gone afterwards.
- **A reserved TLD is refused**: `example` as a domain's top level comes back `invalidPatch`, *"Invalid domain name"*, naming `name`.
The last two were then tried by hand on the live server the same day and behaved as described. **A password set by an administrator** — written to the account's existing credential, `credentials/<index>/secret` — signs in. **The outranking guard** held: an account with more rights than the viewer's role opens read-only. The guard exists because the source shows Stalwart skipping its grant check when only a password changes and on a delete, and it stays for that reason.
- **A refused password shows the server's reason in English.** Every other refusal from the registry is said in the reader's language: each error type has its own message, and a value one of Stalwart's validators refused — a domain name, an address, an empty field — is recognised by the validator's wording and explained again rather than shown. A password policy is the exception, on purpose. Its rule is the server's to set, so there is nothing to translate it from in advance, and its reason follows a translated sentence rather than being dropped, which would leave "not accepted" with no way to find out why.
- **Administration is off for a device not marked as your own, and for an installation that says so.** Both are enforced by the server rather than hidden by the menu: such a session is sent no permissions, and the JMAP proxy refuses registry methods beyond the account's own. That is worth stating because the proxy otherwise forwards whatever the browser sends, and before these gates an administrator's console could make any registry call their role allowed. For a session that may not administer, the proxy reads a request body only when it could name a registry method — a `"x:` in the text, or a `\u` escape that could spell one — so ordinary mail traffic is forwarded untouched.
- **All nine translations have never been read by anybody who speaks them.** They were produced by AI against standard dictionaries on 2026-08-31 — German, Spanish, French, Dutch, Portuguese (Brazil), Russian, Ukrainian, Simplified Chinese and Japanese, which with English makes ten languages in the picker — and every one of the nine is marked **Beta** in the picker, with that stated in Settings beside a link for reporting anything that reads wrongly. This is the entry that matters most on this page, because it is the one thing here that cannot be closed by testing: a translation can be complete, consistent, pass every check, and still read like a machine wrote it, and nobody on this project can tell which. What *is* verified is the machinery around them. A missing key renders its English source, so a bad line can simply be deleted; a stale key — one whose English no longer exists — is caught by `npm run i18n:check` rather than sitting in the file looking correct and never being looked up. Plurals are asked of `Intl.PluralRules` rather than assumed, which is why Russian and Ukrainian carry three forms and Japanese and Chinese carry one; supplying `one` for Japanese would have been filling in a distinction the language does not draw. Confirmed live on the deployed instance (2026-08-31) against a 6,289-message mailbox: role folders localise and the ~20 custom folders keep the names their owner gave them, dates and the calendar follow the language, and 6,289 renders as *6289 листувань* — the genitive plural a number ending in nine takes, which is the first time the plural machinery ran on anything but a hand-picked value.
- **`npm run i18n:coverage` reported 100% while about two hundred strings rendered English in every language.** It reads JSX text, and it was not wrong about what it measured — none of them were JSX text. They were `toast.error(...)` arguments, `confirmDialog({ title, confirmLabel })` props, `title=` and `aria-label=` attributes, and template literals: every one built from an expression a codemod cannot read. The calendar's own view switcher was the clearest case, spelling its labels `v[0].toUpperCase() + v.slice(1)` — correct English, untranslatable anywhere else, and galling because **Day**, **Week**, **Month** and **Agenda** were already in all nine catalogues and the buttons simply never asked for them. Reported from production, where the switcher stayed English in a Japanese interface. All of them are now wrapped, and `npm run i18n:check` grew a second half (`scripts/i18n-literals.mjs`) that accepts a string wrapped where it is written *or* present as a catalogue key — the constant-table convention, where `SECTIONS` holds `label: "About"` and the render site calls `t(s.label)` — and refuses one that is neither, because that is a string no catalogue can translate however many languages ship. It found twenty more than a hand sweep had. Worth recording as a general lesson rather than an i18n one: a coverage number measures the thing it can see, and the strings it cannot see are exactly the ones nobody is checking.
- **A compressing hop in front of Stalwart truncated every blob download, and nothing said so.** Node decompresses a gzip response before the code ever sees the body, but leaves the `content-length` header describing the *compressed* bytes. The blob proxy copied that header onto the longer body it forwarded, so the browser stopped reading exactly that many bytes in and called the download complete. Reported on [#76](https://github.com/Coffey-Labs/ihasmail/issues/76) against a Coolify deployment, where Traefik's compress middleware only engages above 1 KiB: filter rules one and two were fine and the third pushed the script past the threshold, after which it came back cut off mid-rule — 384 bytes of a 1.3 KB script. The size threshold is what made it look like a race. This is the *second* cause behind that issue, and the first fix did not touch it: a truncated script is neither unknown nor empty, so the "refuse to save from a baseline we could not read" guard never fired — the script parsed, just with rules missing, and the next save wrote the short version back over the real one. Every blob download shared the fault, not just Sieve: message source, vCards, signature HTML, attachments being forwarded, and the `settings.json` sync. Settings degraded honestly by luck rather than design — a truncated file fails `JSON.parse`, which is caught and leaves the local cache in charge — so it stopped syncing between devices instead of being overwritten. The proxy now asks upstream for `identity` and, for a hop that compresses anyway, forwards no length at all rather than one describing different bytes. The image proxy is unaffected: it uses `node:http` directly, sends no `accept-encoding`, and never decompresses. The save path no longer trusts the transport either: a script is now checked for completeness against the shape the generator emits — every `# rule:` comment parses, every enabled rule has an `if` and a closed body below it, every block ends with a blank line — and saving refuses on anything short, as does the rule editor, which reports the script as unreadable rather than showing the rules that happened to parse. The check is structural rather than a re-serialize-and-compare, so a script written by an older version with a different serializer is still editable; refusing over a changed byte would be the worse bug. It catches a cut at every offset except the end of a complete rule block, which is a legitimately shorter script and indistinguishable from one in the bytes alone — that residual is what the proxy fix covers.
- **Delete all spam destroys, and does not pass through Deleted Items** — this is the point of the feature and the thing worth checking on a real server, since a folder that empties into another folder has solved nothing. `Email/set destroy`, walked a page at a time so it survives `maxObjectsInSet` the way emptying Deleted Items already had to. **Confirmed live on 0.16.19 (2026-08-26)**: Junk Mail emptied and Deleted Items stayed empty afterwards. There is no undo, which is why all three entry points share one dialog that says so. Only Deleted Items and Junk Mail can be emptied this way, enforced in the store rather than only hidden in the menus.
- **Sharing a mail folder is accepted and does nothing.** `Mailbox/set` with a `shareWith` map is applied, `Mailbox/get` reads it back, and the folder never appears for the account it was shared with — **confirmed live on 0.16.19 (2026-08-27)** with a folder shared read-only to another account on the same server, which never saw it. Stalwart's own sharing documentation lists calendars, address books and file storage; mail folders are not among them. Nothing reports a failure at any point, which is the whole problem: the share is stored, so a client that trusts what it reads back shows it as live for ever. The entry point is withdrawn. A folder that is *already* shared still offers **Stop sharing**, because a share nobody can see is exactly the one you want to be able to clear, and there is no other way to. File sharing is unaffected and works end to end.
- **Address book sharing works, and was briefly withdrawn by mistake.** It was taken out alongside mail folders on 2026-08-27 on a report that it behaved the same way; the report was mistaken and the feature was put back the same day. Nothing was ever shown to be wrong with it, and Stalwart documents address books as shareable. Recorded because the withdrawal is in the history and would otherwise read as a finding. Shared books now appear in the Contacts pane under "Shared with me" rather than behind an account switch, and their contacts are offered when addressing a message.
- **Stalwart lets a sharee subscribe to a shared calendar but not a shared address book.** Subscribing is a write to the *owner's* account -- `isSubscribed` lives on the collection, not on the reader -- and 0.16.19 refuses it for a book shared read-only: `AddressBook/set` answers successfully with the id in `notUpdated`, `forbidden`, *"You are not allowed to modify this address book."* The identical `Calendar/set` on a shared calendar is accepted. **Confirmed live on 0.16.19 (2026-08-27)** from a second account holding both shares, which is the only place it shows: from the owner's own account the write succeeds and everything looks fine. So ihasmail asks the server first, because a preference the server holds is one every client agrees about, and keeps the answer in its own synced settings (`addedShares`) when the server will not. Two things this cost, both worth remembering: the refusal arrives as a *successful* response, so the code that ignored `notUpdated` saw nothing wrong and the button simply did nothing; and it is invisible from the owner's account, so it took two browsers signed in as two accounts to find at all. The mock now refuses the same write for the same reason, since one that accepted it agreed with the belief that shipped.
- **`shareWith` is not returned unless a client asks for it by name.** A `Calendar/get` or `AddressBook/get` with no `properties` comes back without the field at all — not null, not empty, absent — **confirmed live on 0.16.19 (2026-08-27)** against a calendar and an address book that were genuinely shared with another account: omit the list and there is no `shareWith`; name it and the sharee is right there. Every consequence was silent. Nothing was badged as shared, "Stop sharing" never appeared because nothing looked shared, and the share dialog opened on *"not shared with anyone yet"* over a live share — so the one screen that existed to manage sharing was the one most confidently wrong about it. Files never had this, because `fileNodeProps` had always named the property; calendars, address books and mail folders fetched everything and got less. Mail folders mattered in a way of their own: sharing one is withdrawn, and the only way to clear a share already made is a **Stop sharing** entry that appears when a folder looks shared — so without the property the escape hatch for the exact situation it was built for was invisible. The mock omitted it the same way, since one that hands it over unasked lets a client that never asks look correct everywhere except against a real server. **0.16.21 fixed this for calendars and address books**: with `properties` omitted, `Calendar/get` and `AddressBook/get` now return every property, `shareWith` included — **confirmed live on 0.16.21 (2026-09-06)**. `Mailbox/get` on the same server still leaves it out, so the mock now hides it for mail folders alone, and ihasmail keeps naming the property everywhere.
- **Stalwart's `x:PublicKey` registry works, and ihasmail deliberately does not expose it.** A Settings section for it has been built twice — [PR #67](https://github.com/Coffey-Labs/ihasmail/pull/67), closed 2026-08-26, and [PR #285](https://github.com/Coffey-Labs/ihasmail/pull/285) — and withdrawn both times, for a reason that has nothing to do with the server: **nothing in ihasmail signs, encrypts, decrypts or verifies with a key**, so a page for managing them is furniture rather than a feature. It ends up telling the reader, in its own footnote, that adding a key does nothing. The registry is written up here rather than in [ROADMAP.md](ROADMAP.md) because what follows is established fact about Stalwart that cost a live probe, and losing it twice to a closed pull request was how the second attempt came to exist at all. Everything below was **confirmed live on 0.16.20 (2026-09-05)** from a normal account with no administrative rights, and the full round trip — create, read back, rename, patch, destroy — succeeded for both formats.
- **An ordinary user may read *and* write their own keys**, whatever the permissions table says: Stalwart documents every `sysPublicKey*` permission as administrative, and the server granted them anyway. A create carrying a malformed key was refused with `invalidProperties` naming `key` rather than `forbidden` — a rejection of the key, not of the person. Had the documentation been right, any such feature would have been useless to everybody but an administrator, which is why this was probed first.
- **It takes S/MIME certificates as well as OpenPGP keys, and parses both.** A self-signed X.509 certificate carrying `emailProtection` and an `email:` SAN registered, read back and destroyed cleanly, and a malformed one is refused by a decoder of its own: *"Failed to decode X509 certificate: BER decoding error: Expected Tag { class: Universal, value: 16 } tag…"*. Worth checking rather than assuming, because every *other* message the registry returns names OpenPGP — including for input that is not OpenPGP at all — so the server reads as though OpenPGP were the only format it knows. It is not.
- **A key can parse perfectly and still be refused, and says something different when it is.** A sign-and-certify OpenPGP key with no encryption subkey — which is what `gpg --quick-generate-key` produces — comes back *"Could not find any suitable keys in OpenPGP public key"*, distinct from the parser's *"Failed to decode OpenPGP public key: Malformed packet: Malformed CTB…"*. Any client showing these must keep them apart: one says paste it again, the other says the key needs an encryption subkey and no amount of care with the clipboard will help. Certificates have no equivalent trap, since one issued for email use has key encipherment by construction.
- **`emailAddresses` comes back as `{}` when empty** — an object, where a JMAP list property should be an array. Nothing fails loudly: it is a plain `Get` response that type-checks against a hand-written interface and then throws in `join()` while a list renders. A client must check the shape rather than trust the type.
- **A create answers with the id alone**, no `createdAt`, so anything that reads the date back out of the create response gets `undefined`. **Patching `key` on an existing entry is allowed**, which is worth knowing and probably worth not doing: replacing a key by adding one and removing the old keeps `createdAt` meaning what it says.
- **`expiresAt` is the registry's own field and is not derived from the key.** A certificate valid for a year registers with `expiresAt: null`. Reading the real date means parsing the certificate, and a date a client extracted would disagree with the server's field the moment the two ever differed.
- **Signature checking is done here, and its trust model is deliberately small.** Stalwart does not verify S/MIME or OpenPGP signatures and exposes no result for one, so ihasmail does it in the browser: raw message, MIME split, PKCS#7 parse, WebCrypto. What is worth knowing is what it does *not* do, because the gap is a design choice rather than an omission. **No chain of trust is validated** — a browser has no system trust store, no CA bundle is shipped, and revocation is not checked — so a verified signature on its own shows only that the sender held the key inside their own message, which anyone can self-sign. What carries the weight instead is trust on first use: the first signed message from an address pins its fingerprint in the account's settings, and a later message signed by a different certificate is reported loudly. That is why the interface never says the bare word "verified", why a first sighting is grey rather than green, and why a changed signer never overwrites the pin. Verified against real `openssl smime -sign` output rather than hand-built fixtures — RSA and ECDSA, plus a tampered copy — because a signed message written by hand only ever agrees with whatever the author believed the format to be.
- **OpenPGP signatures cannot be checked at all, for a reason that is not effort.** A PGP signature carries no key, so verifying one needs the sender's public key in advance, and there is nowhere to get it: `x:PublicKey` holds the *account's own* keys, not correspondents'. Fetching from a keyserver or via WKD would tell a third party who you correspond with each time you opened a message — the same leak the image proxy exists to close — so it is not done. Such a message says so by name rather than failing as an unknown format, and it says *could not check* rather than *did not check out*, which is a distinction worth keeping: one is ignorance and the other is an accusation.
- **Two signature shapes are declined rather than attempted.** SHA-1 signatures are refused outright — one nobody can forge in practice today is still not one to put a tick beside. RSA-PSS is declined because the salt length lives in parameters ihasmail does not read, and guessing wrong would report a perfectly good signature as *bad*, which is a far worse thing to say than "cannot check". Both are shown as uncheckable, not as broken.
- **Read receipts are built here, not by the server** — JMAP has an extension for them, [RFC 9007](https://www.rfc-editor.org/rfc/rfc9007.html)'s `MDN/send`, and Stalwart does not implement it: `urn:ietf:params:jmap:mdn` is not among its capabilities. So ihasmail assembles the `multipart/report` itself and sends it the long way round — raw MIME uploaded as a blob, `Email/import`, then `EmailSubmission` — which is also why the receipt lands in Sent, where it honestly belongs. Non-ASCII parts are base64 rather than `8bit`, so nothing depends on 8BITMIME surviving every hop. There is deliberately no "always send" setting: a receipt confirms to whoever asked that the address is live and when it was read, to an address of the sender's choosing, so each one is a decision. Verified against the mock end to end (upload, import, submit, `$mdnsent`), and **confirmed live on 0.16.19 (2026-08-26)**: a receipt asked for by a real sender was assembled, uploaded, imported and submitted, landed in Sent, and set `$mdnsent` so a second look does not offer to send another.
- **Where 0.16 advertises `urn:stalwart:jmap`** — not where a JMAP client would look, and this now decides whether a sign-in is allowed at all. Stalwart builds the session-level `capabilities` from a fixed list (`Session::new`, plus WebSocket) that has never contained this capability, in any 0.16.x from 0.16.0 to 0.16.19. It hands it out per-account instead, so it appears in `primaryAccounts` and in each account's `accountCapabilities`. ihasmail tested for it in `capabilities` alone, which made every real 0.16 server read as older than 0.16 — and that one check drove three things: self-service credentials fell back to `POST /api/account/auth`, which 0.16 removed, so password changes, 2FA and app passwords all failed with "this mail server does not offer self-service credential management"; About reported the wrong generation; and Files took the older code path. It now looks in all three places, and is covered by tests on each. Worth restating plainly, because the stakes went up when 0.15 support was dropped: there is no longer a fallback path for this check to be wrong *into*. Getting it wrong now refuses every sign-in against a perfectly good server — a loud failure rather than a quiet misrouting, which is the trade the removal was making.
- **HTML signatures** — Stalwart caps a signature at 2047 **bytes** (`value.len() < 2048` on a Rust string, so UTF-8 bytes, not characters). ihasmail compacts pasted HTML, moves images to Files and, if still too large, keeps the full signature in Files behind a short marker; other clients see a text fallback. Confirmed live on 0.15.5 (2026-08-24): oversized, non-ASCII and inline-image signatures all save, and a test message arrived intact at Gmail with the logo inline.
- **Settings live in the account's Files, not the browser** — every preference used to sit in `localStorage`, so none of them followed anyone between devices. The sharpest edge was the default identity: with none set the address that sorts first wins, so someone who set it at work found it unset at home and mail went out from an address the recipient might not recognise ([#54](https://github.com/Coffey-Labs/ihasmail/issues/54)). They are now a `settings.json` in the `ihasmail` folder in JMAP Files, beside the signature images already kept there — which keeps ihasmail itself stateless: no volume, no database, nothing to back up separately, and the settings are covered by whatever backs up the mail store. `x:AccountSettings` was the other candidate and does not fit; its schema is `locale`/`timeZone`/`description` with no free-form field, and writing it needs `sysAccountSettingsSet`, where the built-in user role carries only the `…Get` half. `localStorage` stays on as a *cache* rather than the source of truth, so the first frame paints from it and the file corrects it a moment later; a browser with no cache shows defaults for that one frame, which is the trade for not gating the whole app on a round trip. Settings that describe *this* screen or browser deliberately stay local — list-pane sizes, density, font size, sidebar state, and the notification toggles, which track a permission the browser grants per-device and would be a claim about somewhere else it cannot make. That split is written as a list of exceptions, so a setting added later syncs by default. Writes are coalesced behind a three-second debounce, since `update()` fires on every frame of a splitter drag, and a tab going away or a sign-out flushes first. The `ihasmail` folder is now hidden from the Files view, contents and all: hiding the folder alone would be worse than showing it, because the tree attaches a node whose parent is missing to the root, so the signature images — visible there since signatures shipped — would have spilled into the top level. **Confirmed live on 0.16.19 (2026-08-26)**: settings set in Chrome came back on a fresh login in Firefox and in an incognito session, both of which start with an empty cache, so each read the account's file rather than anything local. Confirmed again on the deployed instance rather than only a pre-deployment build. Requires 0.16, which ihasmail now requires everywhere — `FileNode/query` cannot see directories before that, and sign-in refuses an older server outright. Two limits worth knowing: conflicts are last-write-wins, and a change made on one device does not reach another that already has ihasmail open until it signs in again.
- **Files on 0.16** — the pre-0.16 quirks this entry used to describe are gone with the support for them: `FileNode/query` masking directories out of its own results, `nodeType` not existing, and rights being a single `mayWrite`. What is left is what has actually been exercised on 0.16.19. Finding and creating a folder, creating a node with `nodeType`, uploading and downloading its blob, and pointing an existing node at a new one all ran live on 2026-08-26, as a side effect of the settings file. Rename, move and delete are **confirmed live on 0.16.19 (2026-08-26)** as well, which closes this out: what had been confirmed on 0.15.5 (2026-08-24) was the older code path, and that path no longer exists. Two fallbacks went with the removal and are worth knowing about: `ensureFolder` and `findInFolder` now filter on `parentId`/`isTopLevel` alone and match names client-side, since `name` is not a filter Stalwart is known to implement and one it does not know fails the whole query; and a refused filter or sort no longer drops the view into fetching every node in the account, which would have hidden a real fault behind a performance cliff nobody would notice.
- **Self-service credentials** — the registry path is **confirmed live** against Stalwart 0.16.19 (2026-08-25): app passwords created and revoked, password changed, 2FA enabled and disabled, with the browser session surviving the switch to an app password. The 0.15 REST path was confirmed live too, on 0.15.5 (2026-08-24), and has since been removed along with the rest of 0.15 support. The mock enforces the same rules the real server does (current password required, password policy, a TOTP code on every request once 2FA is on, app passwords exempt from it). Password changes are refused by Stalwart for accounts backed by an external directory (LDAP/SQL/OIDC); the server's own message is shown when that happens.
- **Scheduled send needs one setting turned on, and says nothing when it is off.** Stalwart advertises the delay in the account's `urn:ietf:params:jmap:submission` capability — `maxDelayedSend: 2592000` (30 days) and `FUTURERELEASE` among its `submissionExtensions`, and note it is the *account* capability, not the session-level one, which is empty. But the MTA only honours a hold when `futureRelease` is set under the session's MTA extensions, and [that setting defaults to `false`](https://stalw.art/docs/ref/object/mta-extensions/). With it off, Stalwart takes the `HOLDUNTIL` parameter, skips the hold and sends the message immediately **without an error** — the capability still says thirty days. So set `futureRelease` (to the longest hold you want to allow) before relying on this; a value shorter than 30 days is fine, and a request past it is refused honestly, with a `forbiddenMailFrom` naming the limit. `npm run dev:mock:no-future-release` reproduces the silent-drop case. ihasmail asks for the delay the way JMAP requires — a `HOLDUNTIL` parameter on the envelope's `mailFrom`, since RFC 8621 makes `sendAt` read-only and server-derived — and files the held message in a **Scheduled** folder, because `onSuccessUpdateEmail` would otherwise drop it in Sent the moment the submission is created. Nothing moves it out when the hold expires, so ihasmail reconciles the folder on the way in: released messages to Sent, cancelled ones back to Drafts. Three fixes this depends on landed in **0.16.17**, below the live instance's 0.16.19: `HOLDUNTIL` taking RFC 3339 date-times again (0.16.16 had it wanting Unix timestamps), `EmailSubmission/query` on `undoStatus` agreeing with `/get` about held submissions, and `EmailSubmission/get` without `ids` iterating the right index. The hold itself is now **confirmed against the live 0.16.19** (2026-08-25), once `futureRelease` was set to `30d` there: a submission carrying a `HOLDUNTIL` ten minutes out came back `pending`, with `sendAt` equal to the time asked for and a `250 2.1.5 Queued` from the MTA, rather than going out at once. Worth repeating that the capability is no evidence either way — it advertised `maxDelayedSend: 2592000` and `FUTURERELEASE` while the setting was still off. Only a submission tells you. The rest of the journey is **confirmed live too (2026-08-26)**: a hold expired and was delivered, and the **Scheduled** folder reconciled on the way in — a released message moved to Sent, a cancelled one back to Drafts. Nothing in Stalwart does that moving, so if ihasmail is never opened again the message still goes out; it is only the folder that waits to be tidied.
- **Stalwart 0.16 and RFC 8984 disagree about the calendar vocabulary, and the server only says so half the time.** A participant's address lives in `calendarAddress`, not RFC 8984's `sendTo`/`email`; the organizer is `organizerCalendarAddress`, not `replyTo`; and a recurrence is a single `recurrenceRule`, not a `recurrenceRules` array. Addressed the RFC's way, `CalendarEvent/set` **keeps the event and discards the whole participant map without an error** — guests disappeared on save and no invitation was ever sent, which is what [#26](https://github.com/Coffey-Labs/ihasmail/issues/26) reported. The array form of the rule is refused honestly, with `invalidProperties`, so recurring events could not be created at all and existing ones showed no repeat ([#30](https://github.com/Coffey-Labs/ihasmail/issues/30)). ihasmail now writes Stalwart's names and reads either, and the mock refuses what the real server refuses, since advertising the RFC spelling is precisely how this got as far as a live server. Verified against 0.16.19 on 2026-08-25, end to end: participants, organizer and rule all survive a create, an update and a re-read; an invitation to an external Gmail address arrived as an invite card, and the decline came back and was applied to the event (`needs-action``declined`, sequence 1). Cancelling the event notified the guest too. Adding guests to an event that had none, and clearing them again with `null`, both work on the update path, as does RSVP — which patches `participants/{key}/participationStatus` (and `participationComment`) rather than sending the whole map. That patch had to be aimed at the base event: through 0.16.19 `CalendarEvent/set` refused a synthetic id with *"Updating synthetic ids is not yet supported"*, which is why RSVP resolves `baseEventId` first. 0.16.20 accepts one, so that resolution is now a choice rather than the only option — an RSVP aimed at an occurrence would answer for that date alone. It still resolves the base, which is the answer people mean. Adding a *new* participant by patch is refused as well (`Patch operation failed`), so a changed guest list is written as the whole `participants` property. One more thing to know when reading this code: an expanded occurrence carries a `recurrenceId` but *no* rule of its own, and `baseEventId` is set on everything an expanded query returns — a one-off included, whose own id differs from its base — so neither is a test for recurrence. Since 0.16.22 the same event read by its *stored* id answers `baseEventId: null` rather than its own id, which changes nothing here: a one-off read through the synthetic id an expanded query gave it still carries a base.
- **Free/busy between accounts needs no sharing, and calendar contents cannot be reached at all.** These are the two halves of the same finding, and the second is what makes the first safe. **Confirmed live on 0.16.20 (2026-09-01)** against the deployed instance: `Principal/getAvailability` was called for all seven principals the directory returns, none of whose calendars are shared with the calling account, and every one was answered — no `forbidden`, no error of any kind, from a server that refuses a malformed call instantly. It returns real data rather than a polite empty list: the caller's own principal reported one busy period against the one event in the next sixty days. And a `Principal` carries only `id`, `type`, `name`, `description` and `email`**no `accountId`** — so there is no handle with which to ask for anybody's calendars. Free/busy is therefore not the weaker of two permissions, it is the only channel between two accounts, and it is open by default. That is the right posture and worth recording, because a client that assumed sharing was a precondition would hide a working feature behind a setting nobody needs to touch. **One thing this did not settle**: the other six principals reported nothing over a nine-month window, which is equally consistent with "those accounts have empty calendars" — likely, since the session reaches one account — and with "an unreadable principal answers with an empty list rather than an error". Distinguishing them needs a second account with an event in it, and until somebody has one, ihasmail assumes the pessimistic reading everywhere it matters: a participant it cannot read is drawn as unknown rather than as free.
- **An override can move an occurrence, and then `start` and `recurrenceId` mean two different times.** The slot stays where the rule put it and only the clock time moves. **Confirmed live on 0.16.20 (2026-08-31)**: one occurrence of a weekly 09:00 series moved to 14:00 came back `start: 2027-06-14T14:00:00` with `recurrenceId` still `2027-06-14T09:00:00`. This is the right behaviour and it is the reason `recurrenceId` is the handle ihasmail holds: it is the one name for an instance that survives *both* a renumbering and a move, so a mutation can always be re-resolved from it. Worth recording because the mock got it wrong in the other direction — it overwrote an override's `start` with the slot time, so a moved occurrence did not move, and per-occurrence *time* editing looked broken against the mock and correct against the server. Found by asking a real server rather than by reading the mock, which is the only way this kind of disagreement ever surfaces.
- **A synthetic id was only true until the next write, through 0.16.20. Fixed in 0.16.21.** Stalwart's expanded-occurrence ids used to encode a position in the series, so writing a `recurrenceOverrides` entry renumbered them. **Confirmed live on 0.16.20 (2026-08-31)**: a five-week series came back as `e i m q u` over 03-01 … 03-29; one override written to 03-08 left the *same five ids* addressing 03-01, 03-15, 03-29, 03-08 and 03-22. Nothing was rejected and nothing reported a change — `i` simply meant a week later than it had a moment earlier, so an id cached across a write silently pointed at another date and a delete meant for one occurrence removed a different one. The failure was never a `notFound` a client would notice; it was a confident answer about the wrong day. **0.16.21 identifies an occurrence by its recurrence id, and confirming that was the point of re-running rather than reading the diff. Confirmed live on 0.16.21 (2026-09-06)**: the same shape of test — five weekly occurrences expanded, the third retitled through its own synthetic id, all five original ids re-read — left every id on its own date, with none renumbered and none `notFound`. A second override written through the interface behaved the same way. The defence stays regardless: ihasmail still never mutates an occurrence by an id it is holding, and `updateEvent` and `destroyEvent` still re-resolve by `recurrenceId` immediately before acting, because a date can still leave a series and because the client supports 0.16 as a whole rather than only its newest release. The mock follows the new behaviour, and the test that pinned the old renumbering now pins the stability instead — rewritten rather than deleted, so the reversal stays on the record.
- **A per-occurrence patch made only of inherited properties creates an override that loses the title.** The twelve properties 0.16.20 drops from a per-occurrence patch are dropped *after* it has decided to write an override, so a patch consisting only of them still writes one — and that override carries the `start` and `duration` the server fills in and nothing else. **Confirmed live on 0.16.20 (2026-08-31)**: `{"privacy": "private"}` aimed at one occurrence answered `updated`, left `privacy` untouched on the series, and left that date with no title at all. A successful response, a silently discarded change, and real data loss on a third property nobody mentioned. ihasmail narrows a per-occurrence patch before sending it and sends nothing when narrowing empties it, which was written as a point of principle — a request whose response could only be a meaningless "updated" is worse than no request — and turns out to prevent this. Worth remembering as the argument for the principle.
- **Recurring events can be edited and deleted one date at a time, since 0.16.20.** A write aimed at a synthetic id was refused outright through 0.16.19; 0.16.20 turns it into a `recurrenceOverrides` entry instead, so "this occurrence" and "the whole series" are now two different things ihasmail asks about before acting. **Confirmed live on 0.16.20 (2026-08-31)** end to end against a five-week series: a legal patch landed on the override with `start` and `duration` filled in by the server; `useDefaultAlerts` was refused with *"This property cannot be modified on a single occurrence."*; a destroy removed one date and left the series; and a base event and one of its instances in the same request were refused together, both ids, with *"A base event and its instances cannot be modified in the same request."* The scope is chosen before the editor opens rather than on save, because it decides which event the form is about — one populated from the master shows the *series'* start date, so editing Wednesday would have offered to move Monday. Two entries below are the sharp edges this turned up.
- Editable date boxes are always Gregorian and in Latin digits, even for locales whose *display* uses another calendar or numbering system (`fa-IR`, `th-TH`, `ar-EG`) — they keep the locale's field order and separator, but a Buddhist-era year in a text box does not round-trip against the Gregorian calendar grid. Non-Gregorian calendar support is not implemented.
- The account locale is read from `x:AccountSettings/get`, whose permission the built-in user role has, falling back to `x:Account/get` (which needs the admin-only `sysAccountGet`). Both are Stalwart 0.16 methods: **on older servers neither is reachable** — they do not implement the registry and reject a request that so much as names the `urn:stalwart:jmap` capability — so there the locale still falls back to the browser's and can be chosen by hand. Confirmed live on 0.16.19 (2026-08-25), once the capability was looked for where Stalwart advertises it; a locale request that is merely refused no longer downgrades the detected generation.
-96
View File
@@ -1,96 +0,0 @@
# Third-party notices
ihasmail is licensed under the AGPL-3.0; see LICENSE. This file records work by
other people that ships inside it and the terms it comes under.
## Colour palettes
Ten of the palettes offered in Settings Appearance are the work of their own
projects and are used under the MIT licence. Only the published colour values
are used — no code, and nothing from anyone else's reimplementation of them.
The values as fetched from each project are recorded in
`.palette-sources/palettes-upstream.md`, and the shades between them are
derived by `scripts/build-palettes.py`, which also lifts any tier that would
not meet the contrast ihasmail claims.
### Dracula and Alucard
Copyright (c) 2016 Dracula Theme — https://github.com/dracula/dracula-theme
Licensed under the MIT licence. "Dracula" is the dark variant and "Alucard" the
light one; both are published in that repository's own "Color Palette (OSS)"
section.
### Gruvbox
Copyright (c) 2018 Pavel Pertsev — https://github.com/morhetz/gruvbox
Licensed under the MIT licence.
### Rosé Pine
Copyright (c) 2021 Rosé Pine — https://github.com/rose-pine/rose-pine-theme
Licensed under the MIT licence. The light variant is "Dawn".
### Tokyo Night
Copyright (c) 2019 enkia — https://github.com/enkia/tokyo-night-vscode-theme
Licensed under the MIT licence. The light variant is "Day".
### Catppuccin
Copyright (c) 2021 Catppuccin — https://github.com/catppuccin/palette
Licensed under the MIT licence. "Mocha" is the dark variant and "Latte" the
light one; both are published in that repository's palette.json.
### Solarized
Copyright (c) 2011 Ethan Schoonover — https://github.com/altercation/solarized
Licensed under the MIT licence. Light and dark are both original to it, and
share one set of accent values by design.
### Ayu
Copyright (c) Konstantin Pschera — https://github.com/ayu-theme/ayu-colors
Licensed under the MIT licence. The two signature accent colours come from the
same author's ayu-theme/vscode-ayu, also MIT.
### Kanagawa
Copyright (c) 2021 Tommaso Laurenzi — https://github.com/rebelot/kanagawa.nvim
Licensed under the MIT licence. "Wave" is the dark variant and "Lotus" the
light one. The theme takes its name from Hokusai's print.
### Everforest
Copyright (c) 2019 Sainnhe Park — https://github.com/sainnhe/everforest
Licensed under the MIT licence. The medium-contrast variant of each mode is
the one used here.
### Primer
Copyright (c) GitHub, Inc. — https://github.com/primer/primitives
Licensed under the MIT licence, which covers the colour values. "GitHub" and
the Invertocat logo are trademarks of GitHub, Inc.; this palette is named
"Primer" after the design system and is neither affiliated with nor endorsed
by GitHub.
---
The MIT licence, under which all ten are used:
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+174 -411
View File
@@ -2,356 +2,94 @@
<img src="web/public/img/logo.png" alt="ihasmail" width="150">
</p>
<p align="center">
<strong><a href="https://demo.ihasmail.com">Try the demo</a></strong><br>
<sub>A working copy with an invented mailbox behind it — no sign-up, nothing real, nothing kept.</sub>
</p>
<p align="center">
<a href="LICENSE"><img alt="Licence: AGPL-3.0-or-later" src="https://img.shields.io/badge/licence-AGPL--3.0--or--later-2dd4bf?style=flat-square"></a>
<a href="https://stalw.art" target="_blank" rel="noreferrer"><img alt="Requires Stalwart 0.16 or newer; tested against 0.16.22" src="https://img.shields.io/badge/Stalwart-0.16.22-6366f1?style=flat-square"></a>
<a href="https://docs.ihasmail.org" target="_blank" rel="noreferrer"><img alt="Documentation: docs.ihasmail.org" src="https://img.shields.io/badge/docs-docs.ihasmail.org-0ea5e9?style=flat-square"></a>
<a href="https://coffeylabs.org" target="_blank" rel="noreferrer"><img alt="by Coffey Labs" src="https://img.shields.io/badge/by-Coffey%20Labs-0f766e?style=flat-square"></a>
<a href="https://stalw.art" target="_blank" rel="noreferrer"><img alt="Tested against Stalwart 0.16.19 and 0.15.5" src="https://img.shields.io/badge/Stalwart-0.16.19%20%7C%200.15.5-6366f1?style=flat-square"></a>
<a href="https://linuxexpert.org" target="_blank" rel="noreferrer"><img alt="by LINUXexpert.org" src="https://img.shields.io/badge/by-LINUXexpert.org-0f766e?style=flat-square"></a>
</p>
# ihasmail
**Immutable webmail for [Stalwart Mail Server](https://stalw.art) — a container
with nothing to persist, and a Gmail-class client on top of it.**
**A fast, friendly, Gmail-class webmail for [Stalwart Mail Server](https://stalw.art) — built on JMAP, from the ground up.**
Mail, calendars, contacts, files and filters in a responsive single-page app
that works equally well on a desktop monitor and a phone. It talks only JMAP
(plus Stalwart's blob/upload/EventSource endpoints) — no IMAP, no SMTP, no
database, and with `IMMUTABLE=1` no writable filesystem either. Everything
durable belongs to Stalwart; the container is disposable.
ihasmail is a JMAP-first web client: mail, calendars, contacts, files, filters and every other modern feature Stalwart exposes, in a responsive single-page app that works equally well on a desktop monitor and a phone. It talks only JMAP (plus Stalwart's blob/upload/EventSource endpoints) — no IMAP, no SMTP, no database.
| | |
| --- | --- |
| 🌐 **[ihasmail.org](https://ihasmail.org)** | What it is, what it looks like, the full feature list |
| 📘 **[docs.ihasmail.org](https://docs.ihasmail.org)** | [Installing](https://docs.ihasmail.org/install/) · [Configuring](https://docs.ihasmail.org/configure/) · [Using it](https://docs.ihasmail.org/using/) · [Shortcuts](https://docs.ihasmail.org/shortcuts/) · [Rebranding](https://docs.ihasmail.org/rebranding/) · [Troubleshooting](https://docs.ihasmail.org/troubleshooting/) |
| 📋 **[FEATURES.md](FEATURES.md)** | Everything it does, feature by feature, with the capability each one needs |
| 🧪 **[KNOWN-ISSUES.md](KNOWN-ISSUES.md)** | What was verified live, and where Stalwart departs from a spec |
| 🛣 **[ROADMAP.md](ROADMAP.md)** | What ihasmail does not do, and why |
> Status: 2.0 rewrite, in QA against a live Stalwart server — **0.16.19**
> since 2026-08-25, 0.15.5 before that. The previous FastAPI/HTMX prototype
> has been removed entirely (only the logo survived, and it has since lost
> the `.com` wordmark it used to carry — ihasmail is the software, not the
> hosted instance).
### Companion tools
ihasmail supports both generations of Stalwart, which are less alike than the
version numbers suggest: 0.16 replaced the REST management API with JMAP
registry objects, changed the shape of `FileNode`, split its rights up, and
moved configuration into the store. Where the two differ, ihasmail detects
which it is talking to rather than assuming — see [Known issues / pending
QA](#known-issues--pending-qa) for what is verified on which.
Two tools for getting a Stalwart server ready for ihasmail, one for each place
you might be starting from:
| | Starting from | What it does |
| --- | --- | --- |
| 🚀 **[ihasmail-oneshot](https://github.com/Coffey-Labs/ihasmail-oneshot)** | **Nothing** — a fresh Linux host with Docker | One command deploys a new Stalwart and a new ihasmail on a single host, already linked: certificates for both, the first mailboxes, and the DNS records to publish. Or `--local` for a loopback-only pair to try it |
| ⬆️ **[stalwart-migrator](https://github.com/Coffey-Labs/stalwart-migrator)** | **An existing Stalwart 0.15.5** server | Upgrades it in place to the 0.16 series ihasmail requires, checkpointing every phase so an interrupted run resumes, and validating the server afterwards. Take a snapshot first: it does not undo a migration |
> **Releases are weekly, so `latest` normally lags `main`.** Automation builds
> and publishes the GHCR image every **Monday at 09:00 UTC**, in a week that had
> changes. Between one Monday and the next, `main` is ahead of the newest image
> — a fix merged on Tuesday is a `docker pull` away only after the following
> Monday. GitHub runs scheduled workflows on a best-effort basis, so treat the
> hour as approximate.
>
> This is worth knowing when a closed issue says a fix is *live*: that means the
> QA webmail server, which deploys from `main`, and not the image you have. If
> you want a change before the next Monday, build from `main` — see
> [Container images](#container-images). Otherwise pull after it, and the dated
> tag tells you exactly which build you are on.
This file is for people working *on* ihasmail. Everything about running it
lives in the docs.
The live instance was moved from 0.15.5 to 0.16.19 with
[stalwart-migrator](https://github.com/LINUXexpert-org/stalwart-migrator), a
companion project: an in-place upgrade tool that checkpoints every phase,
refuses to start on the things that cannot be fixed mid-migration, and
validates the server afterwards. The upgrade is genuinely treacherous by hand
— the store is migrated in place with no way back, and Stalwart's own
converter drops settings without saying so — and that migration took eight
seconds of downtime with nothing lost.
## Screenshots
*Taken against the built-in mock server (`npm run dev:mock`) with sample data — no real mailbox involved.*
*All screenshots are taken against the built-in mock server (`npm run dev:mock`) with sample data — no real mailbox involved.*
| | |
| --- | --- |
| **Inbox & conversation (dark)** ![Inbox, dark theme](docs/screenshots/inbox-dark.jpg) | **Inbox & conversation (light)** ![Inbox, light theme](docs/screenshots/inbox-light.jpg) |
| **Composer** ![Composer](docs/screenshots/compose.jpg) | **Calendar** ![Calendar](docs/screenshots/calendar.jpg) |
| **Contacts** ![Contacts](docs/screenshots/contacts.jpg) | **Sieve filter builder** ![Filters](docs/screenshots/filters.jpg) |
| **Inbox & conversation view (dark)** ![Inbox, dark theme](docs/screenshots/inbox-dark.jpg) | **Inbox & conversation view (light)** ![Inbox, light theme](docs/screenshots/inbox-light.jpg) |
| **Reply composer** — identities, Reply-To, rich text, signature, quoted text ![Composer](docs/screenshots/compose.jpg) | **Calendar (month view)** ![Calendar](docs/screenshots/calendar.jpg) |
| **Contacts** ![Contacts](docs/screenshots/contacts.jpg) | **Sieve filter builder** — also reachable from a message's right-click menu ![Filters](docs/screenshots/filters.jpg) |
| **Sign-in** ![Login](docs/screenshots/login.jpg) | **Mobile layout** <img src="docs/screenshots/mobile.jpg" alt="Mobile" width="300"> |
More, including the mobile layout, on [ihasmail.org](https://ihasmail.org/#screenshots).
## Features
## What's in it
**Mail**
- Gmail-style three-pane layout (reading pane right/bottom/off, **drag-to-resize splitter** in both orientations, quick layout switch in the list menu), conversation view with collapsed messages and "show quoted text", dense/cozy/comfortable density, light/dark/system theme with accent colours
- Virtualised, infinitely-scrolling message list; multi-select (click, ⇧-click, ⌃-click), drag & drop to folders, right-click context menus, hover actions, Gmail keyboard shortcuts (`j/k`, `e`, `#`, `r/a/f`, `g i`, `/`, `?` …)
- Archive / delete / spam / star / mark read / move / labels (IMAP keywords with colours) with **Undo**
- **"Filter messages like this…"** from the message context menu: creates a Sieve rule pre-filled from the sender/list (target folders can be created on the fly), and can **apply it immediately to the existing messages in the folder** (evaluated client-side, actions applied via JMAP)
- Safe HTML rendering: DOMPurify sanitisation inside a Shadow DOM, **remote images blocked by default** with a per-sender allow-list and an optional **privacy image proxy** (like Gmail's)
- Messages sit on a light card by default, untouched as the sender designed them. *Appearance Apply the theme to messages too* lets them follow the app's light/dark theme instead — plain-text mail always does, and with the option on so does HTML mail that brings no colours of its own; mail that styles itself is still left alone
- Attachments: previews for images/PDF/text, download all, inline `cid:` images, `.eml` export, *Show original*, header viewer
- **Read receipts**: when a sender asks for one, the message offers to send it — a real RFC 8098 `multipart/report`, never automatically. Bulk mail, mailing lists and anything marked `Auto-Submitted` are not offered one at all, and a receipt aimed somewhere other than the sender says so before you send it. Sending is recorded with RFC 3503's `$mdnsent` keyword, so a second look — or another client — knows not to ask again
- Invitations: `.ics` parts render as an invite card with **Yes/Maybe/No** RSVP (via `CalendarEvent/parse` + iTIP); `.vcf` parts offer *Add to contacts*; `List-Unsubscribe` one-click
- **Right-click anyone named in a message** — sender, To, Cc, Bcc, Reply-To — to add them to the address book (the contact editor opens prefilled, with the display name split into first/last), edit them if they are already known, write to them, or copy the address
- Search with Gmail operators (`from:`, `to:`, `subject:`, `has:attachment`, `is:unread`, `is:starred`, `in:`, `label:`, `before:`, `after:`, `larger:`, `smaller:` …) plus an advanced-search panel
- Composer: multiple floating/minimised/maximised composers, rich-text editor (formatting, lists, links, colours, images pasted/dropped inline, emoji), plain-text mode, recipient chips with autocomplete from **contacts, the directory (GAL) and recent recipients**, multiple identities with HTML signatures, Cc/Bcc, priority, read-receipt request, templates/canned responses, attachment upload with progress, drag & drop, attachment reminder, **undo send**, **scheduled send** (quick picks or an exact date and time; the message waits in the server's queue, so it goes out whether or not ihasmail is open), autosaved drafts, reply/reply-all/forward with quoting and inline images preserved
- Live updates via JMAP push (EventSource proxied server-side) with polling fallback; desktop notifications, sound, title/favicon unread badge
- AZ folder list with Inbox pinned on top (other special folders mixed in), subfolders nested and collapsed by default with chevrons in their own gutter so every icon lines up; unread folders are bold (a parent is bold when a subfolder has unread mail); right-click a folder to mark it read *including subfolders*, create/rename/hide/share/empty, quota bar, Outlook-style module bar (Mail · Calendar · Contacts · Files) at the bottom of the pane, multi-account switching for shared accounts
- **Mail** — three-pane Gmail-style layout, conversation view, virtualised list, labels, undo, Gmail search operators and keyboard shortcuts, Sieve rules from a message's context menu, sanitised HTML with remote images blocked, read receipts, invitations and RSVP, an event made from a message with its guests already in it, multi-composer rich-text editing with signatures, scheduled send and undo send
- **Calendar** — JMAP Calendars / JSCalendar: month/week/day/agenda, recurrence, attendees and free-busy, colour categories
- **Contacts** — JMAP Contacts / JSContact: address books, groups, full editor, vCard import/export
- **Files** — JMAP FileNode: browse, upload, download, rename, move, delete
- **Signature checking** — S/MIME signed mail is verified as you read it, and the signer is remembered: a later message from the same address signed by somebody else is called out loudly. No certificate authority is involved and none is bundled, so ihasmail never claims more than it can show — see [Checking a signature](FEATURES.md#checking-a-signature)
- **Settings that follow the account**, not the browser — kept in a `settings.json` in the account's own JMAP Files. The format is ihasmail's; the file is the account's, under its quota, and outlives any container that read it. ihasmail holds none of it
- **Runs read-only** — one optional write path, and with it switched off the container needs no volume and no writable root. `IMMUTABLE=1` is checked at startup rather than trusted, so a half-applied switch refuses to boot instead of failing quietly. See [Running immutably](#running-immutably)
- **Nine new interface languages** — German, Spanish, French, Dutch, Portuguese (Brazil), Russian, Ukrainian, Simplified Chinese and Japanese, alongside English and separate from the date-and-time locale. Every one is marked **Beta**: they were made by AI and no native speaker has read them yet, which Settings says plainly, with a link for reporting anything wrong
- **Twelve themes** — Classic and ihasmail's own, plus Catppuccin, Dracula, Gruvbox, Rosé Pine, Tokyo Night, Solarized, Ayu, Kanagawa, Everforest and Primer, each with the light and dark half its own project publishes. Palette and light-or-dark are separate choices, and the accent colour still sits on top of any of them. Only published colour values are used, taken from each project's own repository; the shades between them are derived and every text colour is measured against the surface it sits on, so a palette that would not meet the contrast this app claims is not written at all — see [Themes](FEATURES.md#themes)
- **On a phone** — swipe a message to archive or delete it (either direction, your choice), hold one to select it, hold a folder for its menu, pull the list to refresh, swipe back from a conversation
- **Administration** — for an account whose Stalwart role manages accounts or domains, from the account menu: create, edit and delete accounts and set their passwords; add domains, copy their DNS records one at a time or as a zone file, see their DKIM keys, and remove them once nothing uses them. Each control is there only when the role allows it, and Stalwart decides every call. Only for a session signed in with *This is my own device* ticked, and `ADMINISTRATION=0` turns it off for everyone — see [Administration](FEATURES.md#administration)
- **Platform** — installable PWA, Web Push with ihasmail closed, `mailto:` handler, no credentials in the browser, strict CSP, SSRF-safe image proxy
**Calendar** (JMAP Calendars / JSCalendar)
- Month / week / day / agenda views, mini calendar, multiple calendars with colours, show/hide, create/edit/share calendars
- Create events by click or drag, edit everything: all-day, time zones, recurrence (presets + custom rule builder), location, meeting link, description, reminders, status/privacy/free-busy, colour
- Attendees with invitations (`sendSchedulingMessages`), RSVP, and **free/busy lookup** via `Principal/getAvailability`
- **Right-click menus** on events (open, edit, duplicate, colour, category, delete) and on empty slots/days (new event here, go to day/week)
- **Outlook-style colour categories**: named colours managed in Settings, assigned from the context menu or editor; stored as JSCalendar `categories` (+ `color`) so they sync
The long version is on [ihasmail.org](https://ihasmail.org/#features); how to
drive each one is in [Using ihasmail](https://docs.ihasmail.org/using/).
**Contacts** (JMAP Contacts / JSContact)
- Address books (create/rename/share/default), contact list with search and letter index, full contact editor (names, emails, phones, addresses, org/title, birthday, website, notes, photo), **groups**, vCard import/export, compose-to-contact
## Requires Stalwart 0.16 or newer
**Files** (JMAP FileNode)
- Browse folders, upload (drag & drop), download, create folders, rename, move, delete
Sign-in refuses anything older, by name. 0.16 replaced the REST management API
with JMAP registry objects, changed the shape of `FileNode`, split its rights up
and moved configuration into the store; supporting both generations meant a
wrong guess had somewhere to fall back to, so it failed *quietly* and that
reached production. With one supported generation a wrong guess is a loud error
on the first call.
**Settings**
- **Dates & times**: language/region (every one of the ~620 locales CLDR has data for, each named in its own language and script), date order (locale default, `22.11.2025`, `22/11/2025`, `11/22/2025` or ISO `2025-11-22`) and 12h/24h clock, applied everywhere — message list and headers, calendar, contacts, files, sessions. The default comes from the locale configured for the account in Stalwart (`x:AccountSettings/get`, falling back to `x:Account/get`), and from the browser where the server will not say; POSIX forms are normalised (`de_DE.UTF-8``de-DE`) and script modifiers preserved (`sr_RS@latin``sr-Latn-RS`). Numerals follow the locale (`٢٢.١١.٢٠٢٥` for `ar-EG`), except under ISO 8601, which pins date *and* clock to Latin digits. Dates are **entered** through custom pickers in the same format (browsers render `<input type="date">` in their own locale and ignore the page's), with a calendar popover, a time list, keyboard navigation, and lenient typing — `22.11.`, `221125`, `6:23pm` and bare ISO all parse
- **Self-service credentials** in Settings Security: change your password, manage **app passwords** (a separate password per mail app or device, revocable on its own), and turn **two-factor authentication** on or off by scanning a QR code. Enrolment codes are verified before anything is stored, so a mistyped key cannot lock you out, and switching 2FA on moves this browser's session onto a dedicated app password instead of signing you straight back out. Works against both Stalwart generations: the `x:AccountPassword` / `x:AppPassword` registry objects on 0.16+, and the `/api/account/auth` REST endpoint on 0.15.x (the latter confirmed live)
- **Light and dark** follow the system by default, with a toggle in the top bar for flipping between them and a three-way choice in Settings Appearance
- Identities & signatures, **Sieve filters** (visual rule builder that round-trips to a Sieve script, plus a raw script editor with server-side validation), out-of-office (`VacationResponse`), folders, labels, templates, notifications, calendar defaults, sessions (sign out other devices), keyboard shortcuts, import/export of settings
- **Settings follow the account, not the browser** (Stalwart 0.16+): they are kept in a `settings.json` in the account's own JMAP Files, so the default identity, locale, date and time formats, theme, labels, templates, folder colours and the rest are the same wherever you sign in — including a private window. ihasmail still stores nothing itself; the file lives in the mail store and is backed up with it. Settings that describe *this* screen or browser stay local, because syncing them would be wrong rather than helpful: list-pane sizes, density, font size, sidebar state, and the notification toggles (which track a permission the browser grants per-device). localStorage is kept as a cache so the first frame is already right, and the file corrects it a moment later. On Stalwart 0.15 nothing changes — settings stay local, as before
**Validated against 0.16.22**, released 13 September 2026: the live instance
runs it and the app has been tested against it. Four of its JMAP changes are
visible to a client, all in calendars and contacts:
`CalendarEvent/get` returns `baseEventId` only for a synthetic id, so an event
read by its stored id now carries `null` there rather than its own id; it
returns `null` for `recurrenceRule` and `recurrenceOverrides` asked for on a
synthetic id; `useDefaultAlerts` is stored per user and reads `false` when never
set; and `CalendarEvent/get` and `ContactCard/get` return only `id` for an empty
`properties` list, rather than everything. The mock reproduces all four.
Before it, **0.16.21**, released 6 September 2026: the app was run against a
real instance of it and the mail, calendar and contacts paths were exercised by
hand. Four of that release's JMAP changes are visible to a client
— an occurrence of a recurring event is now identified by its recurrence id
rather than by its position in the series, so an id held across a write no
longer silently names a different date; `Calendar/get` and `AddressBook/get`
return every property when none are named; EventSource advertises its ping
interval in seconds rather than milliseconds; and a calendar write that asks
for scheduling messages is refused when the account may not send them. The mock
reproduces those four.
- Still on 0.15? The last release that runs on it is tagged [`stalwart-0.15-support`](https://github.com/Coffey-Labs/ihasmail/releases/tag/stalwart-0.15-support).
- Upgrading? [stalwart-migrator](https://github.com/Coffey-Labs/stalwart-migrator) does it in place, checkpointing every phase and validating afterwards. The live instance moved 0.15.5 → 0.16.19 with eight seconds of downtime and nothing lost.
## Quick start (Docker)
No Stalwart yet? [ihasmail-oneshot](https://github.com/Coffey-Labs/ihasmail-oneshot)
sets up both on one host in a single command. The steps below are for pointing
ihasmail at a Stalwart you already run.
```bash
cp .env.example .env
# edit: STALWART_URL=https://mail.example.com and APP_SECRET=$(openssl rand -base64 48)
docker compose up --build -d
# → http://localhost:8080 (put Caddy/nginx in front for TLS; see Caddyfile.example / nginx.example.conf)
```
Users sign in with their Stalwart mailbox credentials. **An account with
two-factor authentication needs an app password**, created in Stalwart's own
settings — Stalwart accepts a TOTP code only through an OAuth flow and offers no
password grant, so no client holding a username and password can exchange them
plus a code for a token.
Full instructions, TLS, and every environment variable:
[Installing](https://docs.ihasmail.org/install/) ·
[Configuring](https://docs.ihasmail.org/configure/).
### Container images
Published to GHCR on every release, for `linux/amd64` and `linux/arm64`.
Releases are cut weekly — Mondays, 09:00 UTC, in a week that had changes — so
the newest image is normally behind `main`:
```bash
docker pull ghcr.io/coffey-labs/ihasmail:latest
```
| Tag | What it is |
| --- | --- |
| `latest` | The newest release. Prereleases never move it |
| `2026.9.2-pr243` | One specific build — the [version](#version-numbers) with `+` written as `-`, because a Docker tag may not contain `+` |
Pin the dated tag in anything you care about. `latest` is a moving target by
definition, and rolling back to a named tag is a `docker run` rather than a
rebuild.
Building it yourself stays fully supported and is what `docker compose up
--build` above does — the image is a convenience, not a new requirement. If you
build by hand, pass the version in, because `.dockerignore` excludes `.git` and
the build cannot work out what it is:
```bash
docker build --build-arg IHASMAIL_VERSION="$(node scripts/version.mjs)" -t ihasmail:local .
```
### Running immutably
The server writes to exactly one path, the optional `SESSION_FILE`. Clear it
and there is nothing left to write, so the container can run with no writable
filesystem at all:
```bash
docker run --read-only --tmpfs /tmp -e IMMUTABLE=1 -e SESSION_FILE= ...
```
`IMMUTABLE=1` is an assertion the server checks at startup rather than a switch
that changes what it does: it refuses to start if `SESSION_FILE` is still set,
or if the filesystem it is installed on turns out to be writable after all.
Without it the same misconfiguration is silent — sessions are held in memory
and persisting them is best-effort, so a read-only `/data` costs one warning at
the first sign-in and nothing else until the instance is replaced and everyone
is signed out.
That sign-out is the standing cost of this mode today, since sessions have
nowhere to live across a restart. Removing it means moving the session upstream
into a token Stalwart itself issues and can revoke, which is what the OAuth work
in [ROADMAP.md](ROADMAP.md) is for.
### Several Stalwart servers
One ihasmail can front more than one Stalwart, choosing by the domain somebody
signs in with. **`STALWART_URL` stays required and stays the default**, so an
installation that sets nothing else behaves exactly as it always has.
```bash
-e STALWART_SERVERS_FILE=/etc/ihasmail/servers.json \
-v /srv/ihasmail/servers.json:/etc/ihasmail/servers.json:ro
```
```json
{
"example.com": "https://mail.example.com",
"customer-b.test": "https://jmap.customer-b.test"
}
```
[`stalwart-servers.example.json`](stalwart-servers.example.json) is that file
with the rules written in it.
A domain nobody listed — and a bare username, which Stalwart accepts and which
has no domain at all — goes to `STALWART_URL`. **A listed domain never falls
back.** If its server is unreachable that sign-in fails rather than retrying
against the default, because falling back would authenticate somebody against a
server their domain was deliberately routed away from; if the same account name
existed there they would land in another tenant's mailbox.
Read once at startup, so editing it means restarting the container. Malformed
JSON, a duplicate domain once lower-cased, or a value that is not an `http(s)`
URL stops the server rather than failing quietly at somebody's sign-in. The
servers themselves are not contacted at boot — a mapping is a routing table,
not a health check, and one customer's outage must not stop ihasmail starting
for everybody else.
This is one server per *person*, chosen at sign-in. Several servers at once for
one person, with unified or cross-account views, is not supported: JMAP account
ids are only unique within a server, so it would mean namespacing ids through
the proxy. Reading somebody else's mail, calendars or files on the *same* server
already works through JMAP sharing.
### Settings the installation decides
A deployment can seed and lock user settings, which is what a school wanting
"warn about outside senders" on for three thousand pupils needs — asking three
thousand pupils is not a plan.
```bash
-e SETTINGS_DEFAULTS='{"externalSenderBanner":true}' \
-e SETTINGS_ENFORCED='{"externalRecipientConfirm":true}'
```
Three powers, and the differences between them matter:
| Section | Applies to | Reader can change it |
| --- | --- | --- |
| `defaults` | accounts that have never had settings of their own | yes, at any time |
| `enforced` | everyone, on every load | no — the control goes dead |
| `changes` | everyone, **once each**, including existing accounts | yes, afterwards, and it stays changed |
`changes` is the one that needs explaining. It turns something on for people who
are *already here* — the reason a plain default is not enough — while still
leaving them the last word. Each entry carries its own `version`, which every
account remembers once it has had it, so the change is applied exactly once per
person and a reader who turns it back off keeps it off. It is a schema migration
in shape, and that is deliberately whose idea it was ([#207]).
Nothing is configured by default: an installation that sets none of these
behaves exactly as ihasmail always has.
### Passing a policy to Docker
Where a file is easier to manage than JSON quoted in a unit file — and it
usually is once there are `changes` in it — mount one and name it:
```bash
docker run -d --name ihasmail \
-e STALWART_URL=https://mail.example.org \
-e APP_SECRET="$(openssl rand -hex 32)" \
-e SETTINGS_POLICY_FILE=/etc/ihasmail/policy.json \
-v /srv/ihasmail/policy.json:/etc/ihasmail/policy.json:ro \
-p 8080:8080 ghcr.io/coffey-labs/ihasmail:latest
```
```json
{
"defaults": { "externalSenderBanner": true },
"enforced": { "externalRecipientConfirm": true },
"changes": [
{ "version": "20260902084513", "settings": { "externalSenderBanner": true } },
{ "version": "20261014091500", "settings": { "externalLinkWarning": true } }
]
}
```
[`settings-policy.example.json`](settings-policy.example.json) in this repo is
that file with every section explained in it — copy it and delete what you do
not want.
Mount it read-only: the server only ever reads it, and `:ro` keeps that true
under `--read-only` as well.
Or without a file at all, which is what an immutable deployment with no volume
wants:
```bash
docker run -d --name ihasmail --read-only --tmpfs /tmp \
-e IMMUTABLE=1 -e SESSION_FILE= \
-e STALWART_URL=https://mail.example.org \
-e APP_SECRET="$(openssl rand -hex 32)" \
-e SETTINGS_DEFAULTS='{"externalSenderBanner":true}' \
-e SETTINGS_ENFORCED='{"externalRecipientConfirm":true}' \
-e SETTINGS_CHANGES='[{"version":"20260902084513","settings":{"externalSenderBanner":true}}]' \
-p 8080:8080 ghcr.io/coffey-labs/ihasmail:latest
```
In `docker-compose.yml`:
```yaml
services:
ihasmail:
image: ghcr.io/coffey-labs/ihasmail:latest
environment:
SETTINGS_POLICY_FILE: /etc/ihasmail/policy.json
volumes:
- ./policy.json:/etc/ihasmail/policy.json:ro
```
A policy is read once at startup, so **editing it means restarting the
container**. There is no reload signal, deliberately: an installation-wide
setting changing under a running instance would be harder to reason about than
one that changes when you say so.
### Writing a policy
Both sections take the same names and values a settings export uses, so
`Settings → General → Export` on one account you have configured by hand is the
quickest way to write one — copy the keys you care about out of the file.
Three checks worth knowing about, because they fail loudly rather than quietly:
- **Malformed JSON stops the server at startup.** A policy that silently did not
apply is indistinguishable from the feature not working.
- **Every change needs a unique `version`.** Two changes sharing one, or a change
with no `version` or no `settings`, is a startup error.
- **Keys this build does not have are dropped**, the same rule an imported
settings file gets. A `changes` entry whose keys are *all* unknown is dropped
whole rather than recorded as applied, so it still runs on an ihasmail that
does have the setting.
Enforcement is applied in the settings store rather than only on the controls,
so an imported settings file, a settings file synced from a device that predates
the policy, and "reset to defaults" cannot get around it. Reset returns to your
defaults, not to ihasmail's.
[#207]: https://github.com/Coffey-Labs/ihasmail/issues/207
**Platform**
- Installable PWA (manifest + service worker), mobile layout with bottom tab bar, drawer navigation, full-screen composer, FAB
- **Default mail app**: register ihasmail as the browser's handler for `mailto:` links from Settings General (`registerProtocolHandler`; needs HTTPS and a browser that supports it — Safari does not). Installed as an app it also declares `protocol_handlers` in the manifest, which is what lets the operating system offer ihasmail wherever it asks for a mail client. Links arrive with recipients, Cc, Bcc, subject and body filled in
- **About** reports the Stalwart generation ihasmail detected (0.16+ or older) and the edition where the server gives one. Stalwart does not publish a version number to clients, so no version is shown rather than a made-up one
- Security: no credentials in the browser (server-side session with per-session encrypted upstream credentials), httpOnly SameSite cookies, CSRF header + Sec-Fetch-Site checks, strict CSP, sandboxed blob downloads, SSRF-safe image proxy, login rate limiting, security headers
## Architecture
@@ -361,25 +99,41 @@ browser ──(same-origin /api/*)──► ihasmail server (Node + Hono) ─
JMAP client + stores • /api/jmap, /api/blob, /api/upload, /api/events (SSE), /api/image
```
- `web/` — Vite + React 19 + TypeScript SPA. `src/jmap` (client, push, types), `src/store` (zustand: session, mail, compose, contacts, calendar, files, sieve, settings), `src/views`, `src/lib` (sanitiser, search parser, Sieve codec, locale-aware dates, vCard, …).
- `server/` — Node/Hono backend: authenticates against Stalwart's JMAP session endpoint, seals the credentials with a key derived from the cookie secret, proxies JMAP/blob/SSE, serves the SPA under a strict CSP. `src/mock/` is an in-memory fake Stalwart for development and demos.
- `web/` — Vite + React 19 + TypeScript SPA. `src/jmap` (client, push, types), `src/store` (zustand stores: session, mail, compose, contacts, calendar, files, sieve, settings), `src/views` (mail, compose, calendar, contacts, files, settings), `src/lib` (sanitiser, search parser, Sieve codec, dates and locale-aware formatting, vCard, …).
- `server/` tiny Node/Hono backend: authenticates against Stalwart's JMAP session endpoint, stores the credentials sealed with a key derived from the cookie secret (the server never persists plaintext passwords), proxies JMAP/blob/SSE calls, serves the SPA with a strict CSP. Also contains `src/mock/` an in-memory fake Stalwart for local development and demos.
Capabilities used: `core`, `mail`, `submission`, `vacationresponse`, `sieve`,
`contacts`(+`parse`), `calendars`(+`parse`), `principals`(+`availability`),
`quota`, `blob`, `filenode`, EventSource push, plus Stalwart's own
`urn:stalwart:jmap` (read-only). Features degrade gracefully when one is
missing.
Stalwart capabilities used: `core`, `mail`, `submission`, `vacationresponse`, `sieve`, `contacts`(+`parse`), `calendars`(+`parse`), `principals`(+`availability`), `quota`, `blob`, `filenode`, EventSource push, plus Stalwart's own `urn:stalwart:jmap` (read-only, for the account locale and to tell the generations apart). Features degrade gracefully when a capability is missing.
## Quick start (Docker)
```bash
cp .env.example .env
# edit: STALWART_URL=https://mail.example.com and APP_SECRET=$(openssl rand -base64 48)
docker compose up --build -d
# → http://localhost:8080 (put Caddy/nginx in front for TLS; see Caddyfile.example / nginx.example.conf)
```
Users sign in with their Stalwart mailbox credentials (TOTP codes are supported via the "two-factor code" field, which Stalwart accepts as `password$code`).
## Development
Requirements: Node ≥ 20.19 (26 recommended), npm ≥ 10.
Requirements: Node ≥ 20.10 (22 recommended), npm ≥ 10.
```bash
npm install
npm run dev # real Stalwart (STALWART_URL in .env) — server :8080, Vite :5173
npm run dev:mock # built-in mock Stalwart ([email protected] / demo), mock on :8788
npm run dev:mock:no-future-release # mock that advertises FUTURERELEASE and drops every hold
# against a real Stalwart (set STALWART_URL in .env or the environment)
npm run dev # server on :8080 (tsx watch) + Vite dev server on :5173 (proxying /api)
# against the built-in mock Stalwart ([email protected] / demo) — no real mailbox needed
npm run dev:mock # mock on :8788, server on :8080, Vite on :5173
# the same, with the mock impersonating Stalwart 0.15 instead of 0.16
npm run dev:mock:legacy
# the same, with the mock advertising FUTURERELEASE but dropping every hold —
# the shape of a real server whose `futureRelease` setting was never turned on
npm run dev:mock:no-future-release
npm run typecheck # tsc for both packages
npm test # vitest (web) + node:test (server)
@@ -387,98 +141,107 @@ npm run build # web/dist + server/dist
npm start # serve the production build
```
Open http://localhost:5173 in dev, or http://localhost:8080 for the production
build. Running it for real is covered in
[Installing](https://docs.ihasmail.org/install/) and
[Configuring](https://docs.ihasmail.org/configure/).
Open http://localhost:5173 in dev (or http://localhost:8080 for the production build).
### The mock
### The mock, and which Stalwart it pretends to be
An in-memory fake Stalwart 0.16 — enough JMAP to develop and demo against
without a real mailbox. It reproduces the things a naive fake would get wrong,
because each cost a live debugging session: `urn:stalwart:jmap` advertised
**per-account** rather than session-level, identity signatures capped at 2047
**bytes**, and `CalendarEvent/set` speaking Stalwart's vocabulary rather than
RFC 8984's. Four switches: `MOCK_NO_FUTURE_RELEASE=1` advertises FUTURERELEASE
and then drops every hold; `MOCK_NO_REGISTRY=1` omits the Stalwart capability so
the sign-in refusal can be tested; and `MOCK_NO_SCHEDULING_SEND=1` refuses a
calendar write that asks for scheduling messages, the way an account without
that permission is refused; and `MOCK_ROLE` decides who the demo user is for
Administration — `admin` (the default), `tenant-admin`, `helpdesk` or `user`.
`npm run mock` impersonates **0.16** by default; `MOCK_STALWART=0.15` (or
`npm run mock:legacy`) impersonates the generation before the registry. The
older mode is not a smaller mock — it reproduces the specific ways that
generation differs, none of which the server reports as an error:
It tracks the current release rather than 0.16 in general, and each behaviour
is confirmed against a real server before it is copied here — the comments say
which version and on what date. Where a release changes something a client can
see, the mock changes with it, and the test that pinned the old behaviour is
rewritten rather than deleted, so the reversal stays on the record.
- `urn:stalwart:jmap` is not a capability it knows, and naming one it cannot
parse fails the **whole request**, not the one call that wanted it. On 0.16
it *is* known — but advertised per-account, in `primaryAccounts` and each
account's `accountCapabilities`, never in the session-level `capabilities`.
Stalwart validates `using` by parsing the urn rather than looking it up in
the session, so naming it works regardless; a client that tests for it in
the obvious place, though, mistakes every 0.16 server for an older one
- `x:` methods do not exist, so the registry — credentials, account settings —
is unreachable, and self-service credentials live at `POST /api/account/auth`
- `FileNode/query` masks its results to non-containers, so it returns files and
**never folders**, silently; `FileNode/get` has no such mask
- FileNode has no `nodeType` (a directory is a node with no file properties),
and rights are only `mayRead`/`mayWrite`/`mayShare`
### Version numbers
Both modes enforce the 2047-**byte** cap on identity signatures. Every one of
these cost a live debugging session against a real 0.15.5 server, because the
0.16-shaped mock could not express them; `server/src/account-legacy.test.ts`
now pins them.
`ihasmail v2026.8.30+pr129` — the date of the commit this was built from, and
the pull request that commit arrived through. A commit that did not arrive
through one carries its short SHA instead: `2026.8.30+g1fa6578`. It all comes
from git at build time; nothing writes a version into the tree, and
`package.json` sits at `0.0.0` because it is no longer the source of anything.
## Configuration
The date is the commit's own rather than today's, so rebuilding an old commit
gives the version it had the first time.
All configuration is via environment variables (see `.env.example`):
```bash
node scripts/version.mjs # the version for the current checkout
docker build --build-arg IHASMAIL_VERSION="$(node scripts/version.mjs)" -t ihasmail:2026.8.30 .
```
| Variable | Default | Description |
| --- | --- | --- |
| `STALWART_URL` | `https://mail.example.com` | Base URL of Stalwart; the JMAP session is discovered at `/.well-known/jmap` |
| `APP_SECRET` | *(required in production)* | Secret used to derive session encryption keys |
| `PORT` / `HOST` | `8080` / `0.0.0.0` | Listen address |
| `TRUST_PROXY` | `1` | Honour `X-Forwarded-*`, but only from a peer listed in `TRUSTED_PROXIES` |
| `TRUSTED_PROXIES` | *(loopback + private ranges)* | Comma-separated CIDRs or addresses whose forwarding headers are believed. Anything else is attributed by its socket address, whatever it claims |
| `SECURE_COOKIES` | `auto` | `auto` (Secure on https), `1`, or `0` for plain-HTTP dev |
| `SESSION_TTL` / `SESSION_REMEMBER_TTL` | `43200` / `2592000` | Idle session lifetime (seconds), with/without "keep me signed in" |
| `SESSION_FILE` | *(unset)* | Persist sessions across restarts (ciphertext only) |
| `IMAGE_PROXY` | `1` | Route remote images through the privacy proxy |
| `MAX_UPLOAD_BYTES` | `52428800` | Upload size limit (Stalwart has its own limit too) |
| `APP_NAME` | `ihasmail` | Branding |
`.dockerignore` excludes `.git` deliberately, so an image build cannot work this
out for itself — pass it in. Left out, the build reports `0.0.0`, which is meant
to look wrong: a version with no `+pr` or `+g` means whoever built the image did
not pass one.
## Keyboard shortcuts
The version says nothing about Stalwart, deliberately. It used to: `2.16.x` had
`16` for the 0.16 generation it targeted, which leaves nowhere to go once
Stalwart reaches 1.0 — `2.1` sorts *below* the `2.16` already deployed, so every
image and About screen would read as a downgrade. Which Stalwart a build needs is
stated where it can be precise, in the badge at the top of this file and in
[KNOWN-ISSUES.md](KNOWN-ISSUES.md), rather than compressed into one digit.
Press `?` anywhere. Highlights: `c` compose · `/` search · `j`/`k` navigate · `o`/`Enter` open · `u` back · `e` archive · `#` delete · `!` spam · `s` star · `r`/`a`/`f` reply/reply-all/forward · `v` move · `l` label · `x` select · `⇧I`/`⇧U` read/unread · `g i` inbox · `g l` calendar · `g c` contacts · `Ctrl+Enter` send.
The pull request lives after the `+`, as build metadata, because it is
provenance rather than a rank: at the rate they merge here it climbs without
bound and says nothing about how new a build is. Everything after the `+` is
ignored when versions are compared, which is the right reading — two builds from
the same day differ in where they came from, not in age. Nothing here depends on
that comparison: images are pruned oldest-first by creation time, and a rollback
names a git ref.
## Known issues / pending QA
### Deploying
The live instance ran **0.15.5** until 2026-08-25 and runs **0.16.19** now,
so both generations have been exercised against a real server. Everything
below says which.
[`deploy.example.sh`](deploy.example.sh) is a single-host Docker deploy: it
fetches, refuses anything held back by `.deploy-hold`, shows what is about to be
introduced and asks, rebuilds with the right version baked in, replaces the
container, waits for healthy, then prunes all but the newest
`IHASMAIL_KEEP_VERSIONS` images — never the one actually running.
Verified against a live **0.15.5**: the mail flows, self-service credentials
over the REST path, Files, and signatures.
```bash
./deploy.sh # origin/main, asks before shipping new commits
./deploy.sh --dry-run # run the guards and stop
./deploy.sh v2026.8.30 --yes # a named ref, no prompt (there is no tty over ssh)
```
The 0.16 registry path was previously recorded here as verified live. That
was wrong, and the entry below says why: ihasmail looked for
`urn:stalwart:jmap` in the session-level capabilities, where Stalwart has
never put it, so **every** real 0.16 server was taken for a pre-0.16 one.
Self-service credentials went to a REST endpoint 0.16 had removed, About
reported the wrong generation, and Files ran on the older code path. The mock
advertised the capability in the wrong place too, which is why nothing caught
it. Fixed, and the mock now advertises it where the real server does — but
the registry path is **awaiting live re-verification**.
`--yes` does not override a hold; clearing one means deleting its line.
- **Read receipts are built here, not by the server** — JMAP has an extension for them, [RFC 9007](https://www.rfc-editor.org/rfc/rfc9007.html)'s `MDN/send`, and Stalwart does not implement it: `urn:ietf:params:jmap:mdn` is not among its capabilities. So ihasmail assembles the `multipart/report` itself and sends it the long way round — raw MIME uploaded as a blob, `Email/import`, then `EmailSubmission` — which is also why the receipt lands in Sent, where it honestly belongs. Non-ASCII parts are base64 rather than `8bit`, so nothing depends on 8BITMIME surviving every hop. There is deliberately no "always send" setting: a receipt confirms to whoever asked that the address is live and when it was read, to an address of the sender's choosing, so each one is a decision. Verified against the mock end to end (upload, import, submit, `$mdnsent`); **not yet exercised against the live server**.
- **Where 0.16 advertises `urn:stalwart:jmap`** — not where a JMAP client would look. Stalwart builds the session-level `capabilities` from a fixed list (`Session::new`, plus WebSocket) that has never contained this capability, in any 0.16.x from 0.16.0 to 0.16.19. It hands it out per-account instead, so it appears in `primaryAccounts` and in each account's `accountCapabilities`. ihasmail tested for it in `capabilities` alone, which made every real 0.16 server read as pre-0.16 — and that one check drove three things: self-service credentials fell back to `POST /api/account/auth`, which 0.16 removed, so password changes, 2FA and app passwords all failed with "this mail server does not offer self-service credential management"; About reported the wrong generation; and Files took the pre-0.16 code path. It now looks in all three places. Two related soft spots went with it: a transport error while probing the registry no longer downgrades a server to the legacy REST path (which would have posted the current password to an endpoint that is not there), and a locale request that is merely refused no longer discards a generation the capability had already settled.
- **HTML signatures** — Stalwart caps a signature at 2047 **bytes** (`value.len() < 2048` on a Rust string, so UTF-8 bytes, not characters). ihasmail compacts pasted HTML, moves images to Files and, if still too large, keeps the full signature in Files behind a short marker; other clients see a text fallback. Confirmed live on 0.15.5 (2026-08-24): oversized, non-ASCII and inline-image signatures all save, and a test message arrived intact at Gmail with the logo inline.
- **Files on Stalwart before 0.16** — three things differ there, none of which the server reports as an error. (Confirmed live on 0.15.5 before the upgrade. The live instance now runs 0.16.19, where folder creation, upload, rename, move and delete were also exercised — but under the capability-placement bug below, which means what ran there was this older path against a 0.16 server, not the 0.16 path. Files now takes the 0.16 path and wants checking again on its own terms. The older path is kept for anyone still on 0.15.x and covered by `npm run dev:mock:legacy`.) `FileNode/query` masks its results to non-containers, so it returns files and **never folders**; `nodeType` does not exist, and sending it fails the create outright (a directory is instead a node with no file properties at all); and rights are only `mayRead`/`mayWrite`/`mayShare`, so the finer-grained `mayDelete`/`mayRename` the UI gates on are absent. ihasmail detects the older server by the absence of `urn:stalwart:jmap` — looked for in `primaryAccounts` and `accountCapabilities` as well as the session capabilities, since that is where 0.16 actually advertises it — lists the tree through `FileNode/get` instead of query, shapes creates accordingly, and widens the old rights. Upload, folder creation, listing, rename, move and delete are all confirmed live on 0.15.5 (2026-08-24).
- **Self-service credentials** — the **0.15.x REST path was confirmed live** against Stalwart 0.15.5 (2026-08-24): password change, app passwords, and enabling and disabling 2FA, on a real mailbox. The **0.16 registry path is confirmed live** against Stalwart 0.16.19 (2026-08-25): app passwords created and revoked, password changed, 2FA enabled and disabled, with the browser session surviving the switch to an app password. The mock enforces the same rules either way (current password required, password policy, a TOTP code on every request once 2FA is on, app passwords exempt from it). Password changes are refused by Stalwart for accounts backed by an external directory (LDAP/SQL/OIDC); the server's own message is shown when that happens.
- **Scheduled send needs one setting turned on, and says nothing when it is off.** Stalwart advertises the delay in the account's `urn:ietf:params:jmap:submission` capability — `maxDelayedSend: 2592000` (30 days) and `FUTURERELEASE` among its `submissionExtensions`, and note it is the *account* capability, not the session-level one, which is empty. But the MTA only honours a hold when `futureRelease` is set under the session's MTA extensions, and [that setting defaults to `false`](https://stalw.art/docs/ref/object/mta-extensions/). With it off, Stalwart takes the `HOLDUNTIL` parameter, skips the hold and sends the message immediately **without an error** — the capability still says thirty days. So set `futureRelease` (to the longest hold you want to allow) before relying on this; a value shorter than 30 days is fine, and a request past it is refused honestly, with a `forbiddenMailFrom` naming the limit. `npm run dev:mock:no-future-release` reproduces the silent-drop case. ihasmail asks for the delay the way JMAP requires — a `HOLDUNTIL` parameter on the envelope's `mailFrom`, since RFC 8621 makes `sendAt` read-only and server-derived — and files the held message in a **Scheduled** folder, because `onSuccessUpdateEmail` would otherwise drop it in Sent the moment the submission is created. Nothing moves it out when the hold expires, so ihasmail reconciles the folder on the way in: released messages to Sent, cancelled ones back to Drafts. Three fixes this depends on landed in **0.16.17**, below the live instance's 0.16.19: `HOLDUNTIL` taking RFC 3339 date-times again (0.16.16 had it wanting Unix timestamps), `EmailSubmission/query` on `undoStatus` agreeing with `/get` about held submissions, and `EmailSubmission/get` without `ids` iterating the right index. The hold itself is now **confirmed against the live 0.16.19** (2026-08-25), once `futureRelease` was set to `30d` there: a submission carrying a `HOLDUNTIL` ten minutes out came back `pending`, with `sendAt` equal to the time asked for and a `250 2.1.5 Queued` from the MTA, rather than going out at once. Worth repeating that the capability is no evidence either way — it advertised `maxDelayedSend: 2592000` and `FUTURERELEASE` while the setting was still off. Only a submission tells you. What is still mock-only is the rest of the journey: the **Scheduled** folder reconciling on the way in, and a hold actually expiring and being delivered.
- **Stalwart 0.16 and RFC 8984 disagree about the calendar vocabulary, and the server only says so half the time.** A participant's address lives in `calendarAddress`, not RFC 8984's `sendTo`/`email`; the organizer is `organizerCalendarAddress`, not `replyTo`; and a recurrence is a single `recurrenceRule`, not a `recurrenceRules` array. Addressed the RFC's way, `CalendarEvent/set` **keeps the event and discards the whole participant map without an error** — guests disappeared on save and no invitation was ever sent, which is what [#26](https://github.com/LINUXexpert-org/ihasmail/issues/26) reported. The array form of the rule is refused honestly, with `invalidProperties`, so recurring events could not be created at all and existing ones showed no repeat ([#30](https://github.com/LINUXexpert-org/ihasmail/issues/30)). ihasmail now writes Stalwart's names and reads either, and the mock refuses what the real server refuses, since advertising the RFC spelling is precisely how this got as far as a live server. Verified against 0.16.19 on 2026-08-25, end to end: participants, organizer and rule all survive a create, an update and a re-read; an invitation to an external Gmail address arrived as an invite card, and the decline came back and was applied to the event (`needs-action``declined`, sequence 1). Cancelling the event notified the guest too. Adding guests to an event that had none, and clearing them again with `null`, both work on the update path, as does RSVP — which patches `participants/{key}/participationStatus` (and `participationComment`) rather than sending the whole map. That patch has to be aimed at the base event: `CalendarEvent/set` refuses a synthetic id with *"Updating synthetic ids is not yet supported"*, which is why RSVP resolves `baseEventId` first. Adding a *new* participant by patch is refused as well (`Patch operation failed`), so a changed guest list is written as the whole `participants` property. One more thing to know when reading this code: an expanded occurrence carries a `recurrenceId` but *no* rule of its own, and `baseEventId` is set on everything an expanded query returns — a one-off included, whose own id differs from its base — so neither is a test for recurrence.
- Recurring events: colour/category/edit/delete apply to the whole series (per-occurrence overrides aren't supported by the server yet).
- Editable date boxes are always Gregorian and in Latin digits, even for locales whose *display* uses another calendar or numbering system (`fa-IR`, `th-TH`, `ar-EG`) — they keep the locale's field order and separator, but a Buddhist-era year in a text box does not round-trip against the Gregorian calendar grid. Non-Gregorian calendar support is not implemented.
- The account locale is read from `x:AccountSettings/get`, whose permission the built-in user role has, falling back to `x:Account/get` (which needs the admin-only `sysAccountGet`). Both are Stalwart 0.16 methods: **on older servers neither is reachable** — they do not implement the registry and reject a request that so much as names the `urn:stalwart:jmap` capability — so there the locale still falls back to the browser's and can be chosen by hand. Confirmed live on 0.16.19 (2026-08-25), once the capability was looked for where Stalwart advertises it; a locale request that is merely refused no longer downgrades the detected generation.
## Contributing
## Roadmap / not yet
[CONTRIBUTING.md](CONTRIBUTING.md) · [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) ·
[SECURITY.md](SECURITY.md) — please report vulnerabilities privately.
- Snooze (nothing in JMAP or Stalwart supports it, and ihasmail never stores a password, so nothing could act on a mailbox while you are away)
- Translations (strings are English-only for now)
## License
Copyright (C) 2026 Coffey Labs — AGPL-3.0-or-later. See
[LICENSE](LICENSE).
Copyright (C) 2026 LINUXexpert.org
ihasmail was relicensed from GPL-3.0 to AGPL-3.0 on 2026-08-25: webmail is
nearly always run as a network service rather than handed to anyone as a binary,
and the AGPL's section 13 closes that gap.
ihasmail is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version. See [LICENSE](LICENSE) for the full text.
ihasmail was relicensed from GPL-3.0 to AGPL-3.0 on 2026-08-25. Webmail is
nearly always run as a network service rather than handed to anyone as a
binary, and the AGPL's section 13 closes that gap: anyone running a modified
ihasmail for other people has to offer them its source, which the GPL alone
does not require.
That offer has to point at *your* source, not this one. If you run a modified
ihasmail, set `SOURCE_URL` to your own repository the sign-in page and
Settings About both show it. See
[Rebranding](https://docs.ihasmail.org/rebranding/).
ihasmail, set `SOURCE_URL` to your own repository: the sign-in page and
Settings About both show it, so the people using your instance are told where
the code they are actually running can be found.
-33
View File
@@ -1,33 +0,0 @@
# Roadmap / not yet
Things ihasmail does not do, and why. An issue number here says where the entry
came from, not that it is tracked elsewhere — a report can be closed because the
bug in it was fixed while the larger thing it asked for stays on this page. What
is genuinely open lives in [the issue tracker](https://github.com/Coffey-Labs/ihasmail/issues);
the rest is here because the answer is "no", not "not yet".
See [KNOWN-ISSUES.md](KNOWN-ISSUES.md) for what is built but worth knowing about.
- **Administration beyond accounts and domains.** The Administration menu manages accounts and domains today — see [FEATURES.md](FEATURES.md#administration). Groups, mailing lists, roles, DNS and ACME providers and tenants are Stalwart registry objects behind the same permission model, and each is a section to add rather than a design to invent; so is switching a domain's DNS, DKIM or certificate management, which is shown but not yet changed from ihasmail. Reporting, queues, logs and server settings are not planned: they are operating the server, which is Stalwart's own interface's job, not managing the people on it.
- **Sharing a mail folder.** Stalwart stores the share and never delivers it; see [KNOWN-ISSUES.md](KNOWN-ISSUES.md). Withdrawn until the server does something with it. Sharing files, calendars and address books is unaffected and works.
- **A scheduling view of its own**, for asking "when is everyone free next week?" without an event in hand. The grid itself is built and lives in the event editor — a row per participant, steppable, and clickable to place the event — which is where the question gets asked while you are arranging something. What is not built is the same thing as a destination you can visit with nothing in progress. Came out of [#172](https://github.com/Coffey-Labs/ihasmail/issues/172), which asked for a separate view and is closed by the panel: the reasoning for putting it in the editor is that a separate surface can only ever tell you a time you then retype, whereas one beside the event can set it. It stays here rather than in the tracker because nobody has yet said they want to ask the question on its own.
- **Per-message actions from the message list on a touchscreen.** Reply, Forward and compose-as-new are on the list row's context menu, which is a right-click — and holding a row on a phone starts selection instead, so none of them are reachable there. They are all available inside a thread, which is where the actions on a single message belong; what is missing is the shortcut from the list. Fixing it means deciding what a long press should do when it already means something, which is a bigger question than the actions themselves.
- Snooze (nothing in JMAP or Stalwart supports it, and ihasmail never stores a password, so nothing could act on a mailbox while you are away)
- **A translation anybody has checked.** The translations themselves shipped on 2026-08-31 and are no longer on this page: nine of them, alongside English, and the extraction that had always been the hard half is done — see [FEATURES.md](FEATURES.md#interface-language). What is *not* done is the other half, and it is the half that cannot be bought or automated. All nine were produced by AI against standard dictionaries and **not one has been read by anybody who speaks the language**, which is exactly where a bad translation does harm rather than merely looking untidy. They ship marked Beta, with that said in Settings and a link for reporting anything wrong, because shipping them quietly would ask people to trust text nobody has checked. A language loses the Beta mark when a speaker reads it and says so — a deliberate act by a person, not something a coverage percentage earns. If you speak one of them and are willing to read a few hundred strings, that is the single most useful thing anyone could contribute right now.
- **Right-to-left languages.** Arabic, Hebrew and Persian are held back deliberately, and not for want of translators. RTL is bidi and layout work throughout — mirrored panes, gesture directions, icon sides, the message list's own geometry — and a catalogue without it produces a page that is translated and unusable. Adding one is not another entry in the picker.
- **Two-factor sign-in.** Today an account with 2FA must use an app password (see [Quick start](README.md#quick-start-docker)), and Settings Security offers no way to switch 2FA *on* — only off, for an account that already has it. Supporting a TOTP code directly means implementing OAuth: Stalwart offers the authorization-code and device flows and no password grant, so ihasmail would hand sign-in to Stalwart's own login and come back with a token. That is a better security posture than the sealed password it holds now — a refresh token rather than a credential — but it replaces ihasmail's own sign-in page for those users and may need an OAuth client registered. Came out of [#75](https://github.com/Coffey-Labs/ihasmail/issues/75), which is closed: what was reported there was a sign-in refused with nothing but "Invalid credentials", and that was fixed by saying what is actually happening and pointing at app passwords. The OAuth work it uncovered is tracked here rather than as an open issue, so there is no ticket to watch for it.
- **Signing and encrypting mail.** *Reading* a signature is built: S/MIME signed mail is checked as it is read, and the signer is remembered so a change is called out — see [Checking a signature](FEATURES.md#checking-a-signature). What is not built is anything that produces a signature or touches ciphertext, and the reason is not Stalwart. This is client work over the message body: JMAP hands over the MIME blob and the rest is ours.
The blocker is a security model, not code, and it is the same one it has always been. Signing and decrypting need a **private** key in a page served by the same host that would handle it, which runs straight into two things ihasmail says about itself: that it never stores a credential, and that it runs immutably with nowhere to keep one. Verifying needed none of that — the certificate travels inside the message — which is exactly why it could be built first and why it went first.
**OpenPGP signatures are not checked, and this is a harder problem than it looks.** A PGP signature does not carry the key, so verifying one means having the sender's public key already. ihasmail has no source for it: `x:PublicKey` is the account's *own* registry, and fetching from a keyserver or WKD would tell a third party who you correspond with, which is precisely the leak the image proxy exists to close. A local store of correspondents' keys is possible and is not a small feature; nobody has asked for it yet.
*Managing* keys — publishing your own to `x:PublicKey` — has been built twice ([PR #67](https://github.com/Coffey-Labs/ihasmail/pull/67), [PR #285](https://github.com/Coffey-Labs/ihasmail/pull/285)) and withdrawn twice, because a Settings page for keys nothing uses is furniture. That reasoning is now partly spent: something does use a key. But what signature checking uses is the certificate inside the message, not anything in the registry, so publishing your own key remains a feature waiting for a consumer.
**Encryption at rest is refused rather than deferred.** Stalwart offers it as `encryptionAtRest`, a field on `x:AccountSettings` beside `description`, `locale` and `timeZone` — there is no `x:EncryptionAtRest` object whatever the docs suggest, and its value is a typed object (`{"@type": "Disabled"}`) rather than a bare string. It is self-service, needs no administrator, and would be easy to offer. It will not be: turning it *off does not decrypt what is already there*. Every message delivered while it was on stays encrypted on disk, readable only by a client holding the private key, so switching it on is a one-way door — and a toggle that reads as "make my mail safer" while quietly being irreversible is the wrong thing to hand an ordinary user.
**Why S/MIME rather than OpenPGP, and why neither is urgent.** End-to-end encrypted mail never reached the mainstream and is not on its way there: as a share of the world's email, PGP-encrypted messages are a rounding error, and the most successful use of OpenPGP is signing packages rather than sending mail. The reasons are structural rather than a matter of better tooling. Everyone in a thread has to take part, so the network effect works against it from the first reply. Key discovery was never solved — keyservers were unauthenticated and got weaponised in the 2019 certificate-flooding attacks, which made specific people's keys unusable by any client that fetched them, and WKD is better without being universal. There is no forward secrecy, so one compromised key retroactively opens everything ever received. The metadata stays in the clear: subject lines are cleartext in classic PGP/MIME, and who corresponded with whom is often the sensitive part. Losing a key loses the mail permanently. And it breaks the client — no server-side search, degraded spam filtering, awkward on a phone — while EFAIL showed in 2018 that the clients themselves were exploitable through MIME and HTML handling. Meanwhile the actual privacy win arrived invisibly and without anyone participating, in STARTTLS, MTA-STS and DANE.
So if one of the two gets built here it is S/MIME, because it is the one that is *more* deployed in the places that pay for software: native in Outlook and Apple Mail, and routine in defence, healthcare, finance and government, where a CA issues and revokes certificates that an IT department can actually administer. The web of trust never became something anybody could run at scale.
Expect the asking to be far out of proportion to the using. A self-hosted webmail for Stalwart draws self-hosters, privacy-minded users and European SMEs, which is about the densest concentration of PGP users left alive — so this will be requested much more often than it would be used, and that is an argument for keeping it here, described honestly, rather than either building it on the strength of the requests or refusing it outright.
-274
View File
@@ -1,274 +0,0 @@
#!/bin/bash
# Redeploy ihasmail on a single-host Docker setup, from a git checkout.
#
# Copy it, or run it as-is and set the variables below in the environment.
# Nothing here is specific to any one host: the defaults describe the shape of
# a deployment rather than anyone's particular one.
#
# Usage: ./deploy.sh [git-ref] [-y|--yes] [-n|--dry-run]
#
# Three guards stand between a careless run and production:
#
# .deploy-hold commits that must not reach prod yet, one per line. If the
# target contains one that is not already deployed, the deploy
# is refused outright -- `--yes` does not override it. Clearing
# a hold means deleting its line, which is a deliberate edit.
#
# confirmation anything introducing new commits is listed first and has to
# be confirmed. Over SSH, where there is no terminal to answer
# on, that means passing --yes: a bare `deploy.sh` cannot ship
# whatever main happens to have picked up since the last
# release.
#
# --dry-run checks the hold list, says what it would deploy, and stops
# before building or touching the container. It does not ask
# for confirmation: there is nothing to agree to when nothing
# changes, and needing a terminal would make it useless over
# SSH -- which is where wanting to look before leaping is most
# likely.
#
# The container is replaced rather than restarted, because the image is rebuilt
# from the new checkout. Data lives in a named volume and survives that; the
# environment file is never read here, only handed to Docker.
set -euo pipefail
# --- what to deploy, and where ----------------------------------------------
# The checkout to deploy from. It must be a git clone: the version number is
# read from its history (see scripts/version.mjs).
APP="${IHASMAIL_APP:-$HOME/apps/ihasmail}"
# Environment file passed to the container. Keep it outside the repo's tracked
# files -- it holds APP_SECRET and the upstream URL. Never read by this script.
ENVF="${IHASMAIL_ENV:-$APP/.env.production}"
# Commits held back from production, one per line; blank or missing is fine.
HOLD="${IHASMAIL_HOLD:-$APP/.deploy-hold}"
# Container name, and where to publish it. The default binds to loopback only,
# for a reverse proxy in front (see Caddyfile.example / nginx.example.conf).
NAME="${IHASMAIL_NAME:-ihasmail}"
BIND="${IHASMAIL_BIND:-127.0.0.1:8090}"
# Named volume for /data (sessions). Unused when running immutably.
VOLUME="${IHASMAIL_VOLUME:-ihasmail-data}"
# Run the container immutably: read-only root filesystem, no volume, sessions
# held in memory only. See "Running immutably" in the README. The server is told
# the same thing through IMMUTABLE=1 and checks it, so a half-applied switch --
# the flag without the read-only filesystem, or a SESSION_FILE still pointing
# somewhere -- refuses to start here instead of looking fine until the next
# redeploy signs everyone out.
#
# It defaults to on, and the reason is what happens when it does not. Forgetting
# the variable used to hand back a writable container with a volume mounted --
# quietly, and then report healthy. Nothing in the output said the immutability
# had gone; `docker inspect` was the only place it showed. So the safe posture
# is what you get by default, and giving it up is the half that has to be
# deliberate, which is the way round these two should always have been.
#
# The standing cost is that sessions do not outlive a deploy, because there is
# nowhere left to keep them. Going back is this variable and nothing else:
#
# IHASMAIL_IMMUTABLE=0 ./ihasmail-deploy.sh --yes
#
# The named volume is never touched either way, so whatever was in it when the
# switch was thrown is still there to come back to.
IMMUTABLE="${IHASMAIL_IMMUTABLE:-1}"
# Image repository. Each build is tagged with its version as well, so an
# earlier one can be run again without rebuilding it.
IMAGE_REPO="${IHASMAIL_IMAGE:-ihasmail}"
# How long to wait for the new container to report healthy, in seconds.
HEALTH_TIMEOUT="${IHASMAIL_HEALTH_TIMEOUT:-30}"
# How many past versions to keep as images, for rolling back to. Each is around
# 650 MB, and a deploy adds one, so left alone they accumulate a gigabyte every
# couple of releases -- and `docker image prune` will not touch them, because
# they are tagged. 0 keeps every version.
KEEP_VERSIONS="${IHASMAIL_KEEP_VERSIONS:-3}"
# --- run from a copy, if this script lives in the checkout it resets ---------
# `git reset --hard` below rewrites the working tree, and this script may be
# part of it. Bash does not read a script all at once -- it reads as it goes,
# by byte offset -- so a file replaced underneath it makes the shell stop
# wherever it had reached. Silently, and with exit status 0: a deploy that
# stopped halfway would report success. Re-exec from a copy outside the tree so
# the file being run cannot change while it runs.
SELF="$(readlink -f "$0")"
APP_REAL="$(readlink -f "$APP" 2>/dev/null || printf '%s' "$APP")"
if [ -z "${IHASMAIL_REEXEC:-}" ] && [ "${SELF#"$APP_REAL"/}" != "$SELF" ]; then
COPY="$(mktemp "${TMPDIR:-/tmp}/ihasmail-deploy.XXXXXX")"
cat "$SELF" > "$COPY"
chmod +x "$COPY"
IHASMAIL_REEXEC=1 exec "$COPY" "$@"
fi
# The copy has served its purpose once we exit; the shell has finished reading
# it by then.
if [ -n "${IHASMAIL_REEXEC:-}" ]; then
trap 'rm -f "$SELF"' EXIT
fi
REF=""
ASSUME_YES=0
DRY_RUN=0
for arg in "$@"; do
case "$arg" in
-y|--yes) ASSUME_YES=1 ;;
-n|--dry-run) DRY_RUN=1 ;;
-h|--help) awk 'NR > 1 { if (/^#/) print; else exit }' "$0"; exit 0 ;;
-*) echo "unknown option: $arg" >&2; exit 2 ;;
*)
if [ -n "$REF" ]; then echo "give at most one git-ref (got '$REF' and '$arg')" >&2; exit 2; fi
REF="$arg" ;;
esac
done
REF="${REF:-origin/main}"
cd "$APP"
git fetch --quiet origin
if ! TARGET=$(git rev-parse --verify --quiet "${REF}^{commit}"); then
echo "!! no such commit: $REF" >&2
exit 2
fi
CURRENT=$(git rev-parse --verify HEAD)
# --- guard 1: commits held back from production -----------------------------
if [ -f "$HOLD" ]; then
blocked=""
while IFS= read -r line || [ -n "$line" ]; do
line="${line%%#*}"
line="$(printf '%s' "$line" | tr -d '[:space:]')"
[ -z "$line" ] && continue
if ! held=$(git rev-parse --verify --quiet "${line}^{commit}"); then
echo " (hold list names '$line', which this checkout does not know -- ignoring)" >&2
continue
fi
# Only a problem if the target carries it and production does not already.
if git merge-base --is-ancestor "$held" "$TARGET" && ! git merge-base --is-ancestor "$held" "$CURRENT"; then
blocked="${blocked} $(git log --oneline -1 "$held")"$'\n'
fi
done < "$HOLD"
if [ -n "$blocked" ]; then
echo "!! refusing to deploy $REF: it contains commits held back from production:" >&2
printf '%s' "$blocked" >&2
echo " listed in $HOLD -- delete the line to clear the hold, or deploy a ref without it." >&2
exit 1
fi
fi
# --- guard 2: say what is being introduced, and get a yes --------------------
NEW=$(git log --oneline "$CURRENT..$TARGET")
if [ -n "$NEW" ]; then
echo "==> $(git log --oneline -1 "$CURRENT") -> $(git log --oneline -1 "$TARGET")"
echo "==> introduces:"
printf '%s\n' "$NEW" | sed 's/^/ /'
else
echo "==> already at $(git log --oneline -1 "$TARGET"); rebuilding"
fi
# A dry run has now said everything it has to say, so it stops here -- before
# the confirmation rather than after it. Asking whether to go ahead with
# something that is not going to happen is noise at a terminal; over SSH it was
# worse, because the refusal came out *instead of* the report above and a dry
# run could not be used from another machine at all. Which is the machine you
# are most likely to be on when you want one.
if [ "$DRY_RUN" -eq 1 ]; then
echo "==> dry run: would deploy $(git log --oneline -1 "$TARGET"); nothing was changed"
exit 0
fi
if [ -n "$NEW" ] && [ "$ASSUME_YES" -ne 1 ]; then
if [ -t 0 ]; then
read -r -p "deploy these to production? [y/N] " reply
case "$reply" in
y|Y|yes|YES) ;;
*) echo "aborted."; exit 1 ;;
esac
else
echo "!! refusing: this introduces new commits and there is no terminal to confirm on." >&2
echo " re-run with --yes if that is what you mean, or name the ref you want." >&2
exit 1
fi
fi
git reset --hard --quiet "$TARGET"
# The version is worked out here, from the checkout, because the image build
# cannot: .dockerignore keeps .git out of the build context. Without this the
# build falls back to the base version in package.json and every deployment
# reports the same number -- see "Version numbers" in the README.
# Drop the oldest versioned images, keeping the newest KEEP_VERSIONS of them.
#
# Only ever runs after the new container reports healthy, so a rollback target
# is never removed while the thing replacing it is still unproven. The image in
# use is excluded outright rather than relied on to sort newest -- docker
# refuses to remove an image a container is using, but being refused is not the
# same as not having tried.
prune_old_images() {
[ "$KEEP_VERSIONS" -gt 0 ] || return 0
local in_use stale
in_use="$(docker inspect "$NAME" --format '{{.Config.Image}}' 2>/dev/null || true)"
# Newest first, tags only, skipping the moving ":current" pointer.
stale="$(docker images "$IMAGE_REPO" --format '{{.Repository}}:{{.Tag}}\t{{.CreatedAt}}' \
| grep -v ":current" \
| sort -k2 -r \
| cut -f1 \
| grep -vxF "$in_use" \
| tail -n +"$((KEEP_VERSIONS + 1))")"
[ -n "$stale" ] || return 0
echo "==> removing $(printf '%s\n' "$stale" | wc -l) old image(s), keeping the newest $KEEP_VERSIONS"
printf '%s\n' "$stale" | xargs -r docker rmi >/dev/null 2>&1 || true
}
# The version is the same sum scripts/version.mjs does -- the commit's own
# date, plus the pull request it arrived through or its short SHA -- done here
# in shell because a host that only runs containers has git and docker and no
# node. Given IHASMAIL_VERSION, use it as given, as the script would.
version_from_git() {
local date subject sha y m d
date="$(git show -s --format=%cs HEAD)"
subject="$(git show -s --format=%s HEAD)"
sha="$(git rev-parse --short HEAD)"
IFS=- read -r y m d <<<"$date"
if [[ "$subject" =~ ^Merge\ pull\ request\ \#([0-9]+) ]]; then
printf '%d.%d.%d+pr%s\n' "$((10#$y))" "$((10#$m))" "$((10#$d))" "${BASH_REMATCH[1]}"
else
printf '%d.%d.%d+g%s\n' "$((10#$y))" "$((10#$m))" "$((10#$d))" "$sha"
fi
}
VERSION="${IHASMAIL_VERSION:-$(version_from_git)}"
# A Docker tag may not contain "+", and every version has one now:
# 2026.8.30+pr129, or +g1fa6578 for a commit that did not come through a pull
# request. The image is tagged with the "+" turned into "-"; what the build is
# *told* it is keeps the real form, so About and /api/health still report it
# correctly.
TAG="${VERSION//+/-}"
echo "==> building $(git log --oneline -1) as v$VERSION"
docker build \
--build-arg IHASMAIL_VERSION="$VERSION" \
-t "$IMAGE_REPO:$TAG" \
-t "$IMAGE_REPO:current" \
.
RUN_ARGS=(-d --name "$NAME" --restart unless-stopped -p "$BIND:8080" --env-file "$ENVF")
if [ "$IMMUTABLE" = "1" ]; then
# -e wins over --env-file, so this clears a SESSION_FILE set there or baked
# into the image, rather than needing the environment file edited to match.
RUN_ARGS+=(--read-only --tmpfs /tmp -e IMMUTABLE=1 -e SESSION_FILE=)
echo "==> restarting container -- immutable: read-only, no volume, sessions in memory"
echo " (everyone signed in is signed out; IHASMAIL_IMMUTABLE=0 puts it back)"
else
RUN_ARGS+=(-v "$VOLUME:/data")
echo "==> restarting container"
fi
docker rm -f "$NAME" >/dev/null 2>&1 || true
docker run "${RUN_ARGS[@]}" "$IMAGE_REPO:$TAG" >/dev/null
for _ in $(seq 1 "$HEALTH_TIMEOUT"); do
if health=$(curl -sf "http://$BIND/api/health"); then
echo "==> healthy: $health"
prune_old_images
exit 0
fi
sleep 1
done
echo "!! did not become healthy after ${HEALTH_TIMEOUT}s; logs:" >&2
docker logs "$NAME" 2>&1 | tail -20 >&2
echo "!! the previous image is still tagged, if you need it back:" >&2
docker images "$IMAGE_REPO" --format ' {{.Repository}}:{{.Tag}} {{.CreatedSince}}' | head -5 >&2
exit 1
+2 -9
View File
@@ -1,12 +1,6 @@
services:
ihasmail:
build:
context: .
args:
# Passed to the build as well as the run because the web bundle writes
# its own asset URLs: a build that does not know the prefix produces an
# app that cannot load itself under one. Empty is the domain root.
BASE_PATH: ${BASE_PATH:-}
build: .
image: ihasmail:2
restart: unless-stopped
ports:
@@ -15,8 +9,7 @@ services:
STALWART_URL: ${STALWART_URL:?set STALWART_URL in .env}
APP_SECRET: ${APP_SECRET:?set APP_SECRET in .env (openssl rand -base64 48)}
APP_NAME: ${APP_NAME:-ihasmail}
BASE_PATH: ${BASE_PATH:-}
SOURCE_URL: ${SOURCE_URL:-https://github.com/Coffey-Labs/ihasmail}
SOURCE_URL: ${SOURCE_URL:-https://github.com/LINUXexpert-org/ihasmail}
TRUST_PROXY: "1"
IMAGE_PROXY: "1"
volumes:
+1 -1
View File
@@ -13,7 +13,7 @@ const chrome = spawn("google-chrome-stable", [
"--headless=new", `--remote-debugging-port=${PORT}`, "--hide-scrollbars",
"--no-first-run", "--no-default-browser-check",
"--window-size=1420,790", "--force-device-scale-factor=1",
"--user-data-dir=/tmp/ihasmail-light-profile", "about:blank",
"--user-data-dir=/tmp/claude-light-profile", "about:blank",
], { stdio: "ignore" });
const json = async (p) => { for (let i = 0; i < 60; i++) { try { return await (await fetch(`http://127.0.0.1:${PORT}${p}`)).json(); } catch { await sleep(250); } } throw new Error("no chrome"); };
+1 -43
View File
@@ -11,11 +11,6 @@
* Restart the mock before a run. The filters shot creates rules, so a second
* run against the same mock shows them twice.
*
* The files shot was taken by hand until 2026-08-27, and had gone stale twice
* over by the time anyone noticed. Anything the docs show should be generated
* from the mock, or it describes whatever the app looked like on the day
* somebody had a screenshot tool open.
*
* Two shots are deliberately not taken here:
*
* - **mobile**, because at the tail of this sequence the app would not render
@@ -48,7 +43,7 @@ const PORT = 9333;
const chrome = spawn("google-chrome-stable", [
"--headless=new", `--remote-debugging-port=${PORT}`, "--hide-scrollbars",
"--no-first-run", "--no-default-browser-check", "--disable-gpu",
`--user-data-dir=/tmp/ihasmail-shots-profile`, "about:blank",
`--user-data-dir=/tmp/claude-shots-profile`, "about:blank",
], { stdio: "ignore" });
const json = async (path) => {
@@ -203,26 +198,6 @@ try {
})()`);
await sleep(1800);
await shot("compose.jpg");
// The recipient picker, taken here because the composer is already open. The
// site claims you can pick recipients by reading the address books rather
// than remembering a name, and this is that claim photographed. Doing it from
// a later step meant navigating back to the mail list, which turned out not
// to be reliable once the run had been through Files.
await evaluate(`(() => {
const b = [...document.querySelectorAll('button')].find(x => x.getAttribute('aria-label') === 'Choose from address books');
if (b) b.click();
})()`);
await waitFor("/Choose recipients/.test(document.body.innerText)", "the recipient picker");
await evaluate(`(() => {
// Two ticked, so the shot shows a selection rather than an empty list.
for (const b of [...document.querySelectorAll('.menu-item input[type=checkbox]')].slice(0, 2)) b.click();
})()`);
await sleep(1500);
await shot("recipients.jpg");
await evaluate(`(() => { const c = [...document.querySelectorAll('button')].find(b => b.textContent.trim() === 'Cancel'); if (c) c.click(); })()`);
await sleep(600);
await evaluate(`(() => { const c = [...document.querySelectorAll('button')].find(b => /close|discard/i.test(b.getAttribute('aria-label')||'')); if (c) c.click(); })()`);
await sleep(800);
@@ -252,23 +227,6 @@ try {
await sleep(1800);
await shot("contacts.jpg");
// --- files ---
// Was the one shot taken by hand, which is why it outlived two rewrites of
// the view it was meant to show. The tree makes it worth automating: opening
// a folder is now the difference between a screenshot of a file manager and a
// screenshot of a list.
await go("http://localhost:5173/files");
await waitFor("document.querySelector('.files-table, .files-layout')", "the files view");
await evaluate(`(() => {
// Expand the tree and open a folder, so the shot shows the pane doing its job.
const twisty = document.querySelector('.sidebar .nav-twisty');
if (twisty) twisty.click();
const folder = [...document.querySelectorAll('.sidebar .nav-item')].find(e => /Documents/.test(e.textContent || ""));
if (folder) folder.click();
})()`);
await sleep(1800);
await shot("files.jpg");
// --- filters, with rules that actually say something ---
await go("http://localhost:5173/settings/filters");
await evaluate(HELPERS);
Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 125 KiB

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

-25
View File
@@ -6,31 +6,6 @@ server {
client_max_body_size 60m;
# Compression. The bundle is the bulk of first load -- about 933 KB
# uncompressed against 311 KB gzipped -- and nginx passes through anything
# the upstream already encoded rather than re-encoding it, so this is
# correct whether or not ihasmail compresses on its own.
#
# text/event-stream is deliberately absent from gzip_types: the push stream
# must not be compressed or buffered, which is also why proxy_buffering is
# off below.
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 5;
gzip_min_length 1024;
# text/javascript is listed explicitly: ihasmail serves scripts with that
# type rather than application/javascript, so a conventional gzip_types
# list compresses the stylesheet and leaves the largest asset alone.
gzip_types
application/javascript
application/json
application/manifest+json
image/svg+xml
text/css
text/javascript
text/plain;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
+1714 -1126
View File
File diff suppressed because it is too large Load Diff
+5 -8
View File
@@ -1,6 +1,6 @@
{
"name": "ihasmail",
"version": "0.0.0",
"version": "2.0.0",
"private": true,
"description": "ihasmail \u2014 a fast, modern JMAP webmail for Stalwart Mail Server",
"license": "AGPL-3.0-or-later",
@@ -10,7 +10,7 @@
"web"
],
"engines": {
"node": ">=20.19"
"node": ">=20.10"
},
"scripts": {
"dev": "concurrently -n server,web -c blue,magenta \"npm run dev -w server\" \"npm run dev -w web\"",
@@ -21,14 +21,11 @@
"lint": "npm run typecheck",
"mock": "npm run mock -w server",
"dev:mock": "concurrently -n mock,server,web -c yellow,blue,magenta \"npm run mock -w server\" \"STALWART_URL=http://127.0.0.1:8788 npm run dev -w server\" \"npm run dev -w web\"",
"dev:mock:no-future-release": "concurrently -n mock,server,web -c yellow,blue,magenta \"npm run mock:no-future-release -w server\" \"STALWART_URL=http://127.0.0.1:8788 npm run dev -w server\" \"npm run dev -w web\"",
"i18n:coverage": "node scripts/i18n-coverage.mjs",
"i18n:check": "node scripts/i18n-catalog-check.mjs && node scripts/i18n-literals.mjs",
"dev:mock:no-keyword-sort": "concurrently -n mock,server,web -c yellow,blue,magenta \"npm run mock:no-keyword-sort -w server\" \"STALWART_URL=http://127.0.0.1:8788 npm run dev -w server\" \"npm run dev -w web\""
"dev:mock:legacy": "concurrently -n mock,server,web -c yellow,blue,magenta \"npm run mock:legacy -w server\" \"STALWART_URL=http://127.0.0.1:8788 npm run dev -w server\" \"npm run dev -w web\"",
"dev:mock:no-future-release": "concurrently -n mock,server,web -c yellow,blue,magenta \"npm run mock:no-future-release -w server\" \"STALWART_URL=http://127.0.0.1:8788 npm run dev -w server\" \"npm run dev -w web\""
},
"devDependencies": {
"concurrently": "^9.1.2",
"typescript": "^7.0.2",
"typescript-ast": "npm:typescript@^5.9.3"
"typescript": "^5.7.3"
}
}
-4
View File
@@ -1,4 +0,0 @@
/** Types for `basePath.mjs`, which is plain JS so both packages can import it. */
export function normalizeBasePath(value: string | undefined | null): string;
export function baseUrlOf(basePath: string | undefined | null): string;
export function stripBasePath(basePath: string | undefined | null, pathname: string): string | null;
-70
View File
@@ -1,70 +0,0 @@
/**
* The subpath ihasmail is mounted at, from `BASE_PATH`.
*
* Plain JS, and here rather than in either package, because both halves of the
* app have to agree on the answer: `web/vite.config.ts` bakes it into the built
* asset URLs and `server/src/config.ts` reads it again to decide where the
* routes live. Two implementations of "what does /mail/ mean" is exactly the
* bug where the server serves an app whose own script tags point somewhere
* else, and the page comes up blank with no clue why.
*
* The canonical form is a leading slash and no trailing one -- `/mail` -- with
* the empty string for the root. Empty is the ordinary case and it is chosen
* so that the concatenation `${base}/api/health` is right without a branch:
* anything with a trailing slash would need one, and every caller that forgot
* would produce `//api/health`, which browsers read as a *protocol-relative
* URL* and send to a host called `api`. Getting that wrong once, quietly, in
* one call site is worse than the small awkwardness of an empty string.
*/
/**
* Reduce whatever the operator wrote to the canonical form.
*
* Accepts `/mail`, `mail`, `/mail/`, `mail/`, `//mail//`, an empty string and
* undefined, because the variable is typed by a human into a compose file or a
* `docker run` line and every one of those is a reasonable thing to write.
* Being strict here would mean an instance that refuses to start over a
* trailing slash, which teaches nobody anything.
*
* A value of `/` means the root and is returned as empty, since `/` and `""`
* describe the same mount and only one of them can be the canonical one.
*/
export function normalizeBasePath(value) {
if (typeof value !== "string") return "";
// Collapse repeated separators before trimming: `//mail//` is a typo, not a
// path with empty segments in it, and `path.posix.normalize` is not
// available to the browser bundle that also uses this.
const trimmed = value.trim().replace(/\/+/g, "/").replace(/^\/|\/$/g, "");
if (!trimmed) return "";
return `/${trimmed}`;
}
/**
* The same value as a directory URL -- `/` or `/mail/`.
*
* This is the form Vite's `base` and the PWA scope want, both of which are
* about "the directory the app lives in" rather than a path to join onto.
*/
export function baseUrlOf(basePath) {
return `${normalizeBasePath(basePath)}/`;
}
/**
* Whether `pathname` falls inside the mount, and what is left of it if so.
*
* Returns null for anything outside, so a caller can 404 rather than guess.
* The bare mount with no trailing slash -- a request for `/mail` -- yields
* `/`, because that is the app's own index and typing the prefix without the
* slash is how people reach it.
*
* The comparison is deliberately not `startsWith(base)`: that would let
* `/mailbox` in under a `/mail` mount and serve it the app shell, which is
* both wrong and a small open door for a neighbouring site on the same host.
*/
export function stripBasePath(basePath, pathname) {
const base = normalizeBasePath(basePath);
if (!base) return pathname;
if (pathname === base) return "/";
if (pathname.startsWith(`${base}/`)) return pathname.slice(base.length);
return null;
}
-407
View File
@@ -1,407 +0,0 @@
#!/usr/bin/env python3
"""
Generate the palette CSS blocks in web/src/styles/app.css.
Every colour here comes from the palette's own project (all MIT); the values
are recorded in .palette-sources/palettes-upstream.md. What this script adds is
the *derivation*: ihasmail needs thirty-odd tokens and these projects publish
between twelve and twenty, so the tiers in between are computed rather than
guessed, and every text colour is then checked against the surface it sits on.
The check is the reason this is a script and not a hand-written block. ihasmail
claims WCAG AA, and several of these palettes do not meet it as published --
Dracula's comment grey on its own background is about 3.0:1, well under the 4.5
that normal text needs. Lifting those tiers by eye is how a claim quietly stops
being true; here it is arithmetic, and the script fails loudly if a token it
emitted would not pass.
Run: python3 scripts/build-palettes.py
"""
from __future__ import annotations
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CSS = ROOT / "web/src/styles/app.css"
BEGIN = "/* === generated palettes: begin === */"
END = "/* === generated palettes: end === */"
# ---------------------------------------------------------------- colour maths
def parse(hex_: str) -> tuple[float, float, float]:
h = hex_.lstrip("#")
return tuple(int(h[i : i + 2], 16) / 255 for i in (0, 2, 4)) # type: ignore[return-value]
def to_hex(rgb: tuple[float, float, float]) -> str:
return "#" + "".join(f"{max(0, min(255, round(c * 255))):02x}" for c in rgb)
def _lin(c: float) -> float:
return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
def luminance(hex_: str) -> float:
r, g, b = (_lin(c) for c in parse(hex_))
return 0.2126 * r + 0.7152 * g + 0.0722 * b
def contrast(a: str, b: str) -> float:
la, lb = luminance(a), luminance(b)
hi, lo = max(la, lb), min(la, lb)
return (hi + 0.05) / (lo + 0.05)
def mix(a: str, b: str, t: float) -> str:
ca, cb = parse(a), parse(b)
return to_hex(tuple(ca[i] + (cb[i] - ca[i]) * t for i in range(3)))
def rgba(hex_: str, alpha: float) -> str:
r, g, b = (round(c * 255) for c in parse(hex_))
return f"rgba({r}, {g}, {b}, {alpha})"
def toward_contrast(colour: str, bg: str, target: float, dark_ui: bool) -> str:
"""Nudge `colour` away from `bg` until it clears `target`.
Towards white on a dark background and towards black on a light one, so a
lifted tier keeps its hue instead of washing out to grey.
"""
if contrast(colour, bg) >= target:
return colour
anchor = "#ffffff" if dark_ui else "#000000"
best = colour
for i in range(1, 101):
candidate = mix(colour, anchor, i / 100)
best = candidate
if contrast(candidate, bg) >= target:
return candidate
return best
# ------------------------------------------------------------------- palettes
# Roles as each project publishes them. Nothing here is invented; see
# .palette-sources/palettes-upstream.md for where each value came from.
# ihasmail's own palette has a hand-written dark block further up the file --
# it is the identity this project is painted in, and regenerating it would
# quietly move colours nobody asked to move. Only its light half is derived
# here, which is why it appears in LIGHT_ONLY.
LIGHT_ONLY = {"ihasmail"}
SOURCES = {
"ihasmail": {
# Daylight over the same teal-navy: the dark palette's background
# becomes the text, so the two halves are recognisably one palette read
# from either end. The cat is still orange, so the star still is.
"light": dict(
bg="#f4f9f9", elev="#ffffff", sunken="#e7f1f2", line="#cfe2e4",
fg="#0d2430", muted="#4a6b74", accent="#46cac3", link="#0e7490",
danger="#dc2626", warn="#b45309", success="#15803d", star="#f9a34b",
q1="#0e7490", q2="#15803d", q3="#7c3aed",
),
"dark": {}, # see LIGHT_ONLY
},
"dracula": {
"dark": dict(
bg="#282a36", elev="#2f3140", sunken="#21222c", line="#44475a",
fg="#f8f8f2", muted="#6272a4", accent="#bd93f9", link="#8be9fd",
danger="#ff5555", warn="#ffb86c", success="#50fa7b", star="#f1fa8c",
q1="#8be9fd", q2="#50fa7b", q3="#ff79c6",
),
"light": dict( # Alucard
bg="#fffbeb", elev="#ffffff", sunken="#f6f1de", line="#cfcfde",
fg="#1f1f1f", muted="#6c664b", accent="#644ac9", link="#036a96",
danger="#cb3a2a", warn="#a34d14", success="#14710a", star="#846e15",
q1="#036a96", q2="#14710a", q3="#a3144d",
),
},
"gruvbox": {
"dark": dict(
bg="#282828", elev="#32302f", sunken="#1d2021", line="#504945",
fg="#ebdbb2", muted="#a89984", accent="#83a598", link="#8ec07c",
danger="#fb4934", warn="#fe8019", success="#b8bb26", star="#fabd2f",
q1="#83a598", q2="#b8bb26", q3="#d3869b",
),
"light": dict(
bg="#fbf1c7", elev="#f9f5d7", sunken="#f2e5bc", line="#d5c4a1",
fg="#3c3836", muted="#7c6f64", accent="#076678", link="#427b58",
danger="#9d0006", warn="#af3a03", success="#79740e", star="#b57614",
q1="#076678", q2="#79740e", q3="#8f3f71",
),
},
"rose-pine": {
"dark": dict( # main
bg="#191724", elev="#1f1d2e", sunken="#14121f", line="#26233a",
fg="#e0def4", muted="#908caa", accent="#c4a7e7", link="#9ccfd8",
danger="#eb6f92", warn="#f6c177", success="#31748f", star="#f6c177",
q1="#9ccfd8", q2="#31748f", q3="#c4a7e7",
),
"light": dict( # dawn
bg="#faf4ed", elev="#fffaf3", sunken="#f2e9e1", line="#dfd9d2",
fg="#464261", muted="#797593", accent="#907aa9", link="#286983",
danger="#b4637a", warn="#ea9d34", success="#56949f", star="#ea9d34",
q1="#286983", q2="#56949f", q3="#907aa9",
),
},
"tokyo-night": {
"dark": dict( # night
bg="#1a1b26", elev="#1f2130", sunken="#16161e", line="#363b54",
fg="#c0caf5", muted="#a9b1d6", accent="#7aa2f7", link="#7dcfff",
danger="#f7768e", warn="#e0af68", success="#9ece6a", star="#e0af68",
q1="#7dcfff", q2="#9ece6a", q3="#bb9af7",
),
"light": dict( # day
bg="#e6e7ed", elev="#f2f3f7", sunken="#d6d8df", line="#c1c2c7",
fg="#343b59", muted="#484c61", accent="#2959aa", link="#006c86",
danger="#8c4351", warn="#8f5e15", success="#385f0d", star="#8f5e15",
q1="#006c86", q2="#385f0d", q3="#65359d",
),
},
"catppuccin": {
"dark": dict( # Mocha
bg="#1e1e2e", elev="#313244", sunken="#181825", line="#45475a",
fg="#cdd6f4", muted="#a6adc8", accent="#cba6f7", link="#89b4fa",
danger="#f38ba8", warn="#fab387", success="#a6e3a1", star="#f9e2af",
q1="#89b4fa", q2="#a6e3a1", q3="#f5c2e7",
),
"light": dict( # Latte
bg="#e6e9ef", elev="#eff1f5", sunken="#dce0e8", line="#ccd0da",
fg="#4c4f69", muted="#6c6f85", accent="#8839ef", link="#1e66f5",
danger="#d20f39", warn="#fe640b", success="#40a02b", star="#df8e1d",
q1="#1e66f5", q2="#40a02b", q3="#ea76cb",
),
},
"solarized": {
"dark": dict(
bg="#002b36", elev="#073642", sunken="#001f28", line="#0d4552",
fg="#839496", muted="#586e75", accent="#268bd2", link="#2aa198",
danger="#dc322f", warn="#cb4b16", success="#859900", star="#b58900",
q1="#2aa198", q2="#859900", q3="#6c71c4",
),
"light": dict(
bg="#fdf6e3", elev="#fffdf6", sunken="#eee8d5", line="#e6dfc8",
fg="#657b83", muted="#93a1a1", accent="#268bd2", link="#2aa198",
danger="#dc322f", warn="#cb4b16", success="#859900", star="#b58900",
q1="#2aa198", q2="#859900", q3="#6c71c4",
),
},
"ayu": {
"dark": dict(
bg="#0d1017", elev="#10141c", sunken="#070a0f", line="#1b1f29",
fg="#bfbdb6", muted="#5a6378", accent="#e6b450", link="#59c2ff",
danger="#f07178", warn="#ff8f40", success="#aad94c", star="#ffb454",
q1="#39bae6", q2="#aad94c", q3="#d2a6ff",
),
"light": dict(
bg="#f8f9fa", elev="#fcfcfc", sunken="#ebeef0", line="#dfe2e5",
fg="#5c6166", muted="#828e9f", accent="#f29718", link="#22a4e6",
danger="#f07171", warn="#fa8532", success="#86b300", star="#eba400",
q1="#55b4d4", q2="#86b300", q3="#a37acc",
),
},
"kanagawa": {
"dark": dict( # Wave
bg="#1f1f28", elev="#2a2a37", sunken="#16161d", line="#363646",
fg="#dcd7ba", muted="#727169", accent="#7e9cd8", link="#7fb4ca",
danger="#e82424", warn="#ff9e3b", success="#98bb6c", star="#e6c384",
q1="#7fb4ca", q2="#98bb6c", q3="#d27e99",
),
"light": dict( # Lotus
bg="#e5ddb0", elev="#f2ecbc", sunken="#dcd5ac", line="#d5cea3",
fg="#545464", muted="#716e61", accent="#624c83", link="#4d699b",
danger="#c84053", warn="#cc6d00", success="#6f894e", star="#77713f",
q1="#4d699b", q2="#6f894e", q3="#b35b79",
),
},
"everforest": {
"dark": dict( # medium
bg="#2d353b", elev="#343f44", sunken="#232a2e", line="#475258",
fg="#d3c6aa", muted="#859289", accent="#a7c080", link="#7fbbb3",
danger="#e67e80", warn="#e69875", success="#a7c080", star="#dbbc7f",
q1="#7fbbb3", q2="#a7c080", q3="#d699b6",
),
"light": dict( # medium
bg="#efebd4", elev="#fdf6e3", sunken="#e6e2cc", line="#bdc3af",
fg="#5c6a72", muted="#939f91", accent="#8da101", link="#3a94c5",
danger="#f85552", warn="#f57d26", success="#8da101", star="#dfa000",
q1="#3a94c5", q2="#8da101", q3="#df69ba",
),
},
"primer": {
"dark": dict(
bg="#0d1117", elev="#151b23", sunken="#010409", line="#3d444d",
fg="#f0f6fc", muted="#9198a1", accent="#58a6ff", link="#79c0ff",
danger="#ff7b72", warn="#e3b341", success="#3fb950", star="#d29922",
q1="#79c0ff", q2="#56d364", q3="#d2a8ff",
),
"light": dict(
bg="#f6f8fa", elev="#ffffff", sunken="#eff2f5", line="#d1d9e0",
fg="#25292e", muted="#59636e", accent="#0969da", link="#0550ae",
danger="#cf222e", warn="#9a6700", success="#1a7f37", star="#bf8700",
q1="#0550ae", q2="#116329", q3="#8250df",
),
},
}
# What each token has to clear, and against which surface. Normal text is 4.5;
# the three-to-one entries are borders and large or non-essential marks, which
# is the ratio WCAG asks of a UI component rather than of prose.
TEXT_ON_BG = {"fg": 7.0, "muted": 4.5, "faint": 4.5, "link": 4.5, "danger": 4.5, "warn": 4.5, "success": 4.5}
UI_ON_BG = {"accent": 3.0, "border-strong": 3.0, "star": 3.0}
def build(pid: str, mode: str, src: dict[str, str]) -> tuple[dict[str, str], list[str]]:
dark = mode == "dark"
bg, fg = src["bg"], src["fg"]
notes: list[str] = []
def lift(name: str, colour: str, target: float) -> str:
out = toward_contrast(colour, bg, target, dark)
if out != colour:
notes.append(f"{name} {colour} -> {out} ({contrast(colour, bg):.2f} -> {contrast(out, bg):.2f})")
return out
# Body text is lifted like every other text tone rather than exempted.
# Most of these palettes publish a body colour around 4.5:1 -- their own
# target -- and ihasmail asks 7:1 of the text a reader looks at all day.
# Rejecting a palette over that would have cost five of the six added in
# 2026-09; nudging the published colour along its own hue costs nothing a
# reader can name, and the shift is recorded in the header of the
# generated block like every other one.
fg = lift("fg", fg, TEXT_ON_BG["fg"])
muted = lift("muted", src["muted"], TEXT_ON_BG["muted"])
# Between muted and the background, but still readable: this is timestamps
# and counts, which are small and still prose.
faint = lift("faint", mix(muted, bg, 0.30), TEXT_ON_BG["faint"])
link = lift("link", src["link"], TEXT_ON_BG["link"])
danger = lift("danger", src["danger"], TEXT_ON_BG["danger"])
warn = lift("warn", src["warn"], TEXT_ON_BG["warn"])
success = lift("success", src["success"], TEXT_ON_BG["success"])
accent = lift("accent", src["accent"], UI_ON_BG["accent"])
star = lift("star", src["star"], UI_ON_BG["star"])
border_strong = lift("border-strong", mix(src["line"], fg, 0.15), UI_ON_BG["border-strong"])
accent_soft = rgba(accent, 0.16) if dark else mix(accent, bg, 0.86)
accent_soft_bg = mix(accent, bg, 0.84) if dark else mix(accent, bg, 0.86)
accent_soft_fg = toward_contrast(accent, accent_soft_bg, 4.5, dark)
accent_fg = "#ffffff" if contrast("#ffffff", accent) >= contrast(bg, accent) else bg
tokens = {
"--bg": bg,
"--bg-elev": src["elev"],
"--bg-sunken": src["sunken"],
"--bg-hover": rgba(fg, 0.06),
"--bg-active": rgba(fg, 0.11),
"--fg": fg,
"--fg-muted": muted,
"--fg-faint": faint,
"--border": src["line"],
"--border-strong": border_strong,
"--accent": accent,
"--accent-fg": accent_fg,
"--accent-soft": accent_soft,
"--accent-soft-fg": accent_soft_fg,
"--danger": danger,
"--danger-soft": rgba(danger, 0.15),
"--warn": warn,
"--warn-soft": rgba(warn, 0.15),
"--success": success,
"--success-soft": rgba(success, 0.15),
"--link": link,
"--unread-bg": src["elev"] if dark else "#ffffff",
"--read-bg": src["sunken"] if dark else mix(bg, fg, 0.03),
"--selected-bg": rgba(accent, 0.18) if dark else mix(accent, bg, 0.86),
"--focus-ring": f"0 0 0 3px {rgba(accent, 0.40)}",
"--star": star,
"--q1": lift("q1", src["q1"], 4.5),
"--q2": lift("q2", src["q2"], 4.5),
"--q3": lift("q3", src["q3"], 4.5),
"--scrollbar": rgba(muted, 0.35),
"color-scheme": "dark" if dark else "light",
}
if dark:
tokens["--shadow-1"] = "0 1px 2px rgba(0, 0, 0, 0.45)"
tokens["--shadow-2"] = "0 8px 24px rgba(0, 0, 0, 0.55)"
tokens["--shadow-3"] = "0 22px 60px -28px rgba(0, 0, 0, 0.75)"
return tokens, notes
def verify(pid: str, mode: str, tokens: dict[str, str]) -> list[str]:
"""Fail loudly rather than emit a palette that breaks the AA claim."""
bg = tokens["--bg"]
bad = []
for token, target in [
("--fg", 7.0), ("--fg-muted", 4.5), ("--fg-faint", 4.5), ("--link", 4.5),
("--danger", 4.5), ("--warn", 4.5), ("--success", 4.5),
("--accent", 3.0), ("--border-strong", 3.0), ("--star", 3.0),
("--q1", 4.5), ("--q2", 4.5), ("--q3", 4.5),
]:
ratio = contrast(tokens[token], bg)
if ratio + 1e-9 < target:
bad.append(f"{pid}/{mode} {token} {tokens[token]} on {bg}: {ratio:.2f} < {target}")
ratio = contrast(tokens["--accent-soft-fg"], tokens["--bg-elev"])
return bad
def css_for(pid: str, mode: str, tokens: dict[str, str]) -> str:
sel = f':root[data-palette="{pid}"]' if mode == "light" else f':root[data-theme="dark"][data-palette="{pid}"]'
lines = [f"{sel} {{"]
for k, v in tokens.items():
lines.append(f" {k}: {v};")
lines.append("}")
return "\n".join(lines)
def main() -> int:
blocks: list[str] = [
BEGIN,
"/*",
" * Written by scripts/build-palettes.py -- edit the sources there, not here.",
" *",
" * Every colour is from the palette's own project (all MIT); the published",
" * values are recorded in .palette-sources/palettes-upstream.md. The tiers",
" * between them are derived, and every text colour is checked against the",
" * surface it sits on: 4.5:1 for prose, 3:1 for borders and marks. Several",
" * of these palettes do not meet that as published -- Dracula's comment grey",
" * is about 3.0:1 on its own background -- so those tiers are lifted, which",
" * is why this is arithmetic rather than a hand-written block.",
" */",
]
problems: list[str] = []
for pid, modes in SOURCES.items():
for mode in ("light", "dark"):
if pid in LIGHT_ONLY and mode == "dark":
continue
tokens, notes = build(pid, mode, modes[mode])
problems += verify(pid, mode, tokens)
if notes:
blocks.append(f"/* {pid} ({mode}) lifted for contrast: " + "; ".join(notes) + " */")
blocks.append(css_for(pid, mode, tokens))
blocks.append(END)
generated = "\n\n".join(blocks) + "\n"
if problems:
print("Contrast check failed:", file=sys.stderr)
for p in problems:
print(" " + p, file=sys.stderr)
return 1
css = CSS.read_text(encoding="utf-8")
if BEGIN in css:
css = re.sub(re.escape(BEGIN) + r".*?" + re.escape(END) + r"\n?", generated, css, flags=re.S)
else:
css = css.rstrip() + "\n\n" + generated
CSS.write_text(css, encoding="utf-8")
print(f"Wrote {len(SOURCES) * 2} palette blocks to {CSS.relative_to(ROOT)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
-155
View File
@@ -1,155 +0,0 @@
#!/usr/bin/env node
/*
* Check a catalogue against the strings the code actually asks for.
*
* Two failures, and only one of them is visible without this.
*
* A *missing* key renders English. That is the designed fallback and shows up
* as an untranslated word on screen, which somebody will eventually notice.
*
* A *stale* key -- one whose English no longer exists, usually because it was
* mistyped when the catalogue was written -- is silent. The translation sits
* in the file looking correct, is never looked up, and the app renders English
* for ever. Nothing warns, because a catalogue is only ever read by key.
*/
/*
* The parser, not the compiler.
*
* TypeScript 7 is the native port: its package ships a `tsc` shim over a Go
* binary and nothing else, so `typescript` now exports `version` and
* `versionMajorMinor` and no compiler API at all. Every `ts.createSourceFile`
* in this directory started throwing "Cannot read properties of undefined
* (reading 'Latest')" the day the bump landed, and nothing noticed, because no
* workflow runs these.
*
* `typescript-ast` is an npm alias for the last TypeScript that carries the JS
* API (see package.json). It parses; `typescript` still type-checks and builds.
* Two entries, two jobs -- not a version someone forgot to remove.
*/
import ts from "typescript-ast";
import { readFileSync, globSync } from "node:fs";
/*
* Two sets, because there are two questions and they need different nets.
*
* `wanted` is what a catalogue *owes*: the strings that actually reach t(),
* tc() or plural(). Coverage is measured against it, so it has to stay strict
* -- widening it would count every CSS class and JMAP method name as an
* untranslated string.
*
* `seen` is every string literal in the source, and answers only "is this
* catalogue key still written down anywhere". Stale detection needs the wide
* net: a key reaches t() as a variable often enough that a strict set reports
* mostly false alarms.
*/
const wanted = new Set();
const seen = new Set();
for (const file of globSync("web/src/**/*.{ts,tsx}").filter((f) => !f.includes("__tests__") && !f.includes("/locales/"))) {
const src = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const visit = (n) => {
/*
* Anything held in a constant and translated where it renders -- t(s.label),
* t(b.description), t(group) -- reaches t() as a variable, so there is no
* literal at the call site and every one of them looked "stale".
*
* This used to chase the shapes one at a time: a `label:` property, then an
* object named *_LABELS. It still cried wolf, because the shapes kept
* coming -- `description:` and `group:` on keyboard bindings, the calendar's
* view names, the read-receipt refusals, the palette names. 41 reported,
* 10 of them real. A report that is three-quarters false is one nobody acts
* on, which is how these sat unread long enough to be worth a commit of
* their own.
*
* So: any string literal anywhere in the source counts as a use. That
* under-reports -- a literal that exists but is never passed to t() will not
* be flagged -- and that is the right way round. A missed stale key costs a
* line of dead translation; a false one costs the credibility of the whole
* check, and then every real finding with it.
*/
if (ts.isStringLiteral(n) || ts.isNoSubstitutionTemplateLiteral(n)) seen.add(n.text);
if (ts.isJsxText(n)) { const text = n.text.trim(); if (text) seen.add(text); }
/*
* A `label:` in a constant is still a string somebody has to translate --
* it reaches t() one render later -- so it stays part of what a catalogue
* owes, and out of coverage it would flatter the number.
*/
if (ts.isPropertyAssignment(n) && n.name.getText(src) === "label" && ts.isStringLiteral(n.initializer)) wanted.add(n.initializer.text);
if (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && /_LABELS?$/.test(n.name.text)) {
const walk = (x) => { if (ts.isStringLiteral(x)) wanted.add(x.text); ts.forEachChild(x, walk); };
if (n.initializer) walk(n.initializer);
}
if (ts.isCallExpression(n) && ts.isIdentifier(n.expression)) {
const fn = n.expression.text, a0 = n.arguments[0];
if ((fn === "t" || fn === "translate" || fn === "tNode") && a0 && ts.isStringLiteral(a0)) wanted.add(a0.text);
// tc(context, source) keys the catalogue on both, joined by the same
// control character tc() uses. Without this the contextual entries all
// looked stale, which is the checker's own false alarm rather than a
// catalogue problem.
if (fn === "tc" && a0 && ts.isStringLiteral(a0) && n.arguments[1] && ts.isStringLiteral(n.arguments[1])) {
// Only the contextual key is required. The plain one is tc()'s
// fallback, not a second obligation -- asking for both would report
// work that does not exist.
wanted.add(`${a0.text}\u0004${n.arguments[1].text}`);
seen.add(`${a0.text}\u0004${n.arguments[1].text}`);
}
if (fn === "plural" && n.arguments[1] && ts.isObjectLiteralExpression(n.arguments[1])) {
for (const p of n.arguments[1].properties) {
if (ts.isPropertyAssignment(p) && p.name.getText(src) === "other" && ts.isStringLiteral(p.initializer)) wanted.add(p.initializer.text);
}
}
}
ts.forEachChild(n, visit);
};
visit(src);
}
/*
* A catalogue and a picker entry are two halves of one thing, and either half
* alone is dead weight. A catalogue with no entry in UI_LANGUAGES never
* reaches a reader -- it builds, it passes every test, and the language simply
* is not offered. That happened to Dutch: the entry was added by a text
* replacement anchored on a line that did not exist on that branch, so it was
* a silent no-op and nothing anywhere complained.
*/
const languagesSrc = readFileSync("web/src/lib/languages.ts", "utf8");
const registered = new Set([...languagesSrc.matchAll(/tag:\s*"([\w-]+)"/g)].map((m) => m[1]));
const catalogues = new Set(globSync("web/src/locales/*.ts").map((f) => f.split("/").pop().replace(".ts", "")));
let failed = false;
for (const tag of catalogues) {
if (!registered.has(tag)) {
failed = true;
console.log(`!! ${tag}.ts exists but is not in UI_LANGUAGES — the language is never offered\n`);
}
}
for (const tag of registered) {
if (tag !== "en" && !catalogues.has(tag)) {
failed = true;
console.log(`!! UI_LANGUAGES offers ${tag} but there is no ${tag}.ts — it would fall back to English\n`);
}
}
for (const file of globSync("web/src/locales/*.ts")) {
const tag = file.split("/").pop().replace(".ts", "");
const src = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
const have = new Set();
const visit = (n) => {
if (ts.isPropertyAssignment(n) && ts.isStringLiteral(n.name)) have.add(n.name.text);
ts.forEachChild(n, visit);
};
visit(src);
const stale = [...have].filter((k) => !seen.has(k) && !["one", "other", "few", "many", "zero", "two"].includes(k));
const missing = [...wanted].filter((k) => !have.has(k));
const pct = Math.round(((wanted.size - missing.length) / wanted.size) * 100);
console.log(`${tag}: ${wanted.size - missing.length}/${wanted.size} translated (${pct}%), ${missing.length} falling back to English`);
if (stale.length) {
failed = true;
console.log(`\n ${stale.length} STALE key(s) — translated but never looked up, so they do nothing:`);
for (const k of stale) console.log(` ${JSON.stringify(k)}`);
}
if (process.argv.includes("--missing")) {
console.log(`\n missing:`);
for (const k of missing) console.log(` ${JSON.stringify(k)}`);
}
}
if (failed && process.argv.includes("--check")) process.exit(1);
-86
View File
@@ -1,86 +0,0 @@
#!/usr/bin/env node
/*
* How much of the interface is extracted, and what is left.
*
* Extraction is ~1,000 strings across ~56 files, which is far too many to
* carry in anyone's head or to eyeball in review. This counts what is still
* hardcoded so the work can be done a file at a time and the remainder is
* always a number rather than a feeling.
*
* It is a progress report, not a gate: run it, do a file, run it again. It
* exits non-zero only with --check, so CI can be told to fail on regressions
* later, once the number is low enough for that to mean something.
*/
/*
* The parser, not the compiler.
*
* TypeScript 7 is the native port: its package ships a `tsc` shim over a Go
* binary and nothing else, so `typescript` now exports `version` and
* `versionMajorMinor` and no compiler API at all. Every `ts.createSourceFile`
* in this directory started throwing "Cannot read properties of undefined
* (reading 'Latest')" the day the bump landed, and nothing noticed, because no
* workflow runs these.
*
* `typescript-ast` is an npm alias for the last TypeScript that carries the JS
* API (see package.json). It parses; `typescript` still type-checks and builds.
* Two entries, two jobs -- not a version someone forgot to remove.
*/
import ts from "typescript-ast";
import { readFileSync, globSync } from "node:fs";
/** Attributes a person reads. `className` and `key` are not among them. */
const ATTRS = new Set(["title", "aria-label", "placeholder", "alt", "label", "hint", "confirmLabel", "message", "description"]);
/* Text that is not prose: punctuation, separators, and the single glyphs used
as dividers. Counting these as untranslated would put a floor under the
number that no amount of work could reach. */
const NOT_PROSE = /^[\s·—–\-—:;,.()[\]{}/|+×✓~<>#*@0-9]*$/u;
/*
* Text that is deliberately not translated is not "remaining work". Counting
* it put a floor under the number that no amount of effort could reach -- the
* report sat at 21 with only 6 real items left, which makes the number
* something to argue with rather than act on. Same rule the codemod uses.
*/
const CODE_TAGS = new Set(["code", "kbd", "pre", "samp", "var"]);
const optedOut = (node, src) => {
const opening = ts.isJsxElement(node) ? node.openingElement : ts.isJsxSelfClosingElement(node) ? node : null;
return Boolean(opening?.attributes.properties.some((a) =>
ts.isJsxAttribute(a) && a.name.getText(src) === "translate" &&
a.initializer && ts.isStringLiteral(a.initializer) && a.initializer.text === "no"));
};
const files = globSync("web/src/**/*.tsx").filter((f) => !f.includes("__tests__"));
const rows = [];
let done = 0, todo = 0;
for (const file of files) {
const text = readFileSync(file, "utf8");
const src = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
let left = 0;
const wrapped = (text.match(/\bt\(\s*["'`]/g) || []).length + (text.match(/\bplural\(/g) || []).length;
const visit = (node) => {
if ((ts.isJsxElement(node) && CODE_TAGS.has(node.openingElement.tagName.getText(src).toLowerCase())) || optedOut(node, src)) return;
if (ts.isJsxText(node) && node.text.trim().length > 1 && !NOT_PROSE.test(node.text.trim())) left++;
if (ts.isJsxAttribute(node) && ATTRS.has(node.name.getText(src))) {
const i = node.initializer;
const lit = i && (ts.isStringLiteral(i) ? i : ts.isJsxExpression(i) && i.expression && ts.isStringLiteral(i.expression) ? i.expression : null);
// The same prose test the text nodes get. Without it, placeholders that
// are format examples -- "123456" for a one-time code, "+1 555 0100" for
// a phone -- counted as untranslated work forever.
if (lit && lit.text.trim().length > 1 && !NOT_PROSE.test(lit.text.trim())) left++;
}
ts.forEachChild(node, visit);
};
visit(src);
done += wrapped;
todo += left;
if (left) rows.push([file.replace("web/src/", ""), left, wrapped]);
}
rows.sort((a, b) => b[1] - a[1]);
const pct = done + todo === 0 ? 100 : Math.round((done / (done + todo)) * 100);
console.log(`i18n extraction: ${done} wrapped, ${todo} remaining across ${rows.length} files (${pct}%)\n`);
for (const [f, left, w] of rows.slice(0, Number(process.argv.find((a) => a.startsWith("--top="))?.slice(6) ?? 15))) {
console.log(` ${String(left).padStart(4)} left${w ? `, ${w} done` : " "} ${f}`);
}
if (rows.length > 15 && !process.argv.includes("--all")) console.log(`\n …and ${rows.length - 15} more (--all, or --top=N)`);
if (process.argv.includes("--check") && todo > 0) process.exit(1);
-157
View File
@@ -1,157 +0,0 @@
#!/usr/bin/env node
/*
* Wrap the strings a codemod can safely wrap, and report the ones it cannot.
*
* Roughly 1,000 strings is too many to hand-edit without introducing typos
* into the copy itself, and a parser does not get bored. But it must not be
* trusted with everything: text that is split around an interpolation arrives
* as separate fragments, and wrapping each fragment on its own produces
* "Move " and " messages", which no translator can do anything with. Those are
* left alone and listed, because they need a sentence built by hand.
*
* node scripts/i18n-extract.mjs <file...> rewrite in place
* node scripts/i18n-extract.mjs --dry <file...>
*/
/*
* The parser, not the compiler.
*
* TypeScript 7 is the native port: its package ships a `tsc` shim over a Go
* binary and nothing else, so `typescript` now exports `version` and
* `versionMajorMinor` and no compiler API at all. Every `ts.createSourceFile`
* in this directory started throwing "Cannot read properties of undefined
* (reading 'Latest')" the day the bump landed, and nothing noticed, because no
* workflow runs these.
*
* `typescript-ast` is an npm alias for the last TypeScript that carries the JS
* API (see package.json). It parses; `typescript` still type-checks and builds.
* Two entries, two jobs -- not a version someone forgot to remove.
*/
import ts from "typescript-ast";
import { readFileSync, writeFileSync } from "node:fs";
const ATTRS = new Set(["title", "aria-label", "placeholder", "alt", "label", "hint", "confirmLabel", "description"]);
const NOT_PROSE = /^[\s·—–\-:;,.()[\]{}/|+×✓~<>#*@0-9]*$/u;
/*
* Elements whose text is not prose however much it looks like it. `label:name`
* inside <code> is a search operator: translating it breaks the thing it
* documents. The first run of this wrapped exactly that, which is why the list
* exists.
*/
const CODE_TAGS = new Set(["code", "kbd", "pre", "samp", "var"]);
/*
* JSX decodes HTML entities in text; a JS string literal does not. Moving
* `Language &amp; region` into t("...") without decoding renders the entity
* literally on screen -- which the first run of this did, and which no
* typecheck or test noticed. It took looking at the page.
*/
const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: "\u00a0", mdash: "—", ndash: "", hellip: "…", times: "×", middot: "·" };
const decode = (s) => s.replace(/&(\w+);/g, (whole, name) => ENTITIES[name] ?? whole)
.replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)));
const tagOf = (node, src) => (ts.isJsxElement(node) ? node.openingElement.tagName.getText(src) : "");
const optedOut = (node, src) => {
const opening = ts.isJsxElement(node) ? node.openingElement : ts.isJsxSelfClosingElement(node) ? node : null;
return Boolean(opening?.attributes.properties.some((a) =>
ts.isJsxAttribute(a) && a.name.getText(src) === "translate" &&
a.initializer && ts.isStringLiteral(a.initializer) && a.initializer.text === "no"));
};
const dry = process.argv.includes("--dry");
const files = process.argv.slice(2).filter((a) => !a.startsWith("--"));
let wrapped = 0;
const skipped = [];
for (const file of files) {
const text = readFileSync(file, "utf8");
const src = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
/*
* `t` is a natural name for a callback parameter, and several files already
* use it -- `(t: SieveTest) => ...`, `.map((t) => ...)`. An import called
* `t` is shadowed inside those callbacks, silently where the local happens
* to be callable. So the name is checked first and aliased where it is
* taken, per file, rather than assumed to be free.
*/
let bound = false;
const scan = (n) => {
if ((ts.isParameter(n) || ts.isVariableDeclaration(n) || ts.isBindingElement(n)) && n.name && ts.isIdentifier(n.name) && n.name.text === "t") bound = true;
ts.forEachChild(n, scan);
};
scan(src);
const T = bound ? "translate" : "t";
/** [start, end, replacement] — applied back-to-front so offsets hold. */
const edits = [];
const visit = (node) => {
if (ts.isJsxElement(node) || ts.isJsxFragment(node)) {
if (CODE_TAGS.has(tagOf(node, src).toLowerCase()) || optedOut(node, src)) return; // and not its children
const kids = node.children;
const meaningful = kids.filter((c) => !(ts.isJsxText(c) && !c.text.trim()));
for (const c of kids) {
if (!ts.isJsxText(c)) continue;
const raw = c.text;
const body = raw.trim();
if (body.length < 2 || NOT_PROSE.test(body)) continue;
/*
* "Split around an interpolation" is the dangerous case, and it is
* narrower than "has siblings". `<Plus /> New rule` is a phrase next
* to an icon: wrapping it alone is correct, and refusing it left a
* third of the remaining work to be done by hand for no reason.
* `Your script “{name}” was written by hand` is the real thing --
* a sibling that renders text, so the fragments are not sentences.
*/
const textSibling = kids.some((k) => k !== c && ts.isJsxExpression(k) && k.expression && !(() => {
let jsx = false;
const w = (n) => { if (ts.isJsxElement(n) || ts.isJsxSelfClosingElement(n) || ts.isJsxFragment(n)) { jsx = true; return; } ts.forEachChild(n, w); };
w(k.expression);
return jsx;
})());
if (textSibling) {
const { line } = src.getLineAndCharacterOfPosition(c.getStart(src));
skipped.push({ file, line: line + 1, why: "text split around an expression", text: body.slice(0, 52) });
continue;
}
if (decode(body).includes('"')) {
const { line } = src.getLineAndCharacterOfPosition(c.getStart(src));
skipped.push({ file, line: line + 1, why: "contains a quote", text: body.slice(0, 52) });
continue;
}
// Keep the original leading/trailing whitespace: JSX collapses it, and
// reflowing here would change the rendered spacing.
const lead = raw.slice(0, raw.indexOf(body[0]));
const tail = raw.slice(raw.lastIndexOf(body[body.length - 1]) + 1);
edits.push([c.getStart(src), c.getEnd(), `${lead}{${T}("${decode(body.replace(/\s+/g, " "))}")}${tail}`]);
wrapped++;
}
}
if (ts.isJsxAttribute(node) && ATTRS.has(node.name.getText(src))) {
const i = node.initializer;
const lit = i && (ts.isStringLiteral(i) ? i : ts.isJsxExpression(i) && i.expression && ts.isStringLiteral(i.expression) ? i.expression : null);
if (lit && lit.text.trim().length > 1 && !NOT_PROSE.test(lit.text)) {
if (decode(lit.text).includes('"')) {
const { line } = src.getLineAndCharacterOfPosition(lit.getStart(src));
skipped.push({ file, line: line + 1, why: "contains a quote", text: lit.text.slice(0, 52) });
} else {
edits.push([i.getStart(src), i.getEnd(), `{${T}("${decode(lit.text)}")}`]);
wrapped++;
}
}
}
ts.forEachChild(node, visit);
};
visit(src);
if (!edits.length) continue;
let out = text;
for (const [start, end, rep] of edits.sort((a, b) => b[0] - a[0])) out = out.slice(0, start) + rep + out.slice(end);
if (!/from "@\/lib\/i18n"/.test(out)) {
const lastImport = [...out.matchAll(/^import .*?;$/gm)].pop();
const decl = bound ? 'import { t as translate } from "@/lib/i18n";' : 'import { t } from "@/lib/i18n";';
if (lastImport) out = out.slice(0, lastImport.index + lastImport[0].length) + "\n" + decl + out.slice(lastImport.index + lastImport[0].length);
}
if (!dry) writeFileSync(file, out);
}
console.log(`${dry ? "would wrap" : "wrapped"} ${wrapped} strings across ${files.length} files`);
if (skipped.length) {
console.log(`\n${skipped.length} left for a person:`);
for (const s of skipped) console.log(` ${s.file.replace("web/src/", "")}:${s.line} (${s.why}) ${s.text}`);
}
-138
View File
@@ -1,138 +0,0 @@
#!/usr/bin/env node
/*
* User-visible English the extraction pass cannot see.
*
* `i18n:coverage` reads JSX text, and reported 100% while the calendar's
* Day/Week/Month/Agenda buttons rendered English in all nine languages. It was
* not wrong about what it measured -- those labels were never JSX text. They
* were built from an expression, and so was every toast argument, every
* `confirmDialog({ title })`, and every `Could not save: ${err}`.
*
* A string reaches a reader translated if either is true:
*
* 1. it is wrapped where it is written -- t(), tc(), tNode(), plural()
* 2. it is a catalogue key, translated somewhere else
*
* The second case is a real convention here, not a loophole: constant tables
* hold English and the render site calls `t(s.label)`. What this refuses is a
* string that is neither -- one no catalogue has a key for, which therefore
* cannot be translated at all, however many languages ship.
*/
/*
* The parser, not the compiler.
*
* TypeScript 7 is the native port: its package ships a `tsc` shim over a Go
* binary and nothing else, so `typescript` now exports `version` and
* `versionMajorMinor` and no compiler API at all. Every `ts.createSourceFile`
* in this directory started throwing "Cannot read properties of undefined
* (reading 'Latest')" the day the bump landed, and nothing noticed, because no
* workflow runs these.
*
* `typescript-ast` is an npm alias for the last TypeScript that carries the JS
* API (see package.json). It parses; `typescript` still type-checks and builds.
* Two entries, two jobs -- not a version someone forgot to remove.
*/
import ts from "typescript-ast";
import { readFileSync, globSync } from "node:fs";
/* Where a string literal in this position is shown to somebody. */
const UI_PROPS = new Set([
"title", "message", "label", "confirmLabel", "cancelLabel", "ariaLabel",
"placeholder", "hint", "occurrenceLabel", "occurrenceHint", "seriesLabel", "seriesHint",
]);
const UI_ATTRS = new Set(["title", "aria-label", "placeholder", "alt"]);
const TOASTS = new Set(["error", "success", "info", "show"]);
const WRAPPERS = ["t", "tc", "tNode", "translate", "plural"];
const EQUALITY = new Set([
ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken,
ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsToken,
]);
/*
* Product names, example addresses and URL scaffolding. These reach t() and
* are deliberately absent from every catalogue -- translating "ihasmail" or
* "[email protected]" would be a bug, not a feature -- so they would otherwise
* be reported for ever.
*/
const NEVER_TRANSLATED = new Set([
"ihasmail", "ihasmail.org", "ihasmail test", "Stalwart", "Stalwart Mail Server",
"AGPL-3.0-or-later · {source}", "•••", "https://", "https://…",
"https://meet.example.com/…", "[email protected]", "[email protected]",
"[email protected]", "List-Id", "X-Spam-Status",
]);
/* Prose, not an identifier: opens like a sentence, and has lower-case letters. */
const looksLikeUi = (s) =>
/[a-z]/.test(s) && /^[A-Z(“]/.test(s) && (/\s/.test(s) || /[.?!…]$/.test(s));
const keys = new Set();
{
const src = readFileSync("web/src/locales/de.ts", "utf8");
for (const m of src.matchAll(/^\s{4}"((?:[^"\\]|\\.)*)":/gm)) keys.add(m[1].replace("\\u0004", ""));
}
const found = [];
for (const file of globSync("web/src/**/*.{ts,tsx}").filter((f) => !f.includes("__tests__") && !f.includes("/locales/"))) {
const src = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const report = (node, text) => {
if (!looksLikeUi(text) || keys.has(text) || NEVER_TRANSLATED.has(text)) return;
const { line } = src.getLineAndCharacterOfPosition(node.getStart(src));
found.push({ file, line: line + 1, text });
};
/*
* Literals that are not text on their way to a reader.
*
* Two kinds. One is already inside t("...") -- walking into the call would
* report the very string that proves it is handled. The other is an operand
* of an equality test: `rule.name === "New filter"` compares against a
* sentinel stored in the Sieve script, and translating it would not change
* what a reader sees, it would break the comparison.
*/
const exempt = new Set();
const mark = (n) => {
if (ts.isCallExpression(n) && ts.isIdentifier(n.expression) && WRAPPERS.includes(n.expression.text)) {
const walk = (x) => { if (ts.isStringLiteral(x)) exempt.add(x); ts.forEachChild(x, walk); };
for (const a of n.arguments) walk(a);
}
if (ts.isBinaryExpression(n) && EQUALITY.has(n.operatorToken.kind)) {
for (const side of [n.left, n.right]) if (ts.isStringLiteral(side)) exempt.add(side);
}
ts.forEachChild(n, mark);
};
mark(src);
const wrapped = exempt;
const visit = (n) => {
if (ts.isPropertyAssignment(n) && ts.isStringLiteral(n.initializer) && !wrapped.has(n.initializer)
&& UI_PROPS.has(n.name.getText(src).replace(/['"]/g, ""))) {
report(n.initializer, n.initializer.text);
}
if (ts.isJsxAttribute(n) && n.initializer && UI_ATTRS.has(n.name.getText(src))) {
const walk = (x) => {
if (ts.isStringLiteral(x) && !wrapped.has(x)) report(x, x.text);
if (!ts.isCallExpression(x)) ts.forEachChild(x, walk);
};
walk(n.initializer);
}
if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression)
&& n.expression.expression.getText(src) === "toast" && TOASTS.has(n.expression.name.text)) {
const a0 = n.arguments[0];
if (a0 && ts.isStringLiteral(a0) && !wrapped.has(a0)) report(a0, a0.text);
/* A template literal cannot be a catalogue key at all, so it is always a find. */
if (a0 && ts.isTemplateExpression(a0)) report(a0, a0.head.text + "{}");
}
ts.forEachChild(n, visit);
};
visit(src);
}
if (!found.length) {
console.log("i18n literals: none -- every user-visible string is wrapped or has a catalogue key");
process.exit(0);
}
console.log(`${found.length} user-visible string(s) the extractor cannot see and no catalogue can translate:\n`);
for (const f of found) console.log(` ${f.file}:${f.line}\n ${JSON.stringify(f.text)}`);
console.log("\nWrap them in t() / plural(), or -- for a label held in a constant and");
console.log("translated where it renders -- make sure the English is a catalogue key.");
process.exit(process.argv.includes("--check") ? 1 : 0);
-59
View File
@@ -1,59 +0,0 @@
#!/usr/bin/env node
/*
* Every source string a catalogue needs, straight out of the calls.
*
* The English text is the key, so the catalogue's keys are not a list somebody
* maintains -- they are whatever t(), tNode() and plural() are actually asked
* for. Reading them from the code means a catalogue can never drift out of
* step with the app in the one direction that matters: a key that no longer
* exists is dead weight, but a call with no key is an untranslated string
* nobody noticed.
*/
/*
* The parser, not the compiler.
*
* TypeScript 7 is the native port: its package ships a `tsc` shim over a Go
* binary and nothing else, so `typescript` now exports `version` and
* `versionMajorMinor` and no compiler API at all. Every `ts.createSourceFile`
* in this directory started throwing "Cannot read properties of undefined
* (reading 'Latest')" the day the bump landed, and nothing noticed, because no
* workflow runs these.
*
* `typescript-ast` is an npm alias for the last TypeScript that carries the JS
* API (see package.json). It parses; `typescript` still type-checks and builds.
* Two entries, two jobs -- not a version someone forgot to remove.
*/
import ts from "typescript-ast";
import { readFileSync, globSync } from "node:fs";
const strings = new Set();
const plurals = new Set();
for (const file of globSync("web/src/**/*.{ts,tsx}").filter((f) => !f.includes("__tests__"))) {
const src = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const visit = (node) => {
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
const fn = node.expression.text;
const a0 = node.arguments[0];
if ((fn === "t" || fn === "translate" || fn === "tNode") && a0 && ts.isStringLiteral(a0)) strings.add(a0.text);
if (fn === "plural" && node.arguments[1] && ts.isObjectLiteralExpression(node.arguments[1])) {
const other = node.arguments[1].properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText(src) === "other");
const forms = {};
for (const p of node.arguments[1].properties) {
if (ts.isPropertyAssignment(p) && ts.isStringLiteral(p.initializer)) forms[p.name.getText(src)] = p.initializer.text;
}
if (other) plurals.add(JSON.stringify(forms));
}
}
ts.forEachChild(node, visit);
};
visit(src);
}
const out = { strings: [...strings].sort(), plurals: [...plurals].map((p) => JSON.parse(p)) };
if (process.argv.includes("--json")) console.log(JSON.stringify(out, null, 2));
else {
console.log(`${out.strings.length} strings, ${out.plurals.length} plural sets`);
const short = out.strings.filter((s) => s.length <= 30).length;
console.log(` ${short} short (<=30 chars), ${out.strings.length - short} longer`);
}
-5
View File
@@ -1,5 +0,0 @@
/** Types for `version.mjs`, which is plain JS so the Dockerfile and shell can run it directly. */
export const UNVERSIONED: string;
export function formatVersion(commit: { date: string; subject?: string; sha: string }): string;
export function versionFromGit(): string | null;
export function resolveVersion(): string;
-108
View File
@@ -1,108 +0,0 @@
/**
* Work out this build's version: `2026.8.30+pr129`.
*
* 2026.8.30 the date of the commit this was built from
* +pr129 the pull request it arrived through
*
* The date leads because ihasmail's version used to be `2.16.<pr>`, where `16`
* was the Stalwart generation it targeted -- and Stalwart 1.0 will leave that
* with nowhere to go. `2.1` would sort *below* the `2.16` already deployed, so
* every image and About screen would read as a downgrade. Tying our
* numbering to somebody else's was the mistake; which Stalwart a build needs is
* said properly in the README badge and KNOWN-ISSUES, where it can be precise
* ("0.16 or newer; tested against 0.16.20") rather than one digit.
*
* The pull request moved into build metadata, after the `+`, because it is
* provenance rather than a position in a sequence: at a hundred merges a week
* it climbs without bound and says nothing about how new a build is. SemVer
* ignores everything after the `+` when comparing versions, which is the right
* reading -- two builds from the same day differ in where they came from, not
* in rank. Nothing here relies on that comparison anyway: images are pruned
* oldest-first by creation time and rollbacks name a git ref.
*
* A commit that did not arrive through a pull request carries its short SHA
* instead -- `2026.8.30+g1fa6578` -- which is honest about being some commit on
* that day rather than claiming a pull request it was only built after.
*
* The date is the commit's own, not today's, so rebuilding an old commit gives
* the same answer it gave the first time. It comes from the commit object,
* timezone included, so two machines agree.
*
* Nothing writes a version back into the tree: a committed one would always be
* describing a merge that had not happened yet, and every branch would collide
* on the same line. `package.json` no longer carries it either -- npm wants the
* field, so it stays at `0.0.0`, which is what an unversioned build reports and
* is meant to look wrong.
*
* `.dockerignore` excludes `.git`, so an image build cannot run any of this.
* It takes the answer through `--build-arg IHASMAIL_VERSION=...` instead, and
* whoever builds is responsible for computing it -- see ihasmail-deploy.sh.
*/
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
/** What a build with nothing to go on reports, and it should look wrong. */
export const UNVERSIONED = "0.0.0";
function git(...args) {
return execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
}
const PR_SUBJECT = /^Merge pull request #(\d+)\b/;
/**
* The version for a commit, from the three things about it that decide one.
* Pure, so the rules can be exercised without a repository staged to produce
* them: `{ date: "2026-08-30", subject: "Merge pull request #129 from ...",
* sha: "1fa6578" }` gives `2026.8.30+pr129`.
*
* Leading zeros are stripped because a version field may not carry them, so
* September is `9` rather than `09`.
*/
export function formatVersion({ date, subject = "", sha }) {
const [y, m, d] = date.split("-");
const calendar = `${Number(y)}.${Number(m)}.${Number(d)}`;
const pr = PR_SUBJECT.exec(subject)?.[1];
return pr ? `${calendar}+pr${pr}` : `${calendar}+g${sha}`;
}
/**
* The version for the commit checked out here, or null when there is no git to
* ask -- an unpacked tarball, or the Docker build context.
*/
export function versionFromGit() {
let head;
let date;
try {
head = git("rev-parse", "--short", "HEAD");
// %cs is the committer date in the commit's own timezone, which is stored
// in the commit -- so this does not depend on the clock or zone of whoever
// is building.
date = git("show", "-s", "--format=%cs", "HEAD");
} catch {
return null;
}
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return null;
let subject = "";
try {
subject = git("show", "-s", "--format=%s", "HEAD");
} catch {
/* no subject to read; fall through to the SHA */
}
return formatVersion({ date, subject, sha: head });
}
/** Whatever the environment was told, else git, else an answer that looks wrong. */
export function resolveVersion() {
const fromEnv = process.env.IHASMAIL_VERSION?.trim();
if (fromEnv) return fromEnv;
return versionFromGit() ?? UNVERSIONED;
}
// `node scripts/version.mjs` prints it, for shell scripts and CI.
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
process.stdout.write(resolveVersion() + "\n");
}
+8 -8
View File
@@ -1,6 +1,6 @@
{
"name": "@ihasmail/server",
"version": "2.16.0",
"version": "2.0.0",
"private": true,
"license": "AGPL-3.0-or-later",
"type": "module",
@@ -12,16 +12,16 @@
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "tsx --test src/*.test.ts src/**/*.test.ts",
"mock": "tsx src/mock/index.ts",
"mock:no-future-release": "MOCK_NO_FUTURE_RELEASE=1 tsx src/mock/index.ts",
"mock:no-keyword-sort": "MOCK_NO_KEYWORD_SORT=1 tsx src/mock/index.ts"
"mock:legacy": "MOCK_STALWART=0.15 tsx src/mock/index.ts",
"mock:no-future-release": "MOCK_NO_FUTURE_RELEASE=1 tsx src/mock/index.ts"
},
"dependencies": {
"@hono/node-server": "^2.1.1",
"hono": "^4.13.7"
"@hono/node-server": "^1.13.8",
"hono": "^4.7.4"
},
"devDependencies": {
"@types/node": "^26.5.1",
"tsx": "^4.23.13",
"typescript": "^7.0.2"
"@types/node": "^22.13.10",
"tsx": "^4.19.3",
"typescript": "^5.7.3"
}
}
+183
View File
@@ -0,0 +1,183 @@
import { test, before, after } from "node:test";
import assert from "node:assert/strict";
/**
* The same self-service flows, against a mock impersonating Stalwart 0.15.
*
* That generation has no registry: credentials live behind a REST endpoint,
* `urn:stalwart:jmap` is not a capability it knows, and naming one it cannot
* parse fails the whole request. Until now this adapter had no coverage at all
* — it was the least-tested code in the project, verified only by hand.
*/
const PORT = 18799;
process.env.MOCK_PORT = String(PORT);
process.env.MOCK_STALWART = "0.15";
process.env.MOCK_USER = "[email protected]";
process.env.MOCK_PASS = "demo-password";
process.env.STALWART_URL = `http://127.0.0.1:${PORT}`;
process.env.APP_SECRET = "test-secret-for-legacy-flows";
const mock = await import("./mock/index.js");
const { createApp } = await import("./app.js");
const app = createApp();
let cookie = "";
const HEADERS = { "content-type": "application/json", "x-requested-with": "ihasmail" };
async function call(path: string, init: RequestInit = {}): Promise<{ status: number; body: any }> {
const res = await app.request(path, {
...init,
headers: { ...HEADERS, ...(init.headers as Record<string, string>), ...(cookie ? { cookie } : {}) },
});
const setCookie = res.headers.get("set-cookie");
if (setCookie) cookie = setCookie.split(";")[0]!;
const text = await res.text();
return { status: res.status, body: text ? JSON.parse(text) : null };
}
const post = (path: string, body: unknown) => call(path, { method: "POST", body: JSON.stringify(body) });
before(async () => {
const res = await post("/api/auth/login", { username: "[email protected]", password: "demo-password" });
assert.equal(res.status, 200, "login should succeed against the legacy mock");
});
after(() => {
(mock as { server?: { close(): void } }).server?.close();
});
test("the older server is recognised, and reported as such", async () => {
const res = await call("/api/auth/session");
assert.equal(res.status, 200);
assert.equal(res.body.ihasmail.server.generation, "pre-0.16");
assert.equal(res.body.ihasmail.server.edition, null, "no edition is reported before 0.16");
assert.equal(res.body.capabilities["urn:stalwart:jmap"], undefined, "the capability does not exist here");
});
test("credentials fall back to the REST endpoint", async () => {
const res = await call("/api/account/security");
assert.equal(res.status, 200);
assert.equal(res.body.backend, "legacy");
assert.equal(res.body.otpEnabled, false);
assert.equal(res.body.appPasswordsKeyedByName, true, "this generation has only names to go on");
});
test("app passwords round-trip, keyed by their name", async () => {
const created = await post("/api/account/app-passwords", { description: "Thunderbird" });
assert.equal(created.status, 200);
assert.ok(created.body.secret, "a secret is generated for the user to copy");
assert.equal(created.body.id, "Thunderbird", "the name is the identifier here");
const listed = await call("/api/account/security");
assert.deepEqual(listed.body.appPasswords.map((a: { description: string }) => a.description), ["Thunderbird"]);
await post("/api/account/app-passwords/revoke", { id: "Thunderbird" });
assert.deepEqual((await call("/api/account/security")).body.appPasswords, []);
});
test("the current password is verified before it is changed", async () => {
// The REST endpoint would take our word for it, so ihasmail proves it first.
const wrong = await post("/api/account/password", { current: "not-my-password", next: "a-much-longer-password" });
assert.equal(wrong.status, 403);
assert.match(wrong.body.message, /incorrect/i);
assert.equal((mock as { account: { password: string } }).account.password, "demo-password", "nothing was changed");
});
test("changing the password keeps this session working", async () => {
const res = await post("/api/account/password", { current: "demo-password", next: "a-brand-new-password" });
assert.equal(res.status, 200);
assert.equal((mock as { account: { password: string } }).account.password, "a-brand-new-password");
assert.equal((await call("/api/auth/session")).status, 200, "the session was re-sealed");
});
test("2FA is enabled with a code proved against the new secret", async () => {
const { parseOtpauthUrl, totpCode } = await import("./totp.js");
const begin = await post("/api/account/2fa/begin", {});
const params = parseOtpauthUrl(begin.body.url);
assert.ok(params);
const bad = await post("/api/account/2fa/enable", { url: begin.body.url, code: "000000", current: "a-brand-new-password" });
assert.equal(bad.status, 400);
assert.equal((mock as { account: { otpUrl: string | null } }).account.otpUrl, null, "nothing was stored");
const good = await post("/api/account/2fa/enable", { url: begin.body.url, code: totpCode(params), current: "a-brand-new-password" });
assert.equal(good.status, 200);
assert.equal(good.body.sessionKept, true, "the session moved onto an app password");
assert.equal((await call("/api/account/security")).body.otpEnabled, true);
});
test("2FA is switched off again", async () => {
const { parseOtpauthUrl, totpCode } = await import("./totp.js");
const stored = (mock as { account: { otpUrl: string | null } }).account.otpUrl;
const params = parseOtpauthUrl(stored!);
assert.ok(params);
const res = await post("/api/account/2fa/disable", { current: "a-brand-new-password", code: totpCode(params) });
assert.equal(res.status, 200);
assert.equal((await call("/api/account/security")).body.otpEnabled, false);
});
/**
* The mock is only worth having if it is faithful, so these pin the specific
* behaviours that cost us a live debugging session each. Every one of them was
* invisible to the 0.16 mock, which is how the bugs shipped.
*/
const jmap = (using: string[], methodCalls: unknown[]) => post("/api/jmap", { using, methodCalls });
const CORE = "urn:ietf:params:jmap:core";
const MAIL = "urn:ietf:params:jmap:mail";
const FILES = "urn:ietf:params:jmap:filenode";
test("naming a capability it cannot parse fails the whole request", async () => {
const res = await jmap([CORE, "urn:stalwart:jmap"], [["Mailbox/get", { accountId: "a1", ids: null }, "c0"]]);
assert.notEqual(res.status, 200, "not one failed call - the entire request");
});
test("x: methods do not exist, so they come back unknownMethod", async () => {
const res = await jmap([CORE], [["x:AccountPassword/get", { accountId: "a1", ids: ["singleton"] }, "c0"]]);
assert.equal(res.status, 200);
assert.equal(res.body.methodResponses[0][0], "error");
assert.equal(res.body.methodResponses[0][1].type, "unknownMethod");
});
test("FileNode/set refuses nodeType by name", async () => {
const res = await jmap([CORE, FILES], [["FileNode/set", { accountId: "a1", create: { d: { parentId: null, name: "New", nodeType: "directory" } } }, "c0"]]);
const set = res.body.methodResponses[0][1];
assert.equal(set.notCreated.d.type, "invalidProperties");
assert.deepEqual(set.notCreated.d.properties, ["nodeType"]);
});
test("a directory is a node with no file properties, and query cannot see it", async () => {
const made = await jmap([CORE, FILES], [["FileNode/set", { accountId: "a1", create: { d: { parentId: null, name: "Reports" } } }, "c0"]]);
const id = made.body.methodResponses[0][1].created.d.id;
assert.ok(id);
const queried = await jmap([CORE, FILES], [["FileNode/query", { accountId: "a1" }, "c0"]]);
assert.equal(queried.body.methodResponses[0][1].ids.includes(id), false, "query masks out containers");
// get carries no such mask, which is the only way to find a folder here.
const got = await jmap([CORE, FILES], [["FileNode/get", { accountId: "a1", ids: null }, "c0"]]);
const list = got.body.methodResponses[0][1].list as { id: string; nodeType?: string; myRights: Record<string, boolean> }[];
const dir = list.find((n) => n.id === id);
assert.ok(dir, "get returns the directory");
assert.equal(dir!.nodeType, undefined, "nodeType is not a property here");
assert.deepEqual(Object.keys(dir!.myRights).sort(), ["mayRead", "mayShare", "mayWrite"], "the coarser rights");
});
test("FileNode/query refuses the filters and sorts this generation lacks", async () => {
const filtered = await jmap([CORE, FILES], [["FileNode/query", { accountId: "a1", filter: { isTopLevel: true } }, "c0"]]);
assert.equal(filtered.body.methodResponses[0][1].type, "unsupportedFilter");
const sorted = await jmap([CORE, FILES], [["FileNode/query", { accountId: "a1", sort: [{ property: "nodeType" }] }, "c0"]]);
assert.equal(sorted.body.methodResponses[0][1].type, "unsupportedSort");
});
test("an identity signature is capped in bytes, not characters", async () => {
// 1200 CJK characters: comfortably under 2047 counted as characters, and
// 3600 bytes once encoded.
const tooBig = "日".repeat(1200);
assert.ok(tooBig.length < 2047 && Buffer.byteLength(tooBig, "utf8") > 2047);
const res = await jmap([CORE, MAIL], [["Identity/set", { accountId: "a1", update: { i1: { htmlSignature: tooBig } } }, "c0"]]);
const set = res.body.methodResponses[0][1];
assert.equal(set.notUpdated.i1.type, "invalidProperties");
assert.deepEqual(set.notUpdated.i1.properties, ["htmlSignature"]);
});
+9 -37
View File
@@ -47,25 +47,27 @@ after(() => {
});
/**
* Stalwart advertises `urn:stalwart:jmap` only per-account, never in the
* session-level capabilities. Looking for it at the top level alone reported
* every real 0.16 server as older than 0.16 — and now that the same check
* decides whether a sign-in is allowed at all, that mistake would lock
* everyone out rather than merely misroute credentials.
* What the About page reads. Stalwart advertises `urn:stalwart:jmap` only
* per-account, so a session that looks for it at the top level reports a real
* 0.16 server as older than 0.16 — the same mistake that sent credentials to
* the removed REST endpoint.
*/
test("the session is accepted on a server that advertises the registry per-account", async () => {
test("the session reports the 0.16 generation the server actually is", async () => {
const res = await call("/api/auth/session");
assert.equal(res.status, 200);
assert.equal(res.body.ihasmail.server.generation, "0.16+");
assert.equal(res.body.ihasmail.server.edition, "oss");
assert.equal(res.body.capabilities["urn:stalwart:jmap"], undefined, "not where a client would first look");
assert.ok("urn:stalwart:jmap" in res.body.primaryAccounts, "but here, as on a real server");
});
test("the registry reports an account with nothing set up yet", async () => {
test("the 0.16 registry backend is detected and reported empty", async () => {
const res = await call("/api/account/security");
assert.equal(res.status, 200);
assert.equal(res.body.backend, "registry");
assert.equal(res.body.otpEnabled, false);
assert.deepEqual(res.body.appPasswords, []);
assert.equal(res.body.appPasswordsKeyedByName, false);
});
test("app passwords are created, listed once with their secret, and revoked", async () => {
@@ -174,33 +176,3 @@ test("credential endpoints reject unauthenticated callers", async () => {
assert.equal((await post("/api/account/2fa/begin", {})).status, 401);
cookie = saved;
});
/**
* A sign-in carrying a two-factor code that the server rejects is almost never
* "wrong password". Stalwart accepts TOTP only through an OAuth flow and offers
* no password grant, so the concatenated form ihasmail sends cannot work — and
* saying "invalid credentials" sends the user to check a password that is fine.
*
* Reported as #75: 2FA sign-in failed with a bare 401 while an app password
* worked, which is Stalwart's documented route and gave no hint of itself.
*/
test("a rejected sign-in carrying a TOTP code explains itself", async () => {
const saved = cookie;
cookie = "";
const res = await post("/api/auth/login", { username: "[email protected]", password: "demo-password", totp: "123456" });
cookie = saved;
assert.equal(res.status, 401);
assert.equal(res.body.error, "totp_unsupported", "not the generic invalid_credentials");
assert.match(res.body.message, /app password/i, "points at the route that does work");
assert.match(res.body.message, /probably fine/i, "does not blame the password");
});
test("a rejected sign-in without a code is still a plain credential failure", async () => {
// The explanation must not leak onto ordinary typos.
const saved = cookie;
cookie = "";
const res = await post("/api/auth/login", { username: "[email protected]", password: "wrong" });
cookie = saved;
assert.equal(res.status, 401);
assert.equal(res.body.error, "invalid_credentials");
});
+223 -45
View File
@@ -1,15 +1,17 @@
import { config } from "./config.js";
import { absoluteUpstream, UpstreamError, type UpstreamSession } from "./upstream.js";
import { absoluteUpstream, hasStalwartRegistry, UpstreamError, type UpstreamSession } from "./upstream.js";
import { generateSecret, otpauthUrl, parseOtpauthUrl, verifyTotp } from "./totp.js";
import { randomBytes } from "node:crypto";
/**
* Self-service credential management, over Stalwart's JMAP registry:
* `x:AccountPassword` (a singleton holding the password and the otpauth URL)
* and `x:AppPassword`.
* Self-service credential management, across two incompatible Stalwart APIs.
*
* The registry crate arrived in 0.16, which is the oldest Stalwart ihasmail
* supports. Sign-in refuses anything older, so by the time any of this runs
* the registry is known to be there.
* 0.16+ JMAP registry objects: x:AccountPassword (a singleton holding the
* password and the otpauth URL) and x:AppPassword.
* 0.15.x a REST endpoint, POST /api/account/auth, taking a list of actions.
*
* The registry crate does not exist before 0.16 and the REST endpoint is gone
* after it, so which one answers is the only reliable way to tell them apart.
*/
const STALWART_CAP = "urn:stalwart:jmap";
@@ -19,7 +21,10 @@ const SINGLETON = "singleton";
/** Returned in place of a stored secret; echo it back to leave one unchanged. */
const MASKED = "[********]";
export type Backend = "registry" | "legacy";
export interface AppPasswordRow {
/** Registry object id, or the name itself on legacy servers. */
id: string;
description: string;
createdAt: string | null;
@@ -27,8 +32,14 @@ export interface AppPasswordRow {
}
export interface SecurityState {
backend: Backend;
otpEnabled: boolean;
appPasswords: AppPasswordRow[];
/**
* Legacy servers key app passwords by name and hand back nothing else, so
* the UI must keep names unique and cannot show when one was created.
*/
appPasswordsKeyedByName: boolean;
}
/** An error with a message meant for the person using the app. */
@@ -50,7 +61,49 @@ interface Ctx {
}
/* ------------------------------------------------------------------ */
/* Transport */
/* Backend detection */
/* ------------------------------------------------------------------ */
const backendCache = new Map<string, { backend: Backend; at: number }>();
const BACKEND_CACHE_MS = 30 * 60_000;
export function forgetBackend(sessionId: string): void {
backendCache.delete(sessionId);
}
export async function detectBackend(sessionId: string, ctx: Ctx): Promise<Backend> {
const cached = backendCache.get(sessionId);
if (cached && Date.now() - cached.at < BACKEND_CACHE_MS) return cached.backend;
const backend = await probeBackend(ctx);
backendCache.set(sessionId, { backend, at: Date.now() });
return backend;
}
async function probeBackend(ctx: Ctx): Promise<Backend> {
// A server with the registry answers x:AccountPassword/get; one without it
// fails to parse the method name at all and returns unknownMethod.
if (hasStalwartRegistry(ctx.session)) {
try {
const res = await jmap(ctx, [["x:AccountPassword/get", { accountId: accountId(ctx), ids: [SINGLETON] }, "p"]]);
const [name, args] = res.methodResponses?.[0] ?? [];
if (name && name !== "error") return "registry";
const type = (args as { type?: string } | undefined)?.type;
if (type && type !== "unknownMethod") return "registry"; // present, but refused us
} catch {
// The capability already told us this server has the registry, so a
// request we could not read is a fault to surface, not evidence of an
// older server. Falling back here would post the user's password to a
// REST endpoint 0.16 removed and report the feature as unsupported.
return "registry";
}
// It named the capability and then disowned the method: nothing else to try.
return "registry";
}
return "legacy";
}
/* ------------------------------------------------------------------ */
/* Transports */
/* ------------------------------------------------------------------ */
function accountId(ctx: Ctx): string {
@@ -65,7 +118,7 @@ function accountId(ctx: Ctx): string {
type Invocation = [string, Record<string, unknown>, string];
async function jmap(ctx: Ctx, methodCalls: Invocation[]): Promise<{ methodResponses?: [string, unknown, string][] }> {
const res = await fetch(absoluteUpstream(ctx.session.apiUrl, ctx.session.baseUrl), {
const res = await fetch(absoluteUpstream(ctx.session.apiUrl), {
method: "POST",
headers: { authorization: ctx.authorization, "content-type": "application/json", accept: "application/json" },
body: JSON.stringify({ using: [JMAP_CORE, STALWART_CAP], methodCalls }),
@@ -76,6 +129,29 @@ async function jmap(ctx: Ctx, methodCalls: Invocation[]): Promise<{ methodRespon
return (await res.json()) as { methodResponses?: [string, unknown, string][] };
}
async function legacy<T>(ctx: Ctx, init: RequestInit): Promise<T> {
const res = await fetch(`${config.stalwartUrl}/api/account/auth`, {
...init,
headers: { authorization: ctx.authorization, "content-type": "application/json", accept: "application/json" },
signal: AbortSignal.timeout(config.upstreamTimeout),
});
if (res.status === 401 || res.status === 403) throw new UpstreamError("Invalid credentials", 401);
if (res.status === 404) {
throw new AccountError("This mail server does not offer self-service credential management.", 501, "unsupported");
}
if (!res.ok) {
let detail = "";
try {
const body = (await res.json()) as { error?: string; details?: string; reason?: string };
detail = body.details ?? body.reason ?? body.error ?? "";
} catch {
/* fall through to the generic message */
}
throw new AccountError(detail || `The mail server rejected the change (${res.status}).`, 502, "upstream");
}
return ((await res.json()) as { data: T }).data;
}
/**
* Pull the single result out of a /set, turning JMAP's several failure shapes
* into one error carrying whatever the server was willing to explain.
@@ -116,7 +192,17 @@ function describeSetError(err: { type?: string; description?: string; properties
/* Operations */
/* ------------------------------------------------------------------ */
export async function getState(ctx: Ctx): Promise<SecurityState> {
export async function getState(sessionId: string, ctx: Ctx): Promise<SecurityState> {
const backend = await detectBackend(sessionId, ctx);
if (backend === "legacy") {
const data = await legacy<{ otpEnabled?: boolean; appPasswords?: string[] }>(ctx, { method: "GET" });
return {
backend,
otpEnabled: Boolean(data.otpEnabled),
appPasswords: (data.appPasswords ?? []).map((name) => ({ id: name, description: name, createdAt: null, expiresAt: null })),
appPasswordsKeyedByName: true,
};
}
const id = accountId(ctx);
const res = await jmap(ctx, [
["x:AccountPassword/get", { accountId: id, ids: [SINGLETON] }, "p"],
@@ -125,6 +211,7 @@ export async function getState(ctx: Ctx): Promise<SecurityState> {
const pass = firstListItem(res, "p") as { otpAuth?: { otpUrl?: string | null } } | null;
const apps = listOf(res, "a");
return {
backend,
// The URL itself is masked; its presence is what tells us 2FA is on.
otpEnabled: Boolean(pass?.otpAuth?.otpUrl),
appPasswords: apps.map((a) => ({
@@ -133,6 +220,7 @@ export async function getState(ctx: Ctx): Promise<SecurityState> {
createdAt: typeof a.createdAt === "string" ? a.createdAt : null,
expiresAt: typeof a.expiresAt === "string" ? a.expiresAt : null,
})),
appPasswordsKeyedByName: false,
};
}
@@ -147,25 +235,56 @@ function firstListItem(res: { methodResponses?: [string, unknown, string][] }, c
return listOf(res, callId)[0] ?? null;
}
export async function changePassword(ctx: Ctx, opts: { current: string; next: string; otpCode?: string }): Promise<void> {
const update: Record<string, unknown> = { currentSecret: opts.current, secret: opts.next };
if (opts.otpCode) update["otpAuth/otpCode"] = opts.otpCode;
const res = await jmap(ctx, [["x:AccountPassword/set", { accountId: accountId(ctx), update: { [SINGLETON]: update } }, "s"]]);
setResult(res, "updated");
export async function changePassword(
sessionId: string,
ctx: Ctx,
opts: { current: string; next: string; otpCode?: string },
): Promise<void> {
const backend = await detectBackend(sessionId, ctx);
if (backend === "registry") {
const update: Record<string, unknown> = { currentSecret: opts.current, secret: opts.next };
if (opts.otpCode) update["otpAuth/otpCode"] = opts.otpCode;
const res = await jmap(ctx, [["x:AccountPassword/set", { accountId: accountId(ctx), update: { [SINGLETON]: update } }, "s"]]);
setResult(res, "updated");
return;
}
// The legacy endpoint changes the password without asking for the old one,
// so anyone holding a live session could set it. Prove it ourselves first.
await assertCurrentPassword(ctx, opts.current, opts.otpCode);
await legacy<unknown>(ctx, { method: "POST", body: JSON.stringify([{ type: "setPassword", password: opts.next }]) });
}
export async function createAppPassword(ctx: Ctx, opts: { description: string }): Promise<{ id: string; secret: string }> {
export async function createAppPassword(
sessionId: string,
ctx: Ctx,
opts: { description: string },
): Promise<{ id: string; secret: string }> {
const backend = await detectBackend(sessionId, ctx);
const description = opts.description.trim() || "App password";
const res = await jmap(ctx, [["x:AppPassword/set", { accountId: accountId(ctx), create: { n: { description } } }, "s"]]);
const created = setResult(res, "created");
const secret = created && typeof created.secret === "string" ? created.secret : "";
if (!secret) throw new AccountError("The mail server created the app password but did not return it.", 502, "upstream");
return { id: String(created?.id ?? description), secret };
if (backend === "registry") {
const res = await jmap(ctx, [["x:AppPassword/set", { accountId: accountId(ctx), create: { n: { description } } }, "s"]]);
const created = setResult(res, "created");
const secret = created && typeof created.secret === "string" ? created.secret : "";
if (!secret) throw new AccountError("The mail server created the app password but did not return it.", 502, "upstream");
return { id: String(created?.id ?? description), secret };
}
// Legacy servers take a secret of our choosing and key it by name.
const secret = readableSecret();
await legacy<unknown>(ctx, {
method: "POST",
body: JSON.stringify([{ type: "addAppPassword", name: description, password: secret }]),
});
return { id: description, secret };
}
export async function revokeAppPassword(ctx: Ctx, id: string): Promise<void> {
const res = await jmap(ctx, [["x:AppPassword/set", { accountId: accountId(ctx), destroy: [id] }, "s"]]);
setResult(res, "destroyed");
export async function revokeAppPassword(sessionId: string, ctx: Ctx, id: string): Promise<void> {
const backend = await detectBackend(sessionId, ctx);
if (backend === "registry") {
const res = await jmap(ctx, [["x:AppPassword/set", { accountId: accountId(ctx), destroy: [id] }, "s"]]);
setResult(res, "destroyed");
return;
}
await legacy<unknown>(ctx, { method: "POST", body: JSON.stringify([{ type: "removeAppPassword", name: id }]) });
}
/**
@@ -192,30 +311,89 @@ export function assertEnrolmentCode(url: string, code: string): void {
}
}
export async function enableOtp(ctx: Ctx, opts: { url: string; code: string; current: string }): Promise<void> {
export async function enableOtp(
sessionId: string,
ctx: Ctx,
opts: { url: string; code: string; current: string },
): Promise<void> {
assertEnrolmentCode(opts.url, opts.code);
const res = await jmap(ctx, [
[
"x:AccountPassword/set",
{ accountId: accountId(ctx), update: { [SINGLETON]: { currentSecret: opts.current, "otpAuth/otpUrl": opts.url } } },
"s",
],
]);
setResult(res, "updated");
const backend = await detectBackend(sessionId, ctx);
if (backend === "registry") {
const res = await jmap(ctx, [
[
"x:AccountPassword/set",
{ accountId: accountId(ctx), update: { [SINGLETON]: { currentSecret: opts.current, "otpAuth/otpUrl": opts.url } } },
"s",
],
]);
setResult(res, "updated");
return;
}
await assertCurrentPassword(ctx, opts.current);
await legacy<unknown>(ctx, { method: "POST", body: JSON.stringify([{ type: "enableOtpAuth", url: opts.url }]) });
}
export async function disableOtp(ctx: Ctx, opts: { current: string; code: string }): Promise<void> {
const res = await jmap(ctx, [
[
"x:AccountPassword/set",
{
accountId: accountId(ctx),
update: { [SINGLETON]: { currentSecret: opts.current, "otpAuth/otpCode": opts.code, "otpAuth/otpUrl": null } },
},
"s",
],
]);
setResult(res, "updated");
export async function disableOtp(
sessionId: string,
ctx: Ctx,
opts: { current: string; code: string },
): Promise<void> {
const backend = await detectBackend(sessionId, ctx);
if (backend === "registry") {
const res = await jmap(ctx, [
[
"x:AccountPassword/set",
{
accountId: accountId(ctx),
update: { [SINGLETON]: { currentSecret: opts.current, "otpAuth/otpCode": opts.code, "otpAuth/otpUrl": null } },
},
"s",
],
]);
setResult(res, "updated");
return;
}
await assertCurrentPassword(ctx, opts.current, opts.code);
await legacy<unknown>(ctx, { method: "POST", body: JSON.stringify([{ type: "disableOtpAuth", url: null }]) });
}
/**
* Confirm a password by authenticating with it, for the legacy endpoint that
* would otherwise take our word for it.
*/
async function assertCurrentPassword(ctx: Ctx, current: string, otpCode?: string): Promise<void> {
const secret = otpCode ? `${current}$${otpCode}` : current;
const authorization = `Basic ${Buffer.from(`${ctx.username}:${secret}`, "utf8").toString("base64")}`;
const res = await fetch(`${config.stalwartUrl}/.well-known/jmap`, {
headers: { authorization, accept: "application/json" },
redirect: "follow",
signal: AbortSignal.timeout(config.upstreamTimeout),
});
if (res.status === 401 || res.status === 403) {
throw new AccountError("That password is incorrect.", 403, "bad_password");
}
if (!res.ok) throw new UpstreamError(`Could not verify the current password (${res.status})`, 502);
}
/**
* A legacy app password a person can read off a screen and type.
*
* Drawn by rejection sampling. Plain `% alphabet.length` would favour the
* first 25 characters, because 256 is not a multiple of 33: each of those
* would come up on 8 byte values and the remaining 8 on only 7.
*/
export function readableSecret(): string {
const alphabet = "abcdefghijkmnopqrstuvwxyz23456789"; // no l/1/0 lookalikes
const limit = 256 - (256 % alphabet.length);
const chars: string[] = [];
while (chars.length < 20) {
for (const b of randomBytes(32)) {
if (b >= limit) continue; // the tail that would skew the alphabet
chars.push(alphabet[b % alphabet.length]!);
if (chars.length === 20) break;
}
}
return (chars.join("").match(/.{5}/g) ?? []).join("-");
}
export { MASKED };
+37 -47
View File
@@ -7,8 +7,7 @@ import { getAccountInfo, hasStalwartRegistry, interpretAccountInfo } from "./ups
* the `sysAccountGet` permission — one the built-in `user` role is not given.
* Ordinary users therefore silently fell back to the browser locale. Stalwart
* 0.16 exposes the same field on `x:AccountSettings`, which users *can* read,
* so both are asked for and whichever answers wins. Both are 0.16 methods:
* this is a permissions fallback, not a version one.
* so both are asked for and whichever answers wins.
*/
type Responses = [string, Record<string, unknown>, string][];
@@ -20,6 +19,7 @@ const failed = (id: string, type: string): Responses[number] => ["error", { type
test("prefers the locale a regular user is allowed to read", () => {
const info = interpretAccountInfo([settingsOk("de_DE.UTF-8"), accountOk("fr_FR")]);
assert.equal(info.locale, "de-DE");
assert.equal(info.generation, "0.16+");
});
test("falls back to x:Account when the settings object is forbidden", () => {
@@ -27,14 +27,22 @@ test("falls back to x:Account when the settings object is forbidden", () => {
assert.equal(info.locale, "sr-Latn-RS");
});
test("an account with no locale set yields none, rather than a guess", () => {
test("an older server is recognised by its unknownMethod, and still yields a locale", () => {
const info = interpretAccountInfo([failed("s", "unknownMethod"), accountOk("en_GB")]);
assert.equal(info.generation, "pre-0.16");
assert.equal(info.locale, "en-GB");
});
test("a server answering the new method is 0.16+ even with no locale set", () => {
const info = interpretAccountInfo([["x:AccountSettings/get", { list: [] }, "s"], failed("a", "forbidden")]);
assert.equal(info.generation, "0.16+");
assert.equal(info.locale, null);
});
test("neither answering leaves the locale unknown", () => {
assert.deepEqual(interpretAccountInfo([failed("s", "forbidden"), failed("a", "forbidden")]), { locale: null, edition: null, permissions: [] });
assert.deepEqual(interpretAccountInfo([]), { locale: null, edition: null, permissions: [] });
test("neither answering leaves everything unknown rather than guessing", () => {
const info = interpretAccountInfo([failed("s", "forbidden"), failed("a", "forbidden")]);
assert.deepEqual(info, { locale: null, generation: null, edition: null });
assert.deepEqual(interpretAccountInfo([]), { locale: null, generation: null, edition: null });
});
test("locales that carry no language are dropped, not passed through", () => {
@@ -42,18 +50,20 @@ test("locales that carry no language are dropped, not passed through", () => {
assert.equal(interpretAccountInfo([settingsOk("POSIX")]).locale, null);
});
test("a server without the registry is not asked for anything", async () => {
// Sign-in refuses these, so getAccountInfo should never reach the wire for
// one - and must not, since a server that cannot parse `urn:stalwart:jmap`
// fails the whole request rather than the one call.
test("a server that never heard of the Stalwart capability is reported as pre-0.16", async () => {
// 0.16 always advertises urn:stalwart:jmap and nothing older knows it at all,
// so its absence is the answer - and asking anyway would fail the whole
// request on those servers. This is what the live 0.15.5 box hits.
const session = { capabilities: { "urn:ietf:params:jmap:core": {}, "urn:ietf:params:jmap:mail": {} }, accounts: {}, primaryAccounts: {} };
const info = await getAccountInfo("session-unsupported", "Basic x", session as never);
assert.deepEqual(info, { locale: null, edition: null, permissions: [] });
const info = await getAccountInfo("session-pre-016", "Basic x", session as never);
assert.equal(info.generation, "pre-0.16");
assert.equal(info.locale, null);
assert.equal(info.edition, null);
});
test("no capabilities at all is treated the same way", async () => {
test("no capabilities at all leaves the generation unknown", async () => {
const info = await getAccountInfo("session-no-caps", "Basic x", { accounts: {}, primaryAccounts: {} } as never);
assert.equal(info.locale, null);
assert.equal(info.generation, null);
});
/**
@@ -63,12 +73,9 @@ test("no capabilities at all is treated the same way", async () => {
* fixed list that has never carried this capability, in any 0.16.x. It is
* handed out per-account instead, so it lands in `primaryAccounts` and in each
* account's `accountCapabilities`. Looking only at the session level called
* every real 0.16 server too old, which sent self-service credentials to a
* every real 0.16 server pre-0.16, which sent self-service credentials to a
* REST endpoint 0.16 had removed and made the About page report the wrong
* thing.
*
* This check now decides whether a sign-in is allowed at all, so getting it
* wrong would lock every user out of a perfectly good server.
* generation.
*/
const STALWART = "urn:stalwart:jmap";
const baseCaps = { "urn:ietf:params:jmap:core": {}, "urn:ietf:params:jmap:mail": {} };
@@ -95,7 +102,7 @@ test("the session level still counts, for a server that ever advertises it there
assert.equal(hasStalwartRegistry({ capabilities: { ...baseCaps, [STALWART]: {} }, accounts: {}, primaryAccounts: {} }), true);
});
test("a server that advertises it nowhere is one we do not support", () => {
test("a server that advertises it nowhere is pre-0.16", () => {
assert.equal(hasStalwartRegistry({ capabilities: baseCaps, accounts: { a1: { accountCapabilities: baseCaps } }, primaryAccounts: { "urn:ietf:params:jmap:mail": "a1" } }), false);
assert.equal(hasStalwartRegistry(undefined), false);
});
@@ -111,31 +118,14 @@ test("a shared account carrying the capability is enough to recognise the server
);
});
/**
* With a domain mapped to its own Stalwart (#238), everything asked about the
* account has to go to that server. The locale lookup resolved Stalwart's
* `apiUrl` against the default server instead, so a mapped account's locale
* was requested from a server that had never heard of it.
*/
test("account info is asked of the server that issued the session", async () => {
const seen: string[] = [];
const realFetch = globalThis.fetch;
globalThis.fetch = (async (input: string | URL | Request) => {
seen.push(String(input instanceof Request ? input.url : input));
return new Response(JSON.stringify({ methodResponses: [], edition: "oss" }), { status: 200, headers: { "content-type": "application/json" } });
}) as typeof fetch;
try {
const session = {
capabilities: baseCaps,
accounts: { a1: { accountCapabilities: { [STALWART]: {} } } },
primaryAccounts: { [STALWART]: "a1" },
apiUrl: "https://mail.mapped.test/jmap/",
baseUrl: "https://mail.mapped.test",
};
await getAccountInfo("session-mapped-domain", "Basic x", session as never);
} finally {
globalThis.fetch = realFetch;
}
assert.ok(seen.length >= 2, "asks for both the locale and the edition");
for (const url of seen) assert.ok(url.startsWith("https://mail.mapped.test/"), `${url} went to the wrong server`);
test("a locale request that fails does not talk us out of a generation we proved", () => {
// The capability settled it. A forbidden reply costs the locale, nothing more.
const info = interpretAccountInfo([failed("s", "forbidden"), failed("a", "forbidden")], "0.16+");
assert.equal(info.generation, "0.16+");
assert.equal(info.locale, null);
});
test("a server that disowns the method is still older, whatever we came in believing", () => {
const info = interpretAccountInfo([failed("s", "unknownMethod")], "0.16+");
assert.equal(info.generation, "pre-0.16");
});
-71
View File
@@ -1,71 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { administrationAllowed, gateAdministration, grantsAdministration, mayNameRegistryMethod } from "./adminGate.js";
const req = (...methods: string[]) => JSON.stringify({ using: ["urn:ietf:params:jmap:core"], methodCalls: methods.map((m, i) => [m, {}, `c${i}`]) });
/**
* With ADMINISTRATION=0 an administrator's browser must not be a way round the
* operator's decision. Hiding the menu would leave the proxy forwarding the
* very calls the menu made.
*/
test("mail, calendars and the rest pass untouched", () => {
const r = gateAdministration(req("Email/query", "Mailbox/get", "CalendarEvent/set", "FileNode/get", "Principal/getAvailability"));
assert.equal(r.ok, true);
});
test("the account's own registry objects pass", () => {
assert.equal(gateAdministration(req("x:AccountSettings/get", "x:AppPassword/set", "x:PublicKey/get", "x:MaskedEmail/set")).ok, true);
});
test("directory and server objects are refused, and named", () => {
for (const m of ["x:Account/get", "x:Domain/set", "x:Role/query", "x:Tenant/get", "x:SystemSettings/set", "x:DkimSignature/get"]) {
assert.deepEqual(gateAdministration(req("Email/get", m)), { ok: false, method: m });
}
});
test("a body that could name a registry method and cannot be read is refused rather than forwarded", () => {
assert.deepEqual(gateAdministration('{"methodCalls": [["x:Account/get"'), { ok: false, method: null });
assert.deepEqual(gateAdministration(JSON.stringify({ methodCalls: "x:Account/get" })), { ok: false, method: null });
assert.deepEqual(gateAdministration(JSON.stringify({ methodCalls: [[{}, {}, "c"]], note: "x:" })), { ok: false, method: null });
});
test("a body that cannot name a registry method is forwarded exactly as it came", () => {
// Most traffic from a session that may not administer: no parse, no rewrite.
const raw = '{"using":["urn:ietf:params:jmap:core"],"methodCalls":[["Email/get",{"ids":["a"]},"c"]]}';
assert.equal(mayNameRegistryMethod(raw), false);
assert.deepEqual(gateAdministration(raw), { ok: true, body: raw });
});
test("a method name hidden behind a unicode escape is still found", () => {
// JSON.parse and the server both read \u0078 as "x"; a substring check alone would not.
const raw = '{"methodCalls":[["\\u0078:Account/get",{},"c"]]}';
assert.equal(mayNameRegistryMethod(raw), true);
assert.deepEqual(gateAdministration(raw), { ok: false, method: "x:Account/get" });
});
/**
* The operator's rule: administration only from a session signed in with
* "This is my own device" ticked, and never when the installation turned it off.
*/
test("administration needs both the installation and a device marked as the person's own", () => {
assert.equal(administrationAllowed(true, true), true);
assert.equal(administrationAllowed(true, false), false);
assert.equal(administrationAllowed(false, true), false);
});
test("an account counts as an administrator by the same test the menu makes", () => {
assert.equal(grantsAdministration(["sysAccountQuery", "sysAccountGet"]), true);
assert.equal(grantsAdministration(["sysDomainQuery", "sysDomainGet"]), true);
assert.equal(grantsAdministration(["sysAccountQuery", "sysDomainGet"]), false);
assert.equal(grantsAdministration(["jmapEmailGet", "sysAccountSettingsGet"]), false);
});
test("what is forwarded is what was checked", () => {
// A duplicate key is read one way by JSON.parse; forwarding the parsed form
// means the server cannot read it the other way.
const raw = '{"methodCalls":[["x:Account/get",{},"a"]],"methodCalls":[["Email/get",{},"b"]]}';
const r = gateAdministration(raw);
assert.equal(r.ok, true);
if (r.ok) assert.equal(r.body, JSON.stringify({ methodCalls: [["Email/get", {}, "b"]] }));
});
-85
View File
@@ -1,85 +0,0 @@
/**
* What the JMAP proxy lets through for a session that may not administer:
* the operator turned it off (`ADMINISTRATION=0`), or the session was signed
* in without "This is my own device".
*
* Hiding the menu is not turning it off. `/api/jmap` forwards any method the
* browser sends, and Stalwart's registry answers whatever the credential's role
* allows -- so without this, an administrator could still manage accounts, or
* the whole server, from the browser console of an installation whose operator
* said no. With it off, the proxy refuses every `x:` method except the few that
* are about the signed-in account itself.
*
* An allowlist rather than a list of administrative objects, because the
* registry has dozens of them -- listeners, stores, tracers, system settings --
* and a new release adds more. An object not named here is refused, which errs
* towards the operator's decision.
*
* The standard JMAP methods (mail, calendars, contacts, files, sharing) are not
* touched: they act on what the account can already reach.
*/
const SELF_SERVICE = new Set(["AccountSettings", "AccountPassword", "AppPassword", "ApiKey", "PublicKey", "MaskedEmail"]);
export type GateResult = { ok: true; body: string } | { ok: false; method: string | null };
/**
* Whether a session may administer at all: the installation allows it, and
* the person signing in said the device is their own.
*
* The second half is the operator's rule, not Stalwart's. A borrowed laptop or
* a library machine is exactly where a session should not be able to reset a
* password or remove a domain, and "This is my own device" is the one thing
* the sign-in form already asks that says where it is being used. An untrusted
* session is also signed out when idle and wipes its local data, so nothing
* about it suits an administrator's work.
*/
export function administrationAllowed(enabled: boolean, remember: boolean): boolean {
return enabled && remember;
}
/**
* Whether an account's permissions would put Administration in its menu --
* the same test the client makes, so the server can say why it is missing
* without handing over the permissions themselves.
*/
export function grantsAdministration(permissions: readonly string[]): boolean {
const has = new Set(permissions);
return (has.has("sysAccountQuery") && has.has("sysAccountGet")) || (has.has("sysDomainQuery") && has.has("sysDomainGet"));
}
/**
* Whether a body could hold a registry method name at all, so the common case
* -- mail, calendars, contacts from a session that may not administer -- skips
* the parse. A method name is a JSON string starting `x:`, which appears in the
* text as `"x:` unless written with a `\u` escape; a body with neither cannot
* contain one, and is forwarded exactly as it came.
*/
export function mayNameRegistryMethod(raw: string): boolean {
return raw.includes('"x:') || raw.includes("\\u");
}
/**
* Check a JMAP request body. On success, hands back the body to forward --
* serialised from what was inspected, so the server can never be sent
* something different from what was checked (a duplicate key, say, read one
* way here and another way there).
*/
export function gateAdministration(raw: string): GateResult {
if (!mayNameRegistryMethod(raw)) return { ok: true, body: raw };
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return { ok: false, method: null };
}
const calls = (parsed as { methodCalls?: unknown } | null)?.methodCalls;
if (!Array.isArray(calls)) return { ok: false, method: null };
for (const call of calls) {
const name = Array.isArray(call) ? call[0] : undefined;
if (typeof name !== "string") return { ok: false, method: null };
if (!name.startsWith("x:")) continue;
const object = name.slice(2).split("/")[0] ?? "";
if (!SELF_SERVICE.has(object)) return { ok: false, method: name };
}
return { ok: true, body: JSON.stringify(parsed) };
}
-109
View File
@@ -35,112 +35,3 @@ test("image proxy refuses private targets", async () => {
const res = await app.request("/api/image?url=http://127.0.0.1/x");
assert.equal(res.status, 401);
});
test("a compressed upstream blob is not forwarded with the compressed length", async () => {
const { forwardedContentLength } = await import("./app.js");
// gzip: the body we forward has already been decompressed, so the length on
// the wire describes different bytes and must not be copied (issue #76).
const gz = new Headers({ "content-encoding": "gzip", "content-length": "384" });
assert.equal(forwardedContentLength(gz), null);
// identity, spelled out or absent: the length describes the body we send.
assert.equal(forwardedContentLength(new Headers({ "content-encoding": "identity", "content-length": "1157" })), "1157");
assert.equal(forwardedContentLength(new Headers({ "content-length": "1157" })), "1157");
assert.equal(forwardedContentLength(new Headers({ "content-encoding": "BR", "content-length": "384" })), null);
// Nothing to forward is not an error.
assert.equal(forwardedContentLength(new Headers()), null);
});
test("a Sieve script larger than a compressing hop's threshold survives the proxy", async () => {
const http = await import("node:http");
const zlib = await import("node:zlib");
const { forwardedContentLength } = await import("./app.js");
const script =
"# ihasmail filters v1 - edit with care; rules are stored in the `# rule:` comments\nrequire [\"fileinto\"];\n\n" +
["a", "b", "c"]
.map(
(k) =>
`# rule:{"id":"r${k}","name":"From ${k}@example.com","enabled":true,"join":"allof","tests":[{"type":"header","header":"from","op":"contains","value":"${k}@example.com"}],"actions":[{"type":"fileinto","mailbox":"INBOX/${k}"}]}\n` +
`if header :contains "from" "${k}@example.com"\n{\n fileinto "INBOX/${k}";\n}\n\n`,
)
.join("");
const gz = zlib.gzipSync(Buffer.from(script));
assert.ok(gz.length < Buffer.byteLength(script), "the script has to compress for this test to mean anything");
// A hop that compresses regardless of what we asked for.
const origin = http.createServer((_req, res) => {
res.writeHead(200, { "content-type": "application/sieve", "content-encoding": "gzip", "content-length": String(gz.length) });
res.end(gz);
});
await new Promise<void>((r) => origin.listen(0, () => r()));
const port = (origin.address() as { port: number }).port;
try {
const up = await fetch(`http://127.0.0.1:${port}/`);
// What the blob route forwards.
const headers = new Headers({ "content-type": "application/sieve; charset=utf-8" });
const cl = forwardedContentLength(up.headers);
if (cl) headers.set("Content-Length", cl);
const out = new Response(await up.arrayBuffer(), { status: 200, headers });
assert.equal(out.headers.get("content-length"), null);
assert.equal(await out.text(), script);
} finally {
origin.close();
}
});
test("only a PDF blob may be framed, and only by us", async () => {
/*
* The PDF preview is an iframe, and the blanket X-Frame-Options: DENY on
* every response blocked it -- the dialog showed Chrome's "refused to
* connect" where the file should have been. The middleware now leaves a
* header a route has already set, so this pins both halves: the exception
* exists, and it did not become the rule.
*/
const app = createApp();
const health = await app.request("/api/health");
assert.equal(health.headers.get("x-frame-options"), "DENY");
const { securityHeadersFor } = await import("./app.js");
assert.equal(securityHeadersFor("application/pdf", true), "SAMEORIGIN");
assert.equal(securityHeadersFor("application/pdf", false), "DENY");
assert.equal(securityHeadersFor("image/png", true), "DENY");
assert.equal(securityHeadersFor("text/html", true), "DENY");
});
/*
* #239: retrying through an outage must not lock somebody out of the recovery.
*
* STALWART_URL at the top of this file is 127.0.0.1:1 — nothing listens there,
* so every sign-in here is the outage case. Before the fix, the eleventh of
* these came back 429 and stayed 429 for fifteen minutes, outliving whatever
* had actually been wrong.
*/
test("an unreachable upstream does not spend login attempts", async () => {
const app = createApp();
const login = () =>
app.request("/api/auth/login", {
method: "POST",
headers: { "content-type": "application/json", "x-requested-with": "ihasmail" },
body: JSON.stringify({ username: "[email protected]", password: "hunter2" }),
});
// Comfortably past LOGIN_RATE_LIMIT, which defaults to 10.
for (let i = 0; i < 25; i++) {
const res = await login();
assert.notEqual(res.status, 429, `attempt ${i + 1} was rate limited`);
assert.ok(res.status === 502 || res.status === 504, `attempt ${i + 1} said ${res.status}`);
}
});
test("an unreachable upstream says it is not the password", async () => {
const app = createApp();
const res = await app.request("/api/auth/login", {
method: "POST",
headers: { "content-type": "application/json", "x-requested-with": "ihasmail" },
body: JSON.stringify({ username: "[email protected]", password: "hunter2" }),
});
const body = (await res.json()) as { error: string; message: string };
assert.notEqual(body.error, "invalid_credentials");
assert.match(body.message, /not a problem with your password/i);
});
+48 -459
View File
@@ -1,15 +1,9 @@
import { Hono } from "hono";
import type { Context, MiddlewareHandler } from "hono";
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
import { compress } from "hono/compress";
import { request as httpRequest } from "node:http";
import { request as httpsRequest } from "node:https";
import { RESPONSE_ALREADY_SENT } from "@hono/node-server/utils/response";
import { attach as pushAttach, attachRelay as pushAttachRelay, prepare as pushPrepare, receive as pushReceive, pushStatus } from "./push.js";
import { getConnInfo } from "@hono/node-server/conninfo";
import { config } from "./config.js";
import { administrationAllowed, gateAdministration, grantsAdministration } from "./adminGate.js";
import { SessionStore, type SessionBackend, type LiveSession } from "./sessions.js";
import { SessionStore, type LiveSession } from "./sessions.js";
import { RateLimiter } from "./ratelimit.js";
import { resolveClientIp } from "./clientip.js";
import {
@@ -18,11 +12,9 @@ import {
absoluteUpstream,
expandTemplate,
fetchUpstreamSession,
hasStalwartRegistry,
forgetUpstreamSession,
getAccountInfo,
getUpstreamSession,
upstreamFor,
localizeSession,
} from "./upstream.js";
import {
@@ -33,31 +25,17 @@ import {
createAppPassword,
disableOtp,
enableOtp,
forgetBackend,
getState,
revokeAppPassword,
} from "./account.js";
import { imageProxyHandler } from "./imageproxy.js";
import { icsProxyHandler } from "./icsproxy.js";
import { staticHandler } from "./static.js";
type Env = { Variables: { session: LiveSession } };
export const sessions: SessionBackend = new SessionStore(config.sessionFile);
export const sessions = new SessionStore(config.sessionFile);
const loginLimiter = new RateLimiter(config.loginRateLimit, 15 * 60_000);
/*
* The backstop that is never refunded.
*
* `loginLimiter` guards password guessing and gives its attempts back when the
* upstream never judged the password (#239) -- otherwise retrying through an
* outage locks somebody out until after it has ended. But "not counted" cannot
* mean "unlimited": each attempt still costs ihasmail an outbound connection
* that may sit there until `UPSTREAM_TIMEOUT`, so a flood during an outage is
* the one moment the endpoint is cheapest to abuse.
*
* Hence a second ceiling, per address, twenty times looser and refunded never.
* A person retrying an outage will not come near it; something hammering will.
*/
const loginFloodLimiter = new RateLimiter(config.loginRateLimit * 20, 15 * 60_000);
/**
* Credential changes verify the current password upstream, and Stalwart's
* fail2ban counts those failures against the *caller's* IP — which for a proxy
@@ -65,19 +43,6 @@ const loginFloodLimiter = new RateLimiter(config.loginRateLimit * 20, 15 * 60_00
* cannot get the whole deployment banned.
*/
const accountLimiter = new RateLimiter(10, 15 * 60_000);
const apiLimiter = new RateLimiter(config.apiRateLimit, 60_000);
/** Per-session budget on the data path. See config.apiRateLimit. */
const apiRateLimited: MiddlewareHandler<Env> = async (c, next) => {
if (config.apiRateLimit > 0) {
const session = c.get("session");
if (session && !apiLimiter.check(session.id)) {
c.header("Retry-After", String(apiLimiter.retryAfterSeconds(session.id)));
return c.json({ error: "rate_limited" }, 429);
}
}
await next();
};
const HOP_BY_HOP = new Set([
"connection",
@@ -117,9 +82,7 @@ const securityHeaders: MiddlewareHandler = async (c, next) => {
await next();
const h = c.res.headers;
h.set("X-Content-Type-Options", "nosniff");
/* A route that must be framable says so; everything else is DENY. The blob
route is the only one, and only for PDFs -- see the note there. */
if (!h.has("X-Frame-Options")) h.set("X-Frame-Options", "DENY");
h.set("X-Frame-Options", "DENY");
h.set("Referrer-Policy", "no-referrer");
h.set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=(), usb=()");
h.set("Cross-Origin-Opener-Policy", "same-origin");
@@ -128,72 +91,6 @@ const securityHeaders: MiddlewareHandler = async (c, next) => {
};
/** CSRF: require our custom header on all API calls; reject cross-site fetches. */
/**
* Routes that forward somebody else's bytes rather than producing our own.
*
* Compression is right for the app shell, the bundle and our JSON; it is not
* worth the risk on the proxy paths. Those carry a content-length copied from
* upstream under the rules in `forwardedContentLength`, and issue #76 was a
* silent truncation caused by exactly that header disagreeing with the body.
* Re-encoding them would be safe in principle -- the length is dropped and the
* response goes out chunked -- but the payloads are attachments, images and
* calendar data that are already compressed or too small to matter, so there
* is nothing to win and a scar to respect.
*
* `/api/events` needs no entry here: Hono skips `text/event-stream` by content
* type. It is listed anyway, because a future change to that route's type
* should not quietly start buffering the push stream.
*/
const UNCOMPRESSED_ROUTES = [
"/api/blob/",
"/api/image",
"/api/ics",
"/api/upload/",
"/api/events",
/*
* The liveness probe, which is small enough that gzip makes it bigger: 53
* bytes becomes 73. Hono's size threshold cannot catch this on its own,
* because it only applies when the response carries a content-length and
* `c.json()` does not set one. Every other JSON route is left compressed --
* a JMAP response can run to hundreds of kilobytes and its length is just as
* unknown -- so this is the one place worth naming.
*/
"/api/health",
];
/**
* gzip for what we generate.
*
* The bundle ships uncompressed otherwise: 915 KB on the wire where 307 KB
* would do, on every first load. `Caddyfile.example` and
* `nginx.example.conf` both compress at the proxy, but that only helps the
* deployments that use them, and the default should not depend on reading the
* examples.
*
* Hono's middleware declines anything already carrying `Content-Encoding` or
* `Transfer-Encoding`, so a proxy compressing in front of us wins and we do
* not double-encode.
*/
function compressResponses(basePath: string): MiddlewareHandler {
const inner = compress({ threshold: 1024 });
const skip = UNCOMPRESSED_ROUTES.map((r) => `${basePath}${r}`);
if (!config.compressJmap) skip.push(`${basePath}/api/jmap`);
const offersEncoding = /\b(gzip|deflate)\b/i;
return async (c, next) => {
/*
* A client that did not ask for an encoding must not pay for one. Hono's
* middleware still inspects and re-labels every compressible response it
* declines -- setting Vary forces a streamed passthrough to be rebuilt off
* its fast path -- and that was measured at 1.2 ms per JMAP call, on a
* 1.9 ms operation, for a request that never sent Accept-Encoding.
*/
if (!offersEncoding.test(c.req.header("accept-encoding") ?? "")) return next();
const path = new URL(c.req.url).pathname;
if (skip.some((prefix) => path.startsWith(prefix))) return next();
return inner(c, next);
};
}
const csrfGuard: MiddlewareHandler = async (c, next) => {
const site = c.req.header("sec-fetch-site");
if (site && site !== "same-origin" && site !== "none") {
@@ -217,28 +114,12 @@ const requireSession: MiddlewareHandler<Env> = async (c, next) => {
await next();
};
/**
* Scope the session cookie to the mount, not the whole host.
*
* Under a prefix the browser is talking to a hostname that other applications
* share, and a cookie at `/` would be sent to every one of them. Path scoping
* is not a security boundary -- anything on the origin can reach the cookie
* jar -- but it keeps the credential out of requests that have no business
* carrying it, and it lets two ihasmail instances live at `/mail` and
* `/mail2` on one host without signing each other out, which a shared cookie
* name at `/` would do.
*
* `/` for the root case: an empty Path is not the same thing and browsers
* would fall back to the directory of the request that set it.
*/
const cookiePath = config.basePath || "/";
function setSessionCookie(c: Context, value: string, remember: boolean) {
setCookie(c, config.cookieName, value, {
httpOnly: true,
sameSite: "Lax",
secure: isSecureRequest(c),
path: cookiePath,
path: "/",
...(remember ? { maxAge: config.sessionRememberTtl } : {}),
});
}
@@ -249,42 +130,20 @@ function upstreamFailure(c: Context, err: unknown) {
}
const name = (err as Error)?.name ?? "";
if (name === "TimeoutError" || name === "AbortError") {
return c.json({ error: "upstream_timeout", message: "The mail server did not respond in time. This is not a problem with your password." }, 504);
return c.json({ error: "upstream_timeout", message: "The mail server did not respond in time" }, 504);
}
console.error("[ihasmail] upstream failure:", err);
return c.json({ error: "upstream_error", message: "Could not reach the mail server. This is not a problem with your password." }, 502);
return c.json({ error: "upstream_error", message: "Could not reach the mail server" }, 502);
}
/**
* `basePath` is a parameter rather than read straight from the config so the
* tests can mount the same app twice, at the root and under a prefix, without
* re-importing the module to change one environment variable.
*/
export function createApp(basePath = config.basePath): Hono<Env> {
export function createApp(): Hono<Env> {
const app = new Hono<Env>();
app.use("*", securityHeaders);
app.use("*", compressResponses(basePath));
const api = new Hono<Env>();
api.use("*", csrfGuard);
api.get("/health", (c) => c.json({ ok: true, name: config.appName, version: config.version, push: pushStatus() }));
/*
* Stalwart's push delivery. Authenticated by the token in the path -- 32
* random bytes, one per account, known only to us and to Stalwart -- and by
* nothing else, since Stalwart carries no credential when it POSTs. An
* unknown token is a 404 that looks like any other. See push.ts.
*/
app.post(`${basePath}/api/push/:token`, async (c) => {
if (!(c.req.header("content-type") ?? "").toLowerCase().startsWith("application/json")) return c.body(null, 415);
const len = Number(c.req.header("content-length") ?? "0");
if (!len || len > 64 * 1024) return c.body(null, 413);
let body: unknown;
try { body = await c.req.json(); } catch { return c.body(null, 400); }
return c.body(null, (await pushReceive(c.req.param("token"), body)) as 200 | 400 | 404 | 500);
});
api.get("/health", (c) => c.json({ ok: true, name: config.appName, version: "2.0.0" }));
api.get("/config", (c) =>
c.json({
@@ -292,9 +151,6 @@ export function createApp(basePath = config.basePath): Hono<Env> {
sourceUrl: config.sourceUrl,
imageProxy: config.imageProxy,
maxUploadBytes: config.maxUploadBytes,
/* Sent before sign-in like the rest of this: it says what the
installation has decided, not anything about who is asking. */
settingsPolicy: config.settingsPolicy,
}),
);
@@ -313,24 +169,7 @@ export function createApp(basePath = config.basePath): Hono<Env> {
if (!username || !password) return c.json({ error: "missing_credentials" }, 400);
if (username.length > 320 || password.length > 1024) return c.json({ error: "bad_request" }, 400);
/*
* Three checks, answering different questions.
*
* `limitKey` is this username from this address, and `ip` is any username
* from it -- both guard guessing, and both are given back when the upstream
* never got as far as judging the password. Refunding only the first would
* not fix #239: ten retries through an outage would still spend the address
* budget, and behind one office NAT that budget belongs to the whole
* building.
*
* The flood ceiling is the one that is never refunded, and it is the reason
* the other two safely can be.
*/
const limitKey = `${ip}|${username.toLowerCase()}`;
if (!loginFloodLimiter.check(ip)) {
c.header("Retry-After", String(loginFloodLimiter.retryAfterSeconds(ip)));
return c.json({ error: "rate_limited", message: "Too many login attempts. Please wait and try again." }, 429);
}
if (!loginLimiter.check(limitKey) || !loginLimiter.check(ip)) {
c.header("Retry-After", String(loginLimiter.retryAfterSeconds(limitKey)));
return c.json({ error: "rate_limited", message: "Too many login attempts. Please wait and try again." }, 429);
@@ -340,25 +179,7 @@ export function createApp(basePath = config.basePath): Hono<Env> {
const effectivePassword = totp ? `${password}$${totp}` : password;
const authorization = `Basic ${Buffer.from(`${username}:${effectivePassword}`, "utf8").toString("base64")}`;
try {
const upstream = await fetchUpstreamSession(authorization, upstreamFor(username));
// ihasmail requires Stalwart 0.16 or newer. Refuse here, once and
// clearly, rather than signing someone in and letting Files, the account
// locale and self-service credentials each fail in their own way with
// nothing to connect them. The credentials were good, so say so.
if (!hasStalwartRegistry(upstream)) {
// The credentials were accepted; only the server is too old. Not an
// attempt worth counting against them.
loginLimiter.refund(limitKey);
loginLimiter.refund(ip);
return c.json(
{
error: "unsupported_server",
message:
"Your credentials are fine, but this mail server is older than Stalwart 0.16, which ihasmail needs. Upgrade the server, or run the release tagged stalwart-0.15-support.",
},
501,
);
}
const upstream = await fetchUpstreamSession(authorization);
loginLimiter.reset(limitKey);
const { cookie, session } = sessions.create({
username,
@@ -368,49 +189,9 @@ export function createApp(basePath = config.basePath): Hono<Env> {
ip,
});
setSessionCookie(c, cookie, session.remember);
// Start the account's push subscription now, so it is usually verified
// by the time the browser opens its stream. See push.ts.
const mailAccount = upstream.primaryAccounts?.["urn:ietf:params:jmap:mail"];
if (mailAccount) pushPrepare(session.username, mailAccount, session.authorization);
const info = await getAccountInfo(session.id, session.authorization, upstream);
return c.json(localizeSession(upstream, sessionExtras(session, info)));
} catch (err) {
// A rejected sign-in that carried a two-factor code is worth explaining
// rather than calling "invalid credentials", because the credentials are
// very likely fine.
//
// Stalwart accepts a TOTP code only through an OAuth flow -- its own web
// interface is an OAuth client, which is why signing in there works. It
// offers no password grant, so a client holding a username and password
// cannot exchange them plus a code for a token, and the concatenated
// `password$code` form ihasmail sent is not a route the server has. Its
// documented answer for clients like this one is an app password, which
// bypasses TOTP entirely.
//
// ihasmail already relies on that elsewhere: turning 2FA *on* mints an
// app password and moves the session onto it, precisely because a plain
// password stops working from that moment. The sign-in page was the one
// place still pretending otherwise.
if (totp && err instanceof UpstreamError && err.status === 401) {
return c.json(
{
error: "totp_unsupported",
message:
"This mail server does not accept two-factor codes from webmail. Sign in with an app password instead — create one in Stalwart's own settings, under app passwords. Your password and code are probably fine.",
},
401,
);
}
/*
* A 401 is a judgement about the password and stays counted. Anything
* else -- refused, timed out, DNS, TLS -- is the upstream failing to
* answer, which says nothing about the credentials and must not spend
* somebody's attempts while they wait for it to come back (#239).
*/
if (!(err instanceof UpstreamError && err.status === 401)) {
loginLimiter.refund(limitKey);
loginLimiter.refund(ip);
}
return upstreamFailure(c, err);
}
});
@@ -418,13 +199,13 @@ export function createApp(basePath = config.basePath): Hono<Env> {
api.get("/auth/session", requireSession, async (c) => {
const session = c.get("session");
try {
const upstream = await getUpstreamSession(session.id, session.authorization, upstreamFor(session.username), c.req.query("refresh") === "1");
const upstream = await getUpstreamSession(session.id, session.authorization, c.req.query("refresh") === "1");
const info = await getAccountInfo(session.id, session.authorization, upstream);
return c.json(localizeSession(upstream, sessionExtras(session, info)));
} catch (err) {
if (err instanceof UpstreamError && err.status === 401) {
sessions.destroy(session.id);
deleteCookie(c, config.cookieName, { path: cookiePath });
deleteCookie(c, config.cookieName, { path: "/" });
}
return upstreamFailure(c, err);
}
@@ -437,7 +218,7 @@ export function createApp(basePath = config.basePath): Hono<Env> {
sessions.destroy(session.id);
forgetUpstreamSession(session.id);
}
deleteCookie(c, config.cookieName, { path: cookiePath });
deleteCookie(c, config.cookieName, { path: "/" });
return c.json({ ok: true });
});
@@ -455,16 +236,13 @@ export function createApp(basePath = config.basePath): Hono<Env> {
// ---------- Self-service credentials ----------
/**
* Password, app passwords and 2FA. These live on the server rather than in
* the browser because changing a credential means re-sealing the session
* cookie that holds it, and because the browser only ever sees /api/jmap.
* the browser because the pre-0.16 API is REST rather than JMAP (the browser
* only ever sees /api/jmap), and because changing a credential means
* re-sealing the session cookie that holds it.
*/
const accountCtx = async (c: Context<Env>) => {
const session = c.get("session");
// The account's own server. Without it, the first fetch after the cached
// session expires goes to STALWART_URL -- which, for a domain mapped
// elsewhere, either refuses the password or knows a different account by
// the same name (#238).
const upstream = await getUpstreamSession(session.id, session.authorization, upstreamFor(session.username));
const upstream = await getUpstreamSession(session.id, session.authorization);
return { authorization: session.authorization, session: upstream, username: session.username };
};
@@ -486,7 +264,7 @@ export function createApp(basePath = config.basePath): Hono<Env> {
api.get("/account/security", requireSession, async (c) => {
const session = c.get("session");
try {
return c.json(await getState(await accountCtx(c)));
return c.json(await getState(session.id, await accountCtx(c)));
} catch (err) {
return accountFailure(c, err);
}
@@ -506,7 +284,7 @@ export function createApp(basePath = config.basePath): Hono<Env> {
return c.json({ error: "unchanged", message: "The new password matches the old one." }, 400);
}
try {
await changePassword(await accountCtx(c), { current, next, otpCode: body.otpCode?.trim() || undefined });
await changePassword(session.id, await accountCtx(c), { current, next, otpCode: body.otpCode?.trim() || undefined });
} catch (err) {
return accountFailure(c, err);
}
@@ -522,8 +300,8 @@ export function createApp(basePath = config.basePath): Hono<Env> {
api.get("/account/app-passwords", requireSession, async (c) => {
const session = c.get("session");
try {
const state = await getState(await accountCtx(c));
return c.json({ appPasswords: state.appPasswords });
const state = await getState(session.id, await accountCtx(c));
return c.json({ appPasswords: state.appPasswords, keyedByName: state.appPasswordsKeyedByName });
} catch (err) {
return accountFailure(c, err);
}
@@ -536,7 +314,7 @@ export function createApp(basePath = config.basePath): Hono<Env> {
const description = (body.description ?? "").trim().slice(0, 120);
if (!description) return c.json({ error: "missing_fields", message: "Give the app password a name." }, 400);
try {
return c.json(await createAppPassword(await accountCtx(c), { description }));
return c.json(await createAppPassword(session.id, await accountCtx(c), { description }));
} catch (err) {
return accountFailure(c, err);
}
@@ -547,7 +325,7 @@ export function createApp(basePath = config.basePath): Hono<Env> {
const body = await readJson<{ id?: string }>(c);
if (!body?.id) return c.json({ error: "bad_request" }, 400);
try {
await revokeAppPassword(await accountCtx(c), body.id);
await revokeAppPassword(session.id, await accountCtx(c), body.id);
return c.json({ ok: true });
} catch (err) {
return accountFailure(c, err);
@@ -588,18 +366,18 @@ export function createApp(basePath = config.basePath): Hono<Env> {
}
let app: { id: string; secret: string } | null = null;
try {
app = await createAppPassword(ctx, { description: appPasswordName(c) });
app = await createAppPassword(session.id, ctx, { description: appPasswordName(c) });
} catch (err) {
// Out of app-password quota, say. 2FA is still worth having; the user
// just has to sign in again afterwards.
console.warn("[ihasmail] could not mint a session app password:", (err as Error).message);
}
try {
await enableOtp(ctx, { url: body.url, code, current: body.current });
await enableOtp(session.id, ctx, { url: body.url, code, current: body.current });
} catch (err) {
if (app) {
// Don't leave a credential behind for a change that never happened.
await revokeAppPassword(ctx, app.id).catch(() => {});
await revokeAppPassword(session.id, ctx, app.id).catch(() => {});
}
return accountFailure(c, err);
}
@@ -620,7 +398,7 @@ export function createApp(basePath = config.basePath): Hono<Env> {
const body = await readJson<{ current?: string; code?: string }>(c);
if (!body?.current || !body.code) return c.json({ error: "bad_request" }, 400);
try {
await disableOtp(await accountCtx(c), { current: body.current, code: body.code.trim() });
await disableOtp(session.id, await accountCtx(c), { current: body.current, code: body.code.trim() });
} catch (err) {
return accountFailure(c, err);
}
@@ -628,57 +406,34 @@ export function createApp(basePath = config.basePath): Hono<Env> {
// the plain password works again now, so put it back.
sessions.reseal(getCookie(c, config.cookieName), body.current);
forgetUpstreamSession(session.id);
forgetBackend(session.id);
return c.json({ ok: true });
});
// ---------- JMAP API proxy ----------
api.post("/jmap", requireSession, apiRateLimited, async (c) => {
api.post("/jmap", requireSession, async (c) => {
const session = c.get("session");
const ct = c.req.header("content-type") ?? "";
if (!ct.toLowerCase().startsWith("application/json")) {
return c.json({ error: "unsupported_media_type" }, 415);
}
/*
* For a session that may not administer -- administration switched off, or
* a device not marked as the person's own -- the body is read and checked
* before it goes anywhere. A session that may streams straight through as
* it always has, and pays nothing for this.
*/
let body: ReadableStream<Uint8Array> | string | null = c.req.raw.body;
if (!administrationAllowed(config.administration, session.remember)) {
let raw: string;
try {
// Counted as it arrives: a chunked body carries no length to refuse up front.
raw = c.req.raw.body ? await new Response(c.req.raw.body.pipeThrough(byteCap(MAX_GATED_REQUEST))).text() : "";
} catch {
return c.json({ error: "too_large" }, 413);
}
const gate = gateAdministration(raw);
if (!gate.ok) {
if (!gate.method) return c.json({ error: "bad_request", message: "Not a JMAP request." }, 400);
return config.administration
? c.json({ error: "administration_needs_own_device", message: `Administration is only available when signed in on a device marked as your own (${gate.method}).` }, 403)
: c.json({ error: "administration_disabled", message: `Administration is turned off on this installation (${gate.method}).` }, 403);
}
body = gate.body;
}
try {
const upstream = await getUpstreamSession(session.id, session.authorization, upstreamFor(session.username));
const res = await fetch(absoluteUpstream(upstream.apiUrl, upstream.baseUrl), {
const upstream = await getUpstreamSession(session.id, session.authorization);
const res = await fetch(absoluteUpstream(upstream.apiUrl), {
method: "POST",
headers: {
authorization: session.authorization,
"content-type": "application/json",
accept: "application/json",
},
body,
body: c.req.raw.body,
duplex: "half",
signal: AbortSignal.timeout(config.upstreamTimeout),
});
if (res.status === 401) {
sessions.destroy(session.id);
forgetUpstreamSession(session.id);
deleteCookie(c, config.cookieName, { path: cookiePath });
deleteCookie(c, config.cookieName, { path: "/" });
return c.json({ error: "unauthenticated" }, 401);
}
return passthrough(res);
@@ -697,8 +452,8 @@ export function createApp(basePath = config.basePath): Hono<Env> {
// suggestion; count the bytes as they go past.
const body = c.req.raw.body ? c.req.raw.body.pipeThrough(byteCap(config.maxUploadBytes)) : null;
try {
const upstream = await getUpstreamSession(session.id, session.authorization, upstreamFor(session.username));
const url = absoluteUpstream(expandTemplate(upstream.uploadUrl, { accountId }), upstream.baseUrl);
const upstream = await getUpstreamSession(session.id, session.authorization);
const url = absoluteUpstream(expandTemplate(upstream.uploadUrl, { accountId }));
const res = await fetch(url, {
method: "POST",
headers: {
@@ -717,26 +472,23 @@ export function createApp(basePath = config.basePath): Hono<Env> {
});
// ---------- Blob download ----------
api.get("/blob/:accountId/:blobId/:name", requireSession, apiRateLimited, async (c) => {
api.get("/blob/:accountId/:blobId/:name", requireSession, async (c) => {
const session = c.get("session");
const { accountId, blobId, name } = c.req.param();
const accept = c.req.query("accept") ?? "application/octet-stream";
const inline = c.req.query("inline") === "1";
try {
const upstream = await getUpstreamSession(session.id, session.authorization, upstreamFor(session.username));
const url = absoluteUpstream(expandTemplate(upstream.downloadUrl, { accountId, blobId, name, type: accept }), upstream.baseUrl);
const upstream = await getUpstreamSession(session.id, session.authorization);
const url = absoluteUpstream(expandTemplate(upstream.downloadUrl, { accountId, blobId, name, type: accept }));
const res = await fetch(url, {
// Ask for the bytes as they are. undici would otherwise negotiate gzip
// on our behalf and hand back a decompressed body whose content-length
// header still describes the compressed one -- see forwardedContentLength.
headers: { authorization: session.authorization, "accept-encoding": "identity" },
headers: { authorization: session.authorization },
signal: AbortSignal.timeout(Math.max(config.upstreamTimeout, 5 * 60_000)),
});
if (!res.ok) return c.json({ error: "not_found" }, res.status === 404 ? 404 : 502);
const headers = new Headers();
const type = sanitizeContentType(res.headers.get("content-type") ?? accept);
headers.set("Content-Type", type);
const cl = forwardedContentLength(res.headers);
const cl = res.headers.get("content-length");
if (cl) headers.set("Content-Length", cl);
const safeInline = inline && isInlineSafe(type);
headers.set(
@@ -745,19 +497,7 @@ export function createApp(basePath = config.basePath): Hono<Env> {
);
headers.set("X-Content-Type-Options", "nosniff");
// Sandbox everything except the browser's built-in PDF viewer (which needs scripts to render).
if (securityHeadersFor(type, safeInline) === "SAMEORIGIN") {
/*
* The one response on the server that may be framed.
*
* A PDF is shown in an iframe -- it is its own document and the app
* cannot lay it out -- and the blanket X-Frame-Options: DENY above
* blocked that, so the preview showed Chrome's "refused to connect"
* instead of the file. SAMEORIGIN, not a relaxation to any site: the
* frame is ours, on our origin, and the app's own CSP already says
* frame-src 'self'. Nothing else here is framed, so nothing else asks.
*/
headers.set("X-Frame-Options", "SAMEORIGIN");
} else {
if (!(safeInline && type === "application/pdf")) {
headers.set("Content-Security-Policy", "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:");
}
headers.set("Cache-Control", "private, max-age=3600");
@@ -774,20 +514,8 @@ export function createApp(basePath = config.basePath): Hono<Env> {
const closeafter = c.req.query("closeafter") ?? "no";
const ping = c.req.query("ping") ?? "30";
try {
const upstream = await getUpstreamSession(session.id, session.authorization, upstreamFor(session.username));
const url = absoluteUpstream(expandTemplate(upstream.eventSourceUrl, { types, closeafter, ping }), upstream.baseUrl);
// Subscribe mode: if this account's subscription is verified, the tab is
// served by fan-out and holds nothing upstream. Otherwise it gets its own
// relay, and is moved to fan-out the moment the account verifies.
const accountId = upstream.primaryAccounts?.["urn:ietf:params:jmap:mail"];
const out = (c.env as { outgoing: import("node:http").ServerResponse }).outgoing;
if (accountId && pushAttach(session.username, accountId, session.authorization, out)) {
out.writeHead(200, SSE_HEADERS);
out.flushHeaders();
out.write(": subscribed\n\n");
return RESPONSE_ALREADY_SENT;
}
if (config.rawPushRelay) return relayPushRaw(c, url, session.authorization, session.username);
const upstream = await getUpstreamSession(session.id, session.authorization);
const url = absoluteUpstream(expandTemplate(upstream.eventSourceUrl, { types, closeafter, ping }));
const controller = new AbortController();
c.req.raw.signal.addEventListener("abort", () => controller.abort());
const res = await fetch(url, {
@@ -808,10 +536,7 @@ export function createApp(basePath = config.basePath): Hono<Env> {
});
// ---------- Remote image privacy proxy ----------
api.get("/image", requireSession, apiRateLimited, imageProxyHandler);
// Behind the session for the same reason the image proxy is: an open fetcher
// on someone else's server is a gift to whoever finds it.
api.get("/ics", requireSession, apiRateLimited, icsProxyHandler);
api.get("/image", requireSession, imageProxyHandler);
api.notFound((c) => c.json({ error: "not_found" }, 404));
api.onError((err, c) => {
@@ -819,10 +544,10 @@ api.get("/ics", requireSession, apiRateLimited, icsProxyHandler);
return c.json({ error: "internal_error" }, 500);
});
app.route(`${basePath}/api`, api);
app.route("/api", api);
// ---------- Static SPA ----------
app.get("*", staticHandler(config.staticDir, basePath));
app.get("*", staticHandler(config.staticDir));
return app;
}
@@ -853,7 +578,7 @@ function appPasswordName(c: Context): string {
return `${config.appName} (${browser})`;
}
function sessionExtras(session: LiveSession, info: AccountInfo = { locale: null, edition: null, permissions: [] }) {
function sessionExtras(session: LiveSession, info: AccountInfo = { locale: null, generation: null, edition: null }) {
return {
ihasmail: {
appName: config.appName,
@@ -866,25 +591,7 @@ function sessionExtras(session: LiveSession, info: AccountInfo = { locale: null,
/** Locale configured for the account in Stalwart's directory, if readable. */
userLocale: info.locale,
/** What the upstream server would tell us about itself. */
server: { edition: info.edition },
/**
* Whether this session may administer: the installation offers it
* (ADMINISTRATION) and the person signed in on a device marked as their own.
*/
administration: administrationAllowed(config.administration, session.remember),
/**
* An administrator signed in on a device not marked as their own, so the
* menu can say why Administration is unavailable rather than lose it
* without a word. Says only that the account administers, never what it
* may do.
*/
administrationNeedsOwnDevice: config.administration && !session.remember && grantsAdministration(info.permissions),
/**
* The account's permissions on that server, so the client can offer
* administration to those who have it. Stalwart still decides every call.
* Withheld from a session that may not administer: nothing in it needs them.
*/
permissions: administrationAllowed(config.administration, session.remember) ? info.permissions : [],
server: { generation: info.generation, edition: info.edition },
},
};
}
@@ -894,91 +601,8 @@ function sessionExtras(session: LiveSession, info: AccountInfo = { locale: null,
* denylist: everything else it might set — cookies, auth challenges, CORS
* grants — would be landing on *our* origin, where it means something else.
*/
/**
* The largest JMAP request read into memory for the administration check.
* Stalwart's own default `maxSizeRequest` is 10 MB; uploads never come this way.
*/
const MAX_GATED_REQUEST = 16 * 1024 * 1024;
const PASSTHROUGH_HEADERS = new Set(["content-type", "content-disposition", "content-language", "etag", "last-modified", "retry-after"]);
/**
* Hold a push stream open with the least machinery that will do it.
*
* The fetch() version above builds an undici Response, a web ReadableStream,
* a reader, and Hono's stream-to-Node bridge for every tab, and keeps all of
* it alive for as long as the tab is open. Measured against a real Stalwart
* that is about 44 KiB of JavaScript heap per tab -- twelve times what the
* session itself costs -- and a signed-in tab is otherwise nothing but this
* one held connection. Here the upstream socket is piped straight into the
* Node response, so what stays resident per tab is two sockets and their
* small IncomingMessage/ServerResponse pair.
*
* Returns a Response Hono treats as already sent: the raw bindings are
* written to directly, and the returned value is never serialised.
*/
const SSE_HEADERS = {
"content-type": "text/event-stream",
"cache-control": "no-cache, no-transform",
connection: "keep-alive",
"x-accel-buffering": "no",
} as const;
function relayPushRaw(c: Context<Env>, url: string, authorization: string, username?: string): Response {
const out = (c.env as { outgoing: import("node:http").ServerResponse }).outgoing;
const target = new URL(url);
const req = (target.protocol === "https:" ? httpsRequest : httpRequest)(target, {
method: "GET",
headers: { authorization, accept: "text/event-stream" },
});
const signal = c.req.raw.signal;
const abort = () => req.destroy();
signal.addEventListener("abort", abort);
out.on("close", abort);
const fail = () => {
if (!out.headersSent) {
out.writeHead(502, { "content-type": "application/json", "cache-control": "no-store" });
out.end(JSON.stringify({ error: "upstream_error" }));
} else {
out.end();
}
};
/*
* Once this account's subscription verifies, the upstream request goes and
* the browser stream below is served by fan-out instead. Three things have
* to be true for that to be seamless: the browser must already have its
* headers (verification can beat the upstream response); nothing may treat
* the torn-down upstream as an error; and nothing may keep a reference to
* it -- the request, its response and this handler's context are exactly
* the per-tab weight the subscription exists to shed.
*/
let migrated = false;
const migrate = () => {
migrated = true;
if (!out.headersSent) { out.writeHead(200, SSE_HEADERS); out.flushHeaders(); }
signal.removeEventListener("abort", abort);
out.removeListener("close", abort);
req.removeAllListeners();
req.on("error", () => {});
req.destroy();
};
if (username) pushAttachRelay(username, out, migrate);
req.on("response", (res) => {
if (migrated) { res.destroy(); return; }
if (res.statusCode !== 200) { res.resume(); fail(); return; }
if (!out.headersSent) { out.writeHead(200, SSE_HEADERS); out.flushHeaders(); }
// end: false -- the browser stream outlives the upstream if we migrate.
res.pipe(out, { end: false });
res.on("end", () => { if (!migrated) out.end(); });
res.on("error", () => { if (!migrated) out.end(); });
});
req.on("error", () => { if (!migrated) fail(); });
req.end();
// Tells @hono/node-server the raw ServerResponse has been written to and
// must be left alone.
return RESPONSE_ALREADY_SENT;
}
function passthrough(res: Response): Response {
const headers = new Headers();
res.headers.forEach((v, k) => {
@@ -989,32 +613,6 @@ function passthrough(res: Response): Response {
return new Response(res.body, { status: res.status, headers });
}
/**
* The upstream content-length, but only when it describes the bytes we are
* about to forward.
*
* A compressed response is decompressed for us before we ever see the body --
* undici does it transparently -- while the content-length header is left
* describing the *compressed* length. Copying it onto the longer body we then
* send makes the browser stop reading exactly that many bytes in and call the
* download complete, so the file arrives silently truncated.
*
* That is the second half of issue #76. A hop in front of Stalwart compressed
* responses over 1 KiB, so a Sieve script stayed intact until the third rule
* pushed it past the threshold and it came back cut off mid-rule. Nothing
* reported an error: the script parsed, just with rules missing, and saving
* wrote that shortened version back over the real one.
*
* We ask for `identity` above so the usual case still carries a length the
* browser can show progress against; this is the guard for a hop that
* compresses anyway.
*/
export function forwardedContentLength(headers: Headers): string | null {
const encoding = headers.get("content-encoding")?.trim().toLowerCase();
if (encoding && encoding !== "identity") return null;
return headers.get("content-length");
}
function sanitizeContentType(ct: string): string {
const lower = ct.split(";")[0]!.trim().toLowerCase();
// Never let the browser render HTML/SVG/XML/JS served from the blob endpoint.
@@ -1032,15 +630,6 @@ function sanitizeContentType(ct: string): string {
return lower || "application/octet-stream";
}
/**
* What X-Frame-Options a blob response carries. Exported so the rule is
* testable without standing up an upstream: a PDF served inline may be framed
* by us and nothing else may be framed at all.
*/
export function securityHeadersFor(type: string, safeInline: boolean): "SAMEORIGIN" | "DENY" {
return safeInline && type.split(";")[0]!.trim() === "application/pdf" ? "SAMEORIGIN" : "DENY";
}
function isInlineSafe(type: string): boolean {
const t = type.split(";")[0]!.trim();
return (
-63
View File
@@ -1,63 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
process.env.STALWART_URL = "http://127.0.0.1:1";
const { createApp } = await import("./app.js");
/**
* `BASE_PATH` is read once, into `config`, so these mount the app by argument
* instead of re-importing the module with a different environment. The
* root-mounted half is the one that matters most: every instance in existence
* is at `/`, and this feature has to be invisible to them.
*/
test("at the root, the API is exactly where it was", async () => {
const app = createApp("");
const res = await app.request("/api/health");
assert.equal(res.status, 200);
});
test("under a prefix, the API moves with it", async () => {
const app = createApp("/mail");
const res = await app.request("/mail/api/health");
assert.equal(res.status, 200);
const body = (await res.json()) as { ok?: boolean };
assert.equal(body.ok, true);
});
test("under a prefix, the unprefixed API is gone", async () => {
// Not merely unrouted: a proxy that forwards without the prefix, against a
// server told to expect one, would otherwise appear to half-work -- the API
// answering while the app shell it belongs to 404s.
const app = createApp("/mail");
const res = await app.request("/api/health");
assert.equal(res.status, 404);
});
/*
* Whether a route reached the static handler, without depending on there being
* a web build in the tree. With one it serves the index; without one it says
* the build is missing. Either is proof the request got that far -- a routing
* mistake is the 404, and asserting on 200 or 503 would make these tests pass
* or fail on whether somebody had run `npm run build` first.
*/
const reachedTheApp = (status: number) => status === 200 || status === 503;
test("a deep SPA route under the prefix reaches the static handler", async () => {
const app = createApp("/mail");
const res = await app.request("/mail/calendar/week/2026-09-01");
assert.ok(reachedTheApp(res.status), `expected the app shell, got ${res.status}`);
});
test("a path that only shares the prefix's letters is not the app", async () => {
// `/mailbox` under a `/mail` mount belongs to whatever else the proxy
// serves on this host; answering it with our shell would shadow it.
const app = createApp("/mail");
assert.equal((await app.request("/mailbox")).status, 404);
assert.equal((await app.request("/")).status, 404);
});
test("the root mount still serves the SPA from the root", async () => {
const app = createApp("");
assert.ok(reachedTheApp((await app.request("/calendar/week/2026-09-01")).status));
assert.ok(reachedTheApp((await app.request("/")).status));
});
-107
View File
@@ -1,107 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
/*
* A static root of our own, built before the app is imported.
*
* CI runs `npm test` before `npm run build`, so `web/dist` does not exist when
* these run: pointing at it would serve the "web build not found" fallback,
* which is short, plain text and rightly uncompressed. That failure looked
* exactly like compression being broken.
*/
const root = mkdtempSync(join(tmpdir(), "ihasmail-compress-"));
mkdirSync(join(root, "assets"));
const script = `/* ${"x".repeat(40_000)} */\n`;
writeFileSync(join(root, "assets", "app.js"), script);
writeFileSync(join(root, "index.html"), `<!doctype html><title>t</title>${"<p>hello</p>".repeat(400)}`);
process.env.STATIC_DIR = root;
process.env.STALWART_URL = "http://127.0.0.1:1";
const { createApp } = await import("./app.js");
test("an asset is gzipped when the client asks for it", async () => {
const res = await createApp().request("/assets/app.js", { headers: { "accept-encoding": "gzip" } });
assert.equal(res.status, 200);
assert.equal(res.headers.get("content-encoding"), "gzip");
assert.match(res.headers.get("vary") ?? "", /accept-encoding/i);
});
test("a client that does not ask for gzip does not get it", async () => {
const res = await createApp().request("/assets/app.js", { headers: { "accept-encoding": "identity" } });
assert.equal(res.status, 200);
assert.equal(res.headers.get("content-encoding"), null);
});
test("gzip actually makes the asset smaller", async () => {
const plain = await (await createApp().request("/assets/app.js", { headers: { "accept-encoding": "identity" } })).arrayBuffer();
const gz = await (await createApp().request("/assets/app.js", { headers: { "accept-encoding": "gzip" } })).arrayBuffer();
assert.ok(gz.byteLength < plain.byteLength / 2, `${gz.byteLength} should be well under ${plain.byteLength}`);
});
test("a gzipped response decodes to the bytes we would have sent plain", async () => {
const plain = await (await createApp().request("/assets/app.js", { headers: { "accept-encoding": "identity" } })).arrayBuffer();
const res = await createApp().request("/assets/app.js", { headers: { "accept-encoding": "gzip" } });
const decoded = await new Response(res.body!.pipeThrough(new DecompressionStream("gzip"))).arrayBuffer();
assert.deepEqual(Buffer.from(decoded), Buffer.from(plain));
});
test("the app shell is gzipped", async () => {
const res = await createApp().request("/", { headers: { "accept-encoding": "gzip" } });
assert.equal(res.status, 200);
assert.equal(res.headers.get("content-encoding"), "gzip");
});
test("proxy routes that forward upstream bytes are never compressed", async () => {
// Unauthenticated, so these stop at 401 -- enough to prove the middleware
// declines the path, which is what issue #76 was about.
const app = createApp();
for (const path of ["/api/blob/a/b/c.pdf", "/api/image?url=https://example.com/x.png", "/api/ics?url=https://example.com/x.ics"]) {
const res = await app.request(path, { headers: { "accept-encoding": "gzip" } });
assert.equal(res.headers.get("content-encoding"), null, `${path} must not be compressed`);
}
});
test("the push stream is never compressed", async () => {
const res = await createApp().request("/api/events", { headers: { "accept-encoding": "gzip" } });
assert.equal(res.headers.get("content-encoding"), null);
});
test("the liveness probe is not compressed, since gzip would make it bigger", async () => {
const res = await createApp().request("/api/health", { headers: { "accept-encoding": "gzip" } });
assert.equal(res.status, 200);
assert.equal(res.headers.get("content-encoding"), null);
});
test("advertised upstream URLs are pinned to the configured origin", async () => {
const { absoluteUpstream } = await import("./upstream.js");
const pinned = absoluteUpstream("https://mail.public.example/jmap/eventsource/?types=*", "http://stalwart:8080");
assert.equal(pinned, "http://stalwart:8080/jmap/eventsource/?types=*");
// A relative URL still resolves against the base, as before.
assert.equal(absoluteUpstream("/jmap/", "http://stalwart:8080/"), "http://stalwart:8080/jmap/");
});
test("the data path is rate limited per session, and login stays on its own budget", async () => {
// No session: every call is refused before the limiter, so it must never 429.
const app = createApp();
for (let i = 0; i < 5; i++) {
const res = await app.request("/api/jmap", { method: "POST",
headers: { "content-type": "application/json", "x-requested-with": "ihasmail" }, body: "{}" });
assert.equal(res.status, 401);
}
// The limiter itself: a fresh key gets its budget and nothing more.
const { RateLimiter } = await import("./ratelimit.js");
const l = new RateLimiter(3, 60_000);
assert.deepEqual([l.check("s1"), l.check("s1"), l.check("s1"), l.check("s1")], [true, true, true, false]);
assert.ok(l.retryAfterSeconds("s1") >= 1);
assert.equal(l.check("s2"), true, "another session is not affected");
});
test("a response to a client that offered no encoding is not touched by the compressor", async () => {
const res = await createApp().request("/assets/app.js"); // no Accept-Encoding at all
assert.equal(res.status, 200);
assert.equal(res.headers.get("content-encoding"), null);
assert.equal(res.headers.get("vary"), null, "no Vary: the middleware never ran");
});
-40
View File
@@ -1,40 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { chmodSync, existsSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { assertImmutable } from "./config.js";
function tempRoot(): string {
return mkdtempSync(join(tmpdir(), "ihasmail-immutable-"));
}
test("IMMUTABLE refuses a configured SESSION_FILE", () => {
const root = tempRoot();
try {
assert.throws(() => assertImmutable("/data/sessions.json", root), /SESSION_FILE is \/data\/sessions\.json/);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
test("IMMUTABLE refuses a writable root, and leaves no probe behind", () => {
const root = tempRoot();
try {
assert.throws(() => assertImmutable("", root), /is writable/);
assert.equal(existsSync(join(root, ".immutable-probe")), false);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
test("IMMUTABLE accepts a root it cannot write to", () => {
const root = tempRoot();
try {
chmodSync(root, 0o555);
assert.doesNotThrow(() => assertImmutable("", root));
} finally {
chmodSync(root, 0o755);
rmSync(root, { recursive: true, force: true });
}
});
+3 -242
View File
@@ -1,8 +1,6 @@
import { resolveVersion } from "../../scripts/version.mjs";
import { normalizeBasePath } from "../../scripts/basePath.mjs";
import { randomBytes } from "node:crypto";
import { fileURLToPath } from "node:url";
import { existsSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
import { existsSync, readFileSync } from "node:fs";
import { resolve } from "node:path";
/** Minimal .env loader (no dependency): first match wins, never overrides real env. */
@@ -59,198 +57,9 @@ if (!appSecret || appSecret === "change-me") {
const stalwartUrl = env("STALWART_URL", "https://mail.example.com").replace(/\/+$/, "");
/**
* Declares that this instance is running as an immutable container: read-only
* root filesystem, nothing durable of its own, replaceable by its image.
*
* It is a claim the process checks rather than one it takes on trust, because
* the failure it guards against is silent. Left to itself the server survives
* a read-only filesystem perfectly well -- sessions are held in memory and the
* write is best-effort, so the only sign that `SESSION_FILE` is going nowhere
* is one warning at the first login, long after anyone was watching. The
* instance looks healthy right up until it is replaced and everyone is signed
* out. Setting IMMUTABLE turns both halves of that into a refusal to start.
*/
const immutable = bool("IMMUTABLE", false);
const sessionFile = process.env.SESSION_FILE ?? "";
/**
* Refuse to run when the promise IMMUTABLE makes is not one this instance can
* keep. Exported so it can be tested without a read-only filesystem to hand.
*/
export function assertImmutable(sessionFile: string, root: string): void {
// The image sets SESSION_FILE=/data/sessions.json, so this is a deliberate
// refusal rather than a formality: running immutably means clearing it. It
// is not quietly ignored, because a configured path that silently persists
// nothing is exactly the failure this flag exists to surface.
if (sessionFile) {
throw new Error(
`IMMUTABLE is set, but SESSION_FILE is ${sessionFile}. An immutable instance keeps no durable state of its own: ` +
"pass SESSION_FILE= (empty) to hold sessions in memory, or unset IMMUTABLE.",
);
}
// And check the property itself, not just the intention to have it. Setting
// the variable while forgetting `--read-only` is the easy mistake, and it
// leaves an instance claiming a guarantee it does not have.
const probe = resolve(root, ".immutable-probe");
let writable = false;
try {
writeFileSync(probe, "");
writable = true;
unlinkSync(probe);
} catch {
/* EROFS, or EACCES on a root we do not own: either way, not writable by us */
}
if (writable) {
throw new Error(
`IMMUTABLE is set, but ${root} is writable. Run the container with --read-only (and --tmpfs /tmp), or unset IMMUTABLE.`,
);
}
}
if (immutable) assertImmutable(sessionFile, fileURLToPath(new URL("../..", import.meta.url)));
/**
* Settings an installation decides, rather than each reader.
*
* A school turning on "warn about outside senders" for three thousand pupils
* cannot ask three thousand pupils to turn it on -- issue #207. Two sections,
* which are two different powers:
*
* - `defaults` seed an account that has never had settings of its own. The
* reader can change any of them afterwards; they are a starting point, not a
* rule.
* - `enforced` are applied on every load and cannot be changed here at all. The
* controls stay visible and go dead, which the issue asked for by name: a
* missing control confuses somebody who has used ihasmail elsewhere.
* - `changes` are applied once each, to everybody, including accounts that
* already exist -- and can be changed back afterwards. Each carries its own
* `version`, which is how an account remembers the ones it has had. The
* reporter's own analogy is a schema migration and this is that shape.
*
* Read from a file or straight from the environment, because ihasmail's own
* production runs read-only with no volume -- an installation that cannot mount
* a file can still set a variable.
*/
function readSettingsPolicy(): { defaults: Record<string, unknown>; enforced: Record<string, unknown>; changes: Array<{ version: string; settings: Record<string, unknown> }> } {
const parse = (raw: string, where: string): Record<string, unknown> => {
try {
const v = JSON.parse(raw) as unknown;
if (!v || typeof v !== "object" || Array.isArray(v)) throw new Error("not a JSON object");
return v as Record<string, unknown>;
} catch (err) {
/* Loud, and fatal. A policy that silently did not apply would look like
the feature not working, and the admin would have no way to tell. */
throw new Error(`Invalid ${where}: ${(err as Error).message}`);
}
};
/**
* A change list, checked rather than trusted.
*
* Every entry needs a `version` that is unique within the file: it is what an
* account stores to say it has had this one, so a duplicate would make two
* changes indistinguishable and a missing one would apply for ever.
*/
const parseChanges = (v: unknown, where: string): Array<{ version: string; settings: Record<string, unknown> }> => {
if (v === undefined) return [];
if (!Array.isArray(v)) throw new Error(`Invalid ${where}: "changes" must be a list`);
const seen = new Set<string>();
return v.map((entry, i) => {
const e = entry as { version?: unknown; settings?: unknown };
const version = typeof e.version === "string" ? e.version.trim() : "";
if (!version) throw new Error(`Invalid ${where}: changes[${i}] has no "version"`);
if (seen.has(version)) throw new Error(`Invalid ${where}: two changes share the version "${version}"`);
seen.add(version);
if (!e.settings || typeof e.settings !== "object" || Array.isArray(e.settings)) {
throw new Error(`Invalid ${where}: changes[${i}] ("${version}") has no "settings" object`);
}
return { version, settings: e.settings as Record<string, unknown> };
});
};
const file = process.env.SETTINGS_POLICY_FILE;
if (file) {
if (!existsSync(file)) throw new Error(`SETTINGS_POLICY_FILE does not exist: ${file}`);
const whole = parse(readFileSync(file, "utf8"), `SETTINGS_POLICY_FILE (${file})`);
return {
defaults: (whole.defaults as Record<string, unknown>) ?? {},
enforced: (whole.enforced as Record<string, unknown>) ?? {},
changes: parseChanges(whole.changes, `SETTINGS_POLICY_FILE (${file})`),
};
}
return {
defaults: process.env.SETTINGS_DEFAULTS ? parse(process.env.SETTINGS_DEFAULTS, "SETTINGS_DEFAULTS") : {},
enforced: process.env.SETTINGS_ENFORCED ? parse(process.env.SETTINGS_ENFORCED, "SETTINGS_ENFORCED") : {},
changes: process.env.SETTINGS_CHANGES ? parseChanges(JSON.parse(process.env.SETTINGS_CHANGES), "SETTINGS_CHANGES") : [],
};
}
/**
* Which Stalwart a domain signs in to.
*
* `STALWART_URL` stays required and stays the default; this only adds domains
* that go somewhere else (#238). An installation that sets nothing behaves
* exactly as it always has.
*
* Read once at boot and never written, so it mounts read-only and costs
* nothing in immutability -- the same shape as the settings policy.
*
* Servers are deliberately **not** probed here. A mapping is a routing table,
* not a health check, and refusing to boot because one of five customers is
* having an outage would take the other four down with it. What happens when
* one is unreachable is a sign-in question, answered in #239.
*/
function readStalwartServers(): Record<string, string> {
const file = process.env.STALWART_SERVERS_FILE;
if (!file) return {};
if (!existsSync(file)) throw new Error(`STALWART_SERVERS_FILE does not exist: ${file}`);
let raw: unknown;
try {
raw = JSON.parse(readFileSync(file, "utf8"));
} catch (err) {
throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): ${(err as Error).message}`);
}
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): expected an object of domain to URL`);
}
const out: Record<string, string> = {};
for (const [rawDomain, rawUrl] of Object.entries(raw as Record<string, unknown>)) {
/* Lower-cased and stripped of the root dot, because that is how a domain
taken off a username will arrive and comparing them any other way means
a mapping that silently never matches. */
const domain = rawDomain.trim().toLowerCase().replace(/\.$/, "");
if (!domain) throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): a domain key is empty`);
if (domain in out) throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): "${domain}" appears twice once normalised`);
if (typeof rawUrl !== "string") throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): "${domain}" is not a URL`);
let parsed: URL;
try {
parsed = new URL(rawUrl);
} catch {
throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): "${domain}" is not an absolute URL`);
}
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): "${domain}" must be http or https`);
}
out[domain] = rawUrl.replace(/\/+$/, "");
}
return out;
}
export const config = {
isProd,
appName: env("APP_NAME", "ihasmail"),
settingsPolicy: readSettingsPolicy(),
/**
* What this build calls itself: `2.16.57`. Set by the image build from
* `--build-arg IHASMAIL_VERSION`, since `.dockerignore` keeps `.git` out of
* the build context and nothing in there could work it out. A dev checkout
* has git, so it falls back to asking; see `scripts/version.mjs`.
*/
version: resolveVersion(),
/**
* Where this instance's source can be had, shown to everyone who reaches it.
*
@@ -258,24 +67,10 @@ export const config = {
* source, not the one it was forked from -- so anyone deploying a patched
* ihasmail should point this at their own tree.
*/
sourceUrl: env("SOURCE_URL", "https://github.com/Coffey-Labs/ihasmail"),
sourceUrl: env("SOURCE_URL", "https://github.com/LINUXexpert-org/ihasmail"),
host: env("HOST", "0.0.0.0"),
port: int("PORT", 8080),
/**
* The subpath this instance answers on: `/mail` for a proxy that maps
* `https://example.com/mail/` here, and `""` -- the default -- for the root.
*
* The prefix is expected to arrive intact: a proxy that strips it before
* forwarding should leave BASE_PATH unset, because then as far as this
* process is concerned it *is* at the root. What must match is the web
* build, which bakes the same variable into its asset URLs; a server that
* strips a prefix the bundle still asks for serves an app that cannot load
* its own scripts. `staticHandler` says so at the first request rather than
* leaving a blank page to explain itself.
*/
basePath: normalizeBasePath(process.env.BASE_PATH),
stalwartUrl,
stalwartServers: readStalwartServers(),
appSecret,
trustProxy: bool("TRUST_PROXY", true),
/**
@@ -289,47 +84,13 @@ export const config = {
secureCookies: (process.env.SECURE_COOKIES ?? "auto").toLowerCase(),
sessionTtl: int("SESSION_TTL", 12 * 60 * 60),
sessionRememberTtl: int("SESSION_REMEMBER_TTL", 30 * 24 * 60 * 60),
sessionFile,
/** True when this instance has asserted, and verified, that it is immutable. */
immutable,
sessionFile: process.env.SESSION_FILE ?? "",
upstreamTimeout: int("UPSTREAM_TIMEOUT", 30_000),
maxUploadBytes: int("MAX_UPLOAD_BYTES", 50 * 1024 * 1024),
imageProxy: bool("IMAGE_PROXY", true),
/*
* Whether ihasmail offers administration to accounts whose Stalwart role
* allows it. Off means off: no menu, no permissions sent to the browser, and
* the JMAP proxy refuses registry methods beyond the account's own -- see
* adminGate.ts. Stalwart's own interface is unaffected either way.
*/
administration: bool("ADMINISTRATION", true),
cookieName: env("COOKIE_NAME", "ihm_session"),
staticDir: process.env.STATIC_DIR ?? fileURLToPath(new URL("../../web/dist", import.meta.url)),
loginRateLimit: int("LOGIN_RATE_LIMIT", 10),
/*
* Requests per minute one session may make on the data path -- JMAP, blobs,
* the image and calendar proxies. The proxy is one Node process and saturates
* a core at roughly 2,000 operations a second, so without this a single
* signed-in user can deny service to everyone else. 1,200 a minute is twenty
* a second sustained: well above what a busy tab does, and an order of
* magnitude below where one tab starts to hurt the rest. 0 disables it.
*/
apiRateLimit: int("API_RATE_LIMIT", 1200),
/* Whether JMAP responses are gzipped. Measured: see the bake-off rerun. */
compressJmap: process.env.COMPRESS_JMAP !== "0",
/*
* How push reaches the browser. "relay" holds one upstream stream per tab
* (today's behaviour). "subscribe" registers one JMAP PushSubscription per
* account and fans Stalwart's POSTs out to that account's tabs, holding no
* upstream connection at all -- see push.ts. It needs PUSH_URL: the https
* origin Stalwart can reach ihasmail at, with a certificate it trusts.
* An account that cannot be verified stays on the relay.
*/
pushMode: (process.env.PUSH_MODE === "relay" ? "relay" : "subscribe") as "relay" | "subscribe",
pushUrl: process.env.PUSH_URL || "",
/* See relayPushRaw(): pipe the push stream socket-to-socket instead of through fetch(). */
rawPushRelay: process.env.RAW_PUSH_RELAY !== "0",
/* See absoluteUpstream(): follow Stalwart's advertised origin instead of pinning to ours. */
followAdvertisedUrls: process.env.STALWART_FOLLOW_ADVERTISED_URLS === "1",
};
export type Config = typeof config;
-67
View File
@@ -1,67 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
process.env.STALWART_URL = "https://default.example";
const { upstreamFor } = await import("./upstream.js");
const { config } = await import("./config.js");
/**
* Which Stalwart a username goes to (#238).
*
* `STALWART_URL` is required and is the default. The mapping only adds domains
* that go elsewhere, so an installation with no mapping behaves exactly as it
* always has -- which is what these first cases pin.
*/
test("with no mapping at all, everything goes to the default", () => {
assert.deepEqual(config.stalwartServers, {});
assert.equal(upstreamFor("[email protected]"), "https://default.example");
assert.equal(upstreamFor("[email protected]"), "https://default.example");
});
test("a bare username has no domain to map, so it goes to the default", () => {
// Stalwart accepts a login with no domain at all.
assert.equal(upstreamFor("demo"), "https://default.example");
assert.equal(upstreamFor(""), "https://default.example");
});
test("a mapped domain goes to its own server", () => {
config.stalwartServers["mapped.test"] = "https://mail.mapped.test";
try {
assert.equal(upstreamFor("[email protected]"), "https://mail.mapped.test");
} finally {
delete config.stalwartServers["mapped.test"];
}
});
test("an unmapped domain still goes to the default while others are mapped", () => {
config.stalwartServers["mapped.test"] = "https://mail.mapped.test";
try {
assert.equal(upstreamFor("[email protected]"), "https://default.example");
} finally {
delete config.stalwartServers["mapped.test"];
}
});
test("the domain is matched however it was typed", () => {
// Keys are normalised on load; the username has to be normalised the same
// way or a mapping silently never matches.
config.stalwartServers["mapped.test"] = "https://mail.mapped.test";
try {
assert.equal(upstreamFor("[email protected]"), "https://mail.mapped.test");
assert.equal(upstreamFor("[email protected]."), "https://mail.mapped.test", "root dot");
assert.equal(upstreamFor("someone@ mapped.test "), "https://mail.mapped.test", "stray spaces");
} finally {
delete config.stalwartServers["mapped.test"];
}
});
test("an address with an @ in the local part maps on the last one", () => {
config.stalwartServers["mapped.test"] = "https://mail.mapped.test";
try {
assert.equal(upstreamFor('"odd@name"@mapped.test'), "https://mail.mapped.test");
} finally {
delete config.stalwartServers["mapped.test"];
}
});
-62
View File
@@ -1,62 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
process.env.STALWART_URL = "http://127.0.0.1:1";
process.env.APP_SECRET = "test-secret-for-ics-proxy";
const { safeFetch, safeFetchStatus } = await import("./imageproxy.js");
/**
* Subscribing to a calendar makes the server fetch a URL a stranger published,
* which is the second time this app knocks on a door somebody else chose. It
* goes through the same guard as the first — these tests are about that guard
* being reached, and about `webcal:` not being a way around it.
*/
test("a calendar URL is refused before any connection when it points somewhere private", async () => {
for (const url of [
"http://127.0.0.1/calendar.ics",
"http://169.254.169.254/latest/meta-data/", // cloud metadata
"http://[::1]/calendar.ics",
"http://10.0.0.1/c.ics",
"https://192.168.1.1/c.ics",
]) {
const got = await safeFetch(url, 500);
assert.equal(got, "forbidden_target", url);
}
});
test("webcal: is treated as https rather than waved through", async () => {
// Every subscription URL people are given is a webcal: one. It has to be
// understood, and it must not be a way past the address check.
const got = await safeFetch("webcal://127.0.0.1/calendar.ics", 500);
assert.equal(got, "forbidden_target");
});
test("schemes that are not http, https or webcal are refused", async () => {
for (const url of ["file:///etc/passwd", "ftp://example.com/c.ics", "gopher://example.com", "data:text/calendar,BEGIN:VCALENDAR"]) {
const got = await safeFetch(url, 500);
assert.equal(got, "bad_scheme", url);
}
});
test("a URL carrying credentials is refused", async () => {
// Credentials in a subscription URL would be sent by the server on the
// reader's behalf to a host the reader may not have looked at.
assert.equal(await safeFetch("http://user:[email protected]/c.ics", 500), "bad_url");
});
test("nonsense is refused rather than guessed at", async () => {
for (const url of ["", "not a url", "://missing-scheme"]) {
assert.equal(await safeFetch(url, 500), "bad_url", JSON.stringify(url));
}
});
test("each refusal has a status that says which kind it was", () => {
assert.equal(safeFetchStatus("forbidden_target"), 403);
assert.equal(safeFetchStatus("bad_scheme"), 400);
assert.equal(safeFetchStatus("bad_url"), 400);
assert.equal(safeFetchStatus("bad_redirect"), 400);
assert.equal(safeFetchStatus("dns_failure"), 502);
assert.equal(safeFetchStatus("fetch_failed"), 502);
});
-85
View File
@@ -1,85 +0,0 @@
import type { Context } from "hono";
import { safeFetch, safeFetchStatus } from "./imageproxy.js";
/**
* Fetching a calendar somebody has subscribed to.
*
* The browser cannot do this itself: a calendar URL belongs to whoever
* published it and almost none of them send CORS headers, so the request has
* to be made from here. That makes it the second place ihasmail reaches out to
* an address a stranger chose, and it goes through exactly the same guard as
* the first — `safeFetch` resolves the name, refuses private space on every
* answer, pins the connection to the address it checked, and re-checks each
* redirect. There is deliberately no second implementation of that.
*
* **Nothing is stored.** The text goes straight back to the browser, which
* parses it and holds the result in memory for as long as the tab is open. The
* server keeps no copy, no cache and no schedule, which is what lets an
* immutable container serve this at all.
*/
/** Generous for a calendar, small enough that nobody can post a film through it. */
const MAX_ICS_BYTES = 4 * 1024 * 1024;
/**
* Types a calendar is served as in practice. `text/plain` and the octet-stream
* are here because a great many servers get this wrong, and refusing a real
* calendar over a header the publisher chose badly helps nobody -- the parser
* checks the content itself, which is the claim that actually matters.
*/
const ACCEPTABLE = new Set(["text/calendar", "text/plain", "application/octet-stream", "application/ics", ""]);
export async function icsProxyHandler(c: Context) {
const got = await safeFetch(c.req.query("url") ?? "", 20_000);
if (typeof got === "string") return c.json({ error: got }, safeFetchStatus(got) as 400);
const { res, done } = got;
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
done();
res.resume();
return c.json({ error: "fetch_failed", status: res.statusCode ?? 0 }, 502);
}
const type = (res.headers["content-type"] ?? "").split(";")[0]!.trim().toLowerCase();
if (!ACCEPTABLE.has(type)) {
done();
res.resume();
return c.json({ error: "not_calendar", type }, 415);
}
const declared = Number(res.headers["content-length"] ?? "0");
if (declared > MAX_ICS_BYTES) {
done();
res.resume();
return c.json({ error: "too_large" }, 413);
}
// Read it here rather than streaming: the browser needs the whole document
// to parse it, and the cap has to hold whether or not a length was declared.
let total = 0;
const chunks: Buffer[] = [];
try {
await new Promise<void>((resolve, reject) => {
res.on("data", (chunk: Buffer) => {
total += chunk.byteLength;
if (total > MAX_ICS_BYTES) {
res.destroy();
reject(new Error("too_large"));
return;
}
chunks.push(chunk);
});
res.on("end", () => resolve());
res.on("error", reject);
});
} catch (err) {
done();
return c.json({ error: (err as Error).message === "too_large" ? "too_large" : "fetch_failed" }, 502);
}
done();
return c.body(Buffer.concat(chunks).toString("utf8"), 200, {
"Content-Type": "text/calendar; charset=utf-8",
// Never stored on disk, and never held by anything in between either.
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
});
}
+22 -60
View File
@@ -98,50 +98,32 @@ export function fetchPinned(url: URL, addr: string, signal?: AbortSignal): Promi
* Gmail-style remote content proxy: hides the reader's IP address and
* user-agent from tracking pixels, and blocks SSRF to internal networks.
*/
/** Why a guarded fetch refused, in the words the handlers answer with. */
export type SafeFetchError = "bad_url" | "bad_scheme" | "forbidden_target" | "dns_failure" | "fetch_failed" | "bad_redirect";
export interface SafeFetchResult {
res: IncomingMessage;
/** The URL actually fetched, which is not the one asked for if it redirected. */
url: URL;
done: () => void;
}
/**
* Fetch a URL nobody here chose, with every check the image proxy has always
* made — and made in one place, because a second copy of an SSRF guard is how
* one of them ends up missing a case.
*
* The name is resolved first and *every* answer has to be acceptable, the
* connection is pinned to the address that was checked, and each redirect hop
* is re-resolved and re-pinned rather than handed to the socket library.
*/
export async function safeFetch(raw: string, timeoutMs = 15_000): Promise<SafeFetchResult | SafeFetchError> {
export async function imageProxyHandler(c: Context) {
if (!config.imageProxy) return c.json({ error: "disabled" }, 404);
const raw = c.req.query("url") ?? "";
let url: URL;
try {
url = new URL(raw);
} catch {
return "bad_url";
return c.json({ error: "bad_url" }, 400);
}
// webcal: is an http URL wearing a different word; nothing else is allowed.
if (url.protocol === "webcal:") url = new URL(`https:${raw.slice(raw.indexOf(":") + 1)}`);
if (url.protocol !== "http:" && url.protocol !== "https:") return "bad_scheme";
if (url.username || url.password) return "bad_url";
if (url.protocol !== "http:" && url.protocol !== "https:") return c.json({ error: "bad_scheme" }, 400);
if (url.username || url.password) return c.json({ error: "bad_url" }, 400);
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
const done = () => clearTimeout(timer);
const timer = setTimeout(() => controller.abort(), 15_000);
let res: IncomingMessage;
try {
let addr: string;
try {
addr = await resolveAllowed(url.hostname);
} catch (err) {
done();
return err instanceof BlockedTarget ? "forbidden_target" : "dns_failure";
clearTimeout(timer);
return err instanceof BlockedTarget ? c.json({ error: "forbidden_target" }, 403) : c.json({ error: "dns_failure" }, 502);
}
let res = await fetchPinned(url, addr, controller.signal);
res = await fetchPinned(url, addr, controller.signal);
// Follow a limited number of redirects, re-checking and re-pinning each hop.
let hops = 0;
while (res.statusCode && [301, 302, 303, 307, 308].includes(res.statusCode) && hops < 3) {
const loc = res.headers.location;
@@ -149,58 +131,38 @@ export async function safeFetch(raw: string, timeoutMs = 15_000): Promise<SafeFe
res.resume(); // discard the redirect body
const next = new URL(loc, url);
if (next.protocol !== "http:" && next.protocol !== "https:") {
done();
return "bad_redirect";
clearTimeout(timer);
return c.json({ error: "bad_redirect" }, 400);
}
try {
addr = await resolveAllowed(next.hostname);
} catch (err) {
done();
return err instanceof BlockedTarget ? "forbidden_target" : "dns_failure";
clearTimeout(timer);
return err instanceof BlockedTarget ? c.json({ error: "forbidden_target" }, 403) : c.json({ error: "dns_failure" }, 502);
}
url = next;
res = await fetchPinned(url, addr, controller.signal);
hops++;
}
return { res, url, done };
} catch {
done();
return "fetch_failed";
clearTimeout(timer);
return c.json({ error: "fetch_failed" }, 502);
}
}
const SAFE_FETCH_STATUS: Record<SafeFetchError, number> = {
bad_url: 400,
bad_scheme: 400,
bad_redirect: 400,
forbidden_target: 403,
dns_failure: 502,
fetch_failed: 502,
};
export function safeFetchStatus(err: SafeFetchError): number {
return SAFE_FETCH_STATUS[err];
}
export async function imageProxyHandler(c: Context) {
if (!config.imageProxy) return c.json({ error: "disabled" }, 404);
const got = await safeFetch(c.req.query("url") ?? "");
if (typeof got === "string") return c.json({ error: got }, safeFetchStatus(got) as 400);
const { res, done } = got;
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
done();
clearTimeout(timer);
res.resume();
return c.json({ error: "fetch_failed" }, 502);
}
const type = (res.headers["content-type"] ?? "").split(";")[0]!.trim().toLowerCase();
if (!type.startsWith("image/") || type === "image/svg+xml") {
done();
clearTimeout(timer);
res.resume();
return c.json({ error: "not_image" }, 415);
}
const len = Number(res.headers["content-length"] ?? "0");
if (len > MAX_IMAGE_BYTES) {
done();
clearTimeout(timer);
res.resume();
return c.json({ error: "too_large" }, 413);
}
@@ -214,7 +176,7 @@ export async function imageProxyHandler(c: Context) {
else controller2.enqueue(chunk);
},
});
res.on("close", done);
res.on("close", () => clearTimeout(timer));
const headers = new Headers({
"Content-Type": type,
"Cache-Control": "private, max-age=86400",
-73
View File
@@ -1,73 +0,0 @@
import { test, before, after } from "node:test";
import assert from "node:assert/strict";
/**
* ihasmail requires Stalwart 0.16 or newer. Sign-in is where that is enforced,
* and it matters that it is enforced *there*: the alternative is signing
* someone in and letting Files, the account locale and self-service
* credentials each fail in their own way, with nothing to connect the three or
* to say what the real problem is.
*
* The refusal also has to keep two things apart that look the same from the
* outside. Bad credentials are a 401 the user can fix by typing again; an
* unsupported server is not, and telling someone their password is wrong when
* it is not would send them round in circles.
*/
const PORT = 18799;
process.env.MOCK_PORT = String(PORT);
process.env.MOCK_USER = "[email protected]";
process.env.MOCK_PASS = "demo-password";
process.env.MOCK_NO_REGISTRY = "1"; // a server without urn:stalwart:jmap
process.env.STALWART_URL = `http://127.0.0.1:${PORT}`;
process.env.APP_SECRET = "test-secret-for-login-guard";
const mock = await import("./mock/index.js");
const { createApp } = await import("./app.js");
const app = createApp();
const HEADERS = { "content-type": "application/json", "x-requested-with": "ihasmail" };
async function login(body: unknown): Promise<{ status: number; body: any; setCookie: string | null }> {
const res = await app.request("/api/auth/login", { method: "POST", headers: HEADERS, body: JSON.stringify(body) });
const text = await res.text();
return { status: res.status, body: text ? JSON.parse(text) : null, setCookie: res.headers.get("set-cookie") };
}
before(() => {
assert.equal(process.env.MOCK_NO_REGISTRY, "1");
});
after(() => {
(mock as { server?: { close(): void } }).server?.close();
});
test("a server without the registry is refused, with good credentials", async () => {
const res = await login({ username: "[email protected]", password: "demo-password" });
assert.equal(res.status, 501);
assert.equal(res.body.error, "unsupported_server");
});
test("the message says the credentials were fine, and names the way out", async () => {
const { body } = await login({ username: "[email protected]", password: "demo-password" });
// Someone hitting this has typed a correct password. Saying so is the
// difference between "upgrade your server" and "try your password again".
assert.match(body.message, /credentials are fine/i);
assert.match(body.message, /0\.16/);
assert.match(body.message, /stalwart-0\.15-support/, "the tag to build from if they cannot upgrade");
});
test("no session is minted for a server we cannot talk to", async () => {
// A cookie here would leave a signed-in session against a server every
// other request is going to fail on.
const res = await login({ username: "[email protected]", password: "demo-password" });
assert.equal(res.setCookie, null);
});
test("bad credentials on such a server are still a 401, not the server error", async () => {
// The upstream session request fails first, and that answer is the honest
// one: we never got far enough to learn what the server supports.
const res = await login({ username: "[email protected]", password: "wrong-password" });
assert.equal(res.status, 401);
assert.notEqual(res.body.error, "unsupported_server");
});
-111
View File
@@ -1,111 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { createDirectory, permissionsFor, type MockRole } from "./directory.js";
class Refused extends Error {
constructor(readonly type: string, description?: string) { super(description ?? type); }
}
const make = (role: MockRole) => createDirectory({ accountId: "a1", user: "[email protected]", locale: "en_US", role, fail: (t, d) => new Refused(t, d) });
/**
* The mock stands in for a server that decides what each account may do, so
* the client's administration can be developed against refusals as well as
* successes. These pin the refusals.
*/
test("an ordinary user is refused the directory outright", () => {
const dir = make("user");
assert.throws(() => dir.handlers["x:Account/query"]!({}), (e: Refused) => e.type === "forbidden");
assert.ok(!permissionsFor("user").some((p) => p.startsWith("sysAccountQuery")));
});
test("helpdesk may read and edit but not create or delete", () => {
const dir = make("helpdesk");
const { ids } = dir.handlers["x:Account/query"]!({ filter: { "@type": "User" } }) as { ids: string[] };
assert.ok(ids.length > 20);
assert.throws(() => dir.handlers["x:Account/set"]!({ create: { n: { name: "x", domainId: "d1" } } }), (e: Refused) => e.type === "forbidden");
assert.throws(() => dir.handlers["x:Account/set"]!({ destroy: [ids[0]] }), (e: Refused) => e.type === "forbidden");
});
test("queries page, count and match text the way the client asks", () => {
const dir = make("admin");
const all = dir.handlers["x:Account/query"]!({ filter: { "@type": "User" }, calculateTotal: true }) as { ids: string[]; total: number };
const page = dir.handlers["x:Account/query"]!({ filter: { "@type": "User" }, position: 10, limit: 5, calculateTotal: true }) as { ids: string[]; total: number };
assert.equal(page.total, all.total);
assert.deepEqual(page.ids, all.ids.slice(10, 15));
const ada = dir.handlers["x:Account/query"]!({ filter: { "@type": "User", text: "lovelace" } }) as { ids: string[] };
assert.equal(ada.ids.length, 1);
assert.throws(() => dir.handlers["x:Account/query"]!({ filter: { operator: "OR", conditions: [] } }), (e: Refused) => e.type === "unsupportedFilter");
});
test("an address already used as an alias cannot be taken", () => {
const dir = make("admin");
const res = dir.handlers["x:Account/set"]!({ create: { n: { "@type": "User", name: "postmaster", domainId: "d1", credentials: { "0": { "@type": "Password", secret: "long enough secret" } }, roles: { "@type": "User" } } } }) as { notCreated?: Record<string, { type: string }> };
assert.equal(res.notCreated?.n?.type, "primaryKeyViolation");
});
test("a password is set through its credential's pointer, and a weak one is refused", () => {
const dir = make("admin");
const set = dir.handlers["x:Account/set"]!;
assert.equal((set({ update: { a1: { "credentials/0/secret": "short" } } }) as { notUpdated?: Record<string, { properties: string[] }> }).notUpdated?.a1?.properties[0], "secret");
assert.deepEqual((set({ update: { a1: { "credentials/0/secret": "a much longer secret" } } }) as { updated: object }).updated, { a1: null });
const got = dir.handlers["x:Account/get"]!({ ids: ["a1"], properties: ["credentials"] }) as { list: Array<{ credentials: Record<string, { secret: string }> }> };
assert.equal(got.list[0]!.credentials["0"]!.secret, "[********]", "never echoed back");
});
test("a grant the caller does not hold is refused", () => {
const dir = make("helpdesk");
const res = dir.handlers["x:Account/set"]!({ update: { u101: { roles: { "@type": "Admin" } } } }) as { notUpdated?: Record<string, { type: string }> };
assert.equal(res.notUpdated?.u101?.type, "forbidden");
});
test("an administrator can delete an account, and a group with members is kept", () => {
const dir = make("admin");
const set = dir.handlers["x:Account/set"]!;
assert.deepEqual((set({ destroy: ["u101"] }) as { destroyed: string[] }).destroyed, ["u101"]);
assert.equal((set({ destroy: ["g1"] }) as { notDestroyed?: Record<string, { type: string }> }).notDestroyed?.g1?.type, "objectIsLinked");
});
test("a domain in use is kept, and names what uses it", () => {
const dir = make("admin");
const set = dir.handlers["x:Domain/set"]!;
const res = set({ destroy: ["d1"] }) as { notDestroyed?: Record<string, { type: string; linkedObjects: Array<{ object: string }> }> };
assert.equal(res.notDestroyed?.d1?.type, "objectIsLinked");
const kinds = new Set(res.notDestroyed?.d1?.linkedObjects.map((o) => o.object));
assert.deepEqual([...kinds].sort(), ["Account", "DkimSignature"]);
});
test("an unused domain goes once its keys do", () => {
const dir = make("admin");
const created = dir.handlers["x:Domain/set"]!({ create: { n: { name: "fresh.example.net" } } }) as { created: Record<string, { id: string }> };
const id = created.created.n!.id;
const keys = dir.handlers["x:DkimSignature/query"]!({ filter: { domainId: id } }) as { ids: string[] };
assert.equal(keys.ids.length, 1, "automatic DKIM makes a key straight away");
assert.equal((dir.handlers["x:Domain/set"]!({ destroy: [id] }) as { notDestroyed?: object }).notDestroyed !== undefined, true);
dir.handlers["x:DkimSignature/set"]!({ destroy: keys.ids });
assert.deepEqual((dir.handlers["x:Domain/set"]!({ destroy: [id] }) as { destroyed: string[] }).destroyed, [id]);
});
test("a domain's zone file is computed on read, with long keys split as the server splits them", () => {
const dir = make("admin");
const got = dir.handlers["x:Domain/get"]!({ ids: ["d1"], properties: ["name", "dnsZoneFile"] }) as { list: Array<{ dnsZoneFile: string }> };
const zone = got.list[0]!.dnsZoneFile;
assert.match(zone, /IN MX 10 /);
assert.match(zone, /_domainkey\.example\.com\. IN TXT \(\n {4}"/);
});
test("a filter on a name the registry does not index is refused, as the live server refuses it", () => {
const dir = make("admin");
// Seen on a live 0.16 server: "x:Account/query: unsupportedFilter - type".
assert.throws(() => dir.handlers["x:Account/query"]!({ filter: { type: "User" } }), (e: Refused) => e.type === "unsupportedFilter" && e.message === "type");
assert.doesNotThrow(() => dir.handlers["x:Account/query"]!({ filter: { "@type": "Group", domainId: "d1", text: "x" } }));
});
test("the domain validators refuse what the live server refused, in its words", () => {
const dir = make("admin");
const set = dir.handlers["x:Domain/set"]!;
const created = set({ create: { n: { name: "admin-test.example" } } }) as { notCreated?: Record<string, { type: string; description: string }> };
assert.deepEqual([created.notCreated?.n?.type, created.notCreated?.n?.description], ["invalidPatch", "Invalid domain name"]);
const updated = set({ update: { d2: { catchAllAddress: "postmaster" } } }) as { notUpdated?: Record<string, { type: string; description: string }> };
assert.deepEqual([updated.notUpdated?.d2?.type, updated.notUpdated?.d2?.description], ["invalidPatch", "Invalid email address"]);
});
-427
View File
@@ -1,427 +0,0 @@
/**
* Enough of Stalwart 0.16's directory registry to develop administration
* against: `x:Account`, `x:Domain` and `x:Role`, gated by permission names the
* way the real server gates them.
*
* Shapes follow the 0.16.22 source rather than the documentation, which has
* been wrong about both before:
*
* - a `List<T>` (credentials, aliases) is an object keyed by index -- `{"0": …}`
* -- and a `Set` (memberGroupIds, enabledPermissions) is `{"id": true}`;
* - an account's `name` is the local part only, and it lives on a domain by id;
* - secrets come back masked, and a new one is written through the password
* credential's own pointer, `credentials/<index>/secret`;
* - `x:Account/query` understands AND and nothing else.
*
* What it does not reproduce is tenancy: every caller sees every record. The
* real server scopes a tenant administrator's queries, and nothing in the client
* relies on seeing more or less than it is given.
*
* MOCK_ROLE picks who the demo user is: `admin` (the default), `tenant-admin`,
* `helpdesk` (a custom role that may view and edit accounts but not create or
* delete them) or `user`.
*/
type Obj = Record<string, unknown>;
export type MockRole = "admin" | "tenant-admin" | "helpdesk" | "user";
const OPS = ["Get", "Query", "Create", "Update", "Destroy"] as const;
const all = (...objects: string[]) => objects.flatMap((o) => OPS.map((op) => `sys${o}${op}`));
/** A few of the ordinary ones, so the list looks like what a server sends. */
const USER_PERMISSIONS = ["jmapEmailGet", "jmapEmailSet", "jmapMailboxGet", "sysAccountSettingsGet"];
export function permissionsFor(role: MockRole): string[] {
switch (role) {
case "admin":
return [...USER_PERMISSIONS, ...all("Account", "Domain", "Role", "MailingList", "DkimSignature", "DnsServer", "Tenant"), "impersonate"];
case "tenant-admin":
return [...USER_PERMISSIONS, ...all("Account", "Domain", "Role", "MailingList", "DkimSignature", "DnsServer")];
case "helpdesk":
return [...USER_PERMISSIONS, "sysAccountGet", "sysAccountQuery", "sysAccountUpdate"];
default:
return USER_PERMISSIONS;
}
}
export function mockRole(raw: string | undefined): MockRole {
return raw === "tenant-admin" || raw === "helpdesk" || raw === "user" ? raw : "admin";
}
const MASKED = "[********]";
const GIB = 1024 ** 3;
interface Options {
/** The demo user's JMAP account id, which is also its registry id. */
accountId: string;
/** The demo user's address. */
user: string;
locale: string;
role: MockRole;
/** Build the error a method fails with; the mock server owns the type. */
fail: (type: string, description?: string) => Error;
}
export function createDirectory(opts: Options) {
const permissions = new Set(permissionsFor(opts.role));
const [userLocal, userDomain] = splitAddress(opts.user);
let counter = 100;
const managed = (dns: boolean, dkim: boolean, certs: boolean) => ({
dnsManagement: dns ? { "@type": "Automatic", dnsServerId: "ns1", origin: null, publishRecords: {} } : { "@type": "Manual" },
dkimManagement: dkim ? { "@type": "Automatic", algorithms: { Dkim1Ed25519Sha256: true, Dkim1RsaSha256: true }, selectorTemplate: "v{version}-{algorithm}-{date-%Y%m%d}" } : { "@type": "Manual" },
certificateManagement: certs ? { "@type": "Automatic", acmeProviderId: "acme1", subjectAlternativeNames: {} } : { "@type": "Manual" },
});
const domain = (id: string, name: string, extra: Obj = {}): Obj => ({
id, name, aliases: {}, isEnabled: true, createdAt: "2026-06-01T09:00:00Z", description: null, logo: null,
...managed(false, true, false), memberTenantId: null, directoryId: null, catchAllAddress: null,
subAddressing: { "@type": "Enabled" }, allowRelaying: false, reportAddressUri: "mailto:postmaster", allowScimProvisioning: false, ...extra,
});
const domains: Obj[] = [
domain("d1", userDomain, { ...managed(true, true, true), aliases: { [`mail.${userDomain}`]: true }, description: "Main domain" }),
domain("d2", userDomain === "example.org" ? "example.net" : "example.org", { catchAllAddress: `postmaster@${userDomain}` }),
domain("d3", "old-brand.example", { ...managed(false, false, false), description: "No longer used", subAddressing: { "@type": "Custom", customRule: "..." } }),
];
const dkimKeys: Obj[] = [
{ id: "k1", "@type": "Dkim1Ed25519Sha256", domainId: "d1", selector: "v1-ed25519-20260601", stage: "active", createdAt: "2026-06-01T09:00:00Z", nextTransitionAt: "2026-08-30T09:00:00Z", memberTenantId: null },
{ id: "k2", "@type": "Dkim1RsaSha256", domainId: "d1", selector: "v1-rsa-20260601", stage: "active", createdAt: "2026-06-01T09:00:00Z", nextTransitionAt: "2026-08-30T09:00:00Z", memberTenantId: null },
{ id: "k3", "@type": "Dkim1Ed25519Sha256", domainId: "d2", selector: "v1-ed25519-20260710", stage: "active", createdAt: "2026-07-10T09:00:00Z", nextTransitionAt: null, memberTenantId: null },
];
/** What Stalwart's BIND serialiser writes, including a TXT long enough to be split. */
const zoneFile = (d: Obj): string => {
const n = String(d.name);
const lines = [
`${n}. IN MX 10 mail.${userDomain}.`,
`${n}. IN TXT "v=spf1 mx ra=postmaster -all"`,
];
for (const k of dkimKeys.filter((k) => k.domainId === d.id && k.stage !== "retired")) {
if (String(k["@type"]).includes("Rsa")) {
const p = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA" + "x".repeat(300) + "IDAQAB";
const txt = `v=DKIM1; k=rsa; h=sha256; p=${p}`;
lines.push(`${k.selector}._domainkey.${n}. IN TXT (`, ...(txt.match(/.{1,255}/g) ?? []).map((c) => ` "${c}"`), ")");
} else {
lines.push(`${k.selector}._domainkey.${n}. IN TXT "v=DKIM1; k=ed25519; h=sha256; p=11qYAYKxCrfVS/7TyWQHOg7hcvPapiMlrwIaaPcHURo="`);
}
}
lines.push(
`_dmarc.${n}. IN TXT "v=DMARC1; p=reject; rua=mailto:postmaster@${n}; ruf=mailto:postmaster@${n}"`,
`_jmap._tcp.${n}. IN SRV 0 1 443 mail.${userDomain}.`,
`_submissions._tcp.${n}. IN SRV 0 1 465 mail.${userDomain}.`,
`_imaps._tcp.${n}. IN SRV 0 1 993 mail.${userDomain}.`,
`mta-sts.${n}. IN CNAME mail.${userDomain}.`,
`_mta-sts.${n}. IN TXT "v=STSv1; id=16837364213434767412"`,
`_smtp._tls.${n}. IN TXT "v=TLSRPTv1; rua=mailto:postmaster@${n}"`,
`autoconfig.${n}. IN CNAME mail.${userDomain}.`,
`${n}. IN CAA 0 issue "letsencrypt.org"`,
);
return lines.join("\n") + "\n";
};
const roles: Obj[] = [
{ id: "r1", description: "User", enabledPermissions: flags(USER_PERMISSIONS), disabledPermissions: {}, roleIds: {} },
{ id: "r2", description: "Helpdesk", enabledPermissions: flags(permissionsFor("helpdesk").filter((p) => p.startsWith("sys"))), disabledPermissions: {}, roleIds: { r1: true } },
{ id: "r3", description: "Directory manager", enabledPermissions: flags(all("Account")), disabledPermissions: {}, roleIds: { r1: true } },
];
const ownRoles = opts.role === "admin" || opts.role === "tenant-admin" ? { "@type": "Admin" } : opts.role === "helpdesk" ? { "@type": "Custom", roleIds: { r2: true } } : { "@type": "User" };
const accounts: Obj[] = [];
const user = (o: { id?: string; name: string; domain?: string; description: string; roles?: Obj; used?: number; quota?: number; aliases?: string[]; groups?: string[]; password?: boolean }) => {
const domainId = o.domain === "d2" ? "d2" : "d1";
const row: Obj = {
id: o.id ?? `u${counter++}`,
"@type": "User",
name: o.name,
domainId,
description: o.description,
credentials: o.password === false ? {} : { "0": { "@type": "Password", credentialId: "0", secret: MASKED, otpAuth: null, expiresAt: null, allowedIps: {} } },
createdAt: new Date(Date.now() - counter * 86_400_000).toISOString().replace(/\.\d{3}Z$/, "Z"),
memberGroupIds: flags(o.groups ?? []),
memberTenantId: null,
roles: o.roles ?? { "@type": "User" },
permissions: { "@type": "Inherit" },
quotas: o.quota ? { maxDiskQuota: o.quota * GIB } : {},
usedDiskQuota: Math.round((o.used ?? 0) * GIB),
aliases: Object.fromEntries((o.aliases ?? []).map((name, i) => [String(i), { enabled: true, name, domainId, description: null }])),
locale: opts.locale,
timeZone: null,
};
accounts.push(row);
return row;
};
const group = (id: string, name: string, description: string) =>
accounts.push({ id, "@type": "Group", name, domainId: "d1", description, memberTenantId: null, roles: { "@type": "User" }, permissions: { "@type": "Inherit" }, quotas: {}, usedDiskQuota: 0, aliases: {} });
group("g1", "support", "Support");
group("g2", "office", "Office");
user({ id: opts.accountId, name: userLocal, description: "Demo User", roles: ownRoles, used: 1.4, quota: 10, aliases: ["postmaster"], groups: ["g1"] });
user({ name: "ada", domain: "d2", description: "Ada Lovelace", used: 3.2, quota: 5, groups: ["g2"] });
user({ name: "grace", domain: "d2", description: "Grace Hopper", used: 4.7, quota: 5, groups: ["g2"] });
user({ name: "alan", domain: "d2", description: "Alan Turing", roles: { "@type": "Custom", roleIds: { r2: true } }, used: 0.8, quota: 5, groups: ["g1"] });
user({ name: "margaret", description: "Margaret Hamilton", roles: { "@type": "Admin" }, used: 2.1, quota: 20 });
user({ name: "katherine", description: "Katherine Johnson", roles: { "@type": "Custom", roleIds: { r3: true } }, used: 0.4, quota: 5 });
user({ name: "sso.only", description: "Signs in with SSO", password: false, used: 0.1 });
const people = ["Edsger Dijkstra", "Barbara Liskov", "Donald Knuth", "Frances Allen", "John Backus", "Radia Perlman", "Ken Thompson", "Hedy Lamarr", "Dennis Ritchie", "Karen Spärck Jones", "Tim Berners-Lee", "Sophie Wilson", "Niklaus Wirth", "Jean Sammet", "Leslie Lamport", "Mary Kenneth Keller", "Tony Hoare", "Evelyn Berezin", "Butler Lampson", "Shafi Goldwasser", "Whitfield Diffie", "Adele Goldberg", "Vint Cerf", "Anita Borg", "Bob Kahn", "Lynn Conway", "Charles Babbage", "Annie Easley"];
people.forEach((description, i) => {
const name = description.toLowerCase().split(" ")[0]!.normalize("NFD").replace(/[^a-z]/g, "");
user({ name, domain: i % 3 === 0 ? "d2" : "d1", description, used: (i % 7) * 0.6, quota: i % 4 === 0 ? 0 : 5 });
});
const demand = (perm: string) => {
if (!permissions.has(perm)) throw opts.fail("forbidden", `You do not have the ${perm} permission.`);
};
const domainName = (id: unknown) => domains.find((d) => d.id === id)?.name as string | undefined;
const addressOf = (o: Obj) => `${o.name}@${domainName(o.domainId) ?? "invalid"}`;
/** Every address in use, primary and alias, across accounts. */
const addressTaken = (address: string, except?: string) =>
accounts.some((a) => a.id !== except && (addressOf(a) === address || Object.values((a.aliases as Obj) ?? {}).some((al) => `${(al as Obj).name}@${domainName((al as Obj).domainId)}` === address)));
const view = (o: Obj, properties: unknown): Obj => {
const full: Obj = { ...o };
if (accounts.includes(o)) full.emailAddress = addressOf(o);
if (domains.includes(o)) full.dnsZoneFile = zoneFile(o);
if (full.credentials) {
full.credentials = Object.fromEntries(Object.entries(full.credentials as Obj).map(([k, c]) => [k, { ...(c as Obj), secret: MASKED }]));
}
if (!Array.isArray(properties)) return full;
const out: Obj = { id: o.id };
for (const p of properties as string[]) if (p in full) out[p] = full[p];
return out;
};
const get = (list: Obj[], perm: string) => (a: Obj) => {
demand(perm);
const ids = a.ids as string[] | null | undefined;
const found = ids ? list.filter((x) => ids.includes(x.id as string)) : list;
return { accountId: opts.accountId, state: "1", list: found.map((x) => view(x, a.properties)), notFound: ids ? ids.filter((id) => !list.some((x) => x.id === id)) : [] };
};
/**
* A query, filtered only on what the real server indexes for that object.
* Any other name is refused the way Stalwart refuses it -- `unsupportedFilter`
* with the name as the whole description -- because a mock that took
* `{"type": "User"}` let exactly that ship, and the live server answers it
* with "unsupportedFilter - type".
*/
const query = (list: () => Obj[], perm: string, filterable: string[], match: (o: Obj, filter: Obj) => boolean) => (a: Obj) => {
demand(perm);
const filter = (a.filter as Obj | undefined) ?? {};
if ("operator" in filter) throw opts.fail("unsupportedFilter", "Only AND is supported in filters");
const unknown = Object.keys(filter).find((k) => !filterable.includes(k));
if (unknown) throw opts.fail("unsupportedFilter", unknown);
// Stalwart's default order is newest first, by id.
const rows = list().filter((o) => match(o, filter)).sort((x, y) => String(y.id).localeCompare(String(x.id), undefined, { numeric: true }));
const position = Math.max(0, Number(a.position ?? 0));
const limit = a.limit == null ? rows.length : Number(a.limit);
return {
accountId: opts.accountId,
queryState: "1",
canCalculateChanges: false,
position,
ids: rows.slice(position, position + limit).map((o) => o.id),
...(a.calculateTotal ? { total: rows.length } : {}),
};
};
const matchText = (o: Obj, text: unknown) => {
if (typeof text !== "string" || !text.trim()) return true;
const needle = text.trim().toLowerCase();
return [o.name, o.description, addressOf(o)].some((v) => typeof v === "string" && v.toLowerCase().includes(needle));
};
const setError = (type: string, description: string, properties?: string[]) => ({ type, description, ...(properties ? { properties } : {}) });
/** The password checks, roughly as strict as a default Stalwart. */
const weakPassword = (secret: unknown) => (typeof secret !== "string" || secret.length < 8 ? "Password must be at least 8 characters long." : null);
/** Stalwart checks a grant against the caller's own permissions. */
const grantRefused = (roles: unknown): string | null => {
const r = roles as Obj | undefined;
if (!r) return null;
if (r["@type"] === "Admin" && opts.role !== "admin" && opts.role !== "tenant-admin") return "You are not authorized to grant permissions: administrator.";
if (r["@type"] === "Custom") {
for (const id of Object.keys((r.roleIds as Obj) ?? {})) {
const role = roles_(id);
if (!role) return "Role does not exist.";
const missing = Object.keys((role.enabledPermissions as Obj) ?? {}).filter((p) => !permissions.has(p));
if (missing.length) return `You are not authorized to grant permissions: ${missing.join(", ")}.`;
}
}
return null;
};
const roles_ = (id: string) => roles.find((r) => r.id === id);
const handlers: Record<string, (a: Obj) => Obj> = {
"x:Account/get": get(accounts, "sysAccountGet"),
"x:Account/query": query(() => accounts, "sysAccountQuery", ["text", "@type", "domainId", "externalId", "memberGroupIds", "memberTenantId", "name"], (o, f) =>
(f["@type"] === undefined || o["@type"] === f["@type"]) && (f.domainId === undefined || o.domainId === f.domainId) && matchText(o, f.text) && matchText(o, f.name)),
"x:Account/set": (a) => {
const created: Obj = {};
const notCreated: Obj = {};
const updated: Obj = {};
const notUpdated: Obj = {};
const destroyed: string[] = [];
const notDestroyed: Obj = {};
for (const [cid, raw] of Object.entries((a.create as Obj) ?? {})) {
demand("sysAccountCreate");
const o = { ...(raw as Obj) };
if (typeof o.name !== "string" || !/^[a-z0-9._-]+$/i.test(o.name)) { notCreated[cid] = setError("invalidProperties", "Invalid account name.", ["name"]); continue; }
if (!domainName(o.domainId)) { notCreated[cid] = setError("invalidForeignKey", "Domain does not exist.", ["domainId"]); continue; }
if (addressTaken(`${o.name}@${domainName(o.domainId)}`)) { notCreated[cid] = setError("primaryKeyViolation", "An account or alias with this email address already exists."); continue; }
const refused = grantRefused(o.roles);
if (refused) { notCreated[cid] = setError("forbidden", refused); continue; }
const password = Object.values((o.credentials as Obj) ?? {})[0] as Obj | undefined;
const weak = password ? weakPassword(password.secret) : null;
if (weak) { notCreated[cid] = setError("invalidProperties", weak, ["secret"]); continue; }
const id = `u${counter++}`;
accounts.push({ memberGroupIds: {}, aliases: {}, quotas: {}, permissions: { "@type": "Inherit" }, ...o, id, memberTenantId: null, usedDiskQuota: 0, createdAt: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"), locale: opts.locale, timeZone: null });
created[cid] = { id, emailAddress: `${o.name}@${domainName(o.domainId)}` };
}
for (const [id, raw] of Object.entries((a.update as Obj) ?? {})) {
demand("sysAccountUpdate");
const target = accounts.find((x) => x.id === id);
if (!target) { notUpdated[id] = setError("notFound", "Account not found."); continue; }
const patch = raw as Obj;
const next = structuredClone(target);
let failure: Obj | null = null;
for (const [path, value] of Object.entries(patch)) {
if (path === "id" || path === "@type" || path === "usedDiskQuota" || path === "emailAddress") { failure = setError("invalidProperties", `Property ${path} cannot be changed.`, [path]); break; }
if (path.endsWith("/secret")) {
const weak = weakPassword(value);
if (weak) { failure = setError("invalidProperties", weak, ["secret"]); break; }
}
if (path.startsWith("credentials/") && value && typeof value === "object") {
const weak = weakPassword((value as Obj).secret);
if (weak) { failure = setError("invalidProperties", weak, ["secret"]); break; }
}
setPointer(next, path, value);
}
if (!failure && ("roles" in patch || "permissions" in patch)) {
const refused = grantRefused(next.roles);
if (refused) failure = setError("forbidden", refused);
}
if (!failure) {
for (const al of Object.values((next.aliases as Obj) ?? {})) {
const address = `${(al as Obj).name}@${domainName((al as Obj).domainId)}`;
if (!domainName((al as Obj).domainId)) { failure = setError("invalidForeignKey", "Domain does not exist.", ["aliases"]); break; }
if (addressTaken(address, id)) { failure = setError("primaryKeyViolation", "An account or alias with this email address already exists."); break; }
}
}
if (failure) { notUpdated[id] = failure; continue; }
// Secrets are stored hashed; the mock just stops echoing them.
for (const c of Object.values((next.credentials as Obj) ?? {})) (c as Obj).secret = MASKED;
Object.assign(target, next);
updated[id] = null;
}
for (const id of (a.destroy as string[]) ?? []) {
demand("sysAccountDestroy");
const i = accounts.findIndex((x) => x.id === id);
if (i < 0) { notDestroyed[id] = setError("notFound", "Account not found."); continue; }
if (accounts[i]!["@type"] === "Group" && accounts.some((x) => (x.memberGroupIds as Obj | undefined)?.[id])) {
notDestroyed[id] = { ...setError("objectIsLinked", "Group still has members."), linkedObjects: {} };
continue;
}
accounts.splice(i, 1);
destroyed.push(id);
}
return { accountId: opts.accountId, oldState: "1", newState: "2", created, updated, destroyed, ...(Object.keys(notCreated).length ? { notCreated } : {}), ...(Object.keys(notUpdated).length ? { notUpdated } : {}), ...(Object.keys(notDestroyed).length ? { notDestroyed } : {}) };
},
"x:Domain/get": get(domains, "sysDomainGet"),
"x:Domain/query": query(() => domains, "sysDomainQuery", ["text", "aliases", "memberTenantId", "name"], (o, f) => matchText(o, f.text) && matchText(o, f.name)),
"x:Domain/set": (a) => {
const created: Obj = {};
const notCreated: Obj = {};
const updated: Obj = {};
const notUpdated: Obj = {};
const destroyed: string[] = [];
const notDestroyed: Obj = {};
const taken = (name: string, except?: string) => domains.some((d) => d.id !== except && (d.name === name || Object.keys((d.aliases as Obj) ?? {}).includes(name)));
for (const [cid, raw] of Object.entries((a.create as Obj) ?? {})) {
demand("sysDomainCreate");
const o = raw as Obj;
const name = String(o.name ?? "");
// Live on 2026-09-13: a reserved TLD is refused by the registry's
// domain validator, as invalidPatch with the validator's own words.
if (!/^([a-z0-9-]+\.)+[a-z0-9-]{2,}$/.test(name) || /\.(example|test|invalid|localhost)$/.test(name)) { notCreated[cid] = setError("invalidPatch", "Invalid domain name", ["name"]); continue; }
if (taken(name)) { notCreated[cid] = setError("primaryKeyViolation", "A domain with this name already exists.", ["name"]); continue; }
const id = `d${counter++}`;
domains.push(domain(id, name, { ...o, id, createdAt: new Date().toISOString().replace(/\.\d{3}Z$/, "Z") }));
// Automatic DKIM, the default, makes its keys straight away.
dkimKeys.push({ id: `k${counter++}`, "@type": "Dkim1Ed25519Sha256", domainId: id, selector: "v1-ed25519-20260913", stage: "active", createdAt: new Date().toISOString(), nextTransitionAt: null, memberTenantId: null });
created[cid] = { id };
}
for (const [id, raw] of Object.entries((a.update as Obj) ?? {})) {
demand("sysDomainUpdate");
const target = domains.find((d) => d.id === id);
if (!target) { notUpdated[id] = setError("notFound", "Domain not found."); continue; }
const next = structuredClone(target);
for (const [path, value] of Object.entries(raw as Obj)) setPointer(next, path, value);
// Live on 2026-09-13: a catch-all that is not a whole address.
if (typeof next.catchAllAddress === "string" && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(next.catchAllAddress)) { notUpdated[id] = setError("invalidPatch", "Invalid email address", ["catchAllAddress"]); continue; }
const clash = Object.keys((next.aliases as Obj) ?? {}).find((alias) => alias === next.name || taken(alias, id));
if (clash) { notUpdated[id] = setError("primaryKeyViolation", `The name ${clash} is already in use.`, ["aliases"]); continue; }
Object.assign(target, next);
updated[id] = null;
}
for (const id of (a.destroy as string[]) ?? []) {
demand("sysDomainDestroy");
const i = domains.findIndex((d) => d.id === id);
if (i < 0) { notDestroyed[id] = setError("notFound", "Domain not found."); continue; }
const linked = [
...accounts.filter((x) => x.domainId === id || Object.values((x.aliases as Obj) ?? {}).some((al) => (al as Obj).domainId === id)).map((x) => ({ object: "Account", id: x.id })),
...dkimKeys.filter((k) => k.domainId === id).map((k) => ({ object: "DkimSignature", id: k.id })),
];
if (linked.length) { notDestroyed[id] = { ...setError("objectIsLinked", "Object is linked to other objects."), linkedObjects: linked }; continue; }
domains.splice(i, 1);
destroyed.push(id);
}
return { accountId: opts.accountId, oldState: "1", newState: "2", created, updated, destroyed, ...(Object.keys(notCreated).length ? { notCreated } : {}), ...(Object.keys(notUpdated).length ? { notUpdated } : {}), ...(Object.keys(notDestroyed).length ? { notDestroyed } : {}) };
},
"x:DkimSignature/get": get(dkimKeys, "sysDkimSignatureGet"),
"x:DkimSignature/query": query(() => dkimKeys, "sysDkimSignatureQuery", ["domainId", "memberTenantId"], (o, f) => f.domainId === undefined || o.domainId === f.domainId),
"x:DkimSignature/set": (a) => {
const destroyed: string[] = [];
for (const id of (a.destroy as string[]) ?? []) {
demand("sysDkimSignatureDestroy");
const i = dkimKeys.findIndex((k) => k.id === id);
if (i >= 0) { dkimKeys.splice(i, 1); destroyed.push(id); }
}
if (a.create) throw opts.fail("forbidden", "The mock does not generate DKIM keys; automatic management does that.");
return { accountId: opts.accountId, oldState: "1", newState: "2", created: {}, updated: {}, destroyed };
},
"x:DnsServer/get": (a) => {
demand("sysDnsServerGet");
return { accountId: opts.accountId, state: "1", list: ((a.ids as string[]) ?? ["ns1"]).filter((id) => id === "ns1").map((id) => ({ id, "@type": "Cloudflare", description: "Cloudflare (main zone)" })), notFound: [] };
},
"x:Role/get": get(roles, "sysRoleGet"),
"x:Role/query": query(() => roles, "sysRoleQuery", ["text", "description", "memberTenantId"], (o, f) => matchText(o, f.description)),
};
return { handlers, permissions: [...permissions], accounts };
}
function flags(names: string[]): Obj {
return Object.fromEntries(names.map((n) => [n, true]));
}
function splitAddress(address: string): [string, string] {
const at = address.lastIndexOf("@");
return at < 0 ? [address, "example.com"] : [address.slice(0, at), address.slice(at + 1)];
}
/**
* Apply one JMAP patch entry. A path walks into nested objects; `null` at the
* end removes the key, which is how an alias or a quota is taken away.
*/
function setPointer(obj: Obj, path: string, value: unknown): void {
const parts = path.split("/").map((p) => p.replace(/~1/g, "/").replace(/~0/g, "~"));
let node = obj;
for (const part of parts.slice(0, -1)) {
if (!node[part] || typeof node[part] !== "object") node[part] = {};
node = node[part] as Obj;
}
const last = parts[parts.length - 1]!;
if (value === null) delete node[last];
else node[last] = value;
}
+115 -822
View File
File diff suppressed because it is too large Load Diff
-274
View File
@@ -1,274 +0,0 @@
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { eventGetView, expandOccurrences, occurrenceAt, occurrenceView, parseSyntheticId, splitOccurrencePatch, syntheticId } from "./recurrence.js";
/**
* The mock expands recurrences so that per-occurrence editing can be developed
* against something. What it has to get right is not the expansion — that is
* the easy half — but the three things a live server does that a client will
* otherwise be written against wrongly:
*
* - every expanded id is synthetic, one-offs included;
* - an occurrence carries a `recurrenceId` and no rule;
* - a per-occurrence patch loses some properties in silence.
*/
const WEEKDAYS = { "@type": "RecurrenceRule", frequency: "weekly", byDay: [{ day: "mo" }, { day: "tu" }, { day: "we" }, { day: "th" }, { day: "fr" }] };
/** A standup at 09:00 every weekday, starting Monday 2026-09-07. */
const series = () => ({ id: "ev1", "@type": "Event", uid: "u1", title: "Standup", start: "2026-09-07T09:00:00", duration: "PT30M", recurrenceRule: WEEKDAYS } as Record<string, unknown>);
const oneOff = () => ({ id: "ev2", "@type": "Event", uid: "u2", title: "Lunch", start: "2026-09-08T12:00:00", duration: "PT1H" } as Record<string, unknown>);
const week = (from: string, to: string) => [new Date(from), new Date(to)] as const;
describe("expandOccurrences", () => {
it("gives a weekday rule five dates in a week and skips the weekend", () => {
const [a, b] = week("2026-09-07T00:00:00", "2026-09-14T00:00:00");
const out = expandOccurrences(series(), a, b);
assert.deepEqual(out.map((o) => o.start), [
"2026-09-07T09:00:00", "2026-09-08T09:00:00", "2026-09-09T09:00:00",
"2026-09-10T09:00:00", "2026-09-11T09:00:00",
]);
});
it("gives a one-off exactly one occurrence, at index 0", () => {
const [a, b] = week("2026-09-01T00:00:00", "2026-10-01T00:00:00");
const out = expandOccurrences(oneOff(), a, b);
assert.equal(out.length, 1);
assert.equal(out[0]!.index, 0);
});
it("honours count", () => {
const ev = { ...series(), recurrenceRule: { ...WEEKDAYS, count: 3 } };
const [a, b] = week("2026-09-07T00:00:00", "2026-10-01T00:00:00");
assert.equal(expandOccurrences(ev, a, b).length, 3);
});
it("drops an excluded date from the expansion, keeping the series positions", () => {
const ev = { ...series(), recurrenceOverrides: { "2026-09-08T09:00:00": { excluded: true } } };
const [a, b] = week("2026-09-07T00:00:00", "2026-09-14T00:00:00");
const out = expandOccurrences(ev, a, b);
assert.deepEqual(out.map((o) => o.start), [
"2026-09-07T09:00:00", "2026-09-09T09:00:00", "2026-09-10T09:00:00", "2026-09-11T09:00:00",
]);
// The position within the series is unchanged — Wednesday is still the
// third date the rule produces, whatever happened to Tuesday. It is the
// *id* built on top of that which moves, and only after a write.
assert.equal(out[1]!.index, 2);
});
it("carries an override onto the occurrence it keys", () => {
const ev = { ...series(), recurrenceOverrides: { "2026-09-09T09:00:00": { title: "Standup (long)" } } };
const [a, b] = week("2026-09-07T00:00:00", "2026-09-14T00:00:00");
const out = expandOccurrences(ev, a, b);
assert.deepEqual(out.find((o) => o.start === "2026-09-09T09:00:00")!.override, { title: "Standup (long)" });
});
});
describe("occurrenceView", () => {
it("strips the rule, sets recurrenceId, and points baseEventId at the master", () => {
const base = series();
const occ = occurrenceAt(base, "2026-09-08T09:00:00")!;
const view = occurrenceView(base, occ);
assert.equal(view.id, syntheticId("ev1", "2026-09-08T09:00:00"));
assert.equal(view.baseEventId, "ev1");
assert.equal(view.recurrenceId, "2026-09-08T09:00:00");
assert.equal(view.recurrenceRule, undefined);
assert.equal(view.recurrenceOverrides, undefined);
});
it("gives a one-off a synthetic id over a different base, and no recurrenceId", () => {
// Both halves matter. The id is why `baseEventId` proves nothing about a
// series; the absent `recurrenceId` is why a one-off does not read as one.
const base = oneOff();
const view = occurrenceView(base, occurrenceAt(base, "2026-09-08T12:00:00")!);
assert.equal(view.id, "ev2-r20260908T120000");
assert.equal(view.baseEventId, "ev2");
assert.notEqual(view.id, view.baseEventId);
assert.equal(view.recurrenceId, undefined);
});
it("lets an override win over the series", () => {
const base = { ...series(), recurrenceOverrides: { "2026-09-08T09:00:00": { title: "Moved" } } };
// The same recurrence id as before the override was written, because that
// is now the whole point: the write does not move any other occurrence.
const view = occurrenceView(base, occurrenceAt(base, "2026-09-08T09:00:00")!);
assert.equal(view.start, "2026-09-08T09:00:00");
assert.equal(view.title, "Moved");
});
});
describe("eventGetView", () => {
/*
* What 0.16.22 changed in `CalendarEvent/get`, read from its source and the
* tests that came with it (`tests/src/jmap/calendar/event.rs` and
* `instance.rs`).
*/
it("reports no base for an event read by its stored id", () => {
// 0.16.21 answered with the event's own id here.
assert.deepEqual(eventGetView(oneOff(), false, ["id", "baseEventId"]), { id: "ev2", baseEventId: null });
assert.equal(eventGetView(series(), false, ["baseEventId"]).baseEventId, null);
});
it("still gives a one-off read through its synthetic id a base", () => {
// An expanded query hands a one-off a synthetic id, so this has not
// changed: `baseEventId` is still no evidence of a series.
const base = oneOff();
const view = eventGetView(occurrenceView(base, occurrenceAt(base, "2026-09-08T12:00:00")!), true, ["baseEventId"]);
assert.equal(view.baseEventId, "ev2");
});
it("answers null for the rule and overrides named on an occurrence", () => {
const base = { ...series(), recurrenceOverrides: { "2026-09-09T09:00:00": { title: "Standup (long)" } } };
const view = eventGetView(occurrenceView(base, occurrenceAt(base, "2026-09-08T09:00:00")!), true,
["recurrenceId", "recurrenceRule", "recurrenceOverrides"]);
assert.deepEqual(view, { id: "ev1-r20260908T090000", recurrenceId: "2026-09-08T09:00:00", recurrenceRule: null, recurrenceOverrides: null });
});
it("leaves the rule on the series itself alone", () => {
assert.deepEqual(eventGetView(series(), false, ["recurrenceRule"]).recurrenceRule, WEEKDAYS);
});
it("reads useDefaultAlerts as false until it is set", () => {
// It used to read true until set.
assert.equal(eventGetView(series(), false, ["useDefaultAlerts"]).useDefaultAlerts, false);
assert.equal(eventGetView({ ...series(), useDefaultAlerts: true }, false, ["useDefaultAlerts"]).useDefaultAlerts, true);
assert.equal(eventGetView({ ...series(), useDefaultAlerts: false }, false, ["useDefaultAlerts"]).useDefaultAlerts, false);
});
it("returns only the id for an empty list", () => {
// 0.16.21 treated an empty list as asking for everything.
assert.deepEqual(eventGetView(series(), false, []), { id: "ev1" });
});
it("returns the object unchanged when no list is given", () => {
assert.deepEqual(eventGetView(series(), false, null), series());
});
});
describe("parseSyntheticId", () => {
it("round-trips", () => {
assert.deepEqual(parseSyntheticId(syntheticId("ev1", "2026-09-08T09:00:00")),
{ baseId: "ev1", recurrenceId: "2026-09-08T09:00:00" });
});
it("does not claim a stored id", () => {
assert.equal(parseSyntheticId("ev1"), null);
});
it("does not claim an id that merely ends in digits", () => {
assert.equal(parseSyntheticId("ev1-r2026"), null);
});
});
describe("splitOccurrencePatch", () => {
it("applies what an occurrence takes", () => {
const { rejected, applied } = splitOccurrencePatch({ title: "Just today", color: "#f00" });
assert.equal(rejected, undefined);
assert.deepEqual(applied, { title: "Just today", color: "#f00" });
});
it("refuses an event-level property by name", () => {
assert.equal(splitOccurrencePatch({ calendarIds: { c2: true } }).rejected, "calendarIds");
assert.equal(splitOccurrencePatch({ hideAttendees: true }).rejected, "hideAttendees");
});
it("drops an inherited property in silence, which is the dangerous half", () => {
// No `rejected`, nothing applied, and a real server would still answer
// "updated". Anything that trusts the response believes this landed.
const { rejected, applied } = splitOccurrencePatch({ privacy: "private", recurrenceRule: null });
assert.equal(rejected, undefined);
assert.deepEqual(applied, {});
});
it("judges a pointer patch on its first token", () => {
assert.deepEqual(splitOccurrencePatch({ "participants/me/participationStatus": "accepted" }).applied,
{ "participants/me/participationStatus": "accepted" });
assert.deepEqual(splitOccurrencePatch({ "participants/me/calendarAddress": "mailto:x@y" }).applied, {});
});
});
describe("synthetic ids survive a write", () => {
/*
* This used to assert the opposite, and the reversal is the point.
*
* Up to 0.16.20 a synthetic id encoded a position, so writing one override
* renumbered the series and a held id silently began naming a different
* date — confirmed live on 2026-08-31, and reproduced here on purpose so a
* client could not be written against a comfort the server did not offer.
*
* 0.16.21 identifies an occurrence by its recurrence id instead.
* **Confirmed live on 0.16.21 (2026-09-06):** a five-week series was
* expanded, its third occurrence retitled through the synthetic id, and all
* five original ids re-read. Every one resolved, and every one still named
* its own date. So the hazard is gone, and the mock stops teaching it.
*/
it("keeps a cached id on the same date after an override is written", () => {
const before = series();
const held = syntheticId("ev1", occurrenceAt(before, "2026-09-10T09:00:00")!.recurrenceId);
const dateBefore = occurrenceAt(before, parseSyntheticId(held)!.recurrenceId)!.start;
const after = { ...before, recurrenceOverrides: { "2026-09-07T09:00:00": { title: "changed" } } };
const dateAfter = occurrenceAt(after, parseSyntheticId(held)!.recurrenceId)!.start;
assert.equal(dateAfter, dateBefore);
});
it("resolves every id of a series after one of them is overridden", () => {
const before = series();
const held = expandOccurrences(before, new Date("2026-09-07T00:00:00"), new Date("2026-09-12T00:00:00"))
.map((o) => syntheticId("ev1", o.recurrenceId));
const after = { ...before, recurrenceOverrides: { "2026-09-09T09:00:00": { title: "changed" } } };
for (const id of held) {
const occ = occurrenceAt(after, parseSyntheticId(id)!.recurrenceId);
assert.ok(occ, `${id} should still resolve`);
assert.equal(syntheticId("ev1", occ.recurrenceId), id);
}
});
it("still refuses an id whose date the rule no longer generates", () => {
const base = { ...series(), recurrenceOverrides: { "2026-09-09T09:00:00": { excluded: true } } };
assert.equal(occurrenceAt(base, "2026-09-09T09:00:00"), null);
});
});
describe("an override that moves an occurrence", () => {
/*
* Confirmed live on 0.16.20 (2026-08-31): one occurrence of a weekly 09:00
* series moved to 14:00 comes back with `start` at 14:00 and `recurrenceId`
* still at 09:00 — the slot the rule made, which the move does not touch.
*
* The mock used to clobber the override's `start` with the slot time, so a
* moved occurrence did not move. That made per-occurrence *time* editing —
* one of the main things the feature is for — look broken against the mock
* and fine against the server.
*/
const moved = () => ({
...series(),
recurrenceOverrides: { "2026-09-08T09:00:00": { start: "2026-09-08T14:00:00" } },
});
it("moves the occurrence and leaves its recurrenceId on the original slot", () => {
const [a, b] = week("2026-09-07T00:00:00", "2026-09-14T00:00:00");
const occ = expandOccurrences(moved(), a, b).find((o) => o.recurrenceId === "2026-09-08T09:00:00")!;
assert.equal(occ.start, "2026-09-08T14:00:00");
assert.equal(occ.recurrenceId, "2026-09-08T09:00:00");
});
it("shows the moved time on the occurrence a get returns", () => {
const base = moved();
const occ = expandOccurrences(base, new Date("2026-09-07T00:00:00"), new Date("2026-09-14T00:00:00"))
.find((o) => o.recurrenceId === "2026-09-08T09:00:00")!;
const view = occurrenceView(base, occ);
assert.equal(view.start, "2026-09-08T14:00:00");
assert.equal(view.recurrenceId, "2026-09-08T09:00:00");
});
it("keeps the occurrence findable by recurrenceId after the move", () => {
// This is the property the store depends on: `recurrenceId` survives both
// a renumbering and a move, so it is the handle a mutation resolves from.
const base = moved();
const all = expandOccurrences(base, new Date("2026-09-01T00:00:00"), new Date("2026-10-01T00:00:00"));
assert.equal(all.filter((o) => o.recurrenceId === "2026-09-08T09:00:00").length, 1);
});
});
-278
View File
@@ -1,278 +0,0 @@
/**
* Enough recurrence expansion for the mock to behave like Stalwart 0.16.22.
*
* The mock used to hand a recurring event back once, as its stored self. Three
* things that only a live server showed were therefore impossible to develop
* against, and all three had already cost a debugging session:
*
* - an expanded query gives *everything* a synthetic id over a `baseEventId`,
* a one-off included, so `baseEventId` is no evidence of a series;
* - an occurrence carries a `recurrenceId` and no rule of its own;
* - a write aimed at a synthetic id becomes a `recurrenceOverrides` entry
* rather than touching the series.
*
* A mock that agrees with the client rather than with the server is how #26 and
* #30 reached a live instance, so the refusals matter as much as the successes:
* what Stalwart rejects is rejected here, and what it drops in silence is
* dropped here, in silence, on purpose.
*/
export type Obj = Record<string, unknown>;
/** How far the expander will walk before giving up on a rule. */
const MAX_ITERATIONS = 750;
const DAYS = ["su", "mo", "tu", "we", "th", "fr", "sa"];
/**
* The id an occurrence is addressed by: its `recurrenceId`, not its position.
*
* Stalwart's are opaque; the mock's are parseable because it has to resolve
* them, and nothing in ihasmail may read either.
*
* **They are stable, and that is a change.** Up to 0.16.20 a synthetic id
* encoded a *position* in the expanded series, so writing one override
* renumbered the rest and a held id silently began addressing a different
* date — a hazard this file used to reproduce on purpose. 0.16.21 fixed it:
* an occurrence is now identified by its recurrence id.
*
* **Confirmed live on 0.16.21 (2026-09-06):** a five-week weekly series was
* expanded, the third occurrence retitled through its synthetic id, and all
* five original ids re-read afterwards. Every one still resolved, and every
* one still named its own date; nothing was renumbered and nothing was
* `notFound`. Only the *order* of the ids from an expanded query changed —
* the overridden occurrence moved to the end of the list — which is why a
* client sorts by `start` rather than trusting query order.
*
* The real ids look nothing like these (`h1fo9uaaaaab` for the first of that
* series); what has to match is that holding one across a write stays correct.
*/
const compact = (recurrenceId: string): string => recurrenceId.replace(/[-:]/g, "");
export const syntheticId = (baseId: string, recurrenceId: string): string =>
`${baseId}-r${compact(recurrenceId)}`;
export function parseSyntheticId(id: string): { baseId: string; recurrenceId: string } | null {
const m = /^(.+)-r(\d{8}T\d{6})$/.exec(id);
if (!m) return null;
const c = m[2]!;
const recurrenceId =
`${c.slice(0, 4)}-${c.slice(4, 6)}-${c.slice(6, 8)}` +
`T${c.slice(9, 11)}:${c.slice(11, 13)}:${c.slice(13, 15)}`;
return { baseId: m[1]!, recurrenceId };
}
/** `2026-08-31T09:00:00` — the naive local form the mock stores `start` in. */
export function localDateTime(d: Date): string {
const p = (n: number) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
}
const parseLocal = (s: string): Date => new Date(s);
export interface Occurrence {
index: number;
/** The slot in the series this instance fills, which keys any override. */
recurrenceId: string;
start: string;
/** Set when a `recurrenceOverrides` entry applies to this date. */
override?: Obj;
}
interface Rule {
frequency?: string;
interval?: number;
count?: number;
until?: string;
byDay?: { day: string }[];
}
/**
* Every occurrence of `base` between `from` and `to`, in series order.
*
* An event with no rule has exactly one, at index 0 — which is what gives a
* one-off the synthetic id a real server would give it.
*/
export function expandOccurrences(base: Obj, from: Date, to: Date): Occurrence[] {
const overrides = (base.recurrenceOverrides as Record<string, Obj> | undefined) ?? {};
const startStr = base.start as string;
if (!startStr) return [];
const first = parseLocal(startStr);
const rule = base.recurrenceRule as Rule | undefined;
const out: Occurrence[] = [];
const emit = (index: number, at: Date): boolean => {
const recurrenceId = localDateTime(at);
const override = overrides[recurrenceId];
// An excluded date is simply gone from the expansion. Nothing is
// reserved in its place, and no other occurrence's id moves because of it.
if (override?.excluded === true) return true;
/*
* An override may move the occurrence, and then `start` and `recurrenceId`
* are two different times: the slot it fills stays where the rule put it,
* and only the clock time moves. **Confirmed live on 0.16.20
* (2026-08-31)**: one occurrence of a weekly 09:00 series moved to 14:00
* came back `start: 2027-06-14T14:00:00` with `recurrenceId` still
* `2027-06-14T09:00:00`.
*
* Which is exactly why `recurrenceId` is what a client holds on to, and
* since 0.16.21 what the id is built from: the one name for this instance
* that a move does not change.
*/
const start = (typeof override?.start === "string" ? override.start : null) ?? recurrenceId;
const shown = parseLocal(start);
if (shown >= from && shown < to) {
out.push({ index, recurrenceId, start, ...(override ? { override } : {}) });
}
return at < to;
};
if (!rule?.frequency) {
emit(0, first);
return out;
}
const interval = Math.max(1, rule.interval ?? 1);
const until = rule.until ? parseLocal(rule.until) : null;
const byDay = rule.byDay?.length ? new Set(rule.byDay.map((d) => d.day.toLowerCase())) : null;
let index = 0;
let emitted = 0;
const cursor = new Date(first);
for (let step = 0; step < MAX_ITERATIONS; step++) {
if (until && cursor > until) break;
if (rule.count != null && emitted >= rule.count) break;
const matches = !byDay || byDay.has(DAYS[cursor.getDay()]!);
if (matches) {
emitted++;
const keepGoing = emit(index, new Date(cursor));
index++;
if (!keepGoing) break;
}
// A rule with byDay walks day by day and keeps the days it names; without
// one it steps by its own frequency.
if (byDay) cursor.setDate(cursor.getDate() + 1);
else if (rule.frequency === "daily") cursor.setDate(cursor.getDate() + interval);
else if (rule.frequency === "weekly") cursor.setDate(cursor.getDate() + 7 * interval);
else if (rule.frequency === "monthly") cursor.setMonth(cursor.getMonth() + interval);
else if (rule.frequency === "yearly") cursor.setFullYear(cursor.getFullYear() + interval);
else break;
}
return out;
}
/** Fields that describe the series and never travel down to one instance. */
const SERIES_ONLY = ["recurrenceRule", "recurrenceRules", "excludedRecurrenceRules", "recurrenceOverrides"];
/**
* The object a `CalendarEvent/get` returns for one occurrence.
*
* The rule is stripped, `recurrenceId` is set, and `baseEventId` points at the
* master — so an occurrence is recognisable by its `recurrenceId` and by
* nothing else, which is the shape `isRecurring` was written against.
*/
export function occurrenceView(base: Obj, occ: Occurrence): Obj {
const view: Obj = { ...base };
for (const k of SERIES_ONLY) delete view[k];
Object.assign(view, occ.override ?? {});
view.id = syntheticId(base.id as string, occ.recurrenceId);
view.baseEventId = base.id;
view.start = occ.start;
// Only a genuine instance of a series carries one. A one-off expanded into
// its single occurrence does not, or every one-off would look recurring.
if (base.recurrenceRule) view.recurrenceId = occ.recurrenceId;
delete view.excluded;
return view;
}
/** Series properties a synthetic id answers `null` for, when they are named. */
const NULL_ON_OCCURRENCE = new Set(["recurrenceRule", "recurrenceOverrides"]);
/**
* The object a `CalendarEvent/get` with a `properties` list returns, as 0.16.22
* builds it. Omitted or null `properties` returns the stored object unchanged.
*
* Three of the named properties are no longer read off the object:
*
* - `baseEventId` is the master's id on a synthetic id and `null` on anything
* else. Through 0.16.21 an event read by its stored id reported that id as
* its own base. An expanded query still hands a one-off a synthetic id, so
* one read that way still carries a base, and `baseEventId` is still no
* evidence of a series;
* - `recurrenceRule` and `recurrenceOverrides` come back as `null` on a
* synthetic id rather than being left out;
* - `useDefaultAlerts` is the reader's own preference, and `false` when they
* never set one. It used to read `true` until set. The mock has one reader,
* so a value stored on the event stands in for that reader's.
*
* An empty list returns `id` alone, where 0.16.21 treated it as asking for
* everything. `ContactCard/get` changed the same way.
*
* Read from the 0.16.22 source (`calendar_event/get.rs`) and its tests.
*/
export function eventGetView(event: Obj, synthetic: boolean, properties: string[] | null | undefined): Obj {
if (!properties) return event;
const out: Obj = { id: event.id };
for (const p of properties) {
if (p === "baseEventId") out[p] = synthetic ? event.baseEventId : null;
else if (p === "useDefaultAlerts") out[p] = event.useDefaultAlerts === true;
else if (synthetic && NULL_ON_OCCURRENCE.has(p)) out[p] = null;
else if (p in event) out[p] = event[p];
}
return out;
}
/* ---------- what a single occurrence will not take ---------- */
/** Refused outright, with `invalidProperties`. */
export const OCCURRENCE_REJECTED = new Set([
"baseEventId", "calendarIds", "isDraft", "isOrigin", "utcStart", "utcEnd",
"useDefaultAlerts", "mayInviteSelf", "mayInviteOthers", "hideAttendees",
]);
/**
* Dropped from the patch, with the response still reporting success.
*
* This is the half that has to be reproduced most carefully. A mock that
* *applied* these would agree with a client that sends them, and the belief
* would ship — which is exactly the road #26 took to a live server.
*/
export const OCCURRENCE_INHERITED = new Set([
"@type", "method", "organizerCalendarAddress", "privacy", "prodId",
"recurrenceId", "recurrenceIdTimeZone", "sentBy", "uid",
"recurrenceOverrides", "recurrenceRule", "relatedTo",
]);
/**
* Split a per-occurrence patch the way the server's validator does.
*
* `rejected` is the first property that would be refused, if any; `applied` is
* what actually lands on the override. Everything else vanishes without a word.
*/
export function splitOccurrencePatch(patch: Obj): { rejected?: string; applied: Obj } {
const applied: Obj = {};
for (const [key, value] of Object.entries(patch)) {
const [head, , third] = key.split("/");
const root = head ?? key;
if (OCCURRENCE_REJECTED.has(root)) return { rejected: root, applied };
if (OCCURRENCE_INHERITED.has(root)) continue;
if (root === "participants" && third === "calendarAddress") continue;
if (root === "id") continue;
applied[key] = value;
}
return { applied };
}
/**
* The occurrence a recurrence id addresses, which no later write moves.
*
* An id whose date the rule no longer generates — excluded, or past a `count`
* — resolves to nothing, and the caller turns that into `notFound`.
*/
export function occurrenceAt(base: Obj, recurrenceId: string): Occurrence | null {
const all = expandOccurrences(base, new Date(-8640000000000), new Date(8640000000000));
return all.find((o) => o.recurrenceId === recurrenceId) ?? null;
}
-27
View File
@@ -1,27 +0,0 @@
/**
* Real signed messages, for driving signature checking against the mock.
*
* These are not hand-written. Each was produced by `openssl smime -sign` with a
* generated certificate and is stored base64 so no editor, formatter or
* checkout setting can touch a byte of it -- a signature is over exact octets,
* and a stray line-ending normalisation would turn a working fixture into a
* broken one for reasons invisible in a diff.
*
* The same files back the unit tests, in web/src/lib/smime/__tests__/fixtures.
*
* good Ada Lovelace <[email protected]>, RSA/SHA-256, intact
* tampered the same message with one word of the body changed and the
* signature untouched -- what the feature exists to catch
* imposter signed with a certificate for [email protected] while claiming
* to be from Ada, which is a valid signature by the wrong person
*/
export const SIGNED_MESSAGES = {
good: "VG86IHlvdUBleGFtcGxlLmNvbQpGcm9tOiBBZGEgTG92ZWxhY2UgPGFkYUBleGFtcGxlLmNvbT4KU3ViamVjdDogQSBub3RlCk1JTUUtVmVyc2lvbjogMS4wCkNvbnRlbnQtVHlwZTogbXVsdGlwYXJ0L3NpZ25lZDsgcHJvdG9jb2w9ImFwcGxpY2F0aW9uL3gtcGtjczctc2lnbmF0dXJlIjsgbWljYWxnPSJzaGEtMjU2IjsgYm91bmRhcnk9Ii0tLS0xMkQwMEVCQzBCNUQzMzUyRjBFMkYyNUIxQTVEMzU1MiIKClRoaXMgaXMgYW4gUy9NSU1FIHNpZ25lZCBtZXNzYWdlCgotLS0tLS0xMkQwMEVCQzBCNUQzMzUyRjBFMkYyNUIxQTVEMzU1MgpDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9dXRmLTgNCg0KVGhlIEFuYWx5dGljYWwgRW5naW5lIGhhcyBubyBwcmV0ZW5zaW9ucyB3aGF0ZXZlciB0byBvcmlnaW5hdGUgYW55dGhpbmcuDQoKLS0tLS0tMTJEMDBFQkMwQjVEMzM1MkYwRTJGMjVCMUE1RDM1NTIKQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi94LXBrY3M3LXNpZ25hdHVyZTsgbmFtZT0ic21pbWUucDdzIgpDb250ZW50LVRyYW5zZmVyLUVuY29kaW5nOiBiYXNlNjQKQ29udGVudC1EaXNwb3NpdGlvbjogYXR0YWNobWVudDsgZmlsZW5hbWU9InNtaW1lLnA3cyIKCk1JSUdKd1lKS29aSWh2Y05BUWNDb0lJR0dEQ0NCaFFDQVFFeER6QU5CZ2xnaGtnQlpRTUVBZ0VGQURBTEJna3EKaGtpRzl3MEJCd0dnZ2dPTk1JSURpVENDQW5HZ0F3SUJBZ0lVUGc0OW12c1VhQ0ZvSUdYV1ZyRTlyNWFGVm1NdwpEUVlKS29aSWh2Y05BUUVMQlFBd05ERVZNQk1HQTFVRUF3d01RV1JoSUV4dmRtVnNZV05sTVJzd0dRWURWUVFLCkRCSkJibUZzZVhScFkyRnNJRVZ1WjJsdVpYTXdIaGNOTWpZd09UQTFNRGd5TnpRNFdoY05Nell3T1RBeU1EZ3kKTnpRNFdqQTBNUlV3RXdZRFZRUUREQXhCWkdFZ1RHOTJaV3hoWTJVeEd6QVpCZ05WQkFvTUVrRnVZV3g1ZEdsagpZV3dnUlc1bmFXNWxjekNDQVNJd0RRWUpLb1pJaHZjTkFRRUJCUUFEZ2dFUEFEQ0NBUW9DZ2dFQkFKU0JGYnJCCmtTTFRySG91Zlc1V05Zb0hmUFFZZCtrZWVTc1puaGw4TkdjVFVpb1hMRlBnWCt1ZW9sZWJNQlJ2U1ErZUZuWFYKY1lnRHR1NHllNXFmeVlMM1d2Q1dRb2l3Z3UyblA4ejZrRlRpUUtsdTJaUkNZc20vMCtEU0QyOHdIUUZ4KzlOcwpsTFlDZGsyMmZsVWhNbmtDa1d2ZFJiMDQ4K0o3NjJCY3h4bkRDRXphK0RQZ3ROcy9rSTJVcWNoaStWUVpaV1F1Ck1mRTU4ZzJVTTJaM3NlNTVRZlMydll0NGo3cFFYanRjVHNqT3hUUlVmenNzbGFoR0xjTklTR2w1a2RqTDV3cngKMUx3dzNZRWwxbnVjUzFRWkR0N3BjU0dOVVFsZE83ZTFyaDBReFFabG5SekZ5a09FSEpSakRvMDdZOWJjdmhuYQp2NWVPUHlPRDBweFdTMWNDQXdFQUFhT0JrakNCanpBZEJnTlZIUTRFRmdRVVFPamRqbHJwVkY0TXBsdDNISmNQCkhFVG9tN1F3SHdZRFZSMGpCQmd3Rm9BVVFPamRqbHJwVkY0TXBsdDNISmNQSEVUb203UXdEd1lEVlIwVEFRSC8KQkFVd0F3RUIvekFhQmdOVkhSRUVFekFSZ1E5aFpHRkFaWGhoYlhCc1pTNWpiMjB3Q3dZRFZSMFBCQVFEQWdlQQpNQk1HQTFVZEpRUU1NQW9HQ0NzR0FRVUZCd01FTUEwR0NTcUdTSWIzRFFFQkN3VUFBNElCQVFCSXFHRjRoQmwyClRBTUIxeU9MK3gySiswQVNWYXJyemZ5eVZST2JZK0JaL0dwTG04RGozYkU5a243cVBldjc5dzVqWGlqdkUzOWEKaFpqRG9KWmxsd1ZxbEdNSjZBbWRDR0VkMHcxQStpZnB4SUo2SUs2cTk4SE9vTUVOR0tRZ0RrdTFoUURISVZrLwpsYWVRTEx4Wk12KzlZbHpRTEltR0kyOUl0R2ZFTks2YnZqSzlVaXJyWmNBaGVpSkhCN2ZBOVoyOFRmRkgrTXNPCkpuQlRhbkdrc3d4WUkyZzJKblZiZnNLU3pHVXppUzhQYTVMSTR3UUJqTnZ2OUtMV0tvMk9SbEdlUXltdlRVK2sKL0o5Sk83QngzakphZUpJS0t1K25SVEdjZVFNOE9qandxVzlFQXJYVmZhOTcySWg5bitYditXZitoekVocDZGYQpjT20rNXMweUlVQ0tNWUlDWGpDQ0Fsb0NBUUV3VERBME1SVXdFd1lEVlFRRERBeEJaR0VnVEc5MlpXeGhZMlV4Ckd6QVpCZ05WQkFvTUVrRnVZV3g1ZEdsallXd2dSVzVuYVc1bGN3SVVQZzQ5bXZzVWFDRm9JR1hXVnJFOXI1YUYKVm1Nd0RRWUpZSVpJQVdVREJBSUJCUUNnZ2VRd0dBWUpLb1pJaHZjTkFRa0RNUXNHQ1NxR1NJYjNEUUVIQVRBYwpCZ2txaGtpRzl3MEJDUVV4RHhjTk1qWXdPVEExTURneU56UTRXakF2QmdrcWhraUc5dzBCQ1FReElnUWdENnROCkV1RVc1VWxZdmFuODhqZGJSMEh3RkpuSnhoMFl0SFVHQTlOSXlmOHdlUVlKS29aSWh2Y05BUWtQTVd3d2FqQUwKQmdsZ2hrZ0JaUU1FQVNvd0N3WUpZSVpJQVdVREJBRVdNQXNHQ1dDR1NBRmxBd1FCQWpBS0JnZ3Foa2lHOXcwRApCekFPQmdncWhraUc5dzBEQWdJQ0FJQXdEUVlJS29aSWh2Y05Bd0lDQVVBd0J3WUZLdzREQWdjd0RRWUlLb1pJCmh2Y05Bd0lDQVNnd0RRWUpLb1pJaHZjTkFRRUJCUUFFZ2dFQWppV1VvSmtGbUN4ZGN3cFNRVFdqUmlseTY4NU0KNEpRNTgzMlZSbFdBM0toQ2tuMC9yc3ptR0NzQ1R0MERBQkVWWU1XMU42ck4wbjBpTEt5ZkNlVVNkL1BQVUFWLwp2UEI3b20veWhCWnBTS1NDWWtBajVMOHFzc3M4cEZRVUczUjVtOFBwcjFkN0Vvcm5ydkVxWnJLc2s3S3grMk81CmxGUExSRUpHWUtnSDVoOHI4NGRIek9Hek9sUjZKVVdqbVFUSEJVQ0dkZUhKdmJOaHp1TFoyQnFvU3VVYzJXcEYKWXNnVGJiSWZQSXdaZFRNZVBtUHIrYzBMYkloRE05S0JhL1J6OWVZRjlOUitEL2ZvRnZVQ2dML0tXcEtnZ2FtUQprVjVndUt2T3FzYUtmNC9kYjE4OEl1UkVibkdVd3NjeVR1TlV1OXUrc0toaVlnZDAydFZyS2RZUGhBPT0KCi0tLS0tLTEyRDAwRUJDMEI1RDMzNTJGMEUyRjI1QjFBNUQzNTUyLS0KCg==",
tampered: "VG86IHlvdUBleGFtcGxlLmNvbQpGcm9tOiBBZGEgTG92ZWxhY2UgPGFkYUBleGFtcGxlLmNvbT4KU3ViamVjdDogQSBub3RlCk1JTUUtVmVyc2lvbjogMS4wCkNvbnRlbnQtVHlwZTogbXVsdGlwYXJ0L3NpZ25lZDsgcHJvdG9jb2w9ImFwcGxpY2F0aW9uL3gtcGtjczctc2lnbmF0dXJlIjsgbWljYWxnPSJzaGEtMjU2IjsgYm91bmRhcnk9Ii0tLS0xMkQwMEVCQzBCNUQzMzUyRjBFMkYyNUIxQTVEMzU1MiIKClRoaXMgaXMgYW4gUy9NSU1FIHNpZ25lZCBtZXNzYWdlCgotLS0tLS0xMkQwMEVCQzBCNUQzMzUyRjBFMkYyNUIxQTVEMzU1MgpDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9dXRmLTgNCg0KVGhlIEFuYWx5dGljYWwgRW5naW5lIGhhcyBubyBwcmV0ZW5zaW9ucyB3aGF0c29ldmVyIHRvIG9yaWdpbmF0ZSBhbnl0aGluZy4NCgotLS0tLS0xMkQwMEVCQzBCNUQzMzUyRjBFMkYyNUIxQTVEMzU1MgpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL3gtcGtjczctc2lnbmF0dXJlOyBuYW1lPSJzbWltZS5wN3MiCkNvbnRlbnQtVHJhbnNmZXItRW5jb2Rpbmc6IGJhc2U2NApDb250ZW50LURpc3Bvc2l0aW9uOiBhdHRhY2htZW50OyBmaWxlbmFtZT0ic21pbWUucDdzIgoKTUlJR0p3WUpLb1pJaHZjTkFRY0NvSUlHR0RDQ0JoUUNBUUV4RHpBTkJnbGdoa2dCWlFNRUFnRUZBREFMQmdrcQpoa2lHOXcwQkJ3R2dnZ09OTUlJRGlUQ0NBbkdnQXdJQkFnSVVQZzQ5bXZzVWFDRm9JR1hXVnJFOXI1YUZWbU13CkRRWUpLb1pJaHZjTkFRRUxCUUF3TkRFVk1CTUdBMVVFQXd3TVFXUmhJRXh2ZG1Wc1lXTmxNUnN3R1FZRFZRUUsKREJKQmJtRnNlWFJwWTJGc0lFVnVaMmx1WlhNd0hoY05Nall3T1RBMU1EZ3lOelE0V2hjTk16WXdPVEF5TURneQpOelE0V2pBME1SVXdFd1lEVlFRRERBeEJaR0VnVEc5MlpXeGhZMlV4R3pBWkJnTlZCQW9NRWtGdVlXeDVkR2xqCllXd2dSVzVuYVc1bGN6Q0NBU0l3RFFZSktvWklodmNOQVFFQkJRQURnZ0VQQURDQ0FRb0NnZ0VCQUpTQkZickIKa1NMVHJIb3VmVzVXTllvSGZQUVlkK2tlZVNzWm5obDhOR2NUVWlvWExGUGdYK3Vlb2xlYk1CUnZTUStlRm5YVgpjWWdEdHU0eWU1cWZ5WUwzV3ZDV1FvaXdndTJuUDh6NmtGVGlRS2x1MlpSQ1lzbS8wK0RTRDI4d0hRRngrOU5zCmxMWUNkazIyZmxVaE1ua0NrV3ZkUmIwNDgrSjc2MkJjeHhuRENFemErRFBndE5zL2tJMlVxY2hpK1ZRWlpXUXUKTWZFNThnMlVNMlozc2U1NVFmUzJ2WXQ0ajdwUVhqdGNUc2pPeFRSVWZ6c3NsYWhHTGNOSVNHbDVrZGpMNXdyeAoxTHd3M1lFbDFudWNTMVFaRHQ3cGNTR05VUWxkTzdlMXJoMFF4UVpsblJ6RnlrT0VISlJqRG8wN1k5YmN2aG5hCnY1ZU9QeU9EMHB4V1MxY0NBd0VBQWFPQmtqQ0JqekFkQmdOVkhRNEVGZ1FVUU9qZGpscnBWRjRNcGx0M0hKY1AKSEVUb203UXdId1lEVlIwakJCZ3dGb0FVUU9qZGpscnBWRjRNcGx0M0hKY1BIRVRvbTdRd0R3WURWUjBUQVFILwpCQVV3QXdFQi96QWFCZ05WSFJFRUV6QVJnUTloWkdGQVpYaGhiWEJzWlM1amIyMHdDd1lEVlIwUEJBUURBZ2VBCk1CTUdBMVVkSlFRTU1Bb0dDQ3NHQVFVRkJ3TUVNQTBHQ1NxR1NJYjNEUUVCQ3dVQUE0SUJBUUJJcUdGNGhCbDIKVEFNQjF5T0wreDJKKzBBU1ZhcnJ6Znl5VlJPYlkrQlovR3BMbThEajNiRTlrbjdxUGV2Nzl3NWpYaWp2RTM5YQpoWmpEb0pabGx3VnFsR01KNkFtZENHRWQwdzFBK2lmcHhJSjZJSzZxOThIT29NRU5HS1FnRGt1MWhRREhJVmsvCmxhZVFMTHhaTXYrOVlselFMSW1HSTI5SXRHZkVOSzZidmpLOVVpcnJaY0FoZWlKSEI3ZkE5WjI4VGZGSCtNc08KSm5CVGFuR2tzd3hZSTJnMkpuVmJmc0tTekdVemlTOFBhNUxJNHdRQmpOdnY5S0xXS28yT1JsR2VReW12VFUrawovSjlKTzdCeDNqSmFlSklLS3UrblJUR2NlUU04T2pqd3FXOUVBclhWZmE5NzJJaDluK1h2K1dmK2h6RWhwNkZhCmNPbSs1czB5SVVDS01ZSUNYakNDQWxvQ0FRRXdUREEwTVJVd0V3WURWUVFEREF4QlpHRWdURzkyWld4aFkyVXgKR3pBWkJnTlZCQW9NRWtGdVlXeDVkR2xqWVd3Z1JXNW5hVzVsY3dJVVBnNDltdnNVYUNGb0lHWFdWckU5cjVhRgpWbU13RFFZSllJWklBV1VEQkFJQkJRQ2dnZVF3R0FZSktvWklodmNOQVFrRE1Rc0dDU3FHU0liM0RRRUhBVEFjCkJna3Foa2lHOXcwQkNRVXhEeGNOTWpZd09UQTFNRGd5TnpRNFdqQXZCZ2txaGtpRzl3MEJDUVF4SWdRZ0Q2dE4KRXVFVzVVbFl2YW44OGpkYlIwSHdGSm5KeGgwWXRIVUdBOU5JeWY4d2VRWUpLb1pJaHZjTkFRa1BNV3d3YWpBTApCZ2xnaGtnQlpRTUVBU293Q3dZSllJWklBV1VEQkFFV01Bc0dDV0NHU0FGbEF3UUJBakFLQmdncWhraUc5dzBECkJ6QU9CZ2dxaGtpRzl3MERBZ0lDQUlBd0RRWUlLb1pJaHZjTkF3SUNBVUF3QndZRkt3NERBZ2N3RFFZSUtvWkkKaHZjTkF3SUNBU2d3RFFZSktvWklodmNOQVFFQkJRQUVnZ0VBamlXVW9Ka0ZtQ3hkY3dwU1FUV2pSaWx5Njg1TQo0SlE1ODMyVlJsV0EzS2hDa24wL3Jzem1HQ3NDVHQwREFCRVZZTVcxTjZyTjBuMGlMS3lmQ2VVU2QvUFBVQVYvCnZQQjdvbS95aEJacFNLU0NZa0FqNUw4cXNzczhwRlFVRzNSNW04UHByMWQ3RW9ybnJ2RXFacktzazdLeCsyTzUKbEZQTFJFSkdZS2dINWg4cjg0ZEh6T0d6T2xSNkpVV2ptUVRIQlVDR2RlSEp2Yk5oenVMWjJCcW9TdVVjMldwRgpZc2dUYmJJZlBJd1pkVE1lUG1QcitjMExiSWhETTlLQmEvUno5ZVlGOU5SK0QvZm9GdlVDZ0wvS1dwS2dnYW1RCmtWNWd1S3ZPcXNhS2Y0L2RiMTg4SXVSRWJuR1V3c2N5VHVOVXU5dStzS2hpWWdkMDJ0VnJLZFlQaEE9PQoKLS0tLS0tMTJEMDBFQkMwQjVEMzM1MkYwRTJGMjVCMUE1RDM1NTItLQoK",
imposter: "VG86IHlvdUBleGFtcGxlLmNvbQpGcm9tOiBBZGEgTG92ZWxhY2UgPGFkYUBleGFtcGxlLmNvbT4KU3ViamVjdDogTm90IHJlYWxseSBBZGEKTUlNRS1WZXJzaW9uOiAxLjAKQ29udGVudC1UeXBlOiBtdWx0aXBhcnQvc2lnbmVkOyBwcm90b2NvbD0iYXBwbGljYXRpb24veC1wa2NzNy1zaWduYXR1cmUiOyBtaWNhbGc9InNoYS0yNTYiOyBib3VuZGFyeT0iLS0tLUEzNzZENzYzQzdGNDc1MDk3MUY3QzA0QjI3QTM4Q0E3IgoKVGhpcyBpcyBhbiBTL01JTUUgc2lnbmVkIG1lc3NhZ2UKCi0tLS0tLUEzNzZENzYzQzdGNDc1MDk3MUY3QzA0QjI3QTM4Q0E3CkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbjsgY2hhcnNldD11dGYtOA0KDQpUaGUgQW5hbHl0aWNhbCBFbmdpbmUgaGFzIG5vIHByZXRlbnNpb25zIHdoYXRldmVyIHRvIG9yaWdpbmF0ZSBhbnl0aGluZy4NCgotLS0tLS1BMzc2RDc2M0M3RjQ3NTA5NzFGN0MwNEIyN0EzOENBNwpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL3gtcGtjczctc2lnbmF0dXJlOyBuYW1lPSJzbWltZS5wN3MiCkNvbnRlbnQtVHJhbnNmZXItRW5jb2Rpbmc6IGJhc2U2NApDb250ZW50LURpc3Bvc2l0aW9uOiBhdHRhY2htZW50OyBmaWxlbmFtZT0ic21pbWUucDdzIgoKTUlJRnlnWUpLb1pJaHZjTkFRY0NvSUlGdXpDQ0JiY0NBUUV4RHpBTkJnbGdoa2dCWlFNRUFnRUZBREFMQmdrcQpoa2lHOXcwQkJ3R2dnZ05NTUlJRFNEQ0NBakNnQXdJQkFnSVVGZEtOZmhPdkJDaloxMUk3UGpYM1NtNlBTaFF3CkRRWUpLb1pJaHZjTkFRRUxCUUF3R0RFV01CUUdBMVVFQXd3TlUyOXRaV0p2WkhrZ1JXeHpaVEFlRncweU5qQTUKTURVd09ESTNORGhhRncwek5qQTVNREl3T0RJM05EaGFNQmd4RmpBVUJnTlZCQU1NRFZOdmJXVmliMlI1SUVWcwpjMlV3Z2dFaU1BMEdDU3FHU0liM0RRRUJBUVVBQTRJQkR3QXdnZ0VLQW9JQkFRQ2xkZ3RlR0lwSTdiemlpazJQCmxvc3JkWVdKS1pTZy9FSjQ0YW05QmFiemUrTkNKVHhNdkUvZnpZRFVuVWdVeUw3WEtVNmRhaGtPQlJyS0VqTEgKRW5SblRjcjhrNlpxc2tGSnd3V2FTQUhqdklUZ0hPUTd3R01Jd2NKbGROdy9ZKzRaUUhlSFVuY1RiYUc4YnlONwpkVnRsNE1HNFBvZFdaTVlYRlVLSDJiRW1QUW5yVG1LZm9oL2l4T2xWbk54dTQrUy9HOXFIK0VJOHNaeXJCeUlXClBZNkNoV1hEbzNDNTdpZkpDdHNxdlNEaUhZeEVOOWROL0RIZ2xLMzhielFPdzRRNzRYVG93aUw0NytwbVUwYkYKRFNnMjdxMmUvaC9ESEFIczE4Vy9YRGNEa3hwRU9IL0IwZS9HdEFLL1I1cUFnZm1uVnZJM2Y3d1JpZlc0bWovUAplRXFmQWdNQkFBR2pnWWt3Z1lZd0hRWURWUjBPQkJZRUZMWWYyd2dLVXBsTE8rYlNYNVZDc3B5d1NPSkpNQjhHCkExVWRJd1FZTUJhQUZMWWYyd2dLVXBsTE8rYlNYNVZDc3B5d1NPSkpNQThHQTFVZEV3RUIvd1FGTUFNQkFmOHcKSGdZRFZSMFJCQmN3RllFVGJXRnNiRzl5ZVVCbGVHRnRjR3hsTG01bGREQVRCZ05WSFNVRUREQUtCZ2dyQmdFRgpCUWNEQkRBTkJna3Foa2lHOXcwQkFRc0ZBQU9DQVFFQUxrUkxrdXNmdHFyUkZOa2hiWmZiT3d0NEtPdGZGa1FuClluNEp6T1lOZnVlU2lkcldLWTNGMnMzWGZCaWNoQmVQVjZ0MXRvT2owK2VhZ1lOK3hpSTlLZnR5eWtWVlliNS8KZFBabEhMUmdSRmF2eGxxTExnMjViQlVFenB3M0xwYU1NYTYyWmhjMUNwME44aUFUVms5dnBNeE4vREZOMnc2SApxZSswQ29RWVJNOGFXL0QzYW9zK0VZS2JOc0IxWlYwQVp6dC9NSlllSnZSaHA3b0gyUUE0c1hwODJmMEYwUkFWCnVTWkNYMzhXemJwZnZsRE9vYXNVVWxPZFBFdnhCQmFRSXB0S0cxcTJER2pxTFpVaUh5eW9udGRqelI2K1ZhaVYKeXBCOGdzNy9vRlNLTm9RRVc4d3pvRW51YlhoNzBBMzZQcXIxVkZGWnRMa05KRFVmYkJZelBqR0NBa0l3Z2dJKwpBZ0VCTURBd0dERVdNQlFHQTFVRUF3d05VMjl0WldKdlpIa2dSV3h6WlFJVUZkS05maE92QkNqWjExSTdQalgzClNtNlBTaFF3RFFZSllJWklBV1VEQkFJQkJRQ2dnZVF3R0FZSktvWklodmNOQVFrRE1Rc0dDU3FHU0liM0RRRUgKQVRBY0Jna3Foa2lHOXcwQkNRVXhEeGNOTWpZd09UQTFNRGd5TnpRNFdqQXZCZ2txaGtpRzl3MEJDUVF4SWdRZwpENnRORXVFVzVVbFl2YW44OGpkYlIwSHdGSm5KeGgwWXRIVUdBOU5JeWY4d2VRWUpLb1pJaHZjTkFRa1BNV3d3CmFqQUxCZ2xnaGtnQlpRTUVBU293Q3dZSllJWklBV1VEQkFFV01Bc0dDV0NHU0FGbEF3UUJBakFLQmdncWhraUcKOXcwREJ6QU9CZ2dxaGtpRzl3MERBZ0lDQUlBd0RRWUlLb1pJaHZjTkF3SUNBVUF3QndZRkt3NERBZ2N3RFFZSQpLb1pJaHZjTkF3SUNBU2d3RFFZSktvWklodmNOQVFFQkJRQUVnZ0VBSEtKbXQ0SmYrZ1kvTmtIS0xueTc3VC9KCkQxc3lBM2xGWjAwOGlUR3htQU5mQVV3VlFXeTdmSEd6UG1mMkZCdjN5ais3bGJTQUo0YjBKSVRDbFowMUVlalcKUUdkaE1ybVZBZ2QwTTU1ckNFZGNMcms3aFBzWlE3VU9kamMyTzIyY1MyWkJ3WkdrUzRyZThhMHF5NUQydEhBaAowZm5tdTB6RG9Wd1p1bzc4UGFuYzk2dGgzU2pTcExsSlU4andNeWl3bFJIWHpQMG5ITzhDUFdTRE1Lemk1KzhICkVIRHZjaml2ekdudFZPSHZhZmVva0UyTm1ySXZKcENFdk1FTVZ5Vm15c2dVRU5UUUpZT0loRWJYdTJrdEs3OWYKangrdzZpWVVaam5wRUhKNzlPTEFyWnNWNitlN3g5bnE2bGhBM3pTdDJDd3BPR3ZmUk0xN3ROMGMrT0FMcGc9PQoKLS0tLS0tQTM3NkQ3NjNDN0Y0NzUwOTcxRjdDMDRCMjdBMzhDQTctLQoK",
} as const;
/** The message as bytes, ready to be served as a blob. */
export function signedMessage(which: keyof typeof SIGNED_MESSAGES): Buffer {
return Buffer.from(SIGNED_MESSAGES[which], "base64");
}
-27
View File
@@ -1,27 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { interpretServerAccount, normalizePermission } from "./upstream.js";
/**
* `/api/account` is the only place Stalwart lists what an account may do, and
* ihasmail used to read the edition out of it and throw the rest away.
*/
test("the account's permissions are kept alongside the edition", () => {
const info = interpretServerAccount({ edition: "enterprise", permissions: ["sysAccountGet", "sysAccountQuery"], locale: "en_US" });
assert.deepEqual(info, { edition: "enterprise", permissions: ["sysAccountGet", "sysAccountQuery"] });
});
test("permission names read the same whichever case the server uses", () => {
// The source serialises camelCase; the documentation shows kebab-case.
assert.equal(normalizePermission("sys-account-get"), "sysAccountGet");
assert.equal(normalizePermission("sysAccountGet"), "sysAccountGet");
assert.equal(normalizePermission("sys-dkim-signature-create"), "sysDkimSignatureCreate");
assert.deepEqual(interpretServerAccount({ permissions: ["sys-account-get", "sysAccountGet"] }).permissions, ["sysAccountGet"]);
});
test("a body without a usable list yields no permissions rather than failing", () => {
assert.deepEqual(interpretServerAccount({ edition: "oss" }), { edition: "oss", permissions: [] });
assert.deepEqual(interpretServerAccount({ permissions: "sysAccountGet" }), { edition: null, permissions: [] });
assert.deepEqual(interpretServerAccount({ permissions: [1, null, "sysDomainGet"] }).permissions, ["sysDomainGet"]);
assert.deepEqual(interpretServerAccount(null), { edition: null, permissions: [] });
});
-135
View File
@@ -1,135 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { EventEmitter } from "node:events";
process.env.STALWART_URL = "http://127.0.0.1:1";
process.env.PUSH_URL = "https://ihasmail.example";
const push = await import("./push.js");
// Nothing in this file may reach the network. Background subscribe() calls
// outlive the test that started them, so the stub stays in place for the
// whole file rather than per test; the per-test stubs below layer on top.
const NO_NETWORK = globalThis.fetch;
globalThis.fetch = (async () => new Response("{}", { status: 599 })) as typeof fetch;
process.on("exit", () => { globalThis.fetch = NO_NETWORK; });
/** A stand-in for Node's ServerResponse: records writes, can be closed. */
function fakeOut() {
const e = new EventEmitter() as EventEmitter & { destroyed: boolean; written: string[]; write(s: string): boolean };
e.destroyed = false; e.written = [];
e.write = (s: string) => { e.written.push(s); return true; };
return e;
}
/** Answer any upstream call as Stalwart would for a successful PushSubscription/set. */
function stubUpstream(created = true) {
const real = globalThis.fetch;
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = String(input);
if (url.endsWith("/.well-known/jmap") || url.includes("/jmap/session")) {
return new Response(JSON.stringify({ apiUrl: "http://127.0.0.1:1/jmap/", primaryAccounts: { "urn:ietf:params:jmap:mail": "a" },
accounts: { a: {} }, capabilities: {}, eventSourceUrl: "", downloadUrl: "", uploadUrl: "", state: "s" }),
{ status: 200, headers: { "content-type": "application/json" } });
}
const body = { methodResponses: [["PushSubscription/set", created
? { created: { s: { id: "sub1", expires: new Date(Date.now() + 7 * 86_400_000).toISOString() } }, updated: { sub1: null } }
: { notCreated: { s: { type: "forbidden" } } }, "0"]] };
return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } });
}) as typeof fetch;
return () => { globalThis.fetch = real; };
}
test("an unknown token is a 404", async () => {
assert.equal(await push.receive("nope", { "@type": "StateChange" }), 404);
});
test("a tab opened before verification gets no fan-out, and a subscription is started", async () => {
const restore = stubUpstream();
try {
const out = fakeOut();
const entry = push.attach("[email protected]", "a", "Basic x", out as never);
assert.equal(entry, null, "not verified yet, so the tab must keep its own relay");
await new Promise((r) => setTimeout(r, 30));
const st = push.pushStatus();
assert.equal(st.accounts.pending + st.accounts.verified, 1);
} finally { restore(); }
});
test("verification then fan-out: one POST reaches every open tab for the account", async () => {
const restore = stubUpstream();
try {
// First contact starts the subscription; wait for the stubbed create to land.
const first = fakeOut();
push.attach("[email protected]", "a", "Basic y", first as never);
await new Promise((r) => setTimeout(r, 30));
// Find the token Stalwart would have been given, the way Stalwart learns it: from the subscribe call.
// We cannot read it back through the public API, so verify via the status transition instead:
// deliver a PushVerification to every pending entry by brute force over the known token space is not
// possible, so exercise receive() through the module's own map by re-attaching after verification.
const status = push.pushStatus();
assert.ok(status.accounts.pending >= 1 || status.accounts.verified >= 1);
} finally { restore(); }
});
test("a StateChange is written to attached tabs as an SSE frame, and closed tabs are dropped", async () => {
// Drive the fan-out directly through an entry made verified by the verification path.
const restore = stubUpstream();
try {
const out1 = fakeOut(), out2 = fakeOut();
push.attach("[email protected]", "a", "Basic z", out1 as never);
await new Promise((r) => setTimeout(r, 30));
// Verify by handing the module its own token: pushStatus does not expose it, so read it from the
// subscribe request the stub saw. Simplest faithful route: capture the URL Stalwart would POST to.
let token: string | null = null;
const real = globalThis.fetch;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const b = typeof init?.body === "string" ? init.body : "";
const m = /\/api\/push\/([A-Za-z0-9_-]{20,})/.exec(b);
if (m) token = m[1];
return real(input, init);
}) as typeof fetch;
// Force a renewal-style subscribe so the URL passes through the capturing fetch.
push.attach("[email protected]", "a", "Basic w", out1 as never);
await new Promise((r) => setTimeout(r, 30));
globalThis.fetch = real;
assert.ok(token, "the subscribe call carries the push URL with the token");
assert.equal(await push.receive(token!, { "@type": "PushVerification", verificationCode: "v" }), 200);
const entry = push.attach("[email protected]", "a", "Basic w", out1 as never);
assert.ok(entry, "verified: the tab is served by fan-out");
push.attach("[email protected]", "a", "Basic w", out2 as never);
assert.equal(await push.receive(token!, { "@type": "StateChange", changed: { a: { Email: "s1" } } }), 200);
assert.match(out1.written.at(-1) ?? "", /^event: state\ndata: \{"@type":"StateChange"/);
assert.equal(out2.written.length, 1);
out2.destroyed = true; out2.emit("close");
await push.receive(token!, { "@type": "StateChange", changed: { a: { Email: "s2" } } });
assert.equal(out1.written.length, 2); assert.equal(out2.written.length, 1, "a closed tab receives nothing more");
} finally { restore(); }
});
test("a malformed body is a 400, not a crash", async () => {
assert.equal(await push.receive("nope", "not an object"), 404);
});
test("a tab on the relay is moved to fan-out when its account verifies, and its upstream is dropped", async () => {
const restore = stubUpstream();
try {
let token: string | null = null;
const real = globalThis.fetch;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const m = /\/api\/push\/([A-Za-z0-9_-]{20,})/.exec(typeof init?.body === "string" ? init.body : "");
if (m) token = m[1];
return real(input, init);
}) as typeof fetch;
push.prepare("[email protected]", "a", "Basic m"); // sign-in starts the subscription
await new Promise((r) => setTimeout(r, 30));
globalThis.fetch = real;
assert.ok(token);
const out = fakeOut(); let dropped = 0;
assert.equal(push.attach("[email protected]", "a", "Basic m", out as never), null, "not yet verified: relay");
push.attachRelay("[email protected]", out as never, () => { dropped++; });
assert.equal(push.pushStatus().tabs.relay >= 1, true);
assert.equal(await push.receive(token!, { "@type": "PushVerification", verificationCode: "v" }), 200);
assert.equal(dropped, 1, "the relay's upstream request was ended on verification");
await push.receive(token!, { "@type": "StateChange", changed: { a: { Email: "s9" } } });
assert.match(out.written.at(-1) ?? "", /StateChange/, "the same browser stream now receives fan-out");
} finally { restore(); }
});
-204
View File
@@ -1,204 +0,0 @@
/**
* Push by subscription: hold no upstream connection per tab.
*
* Today every signed-in tab holds a Server-Sent Events stream to ihasmail,
* and ihasmail holds a matching stream to Stalwart behind it. The upstream
* one is most of what a tab costs -- measured, 81 KiB of TLS state plus the
* request objects -- and it is also the only reason Stalwart's connection
* limit applies to ihasmail at all.
*
* RFC 8620 §7.2 defines the other transport: a PushSubscription, where the
* server POSTs StateChange objects to a URL the client registers. Stalwart
* implements it. So ihasmail registers one subscription per *account*, and
* when Stalwart POSTs a change, fans it out to that account's open tabs over
* the browser-facing streams it already holds. Nothing is held upstream.
*
* Nothing here is taken from any other client's implementation; the shapes
* are the RFC's.
*
* The subscription URL must be https and Stalwart must trust its
* certificate -- the RFC requires the scheme and Stalwart enforces it. Where
* that is not the case the subscription never verifies, and the account
* stays on the per-tab relay it uses today. Both paths coexist; the
* transition loses no events, because a tab opened before verification keeps
* its own relay for its whole life.
*/
import { randomBytes } from "node:crypto";
import type { ServerResponse } from "node:http";
import { config } from "./config.js";
import { absoluteUpstream, getUpstreamSession, upstreamFor } from "./upstream.js";
const USING = ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"];
const RENEW_BEFORE_MS = 60 * 60_000; // renew an hour before Stalwart expires it
const VERIFY_TIMEOUT_MS = 3 * 60_000; // Stalwart's first attempt waits 60 s; allow retries
const SWEEP_MS = 30_000;
interface AccountPush {
key: string; // upstream base + username
username: string;
accountId: string;
base: string;
token: string; // what Stalwart puts in the URL
authorization: string; // one live session's credential, for set/verify/renew
subscriptionId: string | null;
state: "pending" | "verified" | "failed";
since: number;
expires: number;
tabs: Set<ServerResponse>;
/** Tabs still on the per-tab relay, with the hook that ends their upstream request. */
relays: Map<ServerResponse, () => void>;
}
const byKey = new Map<string, AccountPush>();
const byToken = new Map<string, AccountPush>();
let sweeper: NodeJS.Timeout | null = null;
export function pushEnabled(): boolean {
return config.pushMode === "subscribe" && !!config.pushUrl;
}
function keyFor(base: string, username: string) { return `${base} ${username}`; }
async function jmap(entry: AccountPush, calls: unknown[]) {
const upstream = await getUpstreamSession(entry.key, entry.authorization, entry.base);
const res = await fetch(absoluteUpstream(upstream.apiUrl, upstream.baseUrl), {
method: "POST",
headers: { authorization: entry.authorization, "content-type": "application/json", accept: "application/json" },
body: JSON.stringify({ using: USING, methodCalls: calls }),
signal: AbortSignal.timeout(config.upstreamTimeout),
});
if (!res.ok) throw new Error(`upstream ${res.status}`);
return (await res.json()) as { methodResponses: [string, Record<string, unknown>, string][] };
}
async function subscribe(entry: AccountPush) {
const url = `${config.pushUrl!.replace(/\/$/, "")}${config.basePath}/api/push/${entry.token}`;
const r = await jmap(entry, [["PushSubscription/set", {
create: { s: { deviceClientId: `ihasmail-${entry.token.slice(0, 8)}`, url,
types: ["Email", "Mailbox", "Thread", "Identity", "EmailSubmission", "VacationResponse"] } },
}, "0"]]);
const created = (r.methodResponses[0]?.[1] as { created?: Record<string, { id: string; expires?: string }> }).created?.s;
if (!created) throw new Error("subscription not created");
entry.subscriptionId = created.id;
entry.expires = created.expires ? Date.parse(created.expires) : Date.now() + 7 * 86_400_000;
}
async function verify(entry: AccountPush, code: string) {
await jmap(entry, [["PushSubscription/set", { update: { [entry.subscriptionId!]: { verificationCode: code } } }, "0"]]);
entry.state = "verified";
// Every tab of this account that has been holding its own upstream stream
// can now let go of it: the subscription is live, so Stalwart will POST the
// same changes here. The browser-facing stream is untouched. Done in this
// order there is no gap -- at worst a change lands twice, which is harmless.
let moved = 0;
for (const [out, dropUpstream] of entry.relays) {
entry.relays.delete(out);
if (out.destroyed) continue;
dropUpstream(); entry.tabs.add(out); moved++;
}
console.log(`[ihasmail] push: subscription verified for ${entry.username}` + (moved ? `, ${moved} tab(s) moved off the relay` : ""));
}
async function unsubscribe(entry: AccountPush) {
if (entry.subscriptionId) {
try { await jmap(entry, [["PushSubscription/set", { destroy: [entry.subscriptionId] }, "0"]]); } catch { /* best effort */ }
}
byKey.delete(entry.key); byToken.delete(entry.token);
}
/**
* Start (or refresh) the account's subscription. Called at sign-in, so that
* by the time the browser opens its stream the verification is usually
* already in flight, and called again by attach() as a safety net.
*/
export function prepare(username: string, accountId: string, authorization: string): AccountPush | null {
if (!pushEnabled()) return null;
const base = upstreamFor(username);
const key = keyFor(base, username);
let entry = byKey.get(key);
if (!entry) {
entry = { key, username, accountId, base, token: randomBytes(32).toString("base64url"),
authorization, subscriptionId: null, state: "pending", since: Date.now(), expires: 0, tabs: new Set(), relays: new Map() };
byKey.set(key, entry); byToken.set(entry.token, entry);
subscribe(entry).catch((err) => {
entry!.state = "failed";
console.warn(`[ihasmail] push: subscribe failed for ${username}: ${(err as Error).message}; relay in use`);
});
startSweeper();
} else {
entry.authorization = authorization; // keep a live credential for renewals
}
return entry;
}
/**
* Called when a tab opens. Returns the account's push entry if the tab can
* be served by fan-out right now, or null if it must hold its own relay.
*/
export function attach(username: string, accountId: string, authorization: string, out: ServerResponse): AccountPush | null {
const entry = prepare(username, accountId, authorization);
if (!entry || entry.state !== "verified") return null;
entry.tabs.add(out);
out.on("close", () => { entry.tabs.delete(out); });
return entry;
}
/**
* A tab that had to start on the relay registers here with the hook that
* ends its upstream request, so verify() can move it to fan-out later.
*/
export function attachRelay(username: string, out: ServerResponse, dropUpstream: () => void): void {
if (!pushEnabled()) return;
const entry = byKey.get(keyFor(upstreamFor(username), username));
if (!entry) return;
entry.relays.set(out, dropUpstream);
out.on("close", () => { entry.relays.delete(out); });
}
/** Stalwart's POST. Returns an HTTP status. */
export async function receive(token: string, body: unknown): Promise<number> {
const entry = byToken.get(token);
if (!entry) return 404;
const msg = body as { "@type"?: string; verificationCode?: string; changed?: unknown };
if (msg["@type"] === "PushVerification" && typeof msg.verificationCode === "string") {
try { await verify(entry, msg.verificationCode); return 200; }
catch (err) { console.warn(`[ihasmail] push: verify failed: ${(err as Error).message}`); return 500; }
}
if (msg["@type"] === "StateChange") {
const frame = `event: state\ndata: ${JSON.stringify(msg)}\n\n`;
for (const out of entry.tabs) { if (!out.destroyed) out.write(frame); }
return 200;
}
return 400;
}
/** One shared timer for every tab: keep-alives, renewals, and cleanup. */
function startSweeper() {
if (sweeper) return;
sweeper = setInterval(() => {
const now = Date.now();
for (const entry of [...byKey.values()]) {
for (const out of entry.tabs) { if (out.destroyed) entry.tabs.delete(out); else out.write(": ping\n\n"); }
if (entry.state === "pending" && now - entry.since > VERIFY_TIMEOUT_MS) {
entry.state = "failed";
console.warn(`[ihasmail] push: no verification for ${entry.username} within ${VERIFY_TIMEOUT_MS / 1000}s; relay in use`);
}
if (entry.state === "verified" && entry.expires - now < RENEW_BEFORE_MS) {
entry.state = "pending"; entry.since = now;
subscribe(entry).catch(() => { entry.state = "failed"; });
}
if (entry.tabs.size === 0 && (entry.state === "failed" || now - entry.since > 10 * 60_000)) {
void unsubscribe(entry);
}
}
if (byKey.size === 0 && sweeper) { clearInterval(sweeper); sweeper = null; }
}, SWEEP_MS);
sweeper.unref();
}
/** For /api/health: how many accounts are on each path. */
export function pushStatus() {
let verified = 0, pending = 0, failed = 0, tabs = 0, relays = 0;
for (const e of byKey.values()) { tabs += e.tabs.size; relays += e.relays.size; if (e.state === "verified") verified++; else if (e.state === "pending") pending++; else failed++; }
return { mode: pushEnabled() ? "subscribe" : "relay", accounts: { verified, pending, failed }, tabs: { fanout: tabs, relay: relays } };
}
-67
View File
@@ -1,67 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { RateLimiter } from "./ratelimit.js";
/**
* The limiter's job is to slow down password guessing. #239 is about the
* attempts it takes for outcomes that were never a guess: ihasmail runs apart
* from Stalwart, so an upstream that refuses a connection is ordinary, and
* retrying through one used to spend the window and lock somebody out until
* after the cause had gone.
*/
test("check allows up to the limit and then refuses", () => {
const rl = new RateLimiter(3, 60_000);
assert.equal(rl.check("k"), true);
assert.equal(rl.check("k"), true);
assert.equal(rl.check("k"), true);
assert.equal(rl.check("k"), false);
});
test("refund gives back exactly one attempt", () => {
const rl = new RateLimiter(2, 60_000);
rl.check("k");
rl.check("k");
assert.equal(rl.check("k"), false, "spent");
rl.refund("k");
assert.equal(rl.check("k"), true, "one back");
assert.equal(rl.check("k"), false, "and only one");
});
test("refunding every attempt leaves the key spending nothing", () => {
// The outage case: every try refunded, so a person retrying through it is
// not locked out when the server returns.
const rl = new RateLimiter(2, 60_000);
for (let i = 0; i < 20; i++) {
assert.equal(rl.check("k"), true, `attempt ${i} allowed`);
rl.refund("k");
}
});
test("a run of real failures still adds up around a refunded one", () => {
// Refund takes one attempt back, not the key's whole history -- an outage in
// the middle of somebody guessing must not clear what they spent before it.
const rl = new RateLimiter(3, 60_000);
rl.check("k"); // a wrong password
rl.check("k"); // another
rl.check("k"); rl.refund("k"); // an outage, given back
assert.equal(rl.check("k"), true, "third real attempt");
assert.equal(rl.check("k"), false, "and now spent");
});
test("refunding a key that never spent anything is harmless", () => {
const rl = new RateLimiter(1, 60_000);
rl.refund("never-seen");
assert.equal(rl.check("never-seen"), true);
});
test("reset clears the key, refund does not", () => {
const rl = new RateLimiter(2, 60_000);
rl.check("k");
rl.check("k");
rl.refund("k");
assert.equal(rl.check("k"), true);
assert.equal(rl.check("k"), false);
rl.reset("k");
assert.equal(rl.check("k"), true, "reset is the successful-sign-in case");
});
-22
View File
@@ -23,28 +23,6 @@ export class RateLimiter {
return true;
}
/**
* Give back the attempt `check` just took.
*
* For an outcome that says nothing about whether the credentials were right.
* ihasmail runs in its own container, usually on its own host, so an upstream
* that never answered is an ordinary Tuesday rather than an attack -- and the
* limiter exists to slow down password guessing, which a server that refused
* the connection has not told us anything about. Without this, retrying
* through a thirty-second outage spends the window and locks somebody out
* until well after the cause has gone (#239).
*
* Refunds one attempt rather than clearing the key, so a run of real failures
* with an outage in the middle still adds up.
*/
refund(key: string): void {
const arr = this.hits.get(key);
if (!arr?.length) return;
arr.pop();
if (arr.length) this.hits.set(key, arr);
else this.hits.delete(key);
}
reset(key: string): void {
this.hits.delete(key);
}
+34
View File
@@ -63,3 +63,37 @@ test("normalizes Stalwart account locales to BCP-47 tags", () => {
assert.equal(normalizeLocale({ locale: "de_DE" }), null);
assert.equal(normalizeLocale("../etc/passwd"), null);
});
test("generated app passwords are unbiased and long enough", async () => {
const { readableSecret } = await import("./account.js");
const alphabet = "abcdefghijkmnopqrstuvwxyz23456789";
const counts = new Map<string, number>();
let samples = 0;
for (let i = 0; i < 2000; i++) {
const secret = readableSecret();
assert.match(secret, /^[a-z2-9]{5}-[a-z2-9]{5}-[a-z2-9]{5}-[a-z2-9]{5}$/, secret);
for (const ch of secret.replace(/-/g, "")) {
counts.set(ch, (counts.get(ch) ?? 0) + 1);
samples++;
}
}
assert.equal(samples, 2000 * 20);
/*
* `% 33` over a byte maps 25 characters onto 8 values each and the last 8
* onto 7, so the digits — the tail of the alphabet — would come up about
* 7/8 as often as they should. Testing each character on its own cannot see
* a skew that size against the noise, so weigh the whole tail at once:
* uniform puts 8/33 of the draw there, the biased version 7/8 of that, and
* over 40,000 draws the two are more than four standard deviations apart.
*/
const tail = alphabet.slice(25); // "23456789"
const tailSeen = [...tail].reduce((n, ch) => n + (counts.get(ch) ?? 0), 0);
const p = tail.length / alphabet.length;
const expected = samples * p;
const sigma = Math.sqrt(samples * p * (1 - p));
assert.ok(
Math.abs(tailSeen - expected) < 4 * sigma,
`digits appeared ${tailSeen} times, expected ~${Math.round(expected)} (sigma ${sigma.toFixed(1)}) - modulo bias?`,
);
});
+9 -58
View File
@@ -34,64 +34,9 @@ export interface LiveSession {
ip: string;
}
/** What `/api/auth/sessions` reports about a session, with nothing secret in it. */
export interface SessionSummary {
id: string;
username: string;
createdAt: number;
lastSeenAt: number;
expiresAt: number;
remember: boolean;
userAgent: string;
ip: string;
}
export interface CreateSessionParams {
username: string;
password: string;
remember: boolean;
userAgent: string;
ip: string;
}
/**
* Everything the rest of the server asks of a session store.
*
* There is one implementation today -- `SessionStore` below, which keeps the
* records in memory and optionally mirrors them to `SESSION_FILE`. The reason
* it is named as an interface anyway is that a second one is planned: a
* stateless backend that carries the whole record in the cookie, so that a
* replica can serve a session it never issued and `/data` can go away. Callers
* written against the concrete class would all have to be revisited then.
*
* Five of these are already stateless in shape -- `create`, `resolve`,
* `reseal` and `destroy` each touch exactly one session, and the sealing key is
* derived from the cookie secret (see `crypto.ts`), so the record can move into
* the cookie without the server keeping a map.
*
* The other two cannot be. `listForUser` and `destroyAllForUser` have to reach
* sessions other than the one presenting itself, which means something has to
* be enumerable somewhere. `destroyAllForUser` is not only the "sign out my
* other sessions" button: `app.ts` also calls it when the password or the app
* password changes, so it carries the guarantee that changing a credential
* invalidates the sessions still holding the old one. A stateless backend
* cannot honour that alone; the plan is for OAuth to hand the job to
* Stalwart's own token registry, which can already answer both questions.
*/
export interface SessionBackend {
init(): Promise<void>;
close(): Promise<void>;
create(params: CreateSessionParams): { cookie: string; session: LiveSession };
resolve(cookie: string | undefined): LiveSession | null;
reseal(cookie: string | undefined, password: string): boolean;
destroy(id: string): void;
destroyAllForUser(username: string, exceptId?: string): number;
listForUser(username: string): SessionSummary[];
}
const COOKIE_SEP = ".";
export class SessionStore implements SessionBackend {
export class SessionStore {
private sessions = new Map<string, StoredSession>();
private dirty = false;
private saveTimer: NodeJS.Timeout | null = null;
@@ -159,7 +104,13 @@ export class SessionStore implements SessionBackend {
}
/** Create a session; returns the cookie value to hand to the client. */
create(params: CreateSessionParams): { cookie: string; session: LiveSession } {
create(params: {
username: string;
password: string;
remember: boolean;
userAgent: string;
ip: string;
}): { cookie: string; session: LiveSession } {
const id = randomToken(18);
const secret = randomToken(32);
const salt = randomBytes(16);
@@ -260,7 +211,7 @@ export class SessionStore implements SessionBackend {
return n;
}
listForUser(username: string): SessionSummary[] {
listForUser(username: string): Array<Omit<StoredSession, "secretHash" | "salt" | "sealedCredentials">> {
const out = [];
for (const s of this.sessions.values()) {
if (s.username !== username) continue;
-82
View File
@@ -1,82 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
/**
* The shipped example policy, checked against the rules the server enforces.
*
* An example that has drifted out of step with the parser is worse than no
* example: somebody copies it, the server refuses to start, and the first
* experience of the feature is a crash loop. This does not import the config
* module -- reading it has side effects and wants a whole environment -- so the
* rules it checks are restated here, and both are short enough that saying them
* twice is cheaper than the machinery to say them once.
*/
const EXAMPLE = fileURLToPath(new URL("../../settings-policy.example.json", import.meta.url));
test("the example policy is valid JSON", () => {
assert.doesNotThrow(() => JSON.parse(readFileSync(EXAMPLE, "utf8")));
});
test("the example policy has the three sections, in the shapes the server reads", () => {
const p = JSON.parse(readFileSync(EXAMPLE, "utf8")) as Record<string, unknown>;
for (const section of ["defaults", "enforced"]) {
const v = p[section];
assert.ok(v && typeof v === "object" && !Array.isArray(v), `${section} must be an object`);
}
assert.ok(Array.isArray(p.changes), "changes must be a list");
});
test("every change in the example has a unique version and settings", () => {
const p = JSON.parse(readFileSync(EXAMPLE, "utf8")) as { changes: Array<{ version?: unknown; settings?: unknown }> };
const seen = new Set<string>();
for (const [i, c] of p.changes.entries()) {
assert.equal(typeof c.version, "string", `changes[${i}] needs a string version`);
assert.ok((c.version as string).trim(), `changes[${i}] needs a non-empty version`);
assert.ok(!seen.has(c.version as string), `changes[${i}] repeats version ${String(c.version)}`);
seen.add(c.version as string);
assert.ok(c.settings && typeof c.settings === "object" && !Array.isArray(c.settings), `changes[${i}] needs a settings object`);
}
});
test("the example's commentary cannot be mistaken for a section", () => {
/*
* JSON has no comments, so the example explains itself in `_`-prefixed keys.
* The server reads three names and ignores everything else, which is what
* makes that safe -- but only for as long as no comment key collides with a
* real one.
*/
const p = JSON.parse(readFileSync(EXAMPLE, "utf8")) as Record<string, unknown>;
const real = new Set(["defaults", "enforced", "changes"]);
for (const key of Object.keys(p)) {
assert.ok(real.has(key) || key.startsWith("_"), `unexpected top-level key ${key}`);
}
});
/**
* The shipped server-mapping example, checked the same way and for the same
* reason: an example that no longer loads is worse than no example, because
* the first experience of the feature is a server that refuses to start.
*/
const SERVERS = fileURLToPath(new URL("../../stalwart-servers.example.json", import.meta.url));
test("the example server mapping is valid JSON", () => {
assert.doesNotThrow(() => JSON.parse(readFileSync(SERVERS, "utf8")));
});
test("every entry in the example mapping is a domain and an http(s) URL", () => {
const m = JSON.parse(readFileSync(SERVERS, "utf8")) as Record<string, unknown>;
const seen = new Set<string>();
for (const [key, value] of Object.entries(m)) {
if (key.startsWith("_")) continue;
const domain = key.trim().toLowerCase().replace(/\.$/, "");
assert.ok(domain, "a domain key is empty");
assert.ok(!seen.has(domain), `${domain} appears twice once normalised`);
seen.add(domain);
assert.equal(typeof value, "string", `${domain} is not a string`);
const url = new URL(value as string);
assert.ok(url.protocol === "http:" || url.protocol === "https:", `${domain} must be http or https`);
}
assert.ok(seen.size > 0, "the example should show at least one mapping");
});
+3 -65
View File
@@ -3,36 +3,6 @@ import { stat, readFile } from "node:fs/promises";
import { extname, join, normalize, resolve, sep } from "node:path";
import { Readable } from "node:stream";
import type { Context, Handler } from "hono";
import { stripBasePath } from "../../scripts/basePath.mjs";
/*
* Files that must not be served from anybody's cache, the way index.html is
* not.
*
* They went out with `max-age=3600` because they are neither hashed assets nor
* HTML, and an hour looks harmless. It is not, for two of them, and a CDN in
* front makes it worse: on a deploy the origin had the new build while
* Cloudflare went on handing out the previous `sw.js` for hours, with
* `cf-cache-status: HIT` and an edge TTL of its own that was longer than what
* we asked for. Caught on the 2026-09-08 deploy, where the new worker was live
* at the origin and the old one was still being installed by every browser
* that asked.
*
* What that costs is specific rather than general. The service worker is the
* app's whole update mechanism: a stale one keeps serving the shell it knows
* and never learns there is a newer build, so the deploy simply does not
* arrive. And a manifest and a worker that disagree is worse than either being
* old -- a fresh manifest advertising a share target to the operating system,
* answered by a worker that has never heard of one, sends the share to the
* server for a 405.
*
* `no-cache` does not mean "do not store": the browser and the CDN may both
* keep it and revalidate, which is a 304 and costs nothing. It means neither
* gets to serve it without asking first, which is the whole requirement.
*/
function isNeverStale(rel: string, ext: string): boolean {
return ext === ".webmanifest" || rel === "/sw.js" || rel === "sw.js";
}
const MIME: Record<string, string> = {
".html": "text/html; charset=utf-8",
@@ -77,30 +47,9 @@ export const APP_CSP = [
"manifest-src 'self'",
].join("; ");
export function staticHandler(root: string, basePath = ""): Handler {
export function staticHandler(root: string): Handler {
const absRoot = resolve(root);
let indexCache: { body: string; mtime: number } | null = null;
let mismatchWarned = false;
/**
* A build that does not know the prefix loads nothing under it, and says so
* with a blank page and a 404 in a console nobody has open. The shell is
* already being read here, so checking what it asks for costs one substring
* search per rebuild and turns a mystery into a line in the log.
*
* A warning rather than a refusal: this reads a built artefact to guess at a
* misconfiguration, and a wrong guess that stops the server from starting is
* worse than the problem it is describing.
*/
function warnOnBaseMismatch(body: string) {
if (mismatchWarned || !basePath) return;
if (body.includes(`src="${basePath}/assets/`)) return;
mismatchWarned = true;
console.warn(
`[ihasmail] BASE_PATH is ${basePath}, but the web build in ${absRoot} references its assets elsewhere. ` +
`The prefix is baked in at build time: rebuild with BASE_PATH=${basePath} set, or the app will not load.`,
);
}
async function serveIndex(c: Context) {
try {
@@ -108,9 +57,7 @@ export function staticHandler(root: string, basePath = ""): Handler {
const st = await stat(p);
if (!indexCache || indexCache.mtime !== st.mtimeMs) {
indexCache = { body: await readFile(p, "utf8"), mtime: st.mtimeMs };
mismatchWarned = false;
}
warnOnBaseMismatch(indexCache.body);
c.header("Content-Type", "text/html; charset=utf-8");
c.header("Cache-Control", "no-cache");
c.header("Content-Security-Policy", APP_CSP);
@@ -123,16 +70,7 @@ export function staticHandler(root: string, basePath = ""): Handler {
return async (c) => {
if (c.req.method !== "GET" && c.req.method !== "HEAD") return c.text("Method Not Allowed", 405);
/*
* Everything below works in paths relative to the mount, so the prefix
* comes off once, here. Anything outside it is a 404 and not the app
* shell: under `/mail` this process shares a hostname with whatever else
* the proxy serves, and answering `/` or `/other-app/thing` with our
* index would shadow a neighbour rather than let it 404 honestly.
*/
const fullPath = decodeURIComponent(new URL(c.req.url).pathname);
const urlPath = stripBasePath(basePath, fullPath);
if (urlPath === null) return c.text("Not Found", 404);
const urlPath = decodeURIComponent(new URL(c.req.url).pathname);
if (urlPath === "/" || urlPath === "/index.html") return serveIndex(c);
const rel = normalize(urlPath).replace(/^(\.\.[/\\])+/, "");
const filePath = join(absRoot, rel);
@@ -145,7 +83,7 @@ export function staticHandler(root: string, basePath = ""): Handler {
c.header("Content-Length", String(st.size));
if (rel.startsWith("/assets/") || rel.startsWith("assets/")) {
c.header("Cache-Control", "public, max-age=31536000, immutable");
} else if (ext === ".html" || isNeverStale(rel, ext)) {
} else if (ext === ".html") {
c.header("Cache-Control", "no-cache");
c.header("Content-Security-Policy", APP_CSP);
} else {
-81
View File
@@ -1,81 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
/*
* What may be served stale, and what may not.
*
* This is not a preference about freshness. The service worker is the app's
* whole update mechanism: a browser holding an old one goes on being served
* the shell that worker knows and never finds out a deploy happened. On
* 2026-09-08 the origin had the new build while Cloudflare handed out the
* previous `sw.js` for hours, because it was neither a hashed asset nor HTML
* and so went out with an hour's max-age that the CDN then extended.
*
* A static root of our own, since CI runs the tests before the build and
* `web/dist` does not exist yet.
*/
const root = mkdtempSync(join(tmpdir(), "ihasmail-cache-"));
mkdirSync(join(root, "assets"));
writeFileSync(join(root, "assets", "app-a1b2c3.js"), "console.log(1)\n");
writeFileSync(join(root, "sw.js"), "/* worker */\n");
writeFileSync(join(root, "manifest.webmanifest"), `{"name":"ihasmail"}`);
writeFileSync(join(root, "index.html"), "<!doctype html><title>t</title>");
writeFileSync(join(root, "img.png"), "not really a png");
process.env.STATIC_DIR = root;
process.env.STALWART_URL = "http://127.0.0.1:1";
const { createApp } = await import("./app.js");
const cacheControl = async (path: string) => {
const res = await createApp().request(path);
assert.equal(res.status, 200, `${path} should be served`);
return res.headers.get("cache-control") ?? "";
};
test("the service worker is never served from a cache without asking", async () => {
// `no-cache` permits storing it and requires revalidating it, which is a 304
// and costs nothing. What it forbids is a browser or a CDN answering with
// its own copy, which is the whole failure.
assert.match(await cacheControl("/sw.js"), /no-cache/);
});
test("nor is the manifest, which the worker has to agree with", async () => {
// A fresh manifest advertising a share target, answered by a worker that has
// never heard of one, sends the share to the server for a 405. Either being
// old is survivable; the two disagreeing is not.
assert.match(await cacheControl("/manifest.webmanifest"), /no-cache/);
});
test("the manifest is still served as a manifest", async () => {
const res = await createApp().request("/manifest.webmanifest");
assert.match(res.headers.get("content-type") ?? "", /application\/manifest\+json/);
});
test("index.html was already revalidated, and still is", async () => {
assert.match(await cacheControl("/"), /no-cache/);
});
test("hashed assets are still immutable for a year", async () => {
// The name changes when the bytes do, so there is nothing to go stale --
// and this is the caching that makes the app load quickly at all.
const cc = await cacheControl("/assets/app-a1b2c3.js");
assert.match(cc, /immutable/);
assert.match(cc, /max-age=31536000/);
});
test("everything else keeps its ordinary hour", async () => {
// The rule is narrow on purpose: two files, named, rather than a policy that
// quietly stops the icons and fonts being cached too.
assert.match(await cacheControl("/img.png"), /max-age=3600/);
});
test("under a prefix, the worker is still the worker", async () => {
// The mount comes off before the path is matched, so this has to hold for a
// subpath deployment as well -- where a stale worker is exactly as bad.
const res = await createApp("/mail").request("/mail/sw.js");
assert.equal(res.status, 200);
assert.match(res.headers.get("cache-control") ?? "", /no-cache/);
});
+59 -126
View File
@@ -10,15 +10,6 @@ export interface UpstreamSession {
uploadUrl: string;
eventSourceUrl: string;
state: string;
/**
* Which Stalwart this document came from.
*
* Recorded rather than looked up again, because the relative URLs inside it
* -- apiUrl, uploadUrl and the rest -- only mean anything against the server
* that issued them. Anything holding a session already knows where to send
* the next request. Not part of the JMAP session resource; ours.
*/
baseUrl: string;
}
export class UpstreamError extends Error {
@@ -33,37 +24,16 @@ export class UpstreamError extends Error {
const sessionCache = new Map<string, { session: UpstreamSession; fetchedAt: number }>();
const SESSION_CACHE_MS = 5 * 60_000;
/**
* The Stalwart a username belongs to.
*
* `STALWART_URL` is the default and is always the answer for a domain nobody
* mapped -- and for a bare username, which Stalwart accepts and which has no
* domain to map (#238).
*
* A *mapped* domain never falls back. If its server is unreachable that
* sign-in fails, because falling back would authenticate somebody against a
* server their domain was deliberately routed away from -- and if the same
* account name exists there, they would land in another tenant's mailbox. The
* fallback is a decision about unmapped domains, taken before any network
* call, not a recovery path.
*/
export function upstreamFor(username: string): string {
const at = username.lastIndexOf("@");
if (at < 0) return config.stalwartUrl;
const domain = username.slice(at + 1).trim().toLowerCase().replace(/\.$/, "");
return config.stalwartServers[domain] ?? config.stalwartUrl;
}
export function wellKnownUrl(base: string = config.stalwartUrl): string {
return `${base}/.well-known/jmap`;
export function wellKnownUrl(): string {
return `${config.stalwartUrl}/.well-known/jmap`;
}
/**
* Fetch the JMAP session resource from Stalwart using the given Authorization
* header. Throws UpstreamError(401) on bad credentials.
*/
export async function fetchUpstreamSession(authorization: string, base: string = config.stalwartUrl): Promise<UpstreamSession> {
const res = await fetch(wellKnownUrl(base), {
export async function fetchUpstreamSession(authorization: string): Promise<UpstreamSession> {
const res = await fetch(wellKnownUrl(), {
headers: { authorization, accept: "application/json" },
redirect: "follow",
signal: AbortSignal.timeout(config.upstreamTimeout),
@@ -76,13 +46,13 @@ export async function fetchUpstreamSession(authorization: string, base: string =
}
const session = (await res.json()) as UpstreamSession;
if (!session.apiUrl) throw new UpstreamError("Upstream returned an invalid JMAP session", 502);
return { ...session, baseUrl: base };
return session;
}
export async function getUpstreamSession(sessionId: string, authorization: string, base: string = config.stalwartUrl, force = false) {
export async function getUpstreamSession(sessionId: string, authorization: string, force = false) {
const cached = sessionCache.get(sessionId);
if (!force && cached && Date.now() - cached.fetchedAt < SESSION_CACHE_MS) return cached.session;
const session = await fetchUpstreamSession(authorization, base);
const session = await fetchUpstreamSession(authorization);
sessionCache.set(sessionId, { session, fetchedAt: Date.now() });
return session;
}
@@ -108,14 +78,10 @@ const JMAP_CORE = "urn:ietf:params:jmap:core";
* builds that list from a fixed set that has never included this capability;
* it hands it out per-account instead, so it turns up in `primaryAccounts` and
* in each account's `accountCapabilities`. Checking only the session level
* therefore reported every real 0.16 server as older than 0.16 which routed
* therefore reports every real 0.16 server as pre-0.16 which routed
* self-service credentials to a REST endpoint 0.16 had removed, and told the
* About page the wrong thing. The session level is still checked last, in case
* a later release advertises it there as well.
*
* This is now what sign-in tests to decide whether a server is supported at
* all, so the same mistake would lock every user out of a working server
* rather than merely misroute them.
*/
export function hasStalwartRegistry(session: Pick<UpstreamSession, "capabilities" | "accounts" | "primaryAccounts"> | undefined): boolean {
if (!session) return false;
@@ -130,23 +96,22 @@ export function hasStalwartRegistry(session: Pick<UpstreamSession, "capabilities
export interface AccountInfo {
/** BCP-47 tag configured for the account, or null if unreadable. */
locale: string | null;
/**
* Which generation of Stalwart's API answered: "0.16+" has the registry
* (`x:AccountSettings`), older builds only have `x:Account`. Null when the
* server is not Stalwart or told us nothing.
*/
generation: "0.16+" | "pre-0.16" | null;
/** "oss" | "community" | "enterprise", where the server reports it. */
edition: string | null;
/**
* The account's effective permissions, as Stalwart reports them for the
* credential in use. Empty when the server would not say.
*
* Carried to the browser so it can offer only what the account may do --
* administration above all. It is never a grant: Stalwart checks every call
* it is sent, and a list that is stale or wrong costs a refused request, not
* access.
*/
permissions: string[];
}
const infoCache = new Map<string, { info: AccountInfo; fetchedAt: number }>();
const INFO_CACHE_MS = 30 * 60_000;
const EMPTY_INFO: AccountInfo = { locale: null, edition: null, permissions: [] };
const EMPTY_INFO: AccountInfo = { locale: null, generation: null, edition: null };
/** A server that has never heard of the registry: nothing to read, but dated. */
const PRE_REGISTRY_INFO: AccountInfo = { locale: null, generation: "pre-0.16", edition: null };
const REGISTRY_INFO: AccountInfo = { locale: null, generation: "0.16+", edition: null };
/**
* glibc modifiers that name a script rather than a dialect or a currency:
@@ -200,17 +165,19 @@ export function normalizeLocale(raw: unknown): string | null {
* tells us which generation we are talking to.
*/
async function fetchAccountInfo(authorization: string, session: UpstreamSession): Promise<AccountInfo> {
// Sign-in refuses a server without the registry, so this should not happen —
// but a session we cannot read capabilities from is not one to ask.
if (!session.capabilities || !hasStalwartRegistry(session)) return EMPTY_INFO;
// Every 0.16 build advertises urn:stalwart:jmap, and no earlier one knows it
// at all, so its absence already answers the question — and asking anyway
// would fail the whole request, since those servers reject a `using` naming
// a capability they cannot parse.
// A session with no capabilities at all is not one we can read anything from.
if (!session.capabilities) return EMPTY_INFO;
if (!hasStalwartRegistry(session)) return PRE_REGISTRY_INFO;
const accountId =
session.primaryAccounts?.[STALWART_CAP] ??
session.primaryAccounts?.["urn:ietf:params:jmap:mail"] ??
Object.keys(session.accounts ?? {})[0];
if (!accountId) return EMPTY_INFO;
// Against the server that issued this session, not the default: with a
// domain mapped elsewhere, the default has never heard of the account.
const res = await fetch(absoluteUpstream(session.apiUrl, session.baseUrl), {
const res = await fetch(absoluteUpstream(session.apiUrl), {
method: "POST",
headers: { authorization, "content-type": "application/json", accept: "application/json" },
body: JSON.stringify({
@@ -222,23 +189,35 @@ async function fetchAccountInfo(authorization: string, session: UpstreamSession)
}),
signal: AbortSignal.timeout(config.upstreamTimeout),
});
// A locale request that fails — a permission we lack, a hiccup upstream —
// costs us the locale and nothing else.
if (!res.ok) return EMPTY_INFO;
// The registry capability already settled the generation. A locale request
// that fails — a permission we lack, a hiccup upstream — can only cost us the
// locale; it must not talk us out of what we know.
if (!res.ok) return REGISTRY_INFO;
const body = (await res.json()) as { methodResponses?: [string, Record<string, unknown>, string][] };
return interpretAccountInfo(body.methodResponses ?? []);
return interpretAccountInfo(body.methodResponses ?? [], "0.16+");
}
/**
* Read the pair of replies: prefer the locale from `x:AccountSettings`, whose
* permission the built-in user role has, and fall back to `x:Account` for the
* accounts allowed the admin-only `sysAccountGet` instead. Both are 0.16
* methods; this is a permissions fallback, not a version one.
* Read the pair of replies: prefer the locale from `x:AccountSettings`, fall
* back to `x:Account` for servers (or permissions) where only that one works,
* and note which generation answered.
*/
export function interpretAccountInfo(responses: [string, Record<string, unknown>, string][]): AccountInfo {
export function interpretAccountInfo(
responses: [string, Record<string, unknown>, string][],
known: AccountInfo["generation"] = null,
): AccountInfo {
const settings = responses.find((r) => r[2] === "s");
const account = responses.find((r) => r[2] === "a");
return { locale: localeOf(settings) ?? localeOf(account), edition: null, permissions: [] };
// Only 0.16+ knows the method at all; older builds cannot even parse the name.
// `known` is what the session capability already proved, and outranks a reply
// that merely refused us.
const generation: AccountInfo["generation"] =
settings && settings[0] !== "error"
? "0.16+"
: (settings?.[1] as { type?: string } | undefined)?.type === "unknownMethod"
? "pre-0.16"
: known;
return { locale: localeOf(settings) ?? localeOf(account), generation, edition: null };
}
function localeOf(call: [string, Record<string, unknown>, string] | undefined): string | null {
@@ -249,51 +228,30 @@ function localeOf(call: [string, Record<string, unknown>, string] | undefined):
}
/**
* Permission names in the form the source serialises them.
*
* Stalwart 0.16 builds `/api/account`'s list from the same enum as everything
* else, which serialises as camelCase (`sysAccountGet`). Its documentation and
* OpenAPI example show kebab-case (`sys-account-get`) instead. Until a live
* server settles which is true, both are read as the one form, so a check
* written against `sysAccountGet` holds either way.
* Which edition the server is running. Stalwart deliberately does not publish
* its version number to clients, but 0.16 does report its edition here.
*/
export function normalizePermission(name: string): string {
return name.includes("-") ? name.replace(/-([a-z0-9])/g, (_m, c: string) => c.toUpperCase()) : name;
}
/**
* What the server says about the signed-in account: its edition and its
* effective permissions. Stalwart deliberately does not publish its version
* number to clients, but 0.16 reports both of these here.
*/
async function fetchServerAccount(authorization: string, base: string): Promise<Pick<AccountInfo, "edition" | "permissions">> {
async function fetchEdition(authorization: string): Promise<string | null> {
try {
const res = await fetch(`${base}/api/account`, {
const res = await fetch(`${config.stalwartUrl}/api/account`, {
headers: { authorization, accept: "application/json" },
signal: AbortSignal.timeout(config.upstreamTimeout),
});
if (!res.ok) return { edition: null, permissions: [] };
return interpretServerAccount(await res.json());
if (!res.ok) return null;
const body = (await res.json()) as { edition?: unknown };
return typeof body.edition === "string" ? body.edition : null;
} catch {
return { edition: null, permissions: [] };
return null;
}
}
export function interpretServerAccount(body: unknown): Pick<AccountInfo, "edition" | "permissions"> {
const b = (body ?? {}) as { edition?: unknown; permissions?: unknown };
const permissions = Array.isArray(b.permissions)
? [...new Set(b.permissions.filter((p): p is string => typeof p === "string").map(normalizePermission))]
: [];
return { edition: typeof b.edition === "string" ? b.edition : null, permissions };
}
export async function getAccountInfo(sessionId: string, authorization: string, session: UpstreamSession): Promise<AccountInfo> {
const cached = infoCache.get(sessionId);
if (cached && Date.now() - cached.fetchedAt < INFO_CACHE_MS) return cached.info;
let info = EMPTY_INFO;
try {
info = await fetchAccountInfo(authorization, session);
info = { ...info, ...(await fetchServerAccount(authorization, session.baseUrl)) };
if (info.generation === "0.16+") info = { ...info, edition: await fetchEdition(authorization) };
} catch {
/* all of this is a nicety - never fail the session over it */
}
@@ -321,34 +279,9 @@ export function localizeSession(s: UpstreamSession, extras: Record<string, unkno
}
/** Resolve a possibly-relative upstream URL template against STALWART_URL. */
/**
* Resolve a URL Stalwart handed us against the server we were configured to
* talk to.
*
* Stalwart advertises absolute URLs in its session -- apiUrl, eventSourceUrl
* and the rest -- built from its public hostname, which is always https. A
* proxy that follows them takes every upstream call, and every held push
* stream, out through the public route even when STALWART_URL names a private
* plain-HTTP hop on the same network. Measured, that TLS leg is ~80 KiB of
* native OpenSSL state per signed-in tab: 60% of what a tab costs, and the
* whole difference between 1,665 and 3,680 tabs in 256 MiB.
*
* So by default only the path and query are taken from the advertised URL;
* scheme, host and port come from the configured base. That is what a proxy
* should have done all along -- the operator named the route on purpose.
* STALWART_FOLLOW_ADVERTISED_URLS=1 restores the old behaviour for a setup
* that genuinely needs to reach Stalwart at a different origin than the one
* it was given.
*/
export function absoluteUpstream(url: string, base: string = config.stalwartUrl): string {
export function absoluteUpstream(url: string): string {
try {
const resolved = new URL(url, base);
if (config.followAdvertisedUrls) return resolved.toString();
const pinned = new URL(base);
pinned.pathname = resolved.pathname;
pinned.search = resolved.search;
pinned.hash = "";
return pinned.toString();
return new URL(url, config.stalwartUrl).toString();
} catch {
return url;
}
-63
View File
@@ -1,63 +0,0 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { formatVersion, resolveVersion, UNVERSIONED, versionFromGit } from "../../scripts/version.mjs";
/**
* The version is this build's public identity: it names the image, and it is
* what About and /api/health report. It had no tests while it was
* `2.16.<pr>`; it has them now that the rules moved.
*/
test("a pull request merge is named by its number", () => {
assert.equal(
formatVersion({ date: "2026-08-30", subject: "Merge pull request #129 from Coffey-Labs/link-project-site-v2", sha: "1fa6578" }),
"2026.8.30+pr129",
);
});
test("a commit that did not come through a pull request carries its SHA", () => {
// Claiming the last PR would say it *is* that PR rather than something after it.
assert.equal(formatVersion({ date: "2026-08-30", subject: "Fix a thing directly on main", sha: "1fa6578" }), "2026.8.30+g1fa6578");
});
test("leading zeros are stripped, since a version field may not carry them", () => {
assert.equal(formatVersion({ date: "2026-09-05", subject: "Merge pull request #7 from x/y", sha: "abc1234" }), "2026.9.5+pr7");
assert.equal(formatVersion({ date: "2027-01-01", subject: "", sha: "abc1234" }), "2027.1.1+gabc1234");
});
test("it sorts forward from the versions it replaces", () => {
// 2.16.129 was deployed. 2.1.x would have read as a downgrade, which is the
// whole reason the Stalwart generation left the version.
const [older, newer] = ["2.16.129", "2026.8.30"].map((v) => v.split(".").map(Number));
assert.ok(newer![0]! > older![0]!, "the leading field has to increase");
});
test("two builds from the same day differ, even though they rank the same", () => {
const a = formatVersion({ date: "2026-08-30", subject: "Merge pull request #128 from x/y", sha: "aaaaaaa" });
const b = formatVersion({ date: "2026-08-30", subject: "Merge pull request #129 from x/y", sha: "bbbbbbb" });
assert.notEqual(a, b);
assert.equal(a.split("+")[0], b.split("+")[0]);
});
test("the same commit always resolves to the same version", () => {
// Built from the commit's own date, not today's, so an old commit rebuilt
// now reports what it reported then.
const commit = { date: "2026-08-30", subject: "Merge pull request #129 from x/y", sha: "1fa6578" };
assert.equal(formatVersion(commit), formatVersion(commit));
});
test("an explicit IHASMAIL_VERSION wins, because the Docker build has no git", () => {
const before = process.env.IHASMAIL_VERSION;
process.env.IHASMAIL_VERSION = "2026.8.30+pr129";
try {
assert.equal(resolveVersion(), "2026.8.30+pr129");
} finally {
if (before === undefined) delete process.env.IHASMAIL_VERSION;
else process.env.IHASMAIL_VERSION = before;
}
});
test("a checkout with git resolves to a real version, and an unversioned build looks wrong", () => {
assert.match(versionFromGit() ?? "", /^\d{4}\.\d{1,2}\.\d{1,2}\+(pr\d+|g[0-9a-f]+)$/);
assert.equal(UNVERSIONED, "0.0.0");
});
-56
View File
@@ -1,56 +0,0 @@
{
"_comment": [
"A settings policy: what this installation decides, rather than each reader.",
"Point at it with SETTINGS_POLICY_FILE=/etc/ihasmail/policy.json and mount it",
"read-only. Read once at startup, so editing it means restarting.",
"Delete the sections you do not want -- all three are optional, and an",
"installation that sets none of them behaves exactly as ihasmail always has.",
"Keys and values are the ones a settings export uses: configure one account",
"by hand, Settings > General > Export, and copy out what you care about.",
"Docs: https://docs.ihasmail.org/configure/#settings-your-installation-decides"
],
"_defaults_comment": [
"A starting point for accounts that have never had settings of their own.",
"The reader can change any of these afterwards. An account that already",
"exists never sees them -- use `changes` below to reach those."
],
"defaults": {
"externalSenderBanner": true,
"conversationMode": true
},
"_enforced_comment": [
"Reapplied on every load, and the reader cannot change them at all. Their",
"controls stay visible in Settings and go dead with a line saying why.",
"Reset, an imported settings file, and a settings file synced from a device",
"that predates this policy all cannot get around them."
],
"enforced": {
"externalRecipientConfirm": true
},
"_changes_comment": [
"Applied once each, to everybody, including accounts that already exist --",
"and the reader may change them back afterwards, which sticks.",
"",
"Each entry needs a `version` that is unique in this file. It is opaque: a",
"timestamp sorts and never repeats, but any unique string works. Every",
"account remembers the versions it has had, so a change runs exactly once",
"per person -- not once per browser.",
"",
"Note that a change DOES override a decision a reader has already made. That",
"is the point of it: it reaches people who are already here. If you want it",
"to stay on regardless of what they do next, that is `enforced`, not this."
],
"changes": [
{
"version": "20260902084513",
"settings": { "externalSenderBanner": true }
},
{
"version": "20261014091500",
"settings": { "externalLinkWarning": true }
}
]
}
-25
View File
@@ -1,25 +0,0 @@
{
"_comment": [
"Optional: which Stalwart a domain signs in to.",
"",
"STALWART_URL stays required and stays the default. This file only adds",
"domains that go somewhere else -- delete it and nothing changes.",
"",
"Point at it with STALWART_SERVERS_FILE=/etc/ihasmail/servers.json and mount",
"it read-only. Read once at startup, so editing it means restarting.",
"",
"A domain that is not listed here, and a bare username with no domain at",
"all, go to STALWART_URL. A domain that IS listed never falls back: if its",
"server is unreachable that sign-in fails, because falling back would",
"authenticate somebody against a server their domain was routed away from.",
"",
"Keys are lower-cased and stripped of a trailing dot when read. Malformed",
"JSON, a duplicate domain, or a value that is not an http(s) URL stops the",
"server at startup rather than failing quietly at somebody's sign-in.",
"",
"Docs: https://docs.ihasmail.org/configure/#several-stalwart-servers"
],
"example.com": "https://mail.example.com",
"customer-b.test": "https://jmap.customer-b.test"
}
+2 -11
View File
@@ -4,17 +4,8 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="color-scheme" content="light dark" />
<!--
One tag, no media query: applyTheme() keeps it in step with the chosen
theme, which a media query cannot do — it only knows what the OS prefers,
not what the user picked here. There used to be two, both with media
attributes, which meant the selector in applyTheme (:not([media])) matched
neither and the colour never moved off whatever the OS implied.
The initial value is the default theme's background, so the browser chrome
is right from the first paint rather than only once JS has run.
-->
<meta name="theme-color" content="#0d2430" />
<meta name="theme-color" content="#0f766e" media="(prefers-color-scheme: light)" />
<meta name="theme-color" content="#0b1220" media="(prefers-color-scheme: dark)" />
<meta name="description" content="ihasmail - fast, friendly JMAP webmail for Stalwart" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
+8 -9
View File
@@ -1,6 +1,6 @@
{
"name": "@ihasmail/web",
"version": "0.0.0",
"version": "2.0.0",
"private": true,
"license": "AGPL-3.0-or-later",
"type": "module",
@@ -13,22 +13,21 @@
},
"dependencies": {
"@tanstack/react-virtual": "^3.13.2",
"dompurify": "^3.4.15",
"dompurify": "^3.2.4",
"lucide-react": "^0.477.0",
"marked": "^18.0.11",
"qrcode-generator": "^2.0.4",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"wouter": "^3.11.0",
"wouter": "^3.6.0",
"zustand": "^5.0.3"
},
"devDependencies": {
"@types/react": "^19.0.10",
"@types/react-dom": "^19.2.7",
"@vitejs/plugin-react": "^6.1.1",
"@types/react-dom": "^19.0.4",
"@vitejs/plugin-react": "^4.3.4",
"jsdom": "^26.0.0",
"typescript": "^7.0.2",
"vite": "^8.3.0",
"vitest": "^4.1.11"
"typescript": "^5.7.3",
"vite": "^6.2.0",
"vitest": "^3.0.8"
}
}
+9 -44
View File
@@ -2,47 +2,12 @@
"name": "ihasmail",
"short_name": "ihasmail",
"description": "Fast, friendly JMAP webmail for Stalwart",
"_comment": "JSON has no comments, so: every URL below is relative on purpose. Manifest members resolve against the manifest's own address, so these follow BASE_PATH with nothing substituted into them at build time. Root-absolute values pinned the installed app, its scope and its shortcuts to the domain root whatever the mount was.",
"_comment_id": "There is deliberately no `id`. It is the one member NOT resolved against this file's address -- the spec resolves it against the origin of start_url, so `./`, `mail` and `/mail` all mean the same thing at the domain root and none of them can name a subpath mount. Adding one would therefore break the same thing the note above describes. Worse, the default id IS start_url, which is already mount-correct: writing an id now would give every installed copy a new identity and orphan it as a second app rather than updating it. If one is ever wanted it has to be substituted at build time from BASE_PATH, and the changeover costs everybody their install.",
"start_url": "mail",
"scope": "./",
"categories": ["productivity", "utilities"],
"_comment_launch": "One window, not one per launch. A `mailto:` link, a manifest shortcut or a notification tapped while ihasmail is already open should arrive in the copy that is running rather than beside it -- two windows on the same inbox disagree about what has been read. `navigate-existing` rather than `focus-existing` because the latter only focuses and leaves the app to handle the target URL through launchQueue, which nothing here consumes: it would swallow the mailto entirely. The navigation goes through the same beforeunload guard as a reload, so an unsent draft still stops it and asks.",
"launch_handler": {
"client_mode": "navigate-existing"
},
"_comment_share_target": "Being in the operating system's share sheet, which is the other half of the Share this app now offers. `action` is relative like everything else here, so it follows the mount; it has to sit inside `scope`, and `./` covers it. POST with multipart because a share can carry files, and a POST to a page is not something the app can answer -- the service worker intercepts it, puts the payload where a tab can collect it, and redirects. `accept` names wildcard families AND explicit types and extensions on purpose: a mail client attaches anything, but wildcard support is not in the specification and operating systems differ over which form they match on, so the explicit list is what holds if the families are ignored. Android and Chromium only -- iOS does not implement share targets at all.",
"share_target": {
"action": "share",
"method": "POST",
"enctype": "multipart/form-data",
"params": {
"title": "title",
"text": "text",
"url": "url",
"files": [
{
"name": "files",
"accept": [
"image/*", "video/*", "audio/*", "text/*",
"application/pdf", "application/zip", "application/json",
"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/vnd.oasis.opendocument.text", "application/vnd.oasis.opendocument.spreadsheet",
"message/rfc822", "text/calendar", "text/vcard",
".pdf", ".zip", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",
".odt", ".ods", ".csv", ".txt", ".md", ".eml", ".ics", ".vcf",
".jpg", ".jpeg", ".png", ".gif", ".webp", ".heic", ".mp4", ".mp3"
]
}
]
}
},
"start_url": "/mail",
"scope": "/",
"protocol_handlers": [
{
"protocol": "mailto",
"url": "mail?mailto=%s"
"url": "/mail?mailto=%s"
}
],
"display": "standalone",
@@ -51,17 +16,17 @@
"theme_color": "#0f766e",
"icons": [
{
"src": "img/icon-192.png",
"src": "/img/icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "img/icon-512.png",
"src": "/img/icon-512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "img/icon-maskable.png",
"src": "/img/icon-maskable.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
@@ -70,16 +35,16 @@
"shortcuts": [
{
"name": "Compose",
"url": "mail?compose=new",
"url": "/mail?compose=new",
"description": "Write a new message"
},
{
"name": "Calendar",
"url": "calendar"
"url": "/calendar"
},
{
"name": "Contacts",
"url": "contacts"
"url": "/contacts"
}
]
}
+6 -344
View File
@@ -1,24 +1,7 @@
/* ihasmail service worker.
Two jobs: app-shell caching for installability and fast loads (API requests
are never cached), and Web Push, which is the only part of ihasmail that runs
when no tab is open. */
/* ihasmail service worker: app-shell caching for installability & fast loads.
API requests are never cached. */
const VERSION = "ihasmail-v2";
/*
* The mount, worked out rather than configured.
*
* This file is copied to the build verbatim -- Vite's `base` never touches
* public/ -- so there is nothing to substitute BASE_PATH into. It does not
* need one: the worker is served from the mount, so its own address says
* where that is. `/mail/sw.js` gives `/mail`, `/sw.js` gives `""`, which is
* the same canonical form the rest of the app uses.
*
* Deriving it here also means the worker cannot disagree with the page that
* registered it, which a second copy of the value in a build-time constant
* eventually would.
*/
const BASE = new URL("./", self.location).pathname.replace(/\/$/, "");
const SHELL = [`${BASE}/`, `${BASE}/manifest.webmanifest`, `${BASE}/img/logo.png`, `${BASE}/img/icon-192.png`, `${BASE}/favicon.ico`];
const SHELL = ["/", "/manifest.webmanifest", "/img/logo.png", "/img/icon-192.png", "/favicon.ico"];
self.addEventListener("install", (event) => {
event.waitUntil(caches.open(VERSION).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting()));
@@ -30,81 +13,15 @@ self.addEventListener("activate", (event) => {
);
});
/*
* Where a share from the operating system is left for a tab to collect.
*
* Absolute and anchored to the mount, for the same reason the verification key
* below is: a relative key is resolved against the URL of whoever asks, and the
* worker and a tab deep in `/mail/inbox/…` are not at the same place.
*
* The files go in one entry each and the rest in a JSON index beside them,
* because the Cache API stores Responses and a File is already one body.
*/
const SHARE_KEY = `${BASE}/ihasmail-share`;
const SHARE_MAX_FILES = 20;
/*
* Take delivery of a share.
*
* This is a POST that navigates: the operating system submits a form at the
* app and expects a page back. Nothing in ihasmail can answer it directly --
* the app is a client-side router with no endpoint at that address, and the
* server behind it would have to grow one that understood the composer. So the
* worker takes the body, puts it where a tab can find it, and redirects to the
* app, which then opens a draft holding it.
*
* The redirect happens whatever went wrong. A share that fails to stash costs
* whatever was being shared, which is bad; a share that fails to *respond*
* costs that and leaves the reader looking at a browser error page where they
* expected their mail, which is worse.
*
* There is one case this cannot cover, and the server is deliberately not
* taught to: an app still installed whose worker has been cleared away. The
* POST then reaches the server, which answers 405, and the share is lost
* either way -- the payload only ever existed in that request body. A server
* route would trade a plain error for a silent nothing, and a share that
* vanishes without saying so is the harder of the two to notice.
*/
async function stashShare(request) {
try {
const form = await request.formData();
const cache = await caches.open(VERSION);
const meta = {
at: Date.now(),
title: String(form.get("title") ?? ""),
text: String(form.get("text") ?? ""),
url: String(form.get("url") ?? ""),
files: [],
};
const files = form.getAll("files").filter((f) => f && typeof f === "object" && "name" in f && f.size > 0);
for (const [i, f] of files.slice(0, SHARE_MAX_FILES).entries()) {
const key = `${SHARE_KEY}/${i}`;
await cache.put(key, new Response(f, { headers: { "content-type": f.type || "application/octet-stream" } }));
meta.files.push({ key, name: f.name || `file-${i + 1}`, type: f.type || "application/octet-stream" });
}
await cache.put(SHARE_KEY, new Response(JSON.stringify(meta), { headers: { "content-type": "application/json" } }));
} catch {
/* nothing to hand on: the app opens on an empty inbox rather than an error */
}
// Absolute, because `Response.redirect` rejects a bare path outright rather
// than resolving it -- so `${BASE}/mail` would throw here and the share
// would end at a browser error page instead of the inbox.
return Response.redirect(new URL(`${BASE}/mail?share=1`, self.location.origin).href, 303);
}
self.addEventListener("fetch", (event) => {
const req = event.request;
if (req.method === "POST" && new URL(req.url).pathname === `${BASE}/share`) {
event.respondWith(stashShare(req));
return;
}
if (req.method !== "GET") return;
const url = new URL(req.url);
if (url.origin !== self.location.origin) return;
if (url.pathname.startsWith(`${BASE}/api/`)) return;
if (url.pathname.startsWith("/api/")) return;
// Hashed build assets: cache-first.
if (url.pathname.startsWith(`${BASE}/assets/`)) {
if (url.pathname.startsWith("/assets/")) {
event.respondWith(
caches.match(req).then((hit) => hit || fetch(req).then((res) => {
const copy = res.clone();
@@ -117,263 +34,8 @@ self.addEventListener("fetch", (event) => {
// Navigations & everything else: network-first, fall back to cached shell.
if (req.mode === "navigate") {
event.respondWith(fetch(req).catch(() => caches.match(`${BASE}/`)));
event.respondWith(fetch(req).catch(() => caches.match("/")));
return;
}
event.respondWith(fetch(req).catch(() => caches.match(req)));
});
/* ------------------------------------------------------------------ */
/* Web Push */
/* ------------------------------------------------------------------ */
/*
* Stalwart signs with VAPID and pushes straight to the browser's push service;
* nothing here talks to ihasmail's server on the way in. The payload is an
* EmailPush object (draft-ietf-jmap-emailpush) carrying enough of the message
* to show a useful notification without a round-trip, which is what lets a
* notification appear immediately rather than after a request.
*
* This file used to say that a round-trip was impossible here, and it was
* wrong: see the note on `jmap()`. What it can do is ask; what it cannot do is
* be sure of an answer, since the session may be gone by the time it does. So
* the payload still carries the message and the request is only made when
* somebody presses something.
*
* A JMAP subscription also delivers a PushVerification first, and stays silent
* until the client echoes its code back. It is stashed for a tab to confirm
* rather than answered here on the same reasoning, and because a
* verification that failed silently would leave push looking broken with
* nothing to show for it. Answering it directly is now possible and is worth
* revisiting.
*/
/*
* Absolute, and anchored to the mount rather than to whatever page happens to
* be open.
*
* A relative key is resolved against the URL of whoever is asking: the worker
* lives at `<base>/sw.js`, so it stored this under `<base>/…`, while a tab at
* `/mail/inbox/abc` looked for it under `/mail/inbox/…`. The two only ever
* agreed when the open page was the root, so a verification code that arrived
* with no tab open was written where the next tab would not look -- and the
* subscription stayed silent, which is the same thing push failing looks like.
*/
const VERIFY_KEY = `${BASE}/ihasmail-push-verification`;
/*
* What a tab wrote down for this worker: the account, which mailbox is the
* archive, and the worker's own text in the reader's language. See
* `lib/swFacts.ts` for why any of that has to be handed over rather than
* worked out here.
*
* Everything that depends on it is skipped when it is missing, which is the
* state between installing this worker and next opening the app. An action
* button with no label, or one that files mail into a mailbox guessed by name,
* is worse than the notification that was here before.
*/
const FACTS_KEY = `${BASE}/ihasmail-worker-facts`;
async function readFacts() {
try {
const hit = await (await caches.open(VERSION)).match(FACTS_KEY);
return hit ? await hit.json() : null;
} catch {
return null;
}
}
/*
* A JMAP call, made as the reader.
*
* This worker was written believing it could not do this -- that acting on
* mail needed a session it had no way to hold. It does not: ihasmail's session
* is an httpOnly cookie against its own origin, and the only other thing the
* API asks for is a fixed `x-requested-with` header that is not a secret and
* is not held anywhere. A same-origin fetch from here carries the cookie like
* any other, so `Email/set` from a notification is an ordinary request.
*
* What is genuinely not available is anything the *tab* holds in memory, and
* the answer is that the API asks for none of it.
*
* The session can still be gone -- expired, signed out, or a cookie that did
* not survive the browser closing -- which arrives as a 401 and is reported
* rather than swallowed. A tap that silently does nothing is the failure worth
* avoiding here: the reader has already put the phone down.
*/
async function jmap(methodCalls) {
const res = await fetch(`${BASE}/api/jmap`, {
method: "POST",
credentials: "same-origin",
headers: { "content-type": "application/json", accept: "application/json", "x-requested-with": "ihasmail" },
body: JSON.stringify({ using: ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"], methodCalls }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const body = await res.json();
// A JMAP method can fail inside a 200. Treat that as a failure too, rather
// than reporting success because the transport was fine.
const first = body?.methodResponses?.[0];
if (!first || first[0] === "error") throw new Error(first?.[1]?.type || "error");
const notUpdated = first[1]?.notUpdated;
if (notUpdated && Object.keys(notUpdated).length) throw new Error("notUpdated");
return body;
}
function textOf(email, strings) {
const from = email?.from?.[0];
const who = from?.name || from?.email || strings.newMessage;
const what = email?.subject || strings.noSubject;
return { title: who, body: what, preview: email?.preview || "" };
}
/*
* Two, because that is what a phone shows. `Notification.maxActions` is 2 on
* Android Chrome, and anything past it is dropped silently -- so these are the
* two worth having rather than the two that happened to come first. Both are
* triage: they are what somebody does to a notification they have read the
* whole of on the lock screen and does not need to open.
*
* Reply is deliberately not among them. It cannot be done from here, so it
* would have to open the app -- and an action that opens the app is what
* tapping the notification already does.
*/
function actionsFor(facts) {
if (!facts) return [];
const actions = [];
if (facts.archiveId) actions.push({ action: "archive", title: facts.strings.archive });
actions.push({ action: "read", title: facts.strings.markRead });
return actions;
}
self.addEventListener("push", (event) => {
let data = null;
try {
data = event.data ? event.data.json() : null;
} catch {
/* not JSON: fall through to the generic notification below */
}
// The verification handshake. No credentials here, so hand it to a tab —
// an open one now, or the next one to start.
if (data && data["@type"] === "PushVerification") {
event.waitUntil((async () => {
const payload = { id: data.pushSubscriptionId, code: data.verificationCode };
const clients = await self.clients.matchAll({ includeUncontrolled: true, type: "window" });
if (clients.length) {
for (const c of clients) c.postMessage({ type: "push-verification", ...payload });
} else {
const cache = await caches.open(VERSION);
await cache.put(VERIFY_KEY, new Response(JSON.stringify(payload)));
}
})());
return;
}
const emails = (data && data["@type"] === "EmailPush" && Array.isArray(data.emails)) ? data.emails : [];
event.waitUntil((async () => {
const facts = await readFacts();
const strings = facts?.strings ?? { newMail: "New mail", newMessage: "New message", noSubject: "(no subject)" };
/*
* Mark the app icon, without claiming a number.
*
* `setAppBadge()` with no count shows a dot rather than a figure, which is
* the only honest thing to show from here: this worker has no session, so
* it cannot ask how many messages are unread, and a push carries the new
* mail rather than a total. Counting the payload would badge "2" over an
* inbox holding forty. The next time a tab opens, `setUnreadBadge` writes
* the real count over the dot.
*/
if ("setAppBadge" in self.navigator) await self.navigator.setAppBadge().catch(() => {});
if (!emails.length) {
// A StateChange, or a payload too large to carry the message. Say
// something true rather than inventing a sender.
await self.registration.showNotification(strings.newMail, {
icon: `${BASE}/img/icon-192.png`, badge: `${BASE}/img/favicon-64.png`, tag: "ihasmail-mail", data: { url: `${BASE}/mail` },
});
return;
}
// One notification per message, collapsing repeats of the same message by
// tag so a re-push does not stack.
for (const email of emails.slice(0, 5)) {
const { title, body, preview } = textOf(email, strings);
await self.registration.showNotification(title, {
body: preview ? `${body}\n${preview}` : body,
icon: `${BASE}/img/icon-192.png`,
badge: `${BASE}/img/favicon-64.png`,
tag: `ihasmail-${email.id || body}`,
// Only where there is a message to act on: a payload without an id can
// be shown but not archived, and a button that cannot work should not
// be drawn.
actions: email.id ? actionsFor(facts) : [],
data: {
url: email.id ? `${BASE}/mail/inbox/${email.id}` : `${BASE}/mail`,
id: email.id || null,
title,
accountId: facts?.accountId ?? null,
archiveId: facts?.archiveId ?? null,
failed: strings.failed ?? null,
},
});
}
})());
});
/*
* Do what the button said, without opening anything.
*
* The whole point of an action is that the phone goes back in the pocket, so
* this must not fall back to opening the app when the call fails -- that is
* the same interruption the action existed to avoid. It re-notifies instead,
* saying it did not happen, and leaves opening ihasmail to the reader.
*
* Archiving replaces the mailbox set rather than adding to it, which is what
* archiving is: the message leaves the inbox. Marking read is a keyword and
* touches nothing else.
*/
async function runAction(action, data) {
const { id, accountId, archiveId } = data;
if (!id || !accountId) return;
const patch = action === "archive"
? { mailboxIds: { [archiveId]: true } }
: { "keywords/$seen": true };
try {
if (action === "archive" && !archiveId) throw new Error("no archive mailbox");
await jmap([["Email/set", { accountId, update: { [id]: patch } }, "0"]]);
} catch {
await self.registration.showNotification(data.title || "ihasmail", {
body: data.failed || "Could not do that — open ihasmail and try again",
icon: `${BASE}/img/icon-192.png`,
badge: `${BASE}/img/favicon-64.png`,
tag: `ihasmail-failed-${id}`,
data: { url: data.url },
});
}
}
self.addEventListener("notificationclick", (event) => {
event.notification.close();
const data = event.notification.data || {};
if (event.action === "archive" || event.action === "read") {
event.waitUntil(runAction(event.action, data));
return;
}
const url = data.url || `${BASE}/mail`;
event.waitUntil((async () => {
const clients = await self.clients.matchAll({ includeUncontrolled: true, type: "window" });
// Reuse a tab if one is open rather than piling up windows. Same origin is
// not enough under a prefix: `includeUncontrolled` widens the match to the
// whole origin, so on a host that also serves something else this would
// navigate a stranger's tab to our inbox.
for (const c of clients) {
const at = new URL(c.url);
if (at.origin === self.location.origin && (at.pathname === BASE || at.pathname.startsWith(`${BASE}/`))) {
await c.focus();
if ("navigate" in c) await c.navigate(url).catch(() => {});
return;
}
}
await self.clients.openWindow(url);
})());
});
+14 -172
View File
@@ -1,5 +1,5 @@
import { Fragment, lazy, Suspense, useEffect, useState } from "react";
import { Route, Switch, Redirect, useLocation, Router } from "wouter";
import { lazy, Suspense, useEffect } from "react";
import { Route, Switch, Redirect, useLocation } from "wouter";
import { useSession } from "@/store/session";
import { useMail } from "@/store/mail";
import { scheduleSupported, useScheduled } from "@/store/scheduled";
@@ -9,7 +9,7 @@ import { useFiles } from "@/store/files";
import { useSieve } from "@/store/sieve";
import { push } from "@/jmap/push";
import { client } from "@/jmap/client";
import { ToastHost, toast } from "@/ui/toast";
import { ToastHost } from "@/ui/toast";
import { ConfirmHost } from "@/ui/dialog";
import { Spinner } from "@/ui/misc";
import { LoginPage } from "@/views/Login";
@@ -17,59 +17,22 @@ import { AppShell } from "@/views/AppShell";
import { MailView } from "@/views/mail/MailView";
import { ComposerDock } from "@/views/compose/ComposerDock";
import { setUnreadBadge } from "@/lib/notify";
import { publishWorkerFacts } from "@/lib/swFacts";
import { PAINTED_FROM_CACHE, useSettings, syncedPart } from "@/store/settings";
import { armSettingsSync, loadRemoteSettings, queueSettingsPush, settingsAlreadyLoadedFor, settingsSyncAvailable } from "@/lib/settingsSync";
import { loadSettingsPolicy } from "@/lib/settingsPolicy";
import { listenForVerification, renewWebPush } from "@/lib/webpushEnable";
import { plural, t, useLanguageVersion, whenLanguageReady } from "@/lib/i18n";
import { confirmLeaveUnsaved, hasUnsavedChanges } from "@/lib/unsavedChanges";
import { BASE_PATH, withBase } from "@/lib/basePath";
import { DEFAULT_APP_NAME } from "@/lib/brand";
import { useSettings, syncedPart } from "@/store/settings";
import { armSettingsSync, loadRemoteSettings, queueSettingsPush, settingsSyncAvailable } from "@/lib/settingsSync";
const ContactsView = lazy(() => import("@/views/contacts/ContactsView").then((m) => ({ default: m.ContactsView })));
const CalendarView = lazy(() => import("@/views/calendar/CalendarView").then((m) => ({ default: m.CalendarView })));
const FilesView = lazy(() => import("@/views/files/FilesView").then((m) => ({ default: m.FilesView })));
const SettingsView = lazy(() => import("@/views/settings/SettingsView").then((m) => ({ default: m.SettingsView })));
// Only ever opened by the few who administer, so nobody else downloads it.
const AdminView = lazy(() => import("@/views/admin/AdminView").then((m) => ({ default: m.AdminView })));
export function App() {
const status = useSession((s) => s.status);
const bootstrap = useSession((s) => s.bootstrap);
/*
* Subscribed once, here, and used as a key below.
*
* `t()` is a plain function rather than a hook, so a component has no way of
* knowing its strings just changed. Rather than make every one of the
* thousand call sites a subscriber -- which would turn extracting a string
* from "wrap it" into "wrap it and add a hook" -- the whole tree is thrown
* away and rebuilt when the catalogue changes. Picking a language is a
* once-in-an-account event; paying for it there is far cheaper than paying
* for it on every render everywhere.
*/
const languageVersion = useLanguageVersion();
useEffect(() => {
void bootstrap();
}, [bootstrap]);
/*
* Wait for the catalogue before the first paint.
*
* The tree is rebuilt when a catalogue lands, so components recover on
* their own -- but a string computed in an effect does not. A toast fired
* in the gap is emitted in English and stays English, in an interface that
* is otherwise not. The wait costs nothing visible: the session bootstrap
* is already showing a spinner, and English resolves immediately.
*/
const [languageReady, setLanguageReady] = useState(false);
useEffect(() => {
let live = true;
void whenLanguageReady().finally(() => live && setLanguageReady(true));
return () => { live = false; };
}, []);
if (status === "loading" || !languageReady) {
if (status === "loading") {
return (
<div className="center" style={{ height: "100%" }}>
<Spinner size="lg" />
@@ -77,43 +40,11 @@ export function App() {
);
}
return (
/*
* Every in-app navigation runs through `aroundNav` -- links, redirects and
* `navigate()` alike, since wouter routes them all through the same place.
* That is what makes the guard hold for the app rail and the settings nav
* without either of them knowing an editor exists.
*
* The back button is the gap: by the time `popstate` arrives the history
* has already moved, and the only way to hold the page would be to push an
* entry back, which breaks the button for everyone who has nothing pending.
* Reload and tab close are covered by `beforeunload` instead.
*/
<Router
/*
* The one place the mount prefix enters the router. Every `<Route path>`,
* `<Link href>` and `navigate()` in the app stays written root-absolute
* -- `/mail/:mailboxId?` -- and wouter strips the base off the address
* before matching and puts it back on when it navigates. So a deep link
* to `/mail/inbox/abc` under a `/mail` mount is `/mail/mail/inbox/abc`
* and nothing in the views has to know it.
*
* Empty is wouter's own default, so the root case is untouched.
*/
base={BASE_PATH}
aroundNav={(navigate, to, options) => {
if (!hasUnsavedChanges()) {
navigate(to, options);
return;
}
void confirmLeaveUnsaved().then((ok) => {
if (ok) navigate(to, options);
});
}}
>
<Fragment key={languageVersion}>{status === "anonymous" ? <LoginPage /> : <AuthedApp />}</Fragment>
<>
{status === "anonymous" ? <LoginPage /> : <AuthedApp />}
<ToastHost />
<ConfirmHost />
</Router>
</>
);
}
@@ -121,66 +52,16 @@ function AuthedApp() {
const accountId = useSession((s) => s.accountId);
const [location] = useLocation();
/*
* Settings that live with the account rather than the browser.
*
* When this browser has them cached they have already painted, and this only
* has to correct them (issue #54). When it does not -- an untrusted device,
* or the sign-out that every deploy causes -- the first frame is the
* defaults, and the defaults are English. Rendering then means anything
* computed before the settings land is computed in the wrong language: not
* the interface, which is rebuilt when the catalogue arrives, but a string
* emitted once, like a toast. That is why the stale-folder toast came out
* in English on an otherwise German screen.
*
* So without a cache the tree waits, which costs nothing: there was nothing
* worth painting yet. With one it does not wait, and the screen is as quick
* as it was.
*
* Once per account, not once per mount: this subtree is keyed on the
* language version, so picking a language throws it away and builds it
* again. Re-reading the settings file there would apply a copy written
* before the change and undo it.
*/
const [ready, setReady] = useState(PAINTED_FROM_CACHE);
// Settings that live with the account rather than the browser. The cached
// ones have already painted, so this only has to correct them (issue #54).
useEffect(() => {
if (settingsAlreadyLoadedFor(accountId)) {
setReady(true);
return;
}
if (!accountId) return;
let cancelled = false;
void (async () => {
/* Before the account's own settings, so both the seeding below and the
enforcement inside `hydrate` have something to apply. */
await loadSettingsPolicy();
if (cancelled) return;
const remote = await loadRemoteSettings();
if (cancelled) return;
if (remote) useSettings.getState().hydrate(remote);
// No settings file: this account has never had settings of its own, so
// the installation's defaults are what it starts on rather than
// ihasmail's. Issue #207.
else useSettings.getState().seedFromPolicy();
/*
* After both, and for everybody: a change the installation wants applied
* once has to reach accounts that already exist, which is the whole of
* why it is not just a default. Each is remembered, so a reader who turns
* one back off keeps it off. Issue #207.
*/
const applied = useSettings.getState().applyPolicyChanges();
if (applied.length) {
toast.show(plural(applied.length, {
one: "Your administrator changed {n} setting",
other: "Your administrator changed {n} settings",
}), { action: { label: t("Settings"), onClick: () => { window.location.href = withBase("/settings/general"); } } });
}
// The catalogue for whatever language that turned out to be. Hydrating
// asks for it; this is waiting for the answer.
await whenLanguageReady();
if (cancelled) return;
setReady(true);
// Pushes were held back until now so they could not race the load. A
// change made while it was in flight was kept, and goes out here.
// Pushes were held back until now so they could not race the load.
armSettingsSync();
// No file yet — seed one from what this browser has, so the next device
// to sign in starts from these rather than from the defaults.
@@ -206,19 +87,6 @@ function AuthedApp() {
void useFiles.getState().init();
void useSieve.getState().init();
push.start();
// A push subscription stays silent until its verification code is echoed
// back, and the code may have arrived while no tab was open.
listenForVerification();
/*
* And a subscription expires -- seven days is the ceiling JMAP puts on one,
* and re-registering before that is the client's job. Nothing did it, so
* background notifications lapsed within a week of being switched on and
* only came back if somebody
* happened to toggle the switch. Opening the app is the only moment this
* can be done -- registering is a JMAP call, and the service worker has no
* session to make one with -- so it is done on every start.
*/
void renewWebPush();
const pending = new Map<string, Set<string>>();
let timer: number | null = null;
const unsub = push.subscribe((acct, type) => {
@@ -258,7 +126,7 @@ function AuthedApp() {
const id = s.roleId("inbox");
return id ? (s.mailboxes[id]?.unreadEmails ?? 0) : 0;
});
const appName = useSession((s) => s.session?.ihasmail?.appName) || DEFAULT_APP_NAME;
const appName = useSession((s) => s.session?.ihasmail?.appName ?? "ihasmail");
useEffect(() => {
void import("@/lib/notify").then((m) => {
m.setBaseTitle(appName);
@@ -266,37 +134,12 @@ function AuthedApp() {
});
}, [inboxUnread, appName]);
/*
* Leave the service worker its briefing.
*
* Written from here rather than once at startup because everything in it can
* change while the app is open -- the language from Settings, the archive
* folder from the mailbox list arriving -- and what is written is what the
* worker will still be reading a week from now, with no tab to correct it.
* See lib/swFacts.ts.
*/
const archiveId = useMail((s) => s.roleId("archive"));
const languageVersion = useLanguageVersion();
useEffect(() => {
void publishWorkerFacts(accountId, archiveId);
}, [accountId, archiveId, languageVersion]);
// Request notification permission lazily when enabled
const notif = useSettings((s) => s.settings.desktopNotifications);
useEffect(() => {
if (notif) void import("@/lib/notify").then((m) => m.requestNotificationPermission());
}, [notif]);
// Nothing worth painting until the account's settings are in force; see the
// comment on `ready` above. With a cache this was true from the first frame.
if (!ready) {
return (
<div className="center" style={{ height: "100%" }}>
<Spinner size="lg" />
</div>
);
}
return (
<AppShell>
<Suspense fallback={<Spinner size="lg" />}>
@@ -307,7 +150,6 @@ function AuthedApp() {
<Route path="/calendar/:view?/:date?">{(p) => <CalendarView view={p.view} date={p.date} />}</Route>
<Route path="/files/:nodeId?">{(p) => <FilesView nodeId={p.nodeId} />}</Route>
<Route path="/settings/:section?">{(p) => <SettingsView section={p.section} />}</Route>
<Route path="/admin/:section?/:id?">{(p) => <AdminView section={p.section} id={p.id} />}</Route>
<Route path="/login">
<Redirect to="/mail" />
</Route>
-8
View File
@@ -1,8 +0,0 @@
/// <reference types="vite/client" />
/**
* The build's version string, substituted by Vite at build time there is no
* git to ask from inside a browser, or inside the Docker build. See
* `scripts/version.mjs`.
*/
declare const __IHASMAIL_VERSION__: string;
+4 -18
View File
@@ -1,5 +1,4 @@
import type { Id, Invocation, JmapResponse, JmapSession, MethodError, UploadResponse } from "./types";
import { withBase } from "@/lib/basePath";
export const CAP = {
core: "urn:ietf:params:jmap:core",
@@ -19,9 +18,6 @@ export const CAP = {
websocket: "urn:ietf:params:jmap:websocket",
} as const;
/** Stalwart's own capability, which carries its `x:` registry methods. */
export const STALWART_CAP = "urn:stalwart:jmap";
export class JmapMethodError extends Error {
constructor(
public readonly method: string,
@@ -66,16 +62,9 @@ export type ResultRef = { resultOf: string; name: string; path: string };
const HEADERS = { "content-type": "application/json", accept: "application/json", "x-requested-with": "ihasmail" };
/**
* Generic fetch against our same-origin API with CSRF header + auth handling.
*
* `path` is written root-absolute at every call site -- `/api/jmap` -- and the
* mount prefix is added here rather than there. One place to get it right, and
* the `startsWith` below keeps working on the path as written rather than on
* whatever the deployment happens to be called.
*/
/** Generic fetch against our same-origin API with CSRF header + auth handling. */
export async function apiFetch<T = unknown>(path: string, init: RequestInit = {}): Promise<T> {
const res = await fetch(withBase(path), {
const res = await fetch(path, {
...init,
headers: { ...HEADERS, ...(init.headers as Record<string, string> | undefined) },
credentials: "same-origin",
@@ -287,12 +276,12 @@ export class JmapClient {
}
uploadUrl(accountId: Id): string {
return withBase(`/api/upload/${encodeURIComponent(accountId)}`);
return `/api/upload/${encodeURIComponent(accountId)}`;
}
downloadUrl(accountId: Id, blobId: Id, name: string, type: string, inline = false): string {
const safeName = (name || "attachment").replace(/[/\\?#%]/g, "_");
const u = withBase(`/api/blob/${encodeURIComponent(accountId)}/${encodeURIComponent(blobId)}/${encodeURIComponent(safeName)}?accept=${encodeURIComponent(type || "application/octet-stream")}`);
const u = `/api/blob/${encodeURIComponent(accountId)}/${encodeURIComponent(blobId)}/${encodeURIComponent(safeName)}?accept=${encodeURIComponent(type || "application/octet-stream")}`;
return inline ? `${u}&inline=1` : u;
}
@@ -352,9 +341,6 @@ export class JmapClient {
/** Map method name prefix → required capability URNs. */
function usingFor(method: string): string[] {
const type = method.split("/")[0] ?? "";
// Stalwart's registry: accounts, domains, credentials. Advertised per
// account rather than in the session, which supportedUsing() allows for.
if (type.startsWith("x:")) return [STALWART_CAP];
switch (type) {
case "Mailbox":
case "Thread":
+1 -2
View File
@@ -1,5 +1,4 @@
import type { Id, StateChange } from "./types";
import { withBase } from "@/lib/basePath";
export type PushListener = (accountId: Id, type: string, newState: string) => void;
@@ -71,7 +70,7 @@ class PushManager {
private connect(): void {
if (this.stopped || this.es) return;
if (this.state !== "connected") this.setState("connecting");
const url = withBase(`/api/events?types=*&closeafter=no&ping=30`);
const url = `/api/events?types=*&closeafter=no&ping=30`;
const es = new EventSource(url, { withCredentials: true });
this.es = es;
es.onopen = () => {
+2 -14
View File
@@ -36,22 +36,10 @@ export interface JmapSession {
userLocale?: string | null;
/** What the upstream server was willing to say about itself. */
server?: {
/** "oss" | "community" | "enterprise". Stalwart publishes no version. */
/** Which API generation answered: Stalwart publishes no version number. */
generation?: "0.16+" | "pre-0.16" | null;
edition?: string | null;
};
/**
* False when this session may not administer: the operator turned it off,
* or the session was signed in without "This is my own device".
*/
administration?: boolean;
/** An administrator on a device not marked as their own; the menu says so. */
administrationNeedsOwnDevice?: boolean;
/**
* The account's effective permissions on that server, as Stalwart reports
* them. What the client offers is shaped by these; what is allowed is
* decided by Stalwart on every call.
*/
permissions?: string[];
};
}
@@ -1,85 +0,0 @@
import { describe, expect, it } from "vitest";
import { accountForCapability, ownAccountForCapability, type SessionLike } from "@/lib/accountRouting";
/**
* Found by sharing a folder between two real accounts.
*
* Switching to the account somebody shared pointed everything at it, because
* the rule was "use the selected account if it can do this" and a shared file
* account can, by definition, do files. ihasmail keeps its own settings in the
* account's Files, so changing any setting while looking at somebody's shared
* folder wrote `settings.json` into *their* storage, creating the `ihasmail`
* folder there to do it. Reading someone else's data by mistake is bad; writing
* yours into it is worse, and it was the same one-line rule doing both.
*/
const CAL = "urn:ietf:params:jmap:calendars";
const FILES = "urn:ietf:params:jmap:filenode";
const MAIL = "urn:ietf:params:jmap:mail";
/** Mine does everything; theirs is a shared account with only files on it. */
const shared = (): SessionLike => ({
accounts: {
mine: { isPersonal: true, accountCapabilities: { [MAIL]: {}, [FILES]: {}, [CAL]: {} } },
theirs: { isPersonal: false, accountCapabilities: { [FILES]: {} } },
},
primaryAccounts: { [MAIL]: "mine", [FILES]: "mine", [CAL]: "mine" },
});
describe("what the reader is looking at", () => {
it("follows the switch into a shared account for what was shared", () => {
expect(accountForCapability(shared(), "theirs", FILES)).toBe("theirs");
});
it("leaves everything else on the reader's own account", () => {
expect(accountForCapability(shared(), "theirs", MAIL)).toBe("mine");
expect(accountForCapability(shared(), "theirs", CAL)).toBe("mine");
});
it("still follows a switch between the reader's own accounts", () => {
const s = shared();
s.accounts.second = { isPersonal: true, accountCapabilities: { [MAIL]: {} } };
expect(accountForCapability(s, "second", MAIL)).toBe("second");
});
it("gives up rather than aim at a shared account for something unshared", () => {
// No primary for calendars, and theirs does not offer them. The old rule
// fell back to the selection, which is somebody else's account.
const s = shared();
delete s.primaryAccounts[CAL];
expect(accountForCapability(s, "theirs", CAL)).toBeNull();
});
it("lets one of the reader's own accounts stand in when there is no primary", () => {
const s = shared();
delete s.primaryAccounts[CAL];
expect(accountForCapability(s, "mine", CAL)).toBe("mine");
});
});
describe("what belongs to the reader", () => {
it("stays on their own account while they look at a shared one", () => {
// The one that matters: settings are written through this.
expect(ownAccountForCapability(shared(), FILES)).toBe("mine");
});
it("ignores a primary account the server says is not the reader's", () => {
const s = shared();
s.primaryAccounts[FILES] = "theirs";
expect(ownAccountForCapability(s, FILES)).toBe("mine");
});
it("finds a personal account when no primary is named", () => {
const s = shared();
delete s.primaryAccounts[FILES];
expect(ownAccountForCapability(s, FILES)).toBe("mine");
});
it("answers nothing rather than a shared account", () => {
const s: SessionLike = {
accounts: { theirs: { isPersonal: false, accountCapabilities: { [FILES]: {} } } },
primaryAccounts: {},
};
expect(ownAccountForCapability(s, FILES)).toBeNull();
});
});
-54
View File
@@ -1,54 +0,0 @@
import { describe, expect, it } from "vitest";
/**
* Whether a shared collection counts as added.
*
* JMAP keeps this on the collection, in `isSubscribed`, and that is the better
* place: a preference the server holds is one every client sees. But
* subscribing writes to the *owner's* account, and Stalwart 0.16.19 refuses
* that for an address book shared read-only "You are not allowed to modify
* this address book" while accepting the identical write on a shared
* calendar. Confirmed against the live server on 2026-08-27, from a second
* account holding the share.
*
* So there are two records and either counts. The rule is the whole of the
* fix, which is why it is worth pinning down here rather than leaving it
* spelled out in three components that could drift apart.
*/
const key = (accountId: string, id: string) => `${accountId}:${id}`;
/** Added if the server remembered it, or the reader's settings did. */
function isAdded(collection: { accountId: string; id: string; isSubscribed?: boolean }, addedShares: string[]): boolean {
return Boolean(collection.isSubscribed) || new Set(addedShares).has(key(collection.accountId, collection.id));
}
const book = (over: Partial<{ accountId: string; id: string; isSubscribed: boolean }> = {}) =>
({ accountId: "acct", id: "ab1", ...over });
describe("whether a shared collection has been added", () => {
it("is added when the server took the subscription", () => {
expect(isAdded(book({ isSubscribed: true }), [])).toBe(true);
});
it("is added when only the settings remember it", () => {
// The address book case: the server refused the write.
expect(isAdded(book(), ["acct:ab1"])).toBe(true);
});
it("is not added when neither says so", () => {
expect(isAdded(book(), [])).toBe(false);
expect(isAdded(book(), ["other:ab1", "acct:ab2"])).toBe(false);
});
});
describe("keys are account-qualified", () => {
it("does not confuse the same id in another account", () => {
// Two accounts each having a book "ab1" is ordinary, not unlucky.
expect(isAdded(book({ accountId: "theirs" }), ["mine:ab1"])).toBe(false);
});
it("distinguishes two collections in one account", () => {
expect(isAdded(book({ id: "ab2" }), ["acct:ab1"])).toBe(false);
});
});
-95
View File
@@ -1,95 +0,0 @@
import { describe, expect, it } from "vitest";
import { ADMIN_BASELINE, adminSections, can, canGrantRole, generatePassword, hasAdministration, outranks, permissionSet, resolveRoles, type RoleDef } from "@/lib/adminAccess";
const set = (...p: string[]) => permissionSet(p);
const everything = set(...ADMIN_BASELINE, "sysTenantGet", "jmapEmailGet", "impersonate");
const helpdesk = set("sysAccountGet", "sysAccountQuery", "sysAccountUpdate", "jmapEmailGet");
const roles = new Map<string, RoleDef>([
["user", { id: "user", enabledPermissions: { jmapEmailGet: true } }],
["helpdesk", { id: "helpdesk", enabledPermissions: { sysAccountGet: true, sysAccountQuery: true, sysAccountUpdate: true }, roleIds: { user: true } }],
["dns", { id: "dns", enabledPermissions: { sysDnsServerUpdate: true }, roleIds: { user: true } }],
["loop", { id: "loop", enabledPermissions: {}, roleIds: { loop: true } }],
]);
describe("who is offered administration", () => {
it("needs both halves of reading the account list", () => {
expect(hasAdministration(set("sysAccountQuery", "sysAccountGet"))).toBe(true);
expect(hasAdministration(set("sysAccountQuery"))).toBe(false);
expect(hasAdministration(set("sysAccountGet"))).toBe(false);
expect(hasAdministration(permissionSet(undefined))).toBe(false);
});
it("offers each section only with both halves of reading it", () => {
expect(adminSections(set("sysDomainQuery", "sysDomainGet"))).toEqual(["domains"]);
expect(hasAdministration(set("sysDomainQuery", "sysDomainGet"))).toBe(true);
expect(adminSections(set("sysAccountQuery", "sysAccountGet", "sysDomainQuery"))).toEqual(["accounts"]);
});
it("reads one permission per object and operation", () => {
expect(can(helpdesk, "Account", "Update")).toBe(true);
expect(can(helpdesk, "Account", "Destroy")).toBe(false);
expect(can(helpdesk, "Domain", "Get")).toBe(false);
});
});
/**
* Stalwart checks a grant, but not a password change or a delete. Without this,
* anyone allowed to edit accounts could take over one that can do more.
*/
describe("an account that outranks the viewer", () => {
it("an ordinary user never does", () => {
expect(outranks(helpdesk, { roles: { "@type": "User" } }, null)).toBe(false);
expect(outranks(helpdesk, {}, null)).toBe(false);
});
it("an administrator does, unless the viewer is one too", () => {
expect(outranks(helpdesk, { roles: { "@type": "Admin" } }, roles)).toBe(true);
expect(outranks(everything, { roles: { "@type": "Admin" } }, roles)).toBe(false);
});
it("a custom role does when it carries something the viewer lacks", () => {
expect(outranks(helpdesk, { roles: { "@type": "Custom", roleIds: { helpdesk: true } } }, roles)).toBe(false);
expect(outranks(helpdesk, { roles: { "@type": "Custom", roleIds: { dns: true } } }, roles)).toBe(true);
});
it("a role that cannot be read counts against the target, not for it", () => {
expect(outranks(helpdesk, { roles: { "@type": "Custom", roleIds: { helpdesk: true } } }, null)).toBe(true);
expect(outranks(everything, { roles: { "@type": "Custom", roleIds: { gone: true } } }, roles)).toBe(true);
});
it("extra permissions on the account itself are counted", () => {
expect(outranks(helpdesk, { roles: { "@type": "User" }, permissions: { "@type": "Merge", enabledPermissions: { sysDomainDestroy: true } } }, roles)).toBe(true);
// Replace ignores the roles entirely, so only what it lists matters.
expect(outranks(helpdesk, { roles: { "@type": "Custom", roleIds: { dns: true } }, permissions: { "@type": "Replace", enabledPermissions: { jmapEmailGet: true } } }, roles)).toBe(false);
});
it("survives a role that names itself", () => {
expect(resolveRoles(["loop"], roles)).toEqual(new Set());
});
});
describe("granting a role", () => {
it("is offered only for roles whose every permission the viewer holds", () => {
expect(canGrantRole(helpdesk, "helpdesk", roles)).toBe(true);
expect(canGrantRole(helpdesk, "dns", roles)).toBe(false);
expect(canGrantRole(everything, "missing", roles)).toBe(false);
});
});
describe("generated passwords", () => {
it("are four groups of five unambiguous characters", () => {
const p = generatePassword();
expect(p).toMatch(/^[a-zA-Z2-9]{5}(-[a-zA-Z2-9]{5}){3}$/);
expect(p).not.toMatch(/[01lIO]/);
});
it("skip bytes that would favour the start of the alphabet", () => {
// 256 % 55 leaves 36 byte values over; a plain modulo would hand those to
// the first 36 characters twice as often. Bytes of 220 and up are dropped
// and more are drawn, so a batch of nothing but those costs a draw.
let call = 0;
const source = (n: number) => (call++ === 0 ? new Uint8Array(n).fill(250) : Uint8Array.from({ length: n }, (_, i) => i));
expect(generatePassword(source)).toBe("abcde-fghjk-mnpqr-stuvw");
expect(call).toBe(2);
});
});
@@ -1,99 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { client } from "@/jmap/client";
import { aliasList, describeDirectoryError, DirectoryError, hasPassword, passwordPatch, queryAccounts, quotasWithDisk } from "@/lib/adminDirectory";
describe("setting a password", () => {
it("writes into the existing password credential, keeping its place", () => {
const account = { credentials: { "0": { "@type": "AppPassword" as const }, "2": { "@type": "Password" as const, secret: "[********]" } } };
expect(passwordPatch(account, "new secret")).toEqual({ "credentials/2/secret": "new secret" });
});
it("adds one after the last index when the account has none", () => {
const account = { credentials: { "0": { "@type": "AppPassword" as const }, "3": { "@type": "ApiKey" as const } } };
expect(passwordPatch(account, "s")).toEqual({ "credentials/4": { "@type": "Password", secret: "s" } });
expect(passwordPatch({}, "s")).toEqual({ "credentials/0": { "@type": "Password", secret: "s" } });
expect(hasPassword(account)).toBe(false);
});
});
describe("lists written back", () => {
it("re-index aliases the way the server stores a list", () => {
expect(aliasList([{ name: "b", domainId: "d1" }, { name: "c", domainId: "d2", enabled: false }])).toEqual({
"0": { enabled: true, name: "b", domainId: "d1", description: null },
"1": { enabled: false, name: "c", domainId: "d2", description: null },
});
});
it("change the disk limit without touching the other quotas", () => {
expect(quotasWithDisk({ maxEmails: 10, maxDiskQuota: 5 }, 7)).toEqual({ maxEmails: 10, maxDiskQuota: 7 });
expect(quotasWithDisk({ maxEmails: 10, maxDiskQuota: 5 }, null)).toEqual({ maxEmails: 10 });
expect(quotasWithDisk(undefined, 0)).toEqual({});
});
});
describe("explaining a refusal", () => {
it("says what a taken address means", () => {
expect(describeDirectoryError(new DirectoryError("primaryKeyViolation", "exists"))).toMatch(/already in use/);
});
it("keeps the server's own words for a password policy", () => {
expect(describeDirectoryError(new DirectoryError("invalidProperties", "Password must be at least 8 characters long.", ["secret"]))).toContain("at least 8 characters");
});
it("handles a method-level refusal as well as a set error", () => {
expect(describeDirectoryError({ type: "forbidden", message: "x:Account/set: forbidden" })).toMatch(/refused/);
});
});
describe("the account query", () => {
it("filters on @type, the property's name on the object", async () => {
// A live 0.16 server answers a plain `type` with "unsupportedFilter - type"
// and fails the whole list, which is how this was found.
const call = vi.spyOn(client, "call").mockResolvedValue({ ids: [], total: 0 });
await queryAccounts({ type: "User", text: " ada ", position: 50, limit: 50 });
expect(call).toHaveBeenCalledWith("x:Account/query", { filter: { "@type": "User", text: "ada" }, position: 50, limit: 50, calculateTotal: true });
call.mockRestore();
});
});
/**
* Stalwart explains a refusal in English, and none of it should reach an
* interface in another language as it is. Each case below is a refusal a
* live server gave, or one its source says it gives.
*/
describe("refusals in the reader's language", () => {
it("recognises the registry's validators and says it again, without the server's words", () => {
// Live, 2026-09-13: a reserved TLD, and a catch-all without a domain.
const domain = describeDirectoryError(new DirectoryError("invalidPatch", "Invalid domain name", ["name"]), "domain");
expect(domain).toMatch(/isn't a valid domain name/);
expect(domain).not.toContain("Invalid domain name");
expect(describeDirectoryError(new DirectoryError("invalidPatch", "Invalid email address", ["catchAllAddress"]), "domain")).toMatch(/full address/);
expect(describeDirectoryError(new DirectoryError("invalidProperties", "Invalid email local part", ["name"]))).toMatch(/before the @/);
});
it("never echoes a description it does not know", () => {
const text = describeDirectoryError(new DirectoryError("invalidPatch", "Something only the server would say", ["whatever"]));
expect(text).not.toContain("Something only the server would say");
expect(describeDirectoryError(new DirectoryError("forbidden", "You are not allowed to do that thing"))).not.toContain("not allowed to do that thing");
expect(describeDirectoryError(new DirectoryError("someNewType", "Brand new English"))).not.toContain("Brand new English");
});
it("tells a grant refusal and a directory-backed account apart from a plain no", () => {
expect(describeDirectoryError(new DirectoryError("forbidden", "You are not authorized to grant permissions: sysDomainDestroy."))).toMatch(/permissions your own role/);
expect(describeDirectoryError(new DirectoryError("forbidden", "Cannot set credentials for accounts in an external directory."))).toMatch(/external directory/);
});
it("words a clash and a missing object for what it was about", () => {
expect(describeDirectoryError(new DirectoryError("primaryKeyViolation", undefined, ["name"]), "domain")).toMatch(/domain name is already in use/);
expect(describeDirectoryError(new DirectoryError("primaryKeyViolation", undefined))).toMatch(/address is already in use/);
expect(describeDirectoryError(new DirectoryError("notFound", undefined), "domain")).toMatch(/domain no longer exists/);
});
it("explains ihasmail's own refusals by their code, not their English message", () => {
const own = { status: 403, code: "administration_needs_own_device", message: "Administration is only available when signed in on a device marked as your own (x:Account/query)." };
expect(describeDirectoryError(own)).toMatch(/marked as your own/);
expect(describeDirectoryError(own)).not.toContain("x:Account/query");
expect(describeDirectoryError({ status: 403, code: "administration_disabled", message: "…" })).toMatch(/turned off/);
expect(describeDirectoryError({ method: "x:Account/query", type: "unsupportedFilter", message: "x:Account/query: unsupportedFilter - type" })).toBe("The mail server could not carry out the request (unsupportedFilter).");
});
});
@@ -1,69 +0,0 @@
import { describe, expect, it } from "vitest";
import { describeLinked, dkimAlgorithm, looksLikeDomain, normaliseDomain, parseZoneFile } from "@/lib/adminDomains";
/**
* Written the way Stalwart's BIND serialiser writes it (dns-update's
* `BindSerializer`): `name IN TYPE value`, and a TXT over 255 bytes as a
* parenthesised run of quoted chunks.
*/
const long = "v=DKIM1; k=rsa; h=sha256; p=" + "A".repeat(400);
const zone = [
"example.com. IN MX 10 mail.example.com.",
'example.com. IN TXT "v=spf1 mx ra=postmaster -all"',
"v1-rsa-20260601._domainkey.example.com. IN TXT (",
...(long.match(/.{1,255}/g) ?? []).map((c) => ` "${c}"`),
")",
'_dmarc.example.com. IN TXT "v=DMARC1; p=reject; rua=mailto:\\"postmaster\\"@example.com"',
"_jmap._tcp.example.com. IN SRV 0 1 443 mail.example.com.",
'example.com. IN CAA 0 issue "letsencrypt.org"',
"",
].join("\n");
describe("reading the zone file", () => {
const records = parseZoneFile(zone);
it("gives one row per record, without the root dot", () => {
expect(records.map((r) => r.type)).toEqual(["MX", "TXT", "TXT", "TXT", "SRV", "CAA"]);
expect(records[0]).toMatchObject({ name: "example.com", value: "10 mail.example.com." });
});
it("joins a split TXT record back into the value a DNS form wants", () => {
expect(records[2]!.name).toBe("v1-rsa-20260601._domainkey.example.com");
expect(records[2]!.value).toBe(long);
expect(records[2]!.line).toContain("(");
});
it("unquotes and unescapes TXT values, and leaves other types as written", () => {
expect(records[1]!.value).toBe("v=spf1 mx ra=postmaster -all");
expect(records[3]!.value).toBe('v=DMARC1; p=reject; rua=mailto:"postmaster"@example.com');
expect(records[5]!.value).toBe('0 issue "letsencrypt.org"');
});
it("keeps a line it cannot read rather than dropping it", () => {
expect(parseZoneFile("something unexpected")).toEqual([{ name: "", type: "", value: "something unexpected", line: "something unexpected" }]);
});
});
describe("domain names", () => {
it("are written back lower-case without the root dot", () => {
expect(normaliseDomain(" Example.COM. ")).toBe("example.com");
});
it("are checked loosely before the server decides", () => {
expect(looksLikeDomain("mail.example.co.uk")).toBe(true);
expect(looksLikeDomain("example")).toBe(false);
expect(looksLikeDomain("exa mple.com")).toBe(false);
expect(looksLikeDomain("-bad.example.com")).toBe(false);
});
});
describe("explaining what still uses a domain", () => {
it("counts by kind", () => {
expect(describeLinked(["Account", "Account", "DkimSignature", "MailingList", "Whatever"])).toBe("2 accounts, 1 DKIM key, 1 mailing list, 1 other item");
});
it("names a key's algorithm from its type", () => {
expect(dkimAlgorithm("Dkim1Ed25519Sha256")).toBe("Ed25519 · DKIM1");
expect(dkimAlgorithm("Dkim2RsaSha256")).toBe("RSA · DKIM2");
});
});
-109
View File
@@ -1,109 +0,0 @@
import { describe, expect, it } from "vitest";
import { appointmentDraft, nextHalfHour } from "@/lib/appointment";
import type { Email, EmailBodyPart } from "@/jmap/types";
/**
* A reminder made out of a mail: the subject becomes the title and the body
* becomes the description, and the reader supplies the one thing the message
* cannot when it happens. What these pin is that the copy is faithful and
* bounded, because everything else about the event is the editor's job.
*/
function part(partId: string, type: string): EmailBodyPart {
return { partId, type } as EmailBodyPart;
}
function email(parts: Partial<Email>): Email {
return { id: "m1", subject: null, ...parts } as Email;
}
function body(subject: string, type: "text/plain" | "text/html", value: string): Email {
const key = type === "text/plain" ? "textBody" : "htmlBody";
return email({ subject, [key]: [part("1", type)], bodyValues: { 1: { value, isEncodingProblem: false, isTruncated: false } } });
}
const text = (value: string) => body("Water bill", "text/plain", value);
describe("the time an appointment starts", () => {
it("rounds up to the next half hour", () => {
expect(nextHalfHour(new Date("2026-08-31T09:12:40")).toTimeString().slice(0, 5)).toBe("09:30");
expect(nextHalfHour(new Date("2026-08-31T09:41:00")).toTimeString().slice(0, 5)).toBe("10:00");
});
it("moves on from a time already on the boundary, rather than starting now", () => {
expect(nextHalfHour(new Date("2026-08-31T09:30:00")).toTimeString().slice(0, 5)).toBe("10:00");
});
it("runs for an hour", () => {
const d = appointmentDraft(text("anything"), new Date("2026-08-31T09:12:00"));
expect(d.end.getTime() - d.start.getTime()).toBe(3600_000);
expect(d.allDay).toBe(false);
});
});
describe("what is copied from the message", () => {
it("takes the subject as the title and the body as the description", () => {
const d = appointmentDraft(text("Due on the 14th.\nAccount 4471.\n"));
expect(d.title).toBe("Water bill");
expect(d.description).toBe("Due on the 14th.\nAccount 4471.");
});
it("reads an HTML-only message as text, so the description is not markup", () => {
const d = appointmentDraft(body("Renewal", "text/html", "<p>Renews <b>Friday</b></p>"));
expect(d.description).toBe("Renews Friday");
});
it("leaves the title empty when there is no subject, for the editor to prompt for", () => {
expect(appointmentDraft(email({ subject: null })).title).toBe("");
});
/*
* A newsletter is a message too. The whole body would be stored on the
* event, synced everywhere, and shown in a three-row box, so the tail is
* dropped visibly, so a truncated bill is not read as the whole of it.
*/
it("truncates a body too long to be a description", () => {
const d = appointmentDraft(text("x".repeat(9000)));
expect(d.description).toHaveLength(5001);
expect(d.description.endsWith("…")).toBe(true);
});
});
const between = (parts: Partial<Email>) => email({ subject: "Kickoff", ...parts });
const addr = (email: string, name: string | null = null) => ({ name, email });
describe("who is invited", () => {
it("carries the sender and everyone it was addressed to", () => {
const d = appointmentDraft(
between({ from: [addr("[email protected]", "Grace")], to: [addr("[email protected]"), addr("[email protected]")], cc: [addr("[email protected]")] }),
new Date(),
["[email protected]"],
);
expect(d.attendees.map((a) => a.email)).toEqual(["[email protected]", "[email protected]", "[email protected]"]);
expect(d.attendees[0]?.name).toBe("Grace");
});
it("leaves the reader out, whatever case their address was written in", () => {
const d = appointmentDraft(between({ from: [addr("[email protected]")], to: [addr("[email protected]")] }), new Date(), ["[email protected]"]);
expect(d.attendees.map((a) => a.email)).toEqual(["[email protected]"]);
});
it("counts someone once, however many headers they appear in", () => {
const d = appointmentDraft(between({ from: [addr("[email protected]")], to: [addr("[email protected]")], cc: [addr("[email protected]")] }));
expect(d.attendees).toHaveLength(1);
});
/*
* On a message the reader sent, a blind copy is still a recipient and
* putting one on a guest list shows them to every other guest. Turning a
* hidden copy into a visible one is not something a menu item may do.
*/
it("never turns a blind copy into a guest", () => {
const d = appointmentDraft(between({ from: [addr("[email protected]")], to: [addr("[email protected]")], bcc: [addr("[email protected]")] }), new Date(), ["[email protected]"]);
expect(d.attendees.map((a) => a.email)).toEqual(["[email protected]"]);
});
it("invites nobody when the message has no addresses at all", () => {
expect(appointmentDraft(between({})).attendees).toEqual([]);
});
});
-103
View File
@@ -1,103 +0,0 @@
import { describe, expect, it } from "vitest";
import { archiveSegments, archivePath, groupByArchivePath } from "@/lib/archiveDate";
/**
* The dates below are written as local-time strings on purpose. The segments
* follow the reader's timezone, so a test pinned to UTC instants would pass or
* fail depending on where it ran.
*/
describe("archiveSegments", () => {
it("gives the year, and the zero-padded month", () => {
expect(archiveSegments("2026-09-04T10:00:00", "year")).toEqual(["2026"]);
expect(archiveSegments("2026-09-04T10:00:00", "month")).toEqual(["2026", "09"]);
});
it("zero-pads every month below October, so the folders sort", () => {
expect(archiveSegments("2026-01-15T10:00:00", "month")).toEqual(["2026", "01"]);
expect(archiveSegments("2026-10-15T10:00:00", "month")).toEqual(["2026", "10"]);
expect(archiveSegments("2026-12-15T10:00:00", "month")).toEqual(["2026", "12"]);
});
it("returns nothing to append when the date cannot be read", () => {
// Archive itself, rather than a folder named after a guess.
expect(archiveSegments(null, "month")).toEqual([]);
expect(archiveSegments(undefined, "month")).toEqual([]);
expect(archiveSegments("", "month")).toEqual([]);
expect(archiveSegments("not a date", "month")).toEqual([]);
});
it("joins to a path", () => {
expect(archivePath(["2026", "09"])).toBe("2026/09");
expect(archivePath([])).toBe("");
});
});
describe("groupByArchivePath", () => {
it("keeps one destination for a selection from one month", () => {
const groups = groupByArchivePath(
[
{ id: "a", receivedAt: "2026-09-04T10:00:00" },
{ id: "b", receivedAt: "2026-09-28T10:00:00" },
],
"month",
);
expect(groups).toHaveLength(1);
expect(groups[0]!.segments).toEqual(["2026", "09"]);
expect(groups[0]!.ids).toEqual(["a", "b"]);
});
it("splits a selection that spans months, which is the case that matters", () => {
const groups = groupByArchivePath(
[
{ id: "a", receivedAt: "2026-09-04T10:00:00" },
{ id: "b", receivedAt: "2026-08-30T10:00:00" },
{ id: "c", receivedAt: "2026-09-01T10:00:00" },
],
"month",
);
expect(groups.map((g) => g.segments)).toEqual([
["2026", "09"],
["2026", "08"],
]);
expect(groups[0]!.ids).toEqual(["a", "c"]);
expect(groups[1]!.ids).toEqual(["b"]);
});
it("collapses the same span back to one group at year granularity", () => {
const entries = [
{ id: "a", receivedAt: "2026-09-04T10:00:00" },
{ id: "b", receivedAt: "2026-02-28T10:00:00" },
];
expect(groupByArchivePath(entries, "month")).toHaveLength(2);
expect(groupByArchivePath(entries, "year")).toHaveLength(1);
});
it("orders groups by where their first message appeared", () => {
const groups = groupByArchivePath(
[
{ id: "a", receivedAt: "2024-01-04T10:00:00" },
{ id: "b", receivedAt: "2026-01-04T10:00:00" },
],
"year",
);
expect(groups.map((g) => archivePath(g.segments))).toEqual(["2024", "2026"]);
});
it("gathers the undatable ones into their own group, bound for Archive itself", () => {
const groups = groupByArchivePath(
[
{ id: "a", receivedAt: "2026-09-04T10:00:00" },
{ id: "b", receivedAt: null },
{ id: "c", receivedAt: "bad" },
],
"month",
);
expect(groups).toHaveLength(2);
expect(groups[1]!.segments).toEqual([]);
expect(groups[1]!.ids).toEqual(["b", "c"]);
});
it("has nothing to do with an empty selection", () => {
expect(groupByArchivePath([], "month")).toEqual([]);
});
});
@@ -1,113 +0,0 @@
import { describe, expect, it } from "vitest";
import { availabilityWindow } from "@/lib/availabilityWindow";
const at = (s: string) => new Date(s);
const hours = (w: { ticks: { time: Date }[] }) => w.ticks.map((t) => `${t.time.getDate()}@${t.time.getHours()}`);
describe("the span an availability bar covers", () => {
it("covers the whole day for an event inside one", () => {
const w = availabilityWindow(at("2026-09-02T09:00:00"), at("2026-09-02T10:30:00"));
expect(w.start.getHours()).toBe(0);
expect(w.days).toBe(1);
expect(w.end.getDate()).toBe(3);
expect(w.end.getHours()).toBe(0);
});
it("stretches to cover an event running over several days", () => {
const w = availabilityWindow(at("2026-09-02T09:00:00"), at("2026-09-04T17:00:00"));
expect(w.days).toBe(3);
expect(w.start.getDate()).toBe(2);
expect(w.end.getDate()).toBe(5);
});
it("ends an event on the day it ends on, not the midnight it stops at", () => {
// An all-day event on the 2nd runs to midnight starting the 3rd; it does
// not touch the 3rd and the bar should not show it.
const w = availabilityWindow(at("2026-09-02T00:00:00"), at("2026-09-03T00:00:00"));
expect(w.days).toBe(1);
expect(w.end.getDate()).toBe(3);
});
it("never collapses to nothing, even when start and end are the same moment", () => {
const w = availabilityWindow(at("2026-09-02T09:00:00"), at("2026-09-02T09:00:00"));
expect(w.days).toBe(1);
expect(w.span).toBeGreaterThan(0);
});
it("marks a single day every three hours, labelling every six", () => {
const w = availabilityWindow(at("2026-09-02T09:00:00"), at("2026-09-02T10:00:00"));
expect(w.scale).toBe("hours");
expect(hours(w)).toEqual(["2@0", "2@3", "2@6", "2@9", "2@12", "2@15", "2@18", "2@21"]);
expect(w.ticks.filter((t) => t.major).map((t) => t.time.getHours())).toEqual([0, 6, 12, 18]);
});
it("thins the marks out to every six hours across two days", () => {
const w = availabilityWindow(at("2026-09-02T09:00:00"), at("2026-09-03T10:00:00"));
expect(w.scale).toBe("hours");
expect(hours(w)).toEqual(["2@0", "2@6", "2@12", "2@18", "3@0", "3@6", "3@12", "3@18"]);
});
it("marks day boundaries once there are more than two", () => {
const w = availabilityWindow(at("2026-09-02T09:00:00"), at("2026-09-05T10:00:00"));
expect(w.scale).toBe("days");
expect(hours(w)).toEqual(["2@0", "3@0", "4@0", "5@0"]);
expect(w.ticks.every((t) => t.major)).toBe(true);
});
it("puts every mark at its true fraction of the span", () => {
const w = availabilityWindow(at("2026-09-02T09:00:00"), at("2026-09-02T10:00:00"));
expect(w.ticks[0]!.at).toBe(0);
expect(w.ticks[4]!.at).toBeCloseTo(0.5, 5); // noon
expect(w.ticks.every((t) => t.at >= 0 && t.at < 1)).toBe(true);
});
it("stops at a week and says how much it left out", () => {
const w = availabilityWindow(at("2026-09-01T09:00:00"), at("2026-09-30T17:00:00"));
expect(w.days).toBe(7);
expect(w.daysHidden).toBe(23);
});
it("hides nothing when the event fits", () => {
expect(availabilityWindow(at("2026-09-02T09:00:00"), at("2026-09-04T17:00:00")).daysHidden).toBe(0);
});
it("lands on real midnights, and measures the span between them", () => {
/*
* The span is what every position is a fraction of, so it has to be the
* distance between the two boundaries rather than a count of 24-hour days:
* on the day a clock changes those differ by an hour, which would end the
* bar early and put every block after the change in the wrong place. This
* asserts the relationship; whether the run happens to sit in a zone with
* DST is not something a test should depend on.
*/
for (const day of ["2026-03-29", "2026-10-25", "2026-09-02"]) {
const w = availabilityWindow(at(`${day}T09:00:00`), at(`${day}T10:00:00`));
expect(w.start.getHours(), day).toBe(0);
expect(w.end.getHours(), day).toBe(0);
expect(w.span, day).toBe(w.end.getTime() - w.start.getTime());
}
});
});
describe("looking around the event without changing it", () => {
it("slides the whole window forward, keeping its width", () => {
const here = availabilityWindow(at("2026-09-02T09:00:00"), at("2026-09-04T17:00:00"));
const later = availabilityWindow(at("2026-09-02T09:00:00"), at("2026-09-04T17:00:00"), { offsetDays: 3 });
expect(later.days).toBe(here.days);
expect(later.start.getDate()).toBe(5);
expect(later.end.getDate()).toBe(8);
});
it("slides backwards, across the end of a month", () => {
const w = availabilityWindow(at("2026-09-02T09:00:00"), at("2026-09-02T10:00:00"), { offsetDays: -3 });
expect(w.start.getMonth()).toBe(7); // August
expect(w.start.getDate()).toBe(30);
expect(w.days).toBe(1);
});
it("keeps the marks in step with where the window moved to", () => {
const w = availabilityWindow(at("2026-09-02T09:00:00"), at("2026-09-02T10:00:00"), { offsetDays: 1 });
expect(w.ticks[0]!.time.getDate()).toBe(3);
expect(w.ticks[0]!.at).toBe(0);
});
});
-113
View File
@@ -1,113 +0,0 @@
import { describe, expect, it } from "vitest";
import { baseUrlOf, normalizeBasePath, stripBasePath } from "../../../../scripts/basePath.mjs";
import { BASE_PATH, withBase } from "@/lib/basePath";
/**
* `BASE_PATH` is typed into a compose file or a `docker run` line by hand, and
* the four spellings below are all reasonable things for someone to write.
* The one that has to be exactly right is the empty one: every deployment that
* exists today is at the root, and this feature must be invisible to them.
*
* The canonical form is a leading slash and no trailing one, so that the
* concatenation `${base}/api/health` is correct with no branch. A trailing
* slash would make the empty case produce `//api/health`, which is not a path
* on this host but a protocol-relative URL pointing at a host called `api` --
* which is why the tests below check the joined result and not just the value.
*/
describe("normalizing what the operator wrote", () => {
it("leaves the canonical form alone", () => {
expect(normalizeBasePath("/mail")).toBe("/mail");
});
it("accepts a missing leading slash", () => {
expect(normalizeBasePath("mail")).toBe("/mail");
});
it("accepts a trailing slash", () => {
expect(normalizeBasePath("/mail/")).toBe("/mail");
expect(normalizeBasePath("mail/")).toBe("/mail");
});
it("accepts a nested mount, however it is punctuated", () => {
expect(normalizeBasePath("apps/mail")).toBe("/apps/mail");
expect(normalizeBasePath("/apps/mail/")).toBe("/apps/mail");
});
it("tidies away doubled separators and stray whitespace", () => {
expect(normalizeBasePath("//mail//")).toBe("/mail");
expect(normalizeBasePath(" /mail ")).toBe("/mail");
});
});
describe("the root, which must behave exactly as it did", () => {
it("is the empty string for every way of saying it", () => {
expect(normalizeBasePath("")).toBe("");
expect(normalizeBasePath("/")).toBe("");
expect(normalizeBasePath("///")).toBe("");
expect(normalizeBasePath(undefined)).toBe("");
expect(normalizeBasePath(null)).toBe("");
});
it("joins onto an app path without doubling the slash", () => {
// `//api/health` would be read as a protocol-relative URL and sent to a
// host called `api`. This is the assertion the whole canonical form is for.
expect(`${normalizeBasePath("/")}/api/health`).toBe("/api/health");
expect(`${normalizeBasePath("/mail")}/api/health`).toBe("/mail/api/health");
});
});
describe("the directory form Vite and the PWA scope want", () => {
it("always ends in a slash", () => {
expect(baseUrlOf("")).toBe("/");
expect(baseUrlOf("mail")).toBe("/mail/");
expect(baseUrlOf("/mail/")).toBe("/mail/");
});
});
describe("taking the prefix off an incoming request", () => {
it("passes everything through untouched at the root", () => {
expect(stripBasePath("", "/")).toBe("/");
expect(stripBasePath("", "/assets/index.js")).toBe("/assets/index.js");
expect(stripBasePath("", "/mail/inbox/abc")).toBe("/mail/inbox/abc");
});
it("strips the mount and keeps the rest", () => {
expect(stripBasePath("/mail", "/mail/assets/index.js")).toBe("/assets/index.js");
expect(stripBasePath("/mail", "/mail/api/health")).toBe("/api/health");
});
it("treats the bare mount as the app's index", () => {
// Typing the prefix without the trailing slash is how people reach it.
expect(stripBasePath("/mail", "/mail")).toBe("/");
expect(stripBasePath("/mail", "/mail/")).toBe("/");
});
it("refuses a path that merely starts with the same letters", () => {
// A plain startsWith would hand `/mailbox` the app shell, shadowing
// whatever else the proxy serves on this host.
expect(stripBasePath("/mail", "/mailbox")).toBe(null);
expect(stripBasePath("/mail", "/mailing/list")).toBe(null);
});
it("refuses anything outside the mount", () => {
expect(stripBasePath("/mail", "/")).toBe(null);
expect(stripBasePath("/mail", "/other-app/thing")).toBe(null);
});
});
describe("the browser's view of the mount", () => {
/*
* Vitest builds with Vite's default base, so this is the root deployment --
* which is the case that must not regress, and the reason these assertions
* are worth writing down rather than dismissing as trivial.
*/
it("is empty in a root build", () => {
expect(BASE_PATH).toBe("");
});
it("leaves app paths exactly as written", () => {
expect(withBase("/api/health")).toBe("/api/health");
expect(withBase("/img/logo.png")).toBe("/img/logo.png");
expect(withBase("/sw.js")).toBe("/sw.js");
});
});
-135
View File
@@ -1,135 +0,0 @@
import { describe, expect, it } from "vitest";
import { birthdaysInRange, isBirthdayEvent, BIRTHDAY_ID_PREFIX } from "@/lib/birthdays";
import type { ContactCard } from "@/jmap/types";
const card = (id: string, full: string, date: { year?: number; month?: number; day?: number; utc?: string } | null, kind = "birth"): ContactCard =>
({
id,
uid: id,
addressBookIds: { b1: true },
name: { full },
...(date ? { anniversaries: { a1: { kind, date } } } : {}),
}) as ContactCard;
const range = (from: string, to: string) => [new Date(from), new Date(to)] as const;
const names = (b: ReturnType<typeof birthdaysInRange>) => b.map((x) => `${x.name} ${x.date.toISOString().slice(0, 10)}${x.age === null ? "" : ` (${x.age})`}`);
describe("birthdaysInRange", () => {
it("puts a birthday in the year the range covers, with the age", () => {
const [s, e] = range("2026-01-01", "2027-01-01");
expect(names(birthdaysInRange([card("c1", "Ada Lovelace", { year: 1990, month: 6, day: 15 })], s, e))).toEqual(["Ada Lovelace 2026-06-15 (36)"]);
});
it("gives no age when the card recorded only a day and month", () => {
// Very common, and a real answer rather than a broken one.
const [s, e] = range("2026-01-01", "2027-01-01");
const out = birthdaysInRange([card("c1", "Ada", { month: 6, day: 15 })], s, e);
expect(out[0]!.age).toBeNull();
expect(out[0]!.date.getMonth()).toBe(5);
});
it("emits one occurrence per year across a range that spans years", () => {
const [s, e] = range("2025-06-01", "2027-06-01");
expect(names(birthdaysInRange([card("c1", "Ada", { year: 2000, month: 12, day: 25 })], s, e))).toEqual([
"Ada 2025-12-25 (25)",
"Ada 2026-12-25 (26)",
]);
});
it("leaves out a birthday outside the range", () => {
const [s, e] = range("2026-07-01", "2026-08-01");
expect(birthdaysInRange([card("c1", "Ada", { month: 6, day: 15 })], s, e)).toEqual([]);
});
it("puts 29 February on the 28th in a year that has no 29th", () => {
// The month is the fact; moving it to 1 March is the arithmetic winning.
const [s, e] = range("2026-01-01", "2027-01-01");
const out = birthdaysInRange([card("c1", "Ada", { year: 2000, month: 2, day: 29 })], s, e);
expect(out[0]!.date.getMonth()).toBe(1);
expect(out[0]!.date.getDate()).toBe(28);
});
it("keeps 29 February on the 29th in a leap year", () => {
const [s, e] = range("2028-01-01", "2029-01-01");
const out = birthdaysInRange([card("c1", "Ada", { year: 2000, month: 2, day: 29 })], s, e);
expect(out[0]!.date.getDate()).toBe(29);
});
it("reads a timestamp date as well as a partial one", () => {
const [s, e] = range("2026-01-01", "2027-01-01");
const out = birthdaysInRange([card("c1", "Ada", { utc: "1990-06-15T00:00:00Z" })], s, e);
expect(out[0]!.date.getMonth()).toBe(5);
expect(out[0]!.age).toBe(36);
});
it("ignores anniversaries that are not birthdays", () => {
const [s, e] = range("2026-01-01", "2027-01-01");
expect(birthdaysInRange([card("c1", "Ada", { month: 6, day: 15 }, "wedding")], s, e)).toEqual([]);
});
it("ignores a card with no anniversary and one with no usable name", () => {
const [s, e] = range("2026-01-01", "2027-01-01");
expect(birthdaysInRange([card("c1", "Ada", null)], s, e)).toEqual([]);
expect(birthdaysInRange([card("c2", "", { month: 6, day: 15 })], s, e)).toEqual([]);
});
it("falls back to a name built from components, then to the organisation", () => {
const [s, e] = range("2026-01-01", "2027-01-01");
const parts = {
id: "c1",
uid: "c1",
addressBookIds: {},
name: { components: [{ kind: "given", value: "Grace" }, { kind: "surname", value: "Hopper" }] },
anniversaries: { a1: { kind: "birth", date: { month: 12, day: 9 } } },
} as unknown as ContactCard;
expect(birthdaysInRange([parts], s, e)[0]!.name).toBe("Grace Hopper");
const org = {
id: "c2",
uid: "c2",
addressBookIds: {},
organizations: { o1: { name: "Acme Ltd" } },
anniversaries: { a1: { kind: "birth", date: { month: 3, day: 1 } } },
} as unknown as ContactCard;
expect(birthdaysInRange([org], s, e)[0]!.name).toBe("Acme Ltd");
});
it("never reports a negative age from a birth year in the future", () => {
const [s, e] = range("2026-01-01", "2027-01-01");
expect(birthdaysInRange([card("c1", "Ada", { year: 2040, month: 6, day: 15 })], s, e)[0]!.age).toBeNull();
});
it("ignores an impossible date rather than inventing one", () => {
const [s, e] = range("2026-01-01", "2027-01-01");
expect(birthdaysInRange([card("c1", "Ada", { month: 13, day: 40 })], s, e)).toEqual([]);
expect(birthdaysInRange([card("c1", "Ada", { month: 4, day: 31 })], s, e)).toEqual([]);
});
it("returns them in date order, whatever order the contacts were in", () => {
const [s, e] = range("2026-01-01", "2027-01-01");
const out = birthdaysInRange(
[card("c1", "Zoe", { month: 11, day: 2 }), card("c2", "Amy", { month: 2, day: 3 })],
s,
e,
);
expect(out.map((b) => b.name)).toEqual(["Amy", "Zoe"]);
});
it("gives each occurrence a stable, unique id that marks it as synthesised", () => {
const [s, e] = range("2025-01-01", "2027-01-01");
const out = birthdaysInRange([card("c1", "Ada", { month: 6, day: 15 })], s, e);
expect(new Set(out.map((b) => b.id)).size).toBe(out.length);
expect(out.every((b) => isBirthdayEvent(b.id))).toBe(true);
expect(out[0]!.id.startsWith(BIRTHDAY_ID_PREFIX)).toBe(true);
// Nothing that came off the server should ever look like one.
expect(isBirthdayEvent("abc123")).toBe(false);
expect(isBirthdayEvent(null)).toBe(false);
});
it("declines a range that is empty, backwards, or absurdly wide", () => {
const cards = [card("c1", "Ada", { month: 6, day: 15 })];
expect(birthdaysInRange(cards, new Date("2026-01-01"), new Date("2026-01-01"))).toEqual([]);
expect(birthdaysInRange(cards, new Date("2027-01-01"), new Date("2026-01-01"))).toEqual([]);
expect(birthdaysInRange(cards, new Date("2000-01-01"), new Date("2100-01-01"))).toEqual([]);
});
});
-40
View File
@@ -1,40 +0,0 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_APP_NAME } from "@/lib/brand";
/*
* The name an instance calls itself.
*
* `APP_NAME` is a runtime variable, so every place showing the name has to ask
* the server rather than have it written in. The sign-in page did not (#236's
* neighbour): it fetched `/api/config`, received the name and used only
* `sourceUrl`, so a rebranded instance still said "ihasmail" on the page a new
* user meets first. These pin the shape of the answer rather than the name.
*/
const nameFrom = (config: { appName?: unknown } | null) =>
config && typeof config.appName === "string" && config.appName.trim() ? config.appName.trim() : DEFAULT_APP_NAME;
describe("resolving the instance name", () => {
it("uses what the server says", () => {
expect(nameFrom({ appName: "Acme Mail" })).toBe("Acme Mail");
});
it("trims it, because a name with an edge of whitespace is a layout bug", () => {
expect(nameFrom({ appName: " Acme Mail " })).toBe("Acme Mail");
});
it("falls back when the request failed", () => {
// A sign-in form with no name on it is worse than one with the wrong name.
expect(nameFrom(null)).toBe(DEFAULT_APP_NAME);
});
it("falls back on a name that is empty or only spaces", () => {
expect(nameFrom({ appName: "" })).toBe(DEFAULT_APP_NAME);
expect(nameFrom({ appName: " " })).toBe(DEFAULT_APP_NAME);
});
it("falls back on a name that is not a string at all", () => {
expect(nameFrom({ appName: 42 })).toBe(DEFAULT_APP_NAME);
expect(nameFrom({})).toBe(DEFAULT_APP_NAME);
});
});
@@ -1,93 +0,0 @@
/**
* The two sentence builders, which had no tests while they were building
* English by concatenation -- and no test would have caught the thing wrong
* with them, since the English output was correct. These pin the two
* properties that matter now: every fragment goes through the catalogue, and
* the joining is Intl's rather than a hardcoded " and ".
*/
import { describe, expect, it } from "vitest";
import { describeRule as describeSieve } from "../sieve";
import { describeRule as describeRecurrence, weekdayOptions } from "../recurrence";
import { setUiLanguageForFormatting } from "../datetime";
import { setCatalog } from "../i18n";
describe("sieve describeRule", () => {
it("names the header and operator through the catalogue", () => {
const s = describeSieve({
id: "1", name: "r", join: "allof", enabled: true,
tests: [{ type: "header", header: "subject", op: "contains", value: "invoice" }],
actions: [{ type: "fileinto", mailbox: "Work" }],
} as never);
expect(s).toContain("Subject");
expect(s).toContain("contains");
expect(s).toContain("invoice");
expect(s).toContain("Work");
});
it("joins an allof rule as a conjunction and anyof as a disjunction", () => {
const base = {
id: "1", name: "r", enabled: true,
tests: [
{ type: "header", header: "from", op: "is", value: "a@b" },
{ type: "header", header: "to", op: "is", value: "c@d" },
],
actions: [{ type: "keep" }],
};
expect(describeSieve({ ...base, join: "allof" } as never)).toContain(" and ");
expect(describeSieve({ ...base, join: "anyof" } as never)).toContain(" or ");
});
it("says 'always' when a rule has no tests", () => {
const s = describeSieve({ id: "1", name: "r", join: "allof", enabled: true, tests: [], actions: [{ type: "stop" }] } as never);
expect(s).toContain("always");
});
});
describe("recurrence describeRule", () => {
it("describes the simple frequencies", () => {
expect(describeRecurrence(undefined)).toBe("Does not repeat");
expect(describeRecurrence({ "@type": "RecurrenceRule", frequency: "daily" } as never)).toBe("Daily");
expect(describeRecurrence({ "@type": "RecurrenceRule", frequency: "daily", interval: 3 } as never)).toBe("Every 3 days");
});
it("recognises Monday to Friday as every weekday", () => {
const rule = {
"@type": "RecurrenceRule", frequency: "weekly",
byDay: ["mo", "tu", "we", "th", "fr"].map((day) => ({ "@type": "NDay", day })),
};
expect(describeRecurrence(rule as never)).toBe("Every weekday");
});
it("uses a word, not a suffix, for the nth weekday of a month", () => {
const s = describeRecurrence({
"@type": "RecurrenceRule", frequency: "monthly",
byDay: [{ "@type": "NDay", day: "tu", nthOfPeriod: 2 }],
} as never);
expect(s).toContain("second");
expect(s).not.toContain("2nd");
});
it("wraps the sentence for count and until rather than appending to it", () => {
const s = describeRecurrence({ "@type": "RecurrenceRule", frequency: "daily", count: 5 } as never);
expect(s).toBe("Daily, 5 times");
const u = describeRecurrence({ "@type": "RecurrenceRule", frequency: "daily", until: "2026-05-03T00:00:00" } as never);
expect(u).toBe("Daily, until 2026-05-03");
});
it("takes its weekday names from the locale, not a table of English", () => {
setUiLanguageForFormatting("de-DE");
const names = weekdayOptions().map((w) => w.label);
expect(names[0]).toBe("Montag");
expect(names).toHaveLength(7);
// The narrow forms collide in English ("T" for both Tuesday and Thursday),
// which is why they cannot be catalogue keys and come from Intl instead.
expect(weekdayOptions().map((w) => w.short)).toHaveLength(7);
setUiLanguageForFormatting(null);
});
it("renders a translated rule through the catalogue", () => {
setCatalog("de", { strings: { Daily: "Täglich" }, plurals: {} });
expect(describeRecurrence({ "@type": "RecurrenceRule", frequency: "daily" } as never)).toBe("Täglich");
setCatalog("en", { strings: {}, plurals: {} });
});
});

Some files were not shown because too many files have changed in this diff Show More