Compare commits

..
Author SHA1 Message Date
jcoffey 3bfe9396b4 Merge pull request #369 from Coffey-Labs/chore/us-spelling-license
Use American English spelling
2026-09-15 11:49:23 -07:00
jcoffey-dev d1731efdb9 Use American English spelling throughout 2026-09-15 11:45:58 -07:00
jcoffey-dev 6ba89696ee Spell license the US way 2026-09-15 11:35:33 -07:00
jcoffey a7d36e1962 Merge pull request #368 from Coffey-Labs/docs/shorter-readme
Shorter README: an introduction and links
2026-09-15 10:54:17 -07:00
jcoffey-dev 8ce8f0590a Cut the README down to an introduction and links
Running ihasmail is covered on docs.ihasmail.org, now including the
published image, the admin URL and BASE_PATH. Architecture, the mock's
switches and version numbers move to CONTRIBUTING.md, and 0.16.21's
client-visible changes to KNOWN-ISSUES.md. The Gmail comparisons go.
2026-09-15 10:51:55 -07:00
jcoffey 8639e9885b Merge pull request #366 from Coffey-Labs/feat/detect-stalwart-admin-url
Find Stalwart's administration instead of asking for it
2026-09-15 10:07:27 -07:00
jcoffey d3fef4acb7 Merge pull request #365 from Coffey-Labs/docs/schema-route-confirmed
Record the schema route working on production
2026-09-15 10:07:10 -07:00
jcoffey 66892c794d Merge pull request #367 from Coffey-Labs/docs/scrub-server-hostnames
Take the production server's domains out of KNOWN-ISSUES
2026-09-15 10:07:01 -07:00
jcoffey-dev bb27501d70 Take the production server's domains out of KNOWN-ISSUES
The notes on today's live runs named the throwaway addresses and domain
they used, which named the production mail server's domains. What was
tried and what it answered stays; where it was tried does not need to be
public.
2026-09-15 10:04:44 -07:00
jcoffey-dev 2e2724c55c Find Stalwart's administration instead of asking for it
The dashboard's link to Stalwart's own administration needed
STALWART_ADMIN_URL, which an operator had to know to set. Everything it
holds can be read from the server:

- the origin is the host Stalwart advertises in its own session URLs, the
  one people reach it at even when ihasmail talks to it on a private
  address;
- the prefix is where its web interface application is installed. The
  production server's x:Application reads "Stalwart Web Interface",
  enabled, urlPrefix {"/admin", "/account"}, and /admin is also what
  Stalwart writes at first boot.

So, for an account that administers, the account info fetch now asks the
account's own server for its applications and links to origin + /admin/.
An installation whose web interface is disabled or moved gets no link; an
administrator who may not read applications gets Stalwart's default
/admin. It is cached with the rest of the account info.

STALWART_ADMIN_URL and a servers file entry's adminUrl still win, for an
administration that lives somewhere else. A routed domain without one now
takes what its own server said, never the default server's.
2026-09-15 10:01:18 -07:00
jcoffey-dev 74982068b2 Record the schema route working on production
After the deploy, /api/admin/permissions answered with all 661 permissions
Stalwart 0.16.22 publishes, the Roles picker drew them, and the bootstrap
roles' counts read as expected. KNOWN-ISSUES said it had not been tried.
2026-09-15 09:55:59 -07:00
jcoffey 53d9cd37fb Merge pull request #364 from Coffey-Labs/feat/admin-tenants
Add Tenants to Administration, and let an account be put in one
2026-09-15 09:51:05 -07:00
jcoffey 5f28393039 Merge pull request #363 from Coffey-Labs/feat/admin-roles
Add Roles to Administration, with Stalwart's permissions in every language
2026-09-15 09:50:55 -07:00
jcoffey 37a0e28871 Merge pull request #362 from Coffey-Labs/feat/admin-lists
Add Mailing lists to Administration
2026-09-15 09:50:42 -07:00
jcoffey 5a7a8019e9 Merge pull request #361 from Coffey-Labs/feat/admin-groups
Add Groups to Administration
2026-09-15 09:50:28 -07:00
jcoffey d17c9a6e1f Merge pull request #360 from Coffey-Labs/feat/admin-dashboard
Open Administration on a dashboard of what the role can read
2026-09-15 09:48:57 -07:00
jcoffey-dev 5f70e5e8d1 Say tenants are Enterprise only where the installation asks, as the demo will
On a server that is not Enterprise the Tenants page is still only the
notice. On Enterprise the notice is gone -- a real installation that has
tenants has the licence -- unless SHOW_ENTERPRISE_NOTICES=1 asks for it above
the list. The public demo will set it: it reports Enterprise so tenants can be
shown, and should not suggest they come without the licence. The setting
reaches the browser as session.ihasmail.server.enterpriseNotices.
2026-09-15 09:43:04 -07:00
jcoffey-dev 40df0f658b Follow what the live server does with tenants and domains
A run on the production server with throwaway tenants, a role, lists and a
domain, all removed, found three things the source reading had not:

- Something in a tenant has to be on a domain in that tenant (a list in a
  tenant on an unassigned domain is invalidForeignKey), while something in
  no tenant may be on a tenant's domain. The account panel's tenant choice
  offered every tenant; it offers only the domain's now, and a new account
  starts in the tenant of the domain it is made on. The domain list reads
  memberTenantId for it.
- A domain created in a tenant puts its DKIM keys there too, and they keep
  the tenant from being deleted. They are counted with the rest, so Delete
  is not offered while any remain.
- Stalwart lets a domain leave a tenant while the tenant still has accounts
  on it, stranding them. The panel asks first and refuses while any are
  there.

The refusal to delete a tenant that holds anything was confirmed, as were
tenant create, quota pointers, logo and rename. The mock follows the domain
rule, filters DKIM keys by tenant, and KNOWN-ISSUES records the run.

The non-Enterprise notice is now just "Tenants are a Stalwart Enterprise
feature." Two sentences were reworded and one plural added, in all nine
catalogues, and the old sentences are gone.
2026-09-15 09:37:00 -07:00
jcoffey-dev ce5eb04c2d Show only the Enterprise notice on Tenants when the server is not Enterprise
On a server that does not report Enterprise -- or reports no edition --
tenants hold nobody to anything beyond an ordinary user's permissions, so
the page is the notice alone: no New tenant, no search, no list, and no
tenant query is made. The mock's edition is MOCK_EDITION now (default oss,
as before), so MOCK_EDITION=enterprise brings the section back to work on.
2026-09-15 09:31:10 -07:00
jcoffey-dev fd104a1f34 Add Tenants to Administration, and let an account be put in one
A tenant is a separate organisation on one server: its own people,
domains and limits, and an administrator who manages only what is in it.
It gets a section under Access, gated by sysTenantQuery and sysTenantGet,
with a notice on a server that does not report Enterprise, where anyone
inside a tenant is held to an ordinary user's permissions.

The panel edits the tenant's name, logo, role and limits. The logo is an
https address, drawn through the image proxy the strict image policy
requires, or an image data URL. Limits change one quotas/<name> pointer
each, so the four ihasmail does not offer keep their values, and an empty
field is no limit. The role is the most anyone inside can be allowed.

Stalwart keeps no list on a tenant -- each account, group, domain, list and
role names its own -- so what a tenant holds is counted with memberTenantId
queries and shown against its limits. Domains are added and taken out from
the tenant's panel, one memberTenantId change each; only a domain in no
tenant can be added, and its accounts stay where they are. Delete is offered
once every count reads zero.

A tenant does nothing until someone administers it, so the account panel
gains a Tenant choice for an administrator who can read tenants: an
Administrator inside a tenant administers that tenant. Nobody moves their
own account.

The mock has a tenant holding a domain and an administrator, a spare domain
to assign, memberTenantId filters on every query, and Stalwart's rule that
only an administrator outside every tenant may move things into one. A test
of taking a domain back out found that the mock's pointer handling dropped a
top-level null instead of storing it, so nothing had ever been cleared that
way; it stores null now, as the server reads it back.

Nothing about tenants has been written on a live server: production has
none. KNOWN-ISSUES says what was read from source.

Thirty-nine new strings and one plural, in all nine catalogues.
2026-09-15 09:28:39 -07:00
jcoffey-dev 7e46ddeb7d Record the roles run on the live server, and drop the mock's made-up permission
A throwaway role on the production server confirmed the create shape,
one-pointer changes to permissions, bases and name together, the grant
refusal, and the in-use refusal when another role builds on it. It also
showed that a permission name Stalwart does not know fails the whole
update -- which is how jmapEmailSet, carried by the mock since Accounts
was built, turned out not to exist. The mock uses jmapEmailUpdate and now
refuses unknown names against the 0.16.22 snapshot.

Some permissions an administrator holds are never listed by /api/account
(sysLogCreate was granted without complaint), so the picker locks their
Allow; KNOWN-ISSUES says so.
2026-09-15 09:16:49 -07:00
jcoffey-dev a00d07b430 Add Roles to Administration, with Stalwart's permissions in every language
A role is a named set of permissions given to accounts, groups and
tenants. It gets its own section under a new Access heading: every role
listed with the permissions it grants once its bases are followed, and a
panel to create, edit and delete one.

A role builds on others and has everything they grant; a denial anywhere in
the tree wins, which is how Stalwart resolves it (permissions.rs unions
enabled and disabled across the tree, then subtracts). The picker is
Stalwart's own list of permissions, under its headings, searchable and
filterable to what is granted or set here. Each permission is not set,
allowed or denied, and one that is inherited says which role it comes from.
Only permissions the viewer holds can be allowed, because Stalwart refuses
the rest, and a role carrying anything the viewer lacks opens read-only with
no delete, because Stalwart checks a grant but not a delete. Saving sends a
pointer for each permission and base role that changed.

The roles Stalwart hands out by default, read from x:Authentication, say so
before they are changed and cannot be deleted here; a role still in use is
kept by the server, and the refusal names what uses it.

The permission list is Stalwart's schema. A new route, GET
/api/admin/permissions, fetches /api/schema as the signed-in account and
returns only names and labels, behind the same two gates as the registry
methods and held in memory for an hour. Its labels are English only, so
every one of the 661 has a translation in each of the eight other
languages, in its own file keyed by permission name and loaded only when
Roles opens. A permission a later Stalwart adds shows its English label. A
test holds every language to the 0.16.22 snapshot: nothing missing, nothing
stale.

The mock answers x:Role/set with the grant check, loops and in-use
refusals, reads the defaults from x:Authentication, and serves the schema
gzipped as the real one is.

Fifty-two new strings and two plurals in all nine catalogues, and 661
permission labels with 59 headings in each of the eight translations.
2026-09-15 09:13:05 -07:00
jcoffey-dev 627422d794 Add Mailing lists to Administration
A mailing list is an address that passes mail on to everyone on it. To
Stalwart it is its own object, x:MailingList, behind sysMailingList*, so
it gets its own section under Directory after Groups: search, fifty to a
page with each list's recipient count, and a panel to create, edit and
delete one.

Recipients are a property of the list, so unlike a group's members they
save with the rest of the panel. What Save sends for them is only what was
added and removed, one recipients/<address> pointer each -- the patch the
live server accepted -- so a recipient added elsewhere while the panel was
open is not taken out. They can be pasted several at a time, from a
spreadsheet column, a comma-separated line or Name <address>; anything with
an @ that is not an address stays in the box with a note. Past a dozen, a
filter narrows them.

That is all a list is in Stalwart -- no owners, moderation or posting
rules -- so that is all the panel offers.

The mock answers x:MailingList with two lists, the recipient set's live
shape, and the refusals a wrong address, a clash with an account and a
missing permission get.

Twenty-five new strings and one plural, in all nine catalogues.
2026-09-15 08:47:04 -07:00
jcoffey-dev 79afc334ab Record the groups run on the live server, and match its refusal shape
A throwaway group on the production server confirmed what the code was
built on: a Group account with Default roles, membership as a pointer on
the member, the members query, and a delete refused while a member still
names the group. Its objectId is an {object, id} pair rather than a bare
id; the mock answers the same way now.
2026-09-15 08:37:39 -07:00
jcoffey-dev e2a531b615 Add Groups to Administration
A group is a shared address and mailbox and the people who share it. To
Stalwart it is an x:Account of type Group, behind the same sysAccount*
permissions as a person, so it sits under Directory beside Accounts:
search, a page of fifty with each group's member count, and a panel to
create, edit and delete one.

Membership lives on the member, not the group. Members are the users whose
memberGroupIds name it, and adding or removing one is a single
memberGroupIds/<group> pointer on that user's account -- true or null --
which leaves their other groups alone. Changes apply straight away rather
than riding on Save, so the list is always what the server has. Nobody can
add or remove themselves, the same line the account panel draws at one's
own role.

A group's role is Default or Custom, not a person's User or Admin, and it
is what the group may do: in 0.16 a user's permissions come from their own
roles only, and a group gives its members what is shared with it. Only
roles the viewer could grant are offered.

Delete takes the members out first and then deletes the group, the order
a domain's keys go before the domain, because the registry keeps anything
another object names. A role that cannot change the members' accounts is
not offered a delete it could only half finish.

The mock's groups had a person's roles, accepted a memberGroupIds filter
without applying it, and answered a linked delete with the wrong shape;
all three follow the source now, and it refuses nested groups and
memberships of things that are not groups.

Nothing about groups has been run against a live server yet: production
has none, and every operation is a write. KNOWN-ISSUES says what was read
from source.

Thirty-five new strings, two of them plurals, in all nine catalogues.
2026-09-15 08:31:36 -07:00
jcoffey-dev 4787e8bf12 Point from the dashboard to Stalwart's own administration
A line under the cards says where the rest is: detailed metrics, the
delivery queue, logs and server settings are in Stalwart's own
administration. It links there when the operator sets STALWART_ADMIN_URL,
and stays plain text otherwise, because STALWART_URL is how this server
reaches Stalwart and is often an address no browser can open.

Several servers: a servers file entry may now be an object,
{"url": ..., "adminUrl": ...}, and a session routed to that server gets its
adminUrl. A routed domain without one gets no link rather than the default
server's, for the same reason routing never falls back. The URL is sent
only to a session that may administer.

The shipped example file stopped the server at startup: its "_comment"
key was read as a domain and refused as not a URL, while the test that
checks the example skipped it. Keys starting with an underscore are notes
now -- no mail domain starts with one -- and the example is also loaded
through the real parser in a test, so the two cannot disagree again.

Two new strings, in all nine catalogues.
2026-09-15 08:16:52 -07:00
jcoffey-dev 0054b8a3ce Open Administration on a dashboard of what the role can read
Administration used to open on its first section. It opens on a grid of
cards now: users, domains, messages waiting in the delivery queue, server
memory, and the last 24 hours' received and sent. Each card is there only
when the role holds what its number needs -- a count is a query, the
metric history a query and a get -- so a helpdesk role that reads accounts
and domains sees those two cards and nothing about the server.

What the cards count is whatever Stalwart answers for the signed-in
account, which scopes a tenant administrator's accounts, domains and queue
to the tenancy. The metric history has no tenant in it, and Stalwart's
Tenant Administrator role does not hold it, so a tenant's dashboard is
users, domains and pending.

The history is Enterprise-only and switched off by default. A server that
refuses it leaves those cards off; one that records nothing says so rather
than showing zeroes. Received and sent add up the queue counters Stalwart's
own dashboard uses, filtered with the comparison names the live server
accepts (a bare timestamp is unsupportedFilter). The column count follows
the number of cards so rows stay even, and falls back by the grid's own
width rather than the window's.

The server's test for whether an account is offered Administration matches
the client's again, now that a count is enough. The mock answers the queue
and an hourly history ending in the current hour; MOCK_METRICS=off refuses
the history as Community does, a tenant administrator gets the queue, and
helpdesk reads domains, as the demo's does.

ROADMAP and FEATURES said reporting and queues were out of scope; they say
the dashboard reads a handful of numbers and that managing queues, logs
and settings stays out. KNOWN-ISSUES records what was settled on the live
server and what was only read from source.

Fourteen new strings, in all nine catalogues.
2026-09-15 08:06:59 -07:00
jcoffey bb8d6eb92d Merge pull request #359 from Coffey-Labs/fix/keyboard-keyless-keydown
Ignore a keydown that carries no key
2026-09-15 07:29:33 -07:00
jcoffey 877566f1cd Merge pull request #358 from Coffey-Labs/fix/contacts-resizable-list
Let the contact list be resized, and give the contact the rest of the page
2026-09-15 07:28:06 -07:00
jcoffey-dev 8e9ca0498a Ignore a keydown that carries no key
Picking a saved login from Chrome's password autofill dispatches a plain
Event named "keydown", with no key on it. The shortcut listener passed it to
comboOf, which read the key's length and threw -- an uncaught TypeError in
the console on every sign-in. Harmless, since nothing was bound to it, but
it was noise that looks like a real fault.

comboOf now returns null for an event with no key, as it already does for a
bare modifier, so the listener stops there.
2026-09-15 07:27:12 -07:00
jcoffey-dev 95395200a3 Let the contact list be resized, and give the contact the rest of the page
The contacts grid still had three columns from when the address books sat
inside the view: 220px for them, 280-360px for the list, the rest for the
contact. The books moved to the app's left pane in 350f4f4 and the grid
never followed, so the list was squeezed into the books' 220px, truncating
names, the contact was held to 360px, and the remaining width sat empty.

It is two columns now, with the same splitter as the message list between
them: drag between 240px and the width that leaves 360px for the contact,
arrow keys move it, double-click puts it back to 320px. The width is a
device setting beside the mail list's, so it is kept by a device marked as
your own and never synced. The splitter is hidden where contacts show one
pane at a time. The unused .contacts-books rules are gone.

"Resize contact list" is in all nine catalogues.
2026-09-15 07:24:56 -07:00
jcoffey 14e22c21fe Merge pull request #354 from Coffey-Labs/dependabot/npm_and_yarn/jsdom-30.0.1
Bump jsdom from 26.1.0 to 30.0.1
2026-09-15 07:17:46 -07:00
dependabot[bot] b7b2455994 Bump jsdom from 26.1.0 to 30.0.1
Bumps [jsdom](https://github.com/jsdom/jsdom) from 26.1.0 to 30.0.1.
- [Release notes](https://github.com/jsdom/jsdom/releases)
- [Commits](https://github.com/jsdom/jsdom/compare/v26.1.0...v30.0.1)

---
updated-dependencies:
- dependency-name: jsdom
  dependency-version: 30.0.1
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-09-15 14:15:26 +00:00
jcoffey 7d96cf22ac Merge pull request #353 from Coffey-Labs/dependabot/npm_and_yarn/vitest-5.0.0
Bump vitest from 4.1.11 to 5.0.0
2026-09-15 07:14:09 -07:00
jcoffey a4022b37ce Merge pull request #352 from Coffey-Labs/dependabot/npm_and_yarn/lucide-react-1.45.0
Bump lucide-react from 0.477.0 to 1.45.0
2026-09-15 07:13:25 -07:00
jcoffey 33d966ba44 Merge pull request #351 from Coffey-Labs/dependabot/npm_and_yarn/concurrently-10.0.5
Bump concurrently from 9.2.4 to 10.0.5
2026-09-15 07:12:53 -07:00
jcoffey 1bf6350d68 Merge pull request #350 from Coffey-Labs/dependabot/npm_and_yarn/minor-and-patch-e9d406726e
Bump @tanstack/react-virtual from 3.14.11 to 3.14.12 in the minor-and-patch group
2026-09-15 07:11:52 -07:00
jcoffey b735685416 Merge pull request #357 from Coffey-Labs/feat/move-folder-picker
Move a folder from its menu, with the same picker as moving mail
2026-09-15 07:11:09 -07:00
jcoffey-dev 0859936f27 Move a folder from its menu, with the same picker as moving mail
A folder could only be moved by dragging it, which is slow in a long list
and not offered at all on a touch screen. Its menu now has "Move to…",
which opens the searchable folder picker that moving messages already
uses, with a "Top level" row above the folders.

The picker lists only legal destinations: the same rules as a drop -- not
into itself, its own subtree or the parent it already has -- plus the
rights a picker has to check up front because it shows every folder at
once: mayRename on the folder being moved, which RFC 8621 uses for
reparenting, and mayCreateChild on the destination. Both only say no on
shared mail. The move itself goes through the same path as a drop, so the
toast and the expanded destination are unchanged.

"Move “{name}” to…" and "Top level" are in all nine catalogues.

Closes #355
2026-09-15 07:00:12 -07:00
dependabot[bot] 1a4377de4a Bump vitest from 4.1.11 to 5.0.0
Bumps [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) from 4.1.11 to 5.0.0.
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v5.0.0/packages/vitest)

---
updated-dependencies:
- dependency-name: vitest
  dependency-version: 5.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-09-15 09:12:21 +00:00
dependabot[bot] 860e89fa6f Bump lucide-react from 0.477.0 to 1.45.0
Bumps [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) from 0.477.0 to 1.45.0.
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.45.0/packages/lucide-react)

---
updated-dependencies:
- dependency-name: lucide-react
  dependency-version: 1.45.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-09-15 09:12:07 +00:00
dependabot[bot] 61916b3a3a Bump concurrently from 9.2.4 to 10.0.5
Bumps [concurrently](https://github.com/open-cli-tools/concurrently) from 9.2.4 to 10.0.5.
- [Release notes](https://github.com/open-cli-tools/concurrently/releases)
- [Commits](https://github.com/open-cli-tools/concurrently/compare/v9.2.4...v10.0.5)

---
updated-dependencies:
- dependency-name: concurrently
  dependency-version: 10.0.5
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-09-15 09:11:57 +00:00
dependabot[bot] 307752921f Bump @tanstack/react-virtual in the minor-and-patch group
Bumps the minor-and-patch group with 1 update: [@tanstack/react-virtual](https://github.com/TanStack/virtual/tree/HEAD/packages/react-virtual).


Updates `@tanstack/react-virtual` from 3.14.11 to 3.14.12
- [Release notes](https://github.com/TanStack/virtual/releases)
- [Changelog](https://github.com/TanStack/virtual/blob/main/packages/react-virtual/CHANGELOG.md)
- [Commits](https://github.com/TanStack/virtual/commits/@tanstack/[email protected]/packages/react-virtual)

---
updated-dependencies:
- dependency-name: "@tanstack/react-virtual"
  dependency-version: 3.14.12
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-09-15 09:11:52 +00:00
jcoffey 7940a15a43 Merge pull request #349 from Coffey-Labs/i18n/template-literal-attributes
Translate English built from template literals in attributes
2026-09-14 08:28:18 -07:00
jcoffey-dev fecae2acd3 Translate English built from template literals in attributes
i18n-literals now flags a template literal in a UI attribute or prop when
there are words between its values: `Remove ${email}`, `${name} — shared by
${owner}`. It cannot be a catalogue key as written, so neither the key
exemption nor the sentence-shape test applies. A template that is only
punctuation around values, like `${name} (${size})`, is left alone.

The twelve it found are now keys with placeholders: the quota bar title,
the address menu's label, a folder's subfolder unread count, a recipient
chip's remove button, the contact editor's title, shared and available
calendars and address books, the date and time fields' labels, the
attachment title's fallback name, and the free/busy bar. The bar showed
the raw JMAP busyStatus ("confirmed") and now says Busy, Tentative or
Unavailable.

11 new keys in all nine catalogues. Remove {address}, Date, Time, Busy and
Tentative already existed.
2026-09-14 08:26:34 -07:00
jcoffey aa57c59703 Merge pull request #348 from Coffey-Labs/i18n/literal-check-component-props
Check component props for untranslated literals, and fail on a finding
2026-09-14 08:10:46 -07:00
jcoffey-dev ac4c4bd267 Check component props for untranslated literals, and fail on a finding
i18n-literals checked title, aria-label, placeholder and alt on elements,
but not the same English passed to a component, so a MenuItem label or a
Popover ariaLabel written as a literal went through. It also excused a
literal that happened to be a catalogue key. That exemption is meant for
English held in a constant and translated where it renders, and a literal
written straight into a JSX attribute has no such render site. No
component passes its props through t(). And neither half of i18n:check
was run with --check, so a finding printed and the script still exited 0.

Component props are checked now, a key no longer excuses a literal in an
attribute, and both scripts run with --check. That found 28 strings
rendering English in every language: 19 already had keys and are wrapped,
and 9 are new keys in all nine catalogues. The contact editor's Save and
Saving… buttons are wrapped as well, on the same line.
2026-09-14 08:03:12 -07:00
jcoffey af092b3942 Merge pull request #347 from Coffey-Labs/feat/resizable-sidebar
Let the sidebar be resized by dragging its edge
2026-09-14 07:56:59 -07:00
jcoffey f0039c87fe Merge pull request #346 from Coffey-Labs/ci/weekly-release-off-the-hour
Move the weekly release off the top of the hour
2026-09-14 07:56:52 -07:00
jcoffey-dev abb07acc80 Let the sidebar be resized by dragging its edge
The sidebar's right edge is now a splitter, like the one between the
message list and the reading pane: drag it between 240 and 480px, move it
with the arrow keys, double-click to put it back. The width is a device
setting, and stays null until someone drags, so a width set in the
reader's own CSS through --sidebar-w is kept until they choose otherwise.
Hidden on a phone, where the sidebar is a drawer, and while collapsed.

Arrow keys on either splitter moved the pane and never saved it: the
keyboard path called onResize without onEnd. It ends each key press now,
and both views keep the in-progress size in a ref as well as state, so
the end reads the value set in the same tick.

The message-list splitter's accessible name was an untranslated literal.
It goes through translate() now, and it and the sidebar's new name are in
all nine catalogues.

Closes #345
2026-09-14 07:54:56 -07:00
jcoffey-dev e1f0904184 Move the weekly release off the top of the hour
The 09:00 UTC schedule competes for GitHub's busiest slot. The first
scheduled run started almost six hours late, and on 2026-09-14 no run had
started four and a half hours in, so that week was cut by hand. 09:17 is
still best-effort, but no longer queues behind every on-the-hour schedule.
2026-09-14 06:40:07 -07:00
222 changed files with 18304 additions and 1815 deletions
+1 -1
View File
@@ -7,7 +7,7 @@ on:
# Without this there is no way to re-run a check that never started: a run # 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 # 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") # Actions outage on 2026-08-26 -- can be neither rerun ("already running")
# nor cancelled ("already completed"), and the workflow has no other trigger # nor canceled ("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 # 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. # change, without pushing an empty commit to move it.
workflow_dispatch: workflow_dispatch:
+2 -2
View File
@@ -4,7 +4,7 @@
# `ghcr.io/coffey-labs/ihasmail:latest` for a long time, and nothing ever # `ghcr.io/coffey-labs/ihasmail:latest` for a long time, and nothing ever
# pushed it: `docker pull` answered `denied`, because the package did not # pushed it: `docker pull` answered `denied`, because the package did not
# exist. This is the workflow that makes those instructions true. It is also # exist. This is the workflow that makes those instructions true. It is also
# the prerequisite for the self-hosted app catalogues -- TrueNAS and Unraid # the prerequisite for the self-hosted app catalogs -- TrueNAS and Unraid
# both install by pulling an image and neither builds from source. # 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 # FIRST RUN: a package GHCR creates for the first time is **private**, even in
@@ -44,7 +44,7 @@ on:
type: boolean type: boolean
default: false default: false
# Same reasoning as ci.yml's dispatch trigger: a run GitHub queues and then # 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 # orphans can be neither rerun nor canceled, and this workflow otherwise
# only fires on a release -- which is not something to cut twice because a # 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 # runner died. `ref` also allows publishing an image for a tag that predates
# this workflow, which is how the first one gets built. # this workflow, which is how the first one gets built.
+14 -6
View File
@@ -13,13 +13,21 @@ name: Weekly release
on: on:
schedule: schedule:
# Mondays, 09:00 UTC. GitHub runs scheduled jobs on a best-effort basis and # Mondays, 09:17 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 # 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 # the exact minute as a promise. The odd minute is deliberate: the top of
# workflows in a repository with no activity for 60 days -- not a concern # the hour is when most schedules fire, and at 09:00 the first scheduled
# while this one is being worked on weekly, but it is why a silent stop is # run started almost six hours late and the second had not started at all
# worth checking for before assuming the file is broken. # four and a half hours in. Moving off the hour does not make GitHub keep
- cron: "0 9 * * 1" # time, but it stops competing for the busiest slot. A missed week can be
# cut by hand with workflow_dispatch; a late scheduled run that follows
# finds the tag already there and does nothing.
#
# 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: "17 9 * * 1"
workflow_dispatch: workflow_dispatch:
inputs: inputs:
dry_run: dry_run:
+6 -6
View File
@@ -84,23 +84,23 @@ violet #6c71c4 · blue #268bd2 · cyan #2aa198 · green #859900
The accents are shared by both modes by design. Two tiers are **derived**: the 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 sunken dark surface #001f28 (below base03) and the raised light surface
#fffdf6 (above base3), neither of which Solarized publishes, plus the two #fffdf6 (above base3), neither of which Solarized publishes, plus the two
rule colours #0d4552 and #e6dfc8. rule colors #0d4552 and #e6dfc8.
## Everforest — sainnhe/everforest, MIT (palette.md), medium contrast ## Everforest — sainnhe/everforest, MIT (palette.md), medium contrast
### Dark ### Dark
bg_dim #232a2e · bg0 #2d353b · bg1 #343f44 · bg3 #475258 bg_dim #232a2e · bg0 #2d353b · bg1 #343f44 · bg3 #475258
fg #d3c6aa · grey1 #859289 fg #d3c6aa · gray1 #859289
red #e67e80 · orange #e69875 · yellow #dbbc7f · green #a7c080 · aqua #83c092 red #e67e80 · orange #e69875 · yellow #dbbc7f · green #a7c080 · aqua #83c092
blue #7fbbb3 · purple #d699b6 blue #7fbbb3 · purple #d699b6
### Light ### Light
bg_dim #efebd4 · bg0 #fdf6e3 · bg3 #e6e2cc · bg5 #bdc3af bg_dim #efebd4 · bg0 #fdf6e3 · bg3 #e6e2cc · bg5 #bdc3af
fg #5c6a72 · grey1 #939f91 fg #5c6a72 · gray1 #939f91
red #f85552 · orange #f57d26 · yellow #dfa000 · green #8da101 · aqua #35a77c red #f85552 · orange #f57d26 · yellow #dfa000 · green #8da101 · aqua #35a77c
blue #3a94c5 · purple #df69ba blue #3a94c5 · purple #df69ba
Light uses bg_dim as the page and bg0 as the raised surface, so the card the 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. reader looks at is the color Everforest calls its background.
## Kanagawa — rebelot/kanagawa.nvim, MIT (lua/kanagawa/colors.lua) ## Kanagawa — rebelot/kanagawa.nvim, MIT (lua/kanagawa/colors.lua)
### Wave (dark) ### Wave (dark)
@@ -118,7 +118,7 @@ lotusGreen #6f894e · lotusYellow #77713f · lotusPink #b35b79
## Ayu — ayu-theme/ayu-colors, MIT (themes/dark.yaml, themes/light.yaml) ## 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 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 roles as references (`$palette.indigo.l2`), and the resolved files are not
committed. The two signature accents are taken from the same organisation's committed. The two signature accents are taken from the same organization's
MIT-licensed ayu-theme/vscode-ayu build. MIT-licensed ayu-theme/vscode-ayu build.
### Dark ### Dark
@@ -134,7 +134,7 @@ red #F07171 · orange #FA8532 · yellow #EBA400 · green #86B300 · teal #4CBF99
indigo #55B4D4 · blue #22A4E6 · purple #A37ACC · accent #F29718 (vscode-ayu) indigo #55B4D4 · blue #22A4E6 · purple #A37ACC · accent #F29718 (vscode-ayu)
## Primer — primer/primitives, MIT (src/tokens/base/color/{dark,light}) ## Primer — primer/primitives, MIT (src/tokens/base/color/{dark,light})
Named "Primer" after the design system. The colour values are MIT; "GitHub" Named "Primer" after the design system. The color values are MIT; "GitHub"
and the Invertocat are trademarks, and nothing here is endorsed by them. and the Invertocat are trademarks, and nothing here is endorsed by them.
### Dark ### Dark
+81 -8
View File
@@ -1,6 +1,6 @@
# Contributing to ihasmail # Contributing to ihasmail
Thanks for your interest in contributing to **ihasmail** — a Gmail-style, JMAP-only webmail client for [Stalwart Mail Server](https://stalw.art/). Contributions of all kinds are welcome: bug reports, feature requests, code, documentation, and testing. Thanks for your interest in contributing to **ihasmail** — an immutable, JMAP-only webmail client for [Stalwart Mail Server](https://stalw.art/). Contributions of all kinds are welcome: bug reports, feature requests, code, documentation, and testing.
## Code of Conduct ## Code of Conduct
@@ -30,7 +30,7 @@ Before opening a new issue, please search [existing issues](https://github.com/C
Open an issue describing: Open an issue describing:
- The problem you're trying to solve (not just the solution) - The problem you're trying to solve (not just the solution)
- How it fits with ihasmail's JMAP-only, Gmail-style design philosophy - How it fits with ihasmail's JMAP-only, nothing-to-persist design
- Any relevant JMAP RFC references (RFC 8620, RFC 8621) if the feature touches protocol behavior - Any relevant JMAP RFC references (RFC 8620, RFC 8621) if the feature touches protocol behavior
For larger changes, please open an issue to discuss the approach **before** submitting a pull request — this saves everyone time if the direction needs adjusting. For larger changes, please open an issue to discuss the approach **before** submitting a pull request — this saves everyone time if the direction needs adjusting.
@@ -74,11 +74,11 @@ failing, so an untranslated string is invisible until somebody reading that
language finds it. language finds it.
**Any change that adds or alters a user-visible string adds work in all nine **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 catalogs.** 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, count before and after — and say so just as explicitly when a change adds none,
so it is never left to be inferred. so it is never left to be inferred.
#### The catalogue key for a plural is the `other` form #### The catalog key for a plural is the `other` form
`plural()` looks the entry up by `forms.other`, so a call site written as `plural()` looks the entry up by `forms.other`, so a call site written as
@@ -86,13 +86,13 @@ so it is never left to be inferred.
plural(n, { one: "Deleted {n} contact", other: "Deleted {n} contacts" }) plural(n, { one: "Deleted {n} contact", other: "Deleted {n} contacts" })
``` ```
is keyed on **`"Deleted {n} contacts"`**. Keying the catalogue on the `one` is keyed on **`"Deleted {n} contacts"`**. Keying the catalog on the `one`
form type-checks, builds, passes every test, and silently falls back to English 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 in all nine languages. Nothing errors. The only signal is the fallback count
going up, so read it: going up, so read it:
```sh ```sh
npm run i18n:check # literals wrapped, and catalogue health npm run i18n:check # literals wrapped, and catalog health; exits 1 on a finding
node scripts/i18n-catalog-check.mjs # per-language: translated / used / falling back node scripts/i18n-catalog-check.mjs # per-language: translated / used / falling back
``` ```
@@ -122,10 +122,83 @@ examples in `web/src/views/*/__tests__/`.
git clone https://github.com/YOUR-USERNAME/ihasmail.git git clone https://github.com/YOUR-USERNAME/ihasmail.git
cd ihasmail cd ihasmail
``` ```
2. Point your local instance at a running Stalwart Mail Server (a test/dev instance is strongly recommended — do not develop against a production mailbox). 2. Point your local instance at a running Stalwart Mail Server (a test/dev instance is strongly recommended — do not develop against a production mailbox), or use the built-in mock below.
3. Follow the setup instructions in the repository's `README.md` for installing dependencies and running the app locally. 3. Install and run, as below.
4. Verify your changes don't break existing JMAP calls by exercising core flows: login, list/read mail, send, search, and folder/label operations. 4. Verify your changes don't break existing JMAP calls by exercising core flows: login, list/read mail, send, search, and folder/label operations.
Requirements: Node ≥ 20.19 (26 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
npm run typecheck # tsc for both packages
npm test # vitest (web) + node:test (server)
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.
#### Architecture
```
browser ──(same-origin /api/*)──► ihasmail server (Node + Hono) ──(JMAP over HTTPS)──► Stalwart
React SPA • session cookie ⇄ Basic auth
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` (sanitizer, 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.
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`. Features degrade gracefully when one is missing.
#### The mock
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.
| Switch | What it does |
| --- | --- |
| `MOCK_NO_FUTURE_RELEASE=1` | Advertises FUTURERELEASE, then drops every hold |
| `MOCK_NO_REGISTRY=1` | Omits the Stalwart capability, so the sign-in refusal can be tested |
| `MOCK_NO_SCHEDULING_SEND=1` | Refuses a calendar write that asks for scheduling messages, as for an account without that permission |
| `MOCK_ROLE` | Who the demo user is for Administration: `admin` (the default), `tenant-admin`, `helpdesk` or `user` |
| `MOCK_METRICS=off` | Refuses the dashboard's metric history, as Community does |
| `MOCK_EDITION=enterprise` | Reports Enterprise, which Tenants needs |
It tracks the current Stalwart release rather than 0.16 in general, and each
behavior 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
behavior is rewritten rather than deleted, so the reversal stays on the record.
#### Version numbers
`2026.8.30+pr129` is the date of the commit a build came from and the pull
request that commit arrived through; a commit that did not come through one
carries its short SHA instead (`2026.8.30+g1fa6578`). It is worked out from git
at build time — nothing writes a version into the tree, and `package.json` stays
at `0.0.0`. `node scripts/version.mjs` prints it for the current checkout.
The PR number sits after the `+` as build metadata because it records where a
build came from, not how new it is. The version says nothing about Stalwart on
purpose: what a build needs from the server is stated in the README badge and
in [KNOWN-ISSUES.md](KNOWN-ISSUES.md). Building an image with the version on it,
and the single-host `deploy.example.sh`, are covered in
[Installing](https://docs.ihasmail.org/install/).
## Review Process ## Review Process
- A maintainer will review your PR and may request changes. - A maintainer will review your PR and may request changes.
+234 -70
View File
@@ -13,7 +13,7 @@ questions:
| [docs.ihasmail.org](https://docs.ihasmail.org) | How to install, configure and drive each of these | | [docs.ihasmail.org](https://docs.ihasmail.org) | How to install, configure and drive each of these |
Written against the tree at Stalwart **0.16.22**, which is the version the live Written against the tree at Stalwart **0.16.22**, which is the version the live
instance runs. Behaviours carrying an older version below were checked against instance runs. Behaviors carrying an older version below were checked against
that one and have not changed since; where a later release changed something, that one and have not changed since; where a later release changed something,
the entry says so and names both. 0.16.22 changed nothing described here: its the entry says so and names both. 0.16.22 changed nothing described here: its
client-visible changes are in what `CalendarEvent/get` and `ContactCard/get` client-visible changes are in what `CalendarEvent/get` and `ContactCard/get`
@@ -71,9 +71,11 @@ per-account shape.
## Layout ## Layout
Three panes: folder tree, message list, reading pane. The splitter between the Three panes: folder tree, message list, reading pane. The splitter between the
list and the reading pane is dragged to resize, and the size is remembered per list and the reading pane is dragged to resize, and so is the edge of the
device — a width chosen on a 27" monitor is wrong on a laptop, so it is one of sidebar, between 240 and 480px; arrow keys move either one, and a double-click
the few settings that does not follow the account. puts it back. The sizes are remembered per device — a width chosen on a 27"
monitor is wrong on a laptop, so they are among the few settings that do not
follow the account.
- **Reading pane** right of the list, below it, or off (messages open full width). - **Reading pane** right of the list, below it, or off (messages open full width).
- **Density** comfortable, cozy or compact, which changes row height as well as padding. - **Density** comfortable, cozy or compact, which changes row height as well as padding.
@@ -101,7 +103,7 @@ every drag.
archives and left deletes by default, which is what the mail app the phone archives and left deletes by default, which is what the mail app the phone
came with already does. Either direction can be set to archive, delete, came with already does. Either direction can be set to archive, delete,
report spam, read/unread, star or move to… — or to nothing, which turns that report spam, read/unread, star or move to… — or to nothing, which turns that
direction off. The coloured strip revealed behind the row names what will direction off. The colored strip revealed behind the row names what will
actually happen *in the folder it is happening in*: "Delete forever" out of actually happen *in the folder it is happening in*: "Delete forever" out of
Deleted Items, "Not spam" inside Junk Mail. Where an action Deleted Items, "Not spam" inside Junk Mail. Where an action
is meaningless there — archiving out of the archive, calling your own drafts is meaningless there — archiving out of the archive, calling your own drafts
@@ -141,14 +143,14 @@ it is silently nothing there.
The arithmetic lives in `web/src/lib/touch.ts`, away from the components and The arithmetic lives in `web/src/lib/touch.ts`, away from the components and
under test, because the numbers are the whole thing. The axis lock is under test, because the numbers are the whole thing. The axis lock is
deliberately biased towards the vertical: scrolling is what a finger on a deliberately biased toward the vertical: scrolling is what a finger on a
message list is doing almost every time, and a scroll misread as a swipe grabs message list is doing almost every time, and a scroll misread as a swipe grabs
the list out from under the reader, while a swipe misread as a scroll costs one the list out from under the reader, while a swipe misread as a scroll costs one
more attempt. A drag that is merely more sideways than not stays a scroll. more attempt. A drag that is merely more sideways than not stays a scroll.
## The message list ## The message list
- **Virtualised** — rows are windowed with `@tanstack/react-virtual`, so a - **Virtualized** — rows are windowed with `@tanstack/react-virtual`, so a
folder of 100,000 messages scrolls at the same speed as one of ten. Row folder of 100,000 messages scrolls at the same speed as one of ten. Row
height follows density and the one- or two-line layout. height follows density and the one- or two-line layout.
- **Infinite scroll** with server-side paging, 50 at a time by default. - **Infinite scroll** with server-side paging, 50 at a time by default.
@@ -234,7 +236,7 @@ for that one, and the dialog says so.
## Folders ## Folders
Real JMAP mailboxes, with the server's roles honoured. Real JMAP mailboxes, with the server's roles honored.
- Create, rename, create a subfolder, delete (with or without its mail). - Create, rename, create a subfolder, delete (with or without its mail).
- **Drag a folder onto another** to reparent it. Folders with a server role - **Drag a folder onto another** to reparent it. Folders with a server role
@@ -244,18 +246,18 @@ Real JMAP mailboxes, with the server's roles honoured.
unsubscribed folder still exists and still receives; it is just out of the unsubscribed folder still exists and still receives; it is just out of the
way. Inbox cannot be hidden. way. Inbox cannot be hidden.
- **Mark all as read**, optionally including subfolders. - **Mark all as read**, optionally including subfolders.
- **Folder colours**, per mailbox id. - **Folder colors**, per mailbox id.
- **Unread counts** per folder, live. - **Unread counts** per folder, live.
- **Storage quota** bar under the tree where the server reports one. - **Storage quota** bar under the tree where the server reports one.
- Rights are respected per folder: rename, delete, create-child and share each - Rights are respected per folder: rename, delete, create-child and share each
grey out when `myRights` says no. gray out when `myRights` says no.
- A folder in the address that this account does not have says *this folder is - A folder in the address that this account does not have says *this folder is
missing*, rather than drawing an empty folder — a stale link should not read missing*, rather than drawing an empty folder — a stale link should not read
as a folder that emptied itself. as a folder that emptied itself.
## Labels ## Labels
Labels are **IMAP keywords** with a colour and a display name kept in settings. Labels are **IMAP keywords** with a color and a display name kept in settings.
Because they are keywords, every other client that reads the mailbox sees them, Because they are keywords, every other client that reads the mailbox sees them,
and they survive ihasmail entirely. A message can carry any number. They are and they survive ihasmail entirely. A message can carry any number. They are
managed in Settings Labels, applied from `l` or the context menu, and managed in Settings Labels, applied from `l` or the context menu, and
@@ -309,7 +311,7 @@ same query string — so what it builds can be read, edited and learned from.
## Reading a message ## Reading a message
- **Sanitised HTML**, rendered inside a **Shadow DOM** so the sender's CSS - **Sanitized HTML**, rendered inside a **Shadow DOM** so the sender's CSS
cannot reach the app. DOMPurify strips scripts, event handlers, forms and cannot reach the app. DOMPurify strips scripts, event handlers, forms and
anything that could navigate the top window. anything that could navigate the top window.
- **Remote images blocked by default**, with a banner offering *Show images* or - **Remote images blocked by default**, with a banner offering *Show images* or
@@ -368,14 +370,14 @@ same query string — so what it builds can be read, edited and learned from.
since the filter applies policy ihasmail cannot see. Mail that arrived without since the filter applies policy ihasmail cannot see. Mail that arrived without
these headers shows nothing. these headers shows nothing.
- **Message body theming** is off by default — sender HTML is left exactly as it - **Message body theming** is off by default — sender HTML is left exactly as it
was designed, on a light card. One setting lets mail that brings no colours of was designed, on a light card. One setting lets mail that brings no colors of
its own follow the app's theme instead. That is a low bar in practice: one its own follow the app's theme instead. That is a low bar in practice: one
`color:#FFFFFF` on one button label opts a whole message out, so for mail `color:#FFFFFF` on one button label opts a whole message out, so for mail
built from a template it changed nothing. A second setting, off unless the built from a template it changed nothing. A second setting, off unless the
first is on, forces the theme over the sender's own colours. It tells a first is on, forces the theme over the sender's own colors. It tells a
*sheet* the design sits on, like a white wrapper table, from a *painted *sheet* the design sits on, like a white wrapper table, from a *painted
surface* like a button or a banner, by relative luminance: the first is surface* like a button or a banner, by relative luminance: the first is
neutralised so the bright card goes away, the second is kept whole so its neutralized so the bright card goes away, the second is kept whole so its
label stays readable on it. Nothing the sender wrote is removed, so the label stays readable on it. Nothing the sender wrote is removed, so the
switch is reversible, and print is unaffected either way. switch is reversible, and print is unaffected either way.
@@ -395,7 +397,7 @@ same query string — so what it builds can be read, edited and learned from.
- **Invitations (iTIP)** render an invite card: what, when, where, the guest - **Invitations (iTIP)** render an invite card: what, when, where, the guest
list with each person's status, and Yes / Maybe / No. The reply is written to list with each person's status, and Yes / Maybe / No. The reply is written to
the event and sent back to the organiser. Cancellations are recognised too. the event and sent back to the organizer. Cancellations are recognized too.
- **vCard attachments** render a card offering to add the person to an address - **vCard attachments** render a card offering to add the person to an address
book. book.
- **Right-click anyone named** in the message — From, To, Cc, Bcc or Reply-To — - **Right-click anyone named** in the message — From, To, Cc, Bcc or Reply-To —
@@ -425,9 +427,9 @@ Requesting one on your own outgoing mail is a separate switch.
## Composing ## Composing
**Multiple composers at once**, floating in a dock at the bottom right, each **Multiple composers at once**, floating in a dock at the bottom right, each
minimisable and maximisable; full-screen on mobile. minimizable and maximizable; full-screen on mobile.
- **Rich text**: bold, italic, underline, strikethrough, text colour, highlight, - **Rich text**: bold, italic, underline, strikethrough, text color, highlight,
font size, alignment, bulleted and numbered lists, indent/outdent, blockquote, font size, alignment, bulleted and numbered lists, indent/outdent, blockquote,
code block, links (`Ctrl+K`), inline images, an emoji picker, and remove code block, links (`Ctrl+K`), inline images, an emoji picker, and remove
formatting. Tab and Shift+Tab indent inside the body. formatting. Tab and Shift+Tab indent inside the body.
@@ -466,7 +468,7 @@ minimisable and maximisable; full-screen on mobile.
- **Attachments** by picking or dragging onto the composer, with progress per - **Attachments** by picking or dragging onto the composer, with progress per
file and the size limit the server states (`MAX_UPLOAD_BYTES`, 50 MB by file and the size limit the server states (`MAX_UPLOAD_BYTES`, 50 MB by
default). A pasted image is inserted inline instead, and pasted HTML is default). A pasted image is inserted inline instead, and pasted HTML is
sanitised on the way in. sanitized on the way in.
- **Attach from Files** — anything the server already holds attaches with **no - **Attach from Files** — anything the server already holds attaches with **no
upload at all**, however large. A file from someone else's shared folder is upload at all**, however large. A file from someone else's shared folder is
copied to your account first, because a message can only carry blobs from the copied to your account first, because a message can only carry blobs from the
@@ -507,7 +509,7 @@ out whether or not ihasmail is open, or ever opened again.
Held messages wait in a **Scheduled** folder ihasmail maintains itself (JMAP has Held messages wait in a **Scheduled** folder ihasmail maintains itself (JMAP has
no role for one), and reconciles when you next open it: released messages move no role for one), and reconciles when you next open it: released messages move
to Sent, cancelled ones back to Drafts. The picker offers presets and an exact to Sent, canceled ones back to Drafts. The picker offers presets and an exact
date and time, bounded by the maximum delay the server advertises. date and time, bounded by the maximum delay the server advertises.
> If Stalwart's `futureRelease` is not configured, a "scheduled" message is sent > If Stalwart's `futureRelease` is not configured, a "scheduled" message is sent
@@ -534,14 +536,14 @@ are settings.
The sidebar keeps three groups apart: The sidebar keeps three groups apart:
- **My calendars** — yours, each with a colour, each hideable with a click. - **My calendars** — yours, each with a color, each hideable with a click.
- **Shared with me** — other people's, once added. - **Shared with me** — other people's, once added.
- **Available to add** — shared with you but not yet added, with a plus beside - **Available to add** — shared with you but not yet added, with a plus beside
each. An unadded calendar draws nothing. This is deliberate: the server each. An unadded calendar draws nothing. This is deliberate: the server
reports every collection in an account you can reach, whether or not anyone reports every collection in an account you can reach, whether or not anyone
meant to share it, so being handed one is not evidence that it was offered. meant to share it, so being handed one is not evidence that it was offered.
Right-click your own to rename, recolour, share, stop sharing or delete; Right-click your own to rename, recolor, share, stop sharing or delete;
right-click one of someone else's to remove it from your view, which changes right-click one of someone else's to remove it from your view, which changes
nothing for anybody else. nothing for anybody else.
@@ -549,7 +551,7 @@ nothing for anybody else.
events), from the calendar's own menu, into that calendar. The events are events), from the calendar's own menu, into that calendar. The events are
filed rather than scheduled: no invitations go out to anyone named in them. filed rather than scheduled: no invitations go out to anyone named in them.
- **Re-importing updates rather than duplicates**, as a contacts import does. - **Re-importing updates rather than duplicates**, as a contacts import does.
An event is recognised by its UID, per calendar, and what the file carries An event is recognized by its UID, per calendar, and what the file carries
wins -- so a corrected export corrects what the first attempt got wrong. wins -- so a corrected export corrects what the first attempt got wrong.
Two things are deliberately left alone: **who accepted**, and **edits to a Two things are deliberately left alone: **who accepted**, and **edits to a
@@ -564,11 +566,11 @@ nothing for anybody else.
since the last import does not arrive, because nothing here can tell that since the last import does not arrive, because nothing here can tell that
apart from an answer given in ihasmail. And an import still sends no apart from an answer given in ihasmail. And an import still sends no
scheduling messages, so an event a re-import moves is moved *here* -- scheduling messages, so an event a re-import moves is moved *here* --
everybody else's copy still says the old time until whoever is organising everybody else's copy still says the old time until whoever is organizing
sends the update from the event itself. sends the update from the event itself.
- **Subscribed calendars** by URL — a timetable, a rota, a public holiday list. - **Subscribed calendars** by URL — a timetable, a rota, a public holiday list.
Added in Settings Calendar & contacts, read-only, and shown beside your own Added in Settings Calendar & contacts, read-only, and shown beside your own
with their own colour. with their own color.
**Nothing is stored.** The document is fetched when you open the calendar and **Nothing is stored.** The document is fetched when you open the calendar and
parsed in the browser; the server keeps no copy, no cache and no schedule, parsed in the browser; the server keeps no copy, no cache and no schedule,
@@ -606,7 +608,7 @@ nothing for anybody else.
They cannot be edited or deleted, and that falls out of the design rather They cannot be edited or deleted, and that falls out of the design rather
than being special-cased: the virtual calendar reports no write rights, so than being special-cased: the virtual calendar reports no write rights, so
every control that asks before offering Edit or Delete already declines. The every control that asks before offering Edit or Delete already declines. The
store refuses a synthesised id as well, whatever calls it. store refuses a synthesized id as well, whatever calls it.
A card that records only a day and month — the common case — gets a birthday A card that records only a day and month — the common case — gets a birthday
with no age rather than no birthday. And 29 February falls on the 28th in a with no age rather than no birthday. And 29 February falls on the 28th in a
@@ -621,16 +623,16 @@ empty space offers a timed or all-day event at that moment, or *Go to day* /
The editor covers title, start and end (all-day or timed, with a time zone), The editor covers title, start and end (all-day or timed, with a time zone),
calendar, location, meeting link, guests, description, reminders, repeat, calendar, location, meeting link, guests, description, reminders, repeat,
status (confirmed / tentative / cancelled), show-as (busy / free), visibility status (confirmed / tentative / canceled), show-as (busy / free), visibility
(default / private / secret), category and colour. (default / private / secret), category and color.
- **Recurrence** — none, daily, weekly, weekdays, monthly, yearly, or a custom - **Recurrence** — none, daily, weekly, weekdays, monthly, yearly, or a custom
builder: interval, by-weekday, by-month-day, and an end by count or by date. builder: interval, by-weekday, by-month-day, and an end by count or by date.
- **Reminders** — one or more alerts before the start, with a default in settings. - **Reminders** — one or more alerts before the start, with a default in settings.
- **Colour categories**, Outlook-style: named colours managed in Settings - **Color categories**, Outlook-style: named colors managed in Settings
Calendar, assigned from the editor or the context menu, and stored as Calendar, assigned from the editor or the context menu, and stored as
JSCalendar `categories` so other clients see them. (The per-event colour JSCalendar `categories` so other clients see them. (The per-event color
picker that predated them is gone; a colour comes from the category, or the picker that predated them is gone; a color comes from the category, or the
calendar.) calendar.)
- **Duplicate** an event from the context menu. - **Duplicate** an event from the context menu.
- **Create event…** from a message, in its context menu and its ⋮ menu (and, - **Create event…** from a message, in its context menu and its ⋮ menu (and,
@@ -647,7 +649,7 @@ status (confirmed / tentative / cancelled), show-as (busy / free), visibility
## Attendees, invitations and free/busy ## Attendees, invitations and free/busy
Invitations go out as iTIP when guests are added, replies come back and are Invitations go out as iTIP when guests are added, replies come back and are
applied to the event, and cancelling notifies the guests. Guests are added by applied to the event, and canceling notifies the guests. Guests are added by
name or address with the same autocomplete the composer uses. name or address with the same autocomplete the composer uses.
Where the server implements `Principal/getAvailability`, the event editor grows Where the server implements `Principal/getAvailability`, the event editor grows
@@ -754,24 +756,24 @@ JMAP Contacts and JSContact.
afterwards is what the server confirmed rather than what was asked for. afterwards is what the server confirmed rather than what was asked for.
- **Letter index** down the list, with `#` for everything that does not start - **Letter index** down the list, with `#` for everything that does not start
with a letter. with a letter.
- **Search** across name, address, organisation and notes, in one book or all. - **Search** across name, address, organization and notes, in one book or all.
- **vCard import** through `ContactCard/parse` (a file of any number of cards), - **vCard import** through `ContactCard/parse` (a file of any number of cards),
and **export** of one card or the whole book as `.vcf`. and **export** of one card or the whole book as `.vcf`.
- **LDIF import**, for address books coming from SOGo, Thunderbird or an LDAP - **LDIF import**, for address books coming from SOGo, Thunderbird or an LDAP
directory. Nothing on the server reads LDIF, so the file is read here: directory. Nothing on the server reads LDIF, so the file is read here:
RFC 2849 for the syntax, [Mozilla's address book schema][ldif-schema] for what RFC 2849 for the syntax, [Mozilla's address book schema][ldif-schema] for what
the attributes mean, which is the one such exports almost always use. Work and the attributes mean, which is the one such exports almost always use. Work and
home addresses, every phone kind, second email, organisation and units, job home addresses, every phone kind, second email, organization and units, job
title, nickname, web pages and the custom fields all come across. The import title, nickname, web pages and the custom fields all come across. The import
control takes either format and decides by what is in the file, not by what it control takes either format and decides by what is in the file, not by what it
is called. is called.
- **Re-importing updates rather than duplicates.** A vCard is recognised by its - **Re-importing updates rather than duplicates.** A vCard is recognized by its
UID; an LDIF entry, whose schema has none, by its distinguished name. The card UID; an LDIF entry, whose schema has none, by its distinguished name. The card
already here is merged with the file's version -- what the file carries wins, already here is merged with the file's version -- what the file carries wins,
what it does not mention is left alone -- so a corrected export can correct what it does not mention is left alone -- so a corrected export can correct
what the first attempt got wrong. Matching is per address book, which is also what the first attempt got wrong. Matching is per address book, which is also
how two directories that each hold a `cn=John Smith` stay two people. An entry how two directories that each hold a `cn=John Smith` stay two people. An entry
no longer recognisable, because its `dn` moved between exports, is imported no longer recognizable, because its `dn` moved between exports, is imported
again and counted: *"3 of them look like contacts you already had."* again and counted: *"3 of them look like contacts you already had."*
[ldif-schema]: https://wiki.mozilla.org/MailNews:Mozilla_LDAP_Address_Book_Schema [ldif-schema]: https://wiki.mozilla.org/MailNews:Mozilla_LDAP_Address_Book_Schema
@@ -896,7 +898,7 @@ individual rights by hand.
Preferences live in a `settings.json` in the account's own JMAP Files, beside Preferences live in a `settings.json` in the account's own JMAP Files, beside
the signature images. So identity, signatures, locale, date and time formats, the signature images. So identity, signatures, locale, date and time formats,
theme, labels, templates, folder colours, trusted image senders and added shares theme, labels, templates, folder colors, trusted image senders and added shares
are the same wherever you sign in, private windows included — and they are are the same wherever you sign in, private windows included — and they are
backed up with the mail store, because they *are* in the mail store. ihasmail backed up with the mail store, because they *are* in the mail store. ihasmail
still stores nothing of its own. still stores nothing of its own.
@@ -921,14 +923,14 @@ not reach another that already has ihasmail open until it signs in again.
| --- | --- | | --- | --- |
| **General** | Reading pane, mark-as-read delay, auto-advance, conversation view, snippets, avatars; compose format, quoting, signature placement, spell check; time zone, week start, language & region, date format, time format; `mailto:` handler; export / import / reset | | **General** | Reading pane, mark-as-read delay, auto-advance, conversation view, snippets, avatars; compose format, quoting, signature placement, spell check; time zone, week start, language & region, date format, time format; `mailto:` handler; export / import / reset |
| **Privacy & safety** | Remote images and the senders trusted with them, read receipts asked for and answered; the three warnings and the domains they measure against; undo-send window, attachment reminder, confirm-before-delete | | **Privacy & safety** | Remote images and the senders trusted with them, read receipts asked for and answered; the three warnings and the domains they measure against; undo-send window, attachment reminder, confirm-before-delete |
| **Appearance** | Theme, accent colour, density, font size, sidebar, swipe actions, interface language | | **Appearance** | Theme, accent color, density, font size, sidebar, swipe actions, interface language |
| **Identities & signatures** | Addresses, names, Reply-To, HTML signatures, the default, and which to hide from the picker | | **Identities & signatures** | Addresses, names, Reply-To, HTML signatures, the default, and which to hide from the picker |
| **Filters & rules** | The visual builder and raw Sieve editor | | **Filters & rules** | The visual builder and raw Sieve editor |
| **Out of office** | Vacation response | | **Out of office** | Vacation response |
| **Folders** | Create, rename, colour, subscribe | | **Folders** | Create, rename, color, subscribe |
| **Labels** | Keyword, display name, colour | | **Labels** | Keyword, display name, color |
| **Templates** | Named subject + body | | **Templates** | Named subject + body |
| **Calendar & contacts** | Colour categories, working hours, default view, default duration, default reminder | | **Calendar & contacts** | Color categories, working hours, default view, default duration, default reminder |
| **Notifications** | In-tab notifications, notify-when-closed (Web Push), sound | | **Notifications** | In-tab notifications, notify-when-closed (Web Push), sound |
| **Security & sessions** | Password, two-factor state, app passwords, active webmail sessions | | **Security & sessions** | Password, two-factor state, app passwords, active webmail sessions |
| **Keyboard shortcuts** | The full list, grouped | | **Keyboard shortcuts** | The full list, grouped |
@@ -938,7 +940,7 @@ not reach another that already has ihasmail open until it signs in again.
between them is worth stating because two similar words in one nav is how a between them is worth stating because two similar words in one nav is how a
menu becomes something people hunt through. Security & sessions is credentials menu becomes something people hunt through. Security & sessions is credentials
and access: password, two-factor state, app passwords, live sessions. Privacy & and access: password, two-factor state, app passwords, live sessions. Privacy &
safety is how the app behaves towards the reader and towards senders: what safety is how the app behaves toward the reader and toward senders: what
loads, what leaks, and what asks before it happens. These had been spread loads, what leaks, and what asks before it happens. These had been spread
through General, which had grown five unrelated headings — remote images filed through General, which had grown five unrelated headings — remote images filed
under "Reading", the read-receipt policy under "Composing", the undo-send window under "Reading", the read-receipt policy under "Composing", the undo-send window
@@ -1008,12 +1010,12 @@ is why they are two settings and not one.
| | | | | |
| --- | --- | | --- | --- |
| English | the source language, and what every other catalogue falls back to | | English | the source language, and what every other catalog falls back to |
| Deutsch · Español · Français · Nederlands · Português (Brasil) | Beta | | Deutsch · Español · Français · Nederlands · Português (Brasil) | Beta |
| Русский · Українська · 简体中文 · 日本語 | Beta | | Русский · Українська · 简体中文 · 日本語 | Beta |
**All nine translations are marked Beta, and the label is not modesty.** **All nine translations are marked Beta, and the label is not modesty.**
The catalogues were produced by AI against standard dictionaries and have not The catalogs were produced by AI against standard dictionaries and have not
been read by anybody who speaks the language. That is stated in Settings, next been read by anybody who speaks the language. That is stated in Settings, next
to a link for reporting anything that reads wrongly, because the alternative — to a link for reporting anything that reads wrongly, because the alternative —
shipping them quietly — would ask people to trust text nobody has checked. A shipping them quietly — would ask people to trust text nobody has checked. A
@@ -1023,7 +1025,7 @@ deliberate act by a person and not something a percentage earns.
Two things follow from the design rather than the translation: Two things follow from the design rather than the translation:
- **A missing entry renders its English source.** So deleting a bad line is a - **A missing entry renders its English source.** So deleting a bad line is a
valid fix, not a regression, and a catalogue is never in a half-broken state. valid fix, not a regression, and a catalog is never in a half-broken state.
- **Plurals are asked for, never assumed.** `Intl.PluralRules` decides the form, - **Plurals are asked for, never assumed.** `Intl.PluralRules` decides the form,
so Russian and Ukrainian get their three (1 письмо, 2–4 письма, 5+ писем) and so Russian and Ukrainian get their three (1 письмо, 2–4 письма, 5+ писем) and
Japanese and Chinese get the one they actually have — with counters doing the Japanese and Chinese get the one they actually have — with counters doing the
@@ -1035,7 +1037,7 @@ The interface language also feeds the *automatic* date locale, so choosing
page that is already in the reader's language — and accepting that offer is page that is already in the reader's language — and accepting that offer is
what rewrites the DOM underneath React. what rewrites the DOM underneath React.
Only languages with a catalogue shipped appear in the picker. A language Only languages with a catalog shipped appear in the picker. A language
offered without strings behind it would leave the page claiming to be in a offered without strings behind it would leave the page claiming to be in a
language it is not, which is worse than not offering it: it stops a browser language it is not, which is worse than not offering it: it stops a browser
offering to translate a page the reader cannot read. offering to translate a page the reader cannot read.
@@ -1059,28 +1061,28 @@ at two.
| **Ayu** | | | **Ayu** | |
| **Kanagawa** | Wave, with Lotus as its light half | | **Kanagawa** | Wave, with Lotus as its light half |
| **Everforest** | The medium-contrast variant of each side | | **Everforest** | The medium-contrast variant of each side |
| **Primer** | The colours behind GitHub's design system. Named for the system, not for GitHub, which has not endorsed anything here | | **Primer** | The colors behind GitHub's design system. Named for the system, not for GitHub, which has not endorsed anything here |
Every one has both halves, so the top-bar toggle only ever changes the side and Every one has both halves, so the top-bar toggle only ever changes the side and
never the colours. Accent colours still sit on top of any of them. never the colors. Accent colors still sit on top of any of them.
The ten borrowed palettes are the work of their own projects and are used The ten borrowed palettes are the work of their own projects and are used
under the MIT licence — see [NOTICE](NOTICE). Only the published colour values under the MIT license — see [NOTICE](NOTICE). Only the published color values
are used, taken from each project's own repository; the values as fetched are are used, taken from each project's own repository; the values as fetched are
recorded in `.palette-sources/palettes-upstream.md`. recorded in `.palette-sources/palettes-upstream.md`.
**The shades between those values are derived, and every one is checked.** **The shades between those values are derived, and every one is checked.**
ihasmail needs about thirty tokens and these projects publish between twelve ihasmail needs about thirty tokens and these projects publish between twelve
and twenty, so the tiers in between are computed by and twenty, so the tiers in between are computed by
`scripts/build-palettes.py`, which then measures every text colour against the `scripts/build-palettes.py`, which then measures every text color against the
surface it sits on — 4.5:1 for prose, 3:1 for borders and marks — and lifts surface it sits on — 4.5:1 for prose, 3:1 for borders and marks — and lifts
anything that falls short, towards white on a dark ground and towards black on anything that falls short, toward white on a dark ground and toward black on
a light one so the hue survives. The script refuses to write a palette that a light one so the hue survives. The script refuses to write a palette that
would not pass. would not pass.
That check is not a formality. **Twenty-one of the twenty-two palette halves That check is not a formality. **Twenty-one of the twenty-two palette halves
needed at least one lift**, because these palettes are designed for code needed at least one lift**, because these palettes are designed for code
editors rather than for prose at this size: Dracula's comment grey is 3.03:1 on editors rather than for prose at this size: Dracula's comment gray is 3.03:1 on
its own background, and Rosé Pine's gold is 2.7:1 on Dawn. Shipping them as its own background, and Rosé Pine's gold is 2.7:1 on Dawn. Shipping them as
published would have quietly ended the WCAG AA claim two sections down. published would have quietly ended the WCAG AA claim two sections down.
@@ -1106,8 +1108,10 @@ redirects them to their mail if they type its address in.
At sign-in the server already asks Stalwart's `GET /api/account` for the At sign-in the server already asks Stalwart's `GET /api/account` for the
edition; it now keeps the account's **permissions** from the same answer and edition; it now keeps the account's **permissions** from the same answer and
hands them to the browser with the session. The menu appears for an account hands them to the browser with the session. The menu appears for an account
that can query and read accounts (`sysAccountQuery`, `sysAccountGet`) or that can count something the dashboard shows — accounts (`sysAccountQuery`),
domains (`sysDomainQuery`, `sysDomainGet`), and each control inside is there only when the matching permission is: domains (`sysDomainQuery`), the delivery queue (`sysQueuedMessageQuery`) or the
metric history (`sysMetricQuery` with `sysMetricGet`) — and each section and
control inside is there only when the matching permission is:
**New account** with `sysAccountCreate`, editing with `sysAccountUpdate`, **New account** with `sysAccountCreate`, editing with `sysAccountUpdate`,
**Delete** with `sysAccountDestroy`. A system administrator, a tenant **Delete** with `sysAccountDestroy`. A system administrator, a tenant
administrator and a custom helpdesk role each see the same screen shaped to administrator and a custom helpdesk role each see the same screen shaped to
@@ -1119,6 +1123,46 @@ account, and Stalwart decides each one — scoping a tenant administrator's
queries to their own tenant and refusing anything the role does not allow. queries to their own tenant and refusing anything the role does not allow.
The client's gating only avoids offering what would fail. The client's gating only avoids offering what would fail.
## Dashboard
Administration opens on a grid of cards, one for each number the role can read:
| Card | What it counts | Needs |
|---|---|---|
| **Users** | user accounts, not groups | `sysAccountQuery` |
| **Domains** | mail domains | `sysDomainQuery` |
| **Pending** | messages waiting in the delivery queue | `sysQueuedMessageQuery` |
| **Server memory** | the latest reading, and when it was taken | `sysMetricQuery`, `sysMetricGet` |
| **Received** | messages queued for delivery in the last 24 hours | the same |
| **Sent** | authenticated submissions, bounces and reports queued in the last 24 hours | the same |
Users and Domains open their sections when the role can. The counts are what
Stalwart answers for the signed-in account, so a **tenant administrator sees
their tenancy**: its accounts, its domains, and the queued messages that touch
them. The last three come from Stalwart's metric history, which has no tenant
in it and which the Tenant Administrator role Stalwart creates does not hold,
so a tenant's dashboard is Users, Domains and Pending. A helpdesk role that can
read accounts and domains sees those two cards.
The history is an Enterprise feature that has to be switched on. A server that
refuses it — Community does — leaves those three cards off rather than showing
them broken, and one that records nothing says *Not recorded on this server*
rather than showing a day of zeroes. Received and sent add up the same metric
names Stalwart's own dashboard uses. The columns follow the number of cards,
so rows come out even: six are three over three, and fall to two and then one
as the space narrows. **Refresh** reads everything again; nothing is polled.
Below the cards, a line says where the rest is: detailed metrics, the delivery
queue, logs and server settings are in Stalwart's own administration, and it
links there. The address is found rather than configured: the public host
Stalwart advertises in its own session — the one people reach it at, even when
ihasmail talks to it on a private address — and the prefix its web interface is
installed under, read from its `x:Application` objects (`/admin` unless it was
moved). A server whose web interface is disabled or moved away gets no link, and
an administrator who may not read applications gets Stalwart's default `/admin`.
`STALWART_ADMIN_URL`, or a servers file entry's `adminUrl`, overrides it for an
administration that lives somewhere else.
## Accounts ## Accounts
- **List and search** by name or address, fifty to a page, newest first — the - **List and search** by name or address, fifty to a page, newest first — the
@@ -1142,6 +1186,120 @@ in as it. ihasmail shows any account that outranks the viewer read-only, and
counts a role it cannot read as outranking rather than not. Nobody can change counts a role it cannot read as outranking rather than not. Nobody can change
their own role or delete the account they are signed in with. their own role or delete the account they are signed in with.
## Groups
A group is a shared address and mailbox, and the people who share it. To
Stalwart it is an account whose type is Group, so it takes the same
permissions as Accounts (`sysAccountQuery`, `sysAccountGet`) and sits beside
it in the menu.
- **List and search** by name or address, with each group's member count.
- **Create** a group on a domain, with a display name, a role and a storage
limit; **edit** those and its other addresses, which save together.
- **Members** are added by searching for a person and removed one at a time,
and each change applies straight away. Stalwart keeps a membership on the
member rather than the group, so every change is a one-line update to that
person's account that leaves their other groups alone. Nobody can add or
remove themselves.
- **What a group gives its members** is what has been shared with it — its
mailbox, a calendar — not its permissions: a person's permissions come from
their own role. The group's own role says what the group may do, and only
roles whose permissions the viewer holds are offered, as for accounts.
- **Delete** asks for the address to be typed. Stalwart keeps anything that
something else still names, and every member's account names its groups, so
deleting takes the members out first and then deletes the group — the same
order a domain's keys go before the domain. A role that cannot change the
members' accounts is not offered a delete it could only half finish.
Groups do not contain groups; Stalwart has no nesting.
## Mailing lists
A mailing list is an address that passes mail on to everyone on it, on this
server or anywhere else. For a role with `sysMailingListQuery` and
`sysMailingListGet`, under Directory after Groups:
- **List and search** by name or address, with each list's recipient count.
- **Create** a list on a domain; **edit** its display name, recipients and
other addresses, which save together.
- **Recipients** can be pasted several at a time — a column from a
spreadsheet, a line of addresses separated by commas, `Name <address>`
and anything with an @ that is not an address stays in the box with a note
rather than being dropped. Past a dozen, a filter narrows them. Saving sends
only the addresses added and removed, so a recipient someone else added while
the panel was open is not lost.
- **Delete** asks for the address to be typed. The recipients' own mail is not
touched.
That is all a list is in Stalwart: there are no owners, moderators or posting
rules to set.
## Roles
A role is a named set of permissions that accounts, groups and tenants are
given. For a role with `sysRoleQuery` and `sysRoleGet`, under Access:
- **List and search** every role, with the number of permissions each grants
once the roles it builds on are followed, what it builds on, and a note on the
ones Stalwart hands out by default.
- **Builds on** other roles, and gets everything they grant. A role cannot build
on itself or on one already built on it.
- **Permissions** come from Stalwart's own list — every permission the server
knows, grouped under its headings, searchable, and filterable to the ones
granted or set on this role. Each is not set, allowed or denied; one it
inherits says which role it comes from. A denial wins over anything allowed,
here or on any role underneath, as it does in Stalwart. Only permissions the
viewer holds can be allowed: Stalwart refuses the rest.
- **Saving** sends only the permissions and roles that changed.
- **A role that carries permissions the viewer lacks opens read-only**, with no
delete — Stalwart checks a grant but not a delete, so this stands in for it.
- **A default role** — one Stalwart gives new users, groups, tenant
administrators or administrators — says so before anything is changed, and
cannot be deleted from here. A role still in use is kept by the server, and
the refusal names what uses it.
The list of permissions is Stalwart's schema (`GET /api/schema`), fetched by
ihasmail's server as the signed-in account and cut down to names and labels.
Its labels are English only, so ihasmail ships its own translation of every one
of them, loaded only when the Roles screen opens; a permission added by a later
Stalwart shows the server's English until it is translated.
## Tenants
A tenant is a separate organization on the same server — its own people,
domains and limits, and an administrator who manages only what is in it. It is
a Stalwart Enterprise feature. On a server that does not report Enterprise — or
reports no edition at all — the page is only the notice *Tenants are a Stalwart
Enterprise feature.*: no list, no search, nothing to create. On Enterprise the
notice is left out, unless `SHOW_ENTERPRISE_NOTICES=1` asks for it above the
list, as the public demo does. On Enterprise, for a role with `sysTenantQuery`
and `sysTenantGet`, under Access:
- **List and search** tenants, with each one's storage and account limit.
- **Create and edit** a tenant's name, logo (an https address, drawn through the
image proxy, or an image data URL), role and limits — accounts, groups,
mailing lists, domains, roles, DKIM keys and storage. An empty limit is no
limit, and a limit ihasmail does not offer keeps whatever it had.
- **The tenant's role** is the most anyone inside it can be allowed: their own
roles are cut down to it.
- **What it holds** is counted, each against its limit. Stalwart keeps no list
on the tenant; each account, group, domain, list, role and DKIM key names its
tenant, so the counts are queries for those. A domain created in a tenant
brings its keys with it.
- **Domains** are added to a tenant, or taken out, from its panel. Only a domain
in no tenant can be added, and the accounts already on it stay where they
are. A domain comes out only once none of the tenant's accounts are on it —
Stalwart would allow it, and strand them.
- **An account's tenant** is chosen on the account's own panel, which is how a
tenant gets its first administrator: an Administrator inside a tenant
administers that tenant. Stalwart puts something in a tenant only on a domain
in that tenant, so the choice is between no tenant and the domain's own, and
a new account starts in its domain's tenant.
- **Delete** is offered once the tenant holds nothing.
Only an administrator outside every tenant can put anything into one; Stalwart
refuses anyone else, and inside a tenant it scopes every list to that tenant.
## Domains ## Domains
For a role that can read domains (`sysDomainQuery`, `sysDomainGet`): For a role that can read domains (`sysDomainQuery`, `sysDomainGet`):
@@ -1178,7 +1336,7 @@ one question the sign-in page already asks about where it is being used.
It is enforced the same way as the switch below: an untrusted session is sent It is enforced the same way as the switch below: an untrusted session is sent
no permissions, and the JMAP proxy refuses registry methods beyond the account's no permissions, and the JMAP proxy refuses registry methods beyond the account's
own. The menu still shows **Administration** to an administrator in that own. The menu still shows **Administration** to an administrator in that
session, greyed out, with the reason and what to do about it — signing in again session, grayed out, with the reason and what to do about it — signing in again
with the box ticked — rather than losing the entry without a word. All the with the box ticked — rather than losing the entry without a word. All the
server tells that session is that the account administers, never what it may do. server tells that session is that the account administers, never what it may do.
@@ -1200,9 +1358,9 @@ session information already kept for thirty minutes — so a role granted or
taken away shows in the menu at the next sign-in or within half an hour, and in taken away shows in the menu at the next sign-in or within half an hour, and in
the meantime Stalwart refuses what is no longer allowed. the meantime Stalwart refuses what is no longer allowed.
Accounts and domains are the first two sections. Groups, mailing lists, roles The dashboard, accounts, groups, mailing lists, tenants, roles and domains are
and tenants are Stalwart capabilities the same screen is laid out to take; the sections so far. Beyond the dashboard's counts, managing queues, logs and
reporting, queues, logs and server settings are deliberately out of scope. server settings is deliberately out of scope.
--- ---
@@ -1305,7 +1463,7 @@ reporting, queues, logs and server settings are deliberately out of scope.
worker genuinely cannot reach is anything a *tab* holds in memory — and the worker genuinely cannot reach is anything a *tab* holds in memory — and the
API asks for none of it. API asks for none of it.
What it cannot reach is a catalogue. The worker is plain JavaScript outside What it cannot reach is a catalog. The worker is plain JavaScript outside
the bundle, with no i18n and no idea which mailbox is the archive, so the app the bundle, with no i18n and no idea which mailbox is the archive, so the app
writes both down for it whenever the language, the account or the folder list writes both down for it whenever the language, the account or the folder list
changes. Where there is no such note — between installing a new worker and changes. Where there is no such note — between installing a new worker and
@@ -1392,7 +1550,7 @@ costs something to get wrong is the one that assumes the machine is yours.
| Administration | unavailable | available, if the role allows it | | Administration | unavailable | available, if the role allows it |
Local storage is gated on that answer for **reads** as well as writes — a Local storage is gated on that answer for **reads** as well as writes — a
machine trusted once still has residue, and honouring it would let a previous machine trusted once still has residue, and honoring it would let a previous
session's data surface in a later untrusted one. Signing out clears the settings session's data surface in a later untrusted one. Signing out clears the settings
cache and recent addresses and tears down the push subscription, whichever cache and recent addresses and tears down the push subscription, whichever
answer was given. answer was given.
@@ -1456,10 +1614,10 @@ This is S/MIME only, and it stops at reading: nothing here signs, encrypts or
decrypts anything. decrypts anything.
**What it checks.** For a `multipart/signed` message carrying a PKCS#7 **What it checks.** For a `multipart/signed` message carrying a PKCS#7
signature, the exact bytes of the signed part — headers included, canonicalised signature, the exact bytes of the signed part — headers included, canonicalized
to CRLF — are hashed and compared against the `messageDigest` the signature to CRLF — are hashed and compared against the `messageDigest` the signature
covers, and the signature over the signed attributes is verified with WebCrypto covers, and the signature over the signed attributes is verified with WebCrypto
against the certificate travelling inside the message. RSA (PKCS#1 v1.5) and against the certificate traveling inside the message. RSA (PKCS#1 v1.5) and
ECDSA over P-256, P-384 and P-521 are supported, with SHA-256, SHA-384 or ECDSA over P-256, P-384 and P-521 are supported, with SHA-256, SHA-384 or
SHA-512. SHA-512.
@@ -1476,12 +1634,12 @@ authority:
| what happened | what you see | | what happened | what you see |
|---|---| |---|---|
| first signed message from this address | *"Signed by X, seen here for the first time"* — grey, and deliberately not congratulatory | | first signed message from this address | *"Signed by X, seen here for the first time"* — gray, and deliberately not congratulatory |
| same certificate as before | *"the same signer as before"* — the only case that gets a tick | | same certificate as before | *"the same signer as before"* — the only case that gets a tick |
| **different certificate than before** | **loud**: both names, and told to check by some other route | | **different certificate than before** | **loud**: both names, and told to check by some other route |
| valid signature, certificate for a different address | **loud**: the signature is not for this sender | | valid signature, certificate for a different address | **loud**: the signature is not for this sender |
| body changed after signing | **loud**: the signature does not check out | | body changed after signing | **loud**: the signature does not check out |
| signed, but uncheckable | grey, and careful to say *could not check* rather than *did not check out* | | signed, but uncheckable | gray, and careful to say *could not check* rather than *did not check out* |
The pins live in the account's settings file rather than in the browser, so the The pins live in the account's settings file rather than in the browser, so the
same correspondent is not greeted as new on every device — which is what trains same correspondent is not greeted as new on every device — which is what trains
@@ -1531,7 +1689,7 @@ docker run --read-only --tmpfs /tmp -e IMMUTABLE=1 -e SESSION_FILE= ...
``` ```
`IMMUTABLE=1` is an **assertion the server checks at startup**, not a switch `IMMUTABLE=1` is an **assertion the server checks at startup**, not a switch
that changes behaviour. It refuses to boot if `SESSION_FILE` is still set, or if that changes behavior. It refuses to boot if `SESSION_FILE` is still set, or if
the filesystem it is installed on turns out to be writable after all. Without 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 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 persisting them is best-effort, so a read-only `/data` costs one warning at the
@@ -1560,6 +1718,8 @@ wizard, because either would be state.
| Variable | Default | Does | | Variable | Default | Does |
| --- | --- | --- | | --- | --- | --- |
| `STALWART_URL` | — | Where Stalwart is; the JMAP session is discovered at `/.well-known/jmap` | | `STALWART_URL` | — | Where Stalwart is; the JMAP session is discovered at `/.well-known/jmap` |
| `SHOW_ENTERPRISE_NOTICES` | `0` | Say an Enterprise-only section (Tenants) is Enterprise-only even when the server is Enterprise. For a demo that reports Enterprise to show those sections; a real installation leaves it off |
| `STALWART_ADMIN_URL` | found | Where a browser opens Stalwart's own administration, linked from the Administration dashboard. Unset, it is found: the host Stalwart advertises and its web interface's prefix. Set it only when the administration lives somewhere else |
| `APP_SECRET` | — | Key material for sealing sessions. **Required in production** — the server refuses to start without it | | `APP_SECRET` | — | Key material for sealing sessions. **Required in production** — the server refuses to start without it |
| `HOST` / `PORT` | `0.0.0.0` / `8080` | Listen address | | `HOST` / `PORT` | `0.0.0.0` / `8080` | Listen address |
| `BASE_PATH` | — (the domain root) | Subpath to serve from, e.g. `/mail`. Must be set for the **build** as well as the run — see below | | `BASE_PATH` | — (the domain root) | Subpath to serve from, e.g. `/mail`. Must be set for the **build** as well as the run — see below |
@@ -1660,11 +1820,15 @@ moves an occurrence renumbering the ids around it. Two switches:
tested. tested.
Administration works against it too, with a directory of about thirty accounts, Administration works against it too, with a directory of about thirty accounts,
three domains with their DKIM keys and zone files, behind the same permission three domains with their DKIM keys and zone files, nine queued messages and
names Stalwart uses. `MOCK_ROLE` decides who the thirty hours of metric history ending in the current hour, behind the same
demo user is: `admin` (the default), `tenant-admin`, `helpdesk` — a custom role permission names Stalwart uses. `MOCK_ROLE` decides who the
that may view and edit accounts but not create or delete them — or `user`, who demo user is: `admin` (the default), `tenant-admin` (the queue but not the
is not offered the menu at all. history), `helpdesk` — a custom role that may view and edit accounts but not
create or delete them, and read domains — or `user`, who is not offered the
menu at all. `MOCK_METRICS=off` refuses the history the way a Community server
does, and `MOCK_EDITION=enterprise` reports Enterprise so Tenants can be
worked on (the default, `oss`, shows only its notice). Two mailing lists round it out.
--- ---
+59 -11
View File
@@ -13,7 +13,13 @@ 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.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 **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 things a client can see, one of which resolved an entry below outright: an
occurrence of a recurring event is identified by its recurrence id rather than
its position in the series, so an id held across a write no longer 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 all four. The app
was run against a real 0.16.21 with mail, calendar and contacts exercised by 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 hand, including editing one occurrence of a recurring series through the
interface and confirming the rest of the series stayed where it was. interface and confirming the rest of the series stayed where it was.
@@ -48,7 +54,7 @@ works the same way — and dropped where 0.15 was the whole subject. Support for
- **The Basic credential ihasmail proxies with reaches the admin `x:` methods**, as it already reached the self-service ones. No separate token is involved. - **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`. - **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. - **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. - **`dnsZoneFile` is BIND text**, one record per line as `name IN TYPE value`, with a long TXT record split into a parenthesized 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.** - **`x:DkimSignature/query` accepts a `domainId` filter.**
- **`catchAllAddress` wants a whole address.** A bare local part is refused with `invalidPatch`, *"Invalid email address"*. - **`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 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.
@@ -56,13 +62,55 @@ works the same way — and dropped where 0.15 was the whole subject. Support for
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. 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. - **The dashboard's feeds were settled on the live server before the code was written (2026-09-15, 0.16.22 Enterprise, read-only calls from an administrator's session).** The first probes guessed two of these wrong — filtering on `timestamp`, and counting received mail from `message-ingest.*` — and the server and the 0.16.22 source agreed on the answers below:
- **The metric history filters on comparison names.** `x:Metric/query` accepts `{"timestampIsGreaterThanOrEqual": …, "metric": [names]}`; a bare `timestamp`, `after` or `metric` as a string is `unsupportedFilter`. Sorting on `timestamp` works. At the default interval a day is about 80 records for the six metrics the dashboard reads, and a get takes at most 500.
- **Received and sent are `queue.*` counters**, not `message-ingest.*`: `queue.message-queued` for received, and `queue.authenticated-message-queued` + `queue.dsn-queued` + `queue.report-queued` for sent, which is what Stalwart's own dashboard adds up. A Counter holds its interval's count and a zero one is not written; the `*-time` histograms are cumulative, which is why nothing reads them.
- **Memory is the `server.memory` Gauge**, in bytes, one per interval. **Counts** come from `/query` with `calculateTotal: true` and `limit: 0`, which returned the whole total for `x:Account` (users only, via `@type`), `x:Domain` and `x:QueuedMessage`.
- **`x:Metrics/get` is not the history.** It is the singleton holding the collection settings (Prometheus and OpenTelemetry export, the metrics policy); the history is `x:Metric`.
**Not confirmed live:** that a tenant administrator's counts are scoped to the tenancy, and that a Community server refuses `x:Metric` as `forbidden`. Both are read from the 0.16.22 source (`query.rs`, `queued_message.rs`, `registry/mod.rs`); the production server has no tenants and is Enterprise, so neither could be tried there without writing. The dashboard's handling of both is covered by tests against the refusal Stalwart's source gives.
- **Groups were built from the 0.16.22 source and a mock, then confirmed on the live server (2026-09-15)** with a throwaway group on one of the server's domains, created and removed, its only member the administrator's own account:
- **A group is created** as `x:Account` with `@type: "Group"`, no credentials and no encryption setting, and reads back with roles `{"@type": "Default"}`, `permissions` `Inherit`, a `locale` of `en-US` and `usedDiskQuota` 0.
- **Membership is the member's.** `"memberGroupIds/<group>": true` on the user was accepted; `{"@type": "User", "memberGroupIds": <group>}` then found them with a total of 1, and the user's own `memberGroupIds` read `{"<group>": true}`. The same pointer with `null` took them out again and left the set as it was before.
- **A group with members cannot be deleted**: `objectIsLinked`, with `objectId` as `{"object": "Account", "id": <group>}` and `linkedObjects` listing each member as `{"object": "Account", "id": …}`. With the member out, the delete went through and the group read back as `notFound`.
The same run tried a throwaway mailing list before the Mailing lists section was written. It was created with `recipients` as a set, `{"[email protected]": true}`, and read back as `name`, `domainId`, `description`, `aliases`, `memberTenantId`, `recipients` and a computed `emailAddress`. `"recipients/<address>": true` added one and left the other; a `text` filter found it; it was destroyed with nothing linked. Not tried: removing a recipient with `null` (the same set patch as a group membership, which was), and how the server words a recipient that is not an address.
Still from source only: that membership gives a member no permissions (`access_token.rs` builds a user's permissions from their own roles), and that groups cannot nest.
- **Roles were built from the 0.16.22 source, its schema and the mock, then confirmed on the live server (2026-09-15)** with throwaway `ihasmail-role-test` roles, created and removed:
- **A role is created** with `description`, `roleIds`, `enabledPermissions` and `disabledPermissions` as sets, and reads back with them and `memberTenantId`.
- **Pointers change one entry each**: `enabledPermissions/<p>` and `disabledPermissions/<p>` with `true` or `null`, `roleIds/<id>` likewise, and `description` in the same update, all applied together.
- **A name that is not a permission fails the whole update** as `invalidPatch`, *"Invalid value for object property"*, naming the pointer — which is how a probe using the mock's made-up `jmapEmailSet` found that the mock had carried a permission Stalwart does not have since Accounts was built; it is `jmapEmailUpdate` now, and the mock refuses unknown names.
- **A grant the caller does not hold is refused**: `forbidden`, *"You are not authorized to grant permissions: scimAccess"*.
- **A role another role builds on cannot be deleted**: `objectIsLinked`, `objectId` `{"object": "Role", …}`, `linkedObjects` naming the child.
- **The defaults** read from `x:Authentication`: users get User; groups get Group; tenant administrators get Tenant Administrator and User; administrators get System Administrator and User.
**The picker is stricter than the server for a few permissions.** `GET /api/account` never lists some permissions an administrator holds — `sysLogCreate` among them, which was granted without complaint — so their *Allow* is locked for everyone. That errs toward refusing and can be revisited if it gets in anyone's way. Still from source only: that a denial anywhere in a role's tree wins (`permissions.rs` unions enabled and disabled across the tree, then subtracts). **`GET /api/schema` through ihasmail's server was confirmed on production after the deploy (2026-09-15, v2026.9.15+pr364)**: `/api/admin/permissions` answered 200 with all 661 permissions, the same list as the 0.16.22 snapshot, and the Roles picker drew them under 60 headings. The four bootstrap roles grant 244 (User), 229 (Group), 50 (Tenant Administrator) and 452 (System Administrator) once their trees are followed.
- **Tenants were built from the 0.16.22 source, its schema and the mock, then tried on the live server (2026-09-15)** with throwaway `ihasmail-tenant-test` tenants, a throwaway role, two throwaway lists and a throwaway domain, all removed. The live run changed the design twice:
- **A tenant is created and edited as built**: `name`, `logo`, `roles`, `permissions`, `quotas`; `quotas/<name>` pointers, a logo and a rename in one update; an unknown quota name is `invalidPatch`.
- **Something in a tenant has to be on a domain in that tenant.** A list in the tenant on a domain in none was refused, `invalidForeignKey` with `objectId` `{"object": "Domain", …}`; the same list on a domain created in the tenant was accepted — and so was a list in *no* tenant on that domain. **So an account's tenant choice offers only its domain's tenant**, and a new account starts in the tenant of the domain it is made on.
- **A domain created in a tenant puts its DKIM keys in the tenant too**, and they stay there. They count against `maxDkimKeys` and keep the tenant from being deleted, so they are counted with everything else.
- **Stalwart lets a domain leave a tenant while the tenant still has things on it**, leaving them in a tenant on a domain outside it. **The panel refuses to take a domain out while any of the tenant's accounts are on it.** Mailing lists cannot be filtered by domain, so a list is not checked.
- **A tenant still holding anything is kept**: `objectIsLinked`, `objectId` `{"object": "Tenant", …}`, `linkedObjects` naming a role, a list and DKIM keys. A role set to `memberTenantId: null` left it, after which the tenant was deleted.
Still from source only: that only a caller outside every tenant may set `memberTenantId` (`set.rs` passes `can_set_tenant` only when the token has no tenant), and that a tenant administrator's queries are scoped to the tenant. On a server that does not report Enterprise the Tenants page is only its notice.
- **The permission labels in eight languages are machine translations awaiting native review.** 661 labels and 59 headings per language, written against each catalog's existing terms. The translators flagged the terms they were least sure of, which are the place to start: *principal* (JMAP/DAV), *throttles*, *listeners*, *lookups*, *milters*, *masked emails*, *samples* (spam training), *schedules* (MTA delivery), *email submission*, and the MTA stage settings. Several of Stalwart's own English labels are identical for different permissions (ARF, DMARC and TLS reports are all "Get reports"), and the translations inherit that; the heading above tells them apart.
- **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 recognized 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. - **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. - **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 localize 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. - **`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 catalogs 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 catalog 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 catalog 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. **The check had the same blind spot one level down (2026-09-14).** It looked at `title=`, `aria-label=`, `placeholder=` and `alt=` on elements, but not at props passed to components, so `<MenuItem label={x ? "Collapse all" : "Expand all"}>` passed. It also accepted a JSX literal that was a catalog key, although no component here runs its props through `t()`, so 19 strings with translations in every catalog (Report spam, Mark as read, Add star, Save…) still rendered in English. And the script only exited non-zero with `--check`, which `npm run i18n:check` never passed, so it could print a finding without failing. Component props are checked now, a key no longer excuses a literal in an attribute, and both halves run with `--check`. That turned up 28 strings, all fixed: 19 wrapped, and 9 that needed new keys in all nine catalogs. English built with a template literal inside an attribute, such as ``aria-label={`Remove ${email}`}``, was the last gap. It can't be a catalog key as written. Since 2026-09-14 the check flags any template literal in one of these positions that has words between its values, and the twelve that existed are now keys with placeholders. They were the quota bar, the address menu, a folder's unread count, the recipient chips, the contact editor's title, shared calendars and address books, the date and time fields, the attachment fallback name, and the free/busy bar. That bar showed the raw JMAP value (`confirmed`) in every language.
- **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. - **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.
@@ -80,22 +128,22 @@ works the same way — and dropped where 0.15 was the whole subject. Support for
- **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. - **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. - **`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. - **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 gray 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. - **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. - **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. - **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. - **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. - **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. - **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 recognize ([#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. - **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. - **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. - **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 honors 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, canceled 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 canceled 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. - **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). Canceling 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. - **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. - **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 behavior 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 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 defense 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 behavior, 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. - **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.
+13 -13
View File
@@ -3,10 +3,10 @@
ihasmail is licensed under the AGPL-3.0; see LICENSE. This file records work by 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. other people that ships inside it and the terms it comes under.
## Colour palettes ## Color palettes
Ten of the palettes offered in Settings Appearance are the work of their own 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 projects and are used under the MIT license. Only the published color values
are used — no code, and nothing from anyone else's reimplementation of them. are used — no code, and nothing from anyone else's reimplementation of them.
The values as fetched from each project are recorded in The values as fetched from each project are recorded in
`.palette-sources/palettes-upstream.md`, and the shades between them are `.palette-sources/palettes-upstream.md`, and the shades between them are
@@ -16,66 +16,66 @@ not meet the contrast ihasmail claims.
### Dracula and Alucard ### Dracula and Alucard
Copyright (c) 2016 Dracula Theme — https://github.com/dracula/dracula-theme Copyright (c) 2016 Dracula Theme — https://github.com/dracula/dracula-theme
Licensed under the MIT licence. "Dracula" is the dark variant and "Alucard" the Licensed under the MIT license. "Dracula" is the dark variant and "Alucard" the
light one; both are published in that repository's own "Color Palette (OSS)" light one; both are published in that repository's own "Color Palette (OSS)"
section. section.
### Gruvbox ### Gruvbox
Copyright (c) 2018 Pavel Pertsev — https://github.com/morhetz/gruvbox Copyright (c) 2018 Pavel Pertsev — https://github.com/morhetz/gruvbox
Licensed under the MIT licence. Licensed under the MIT license.
### Rosé Pine ### Rosé Pine
Copyright (c) 2021 Rosé Pine — https://github.com/rose-pine/rose-pine-theme Copyright (c) 2021 Rosé Pine — https://github.com/rose-pine/rose-pine-theme
Licensed under the MIT licence. The light variant is "Dawn". Licensed under the MIT license. The light variant is "Dawn".
### Tokyo Night ### Tokyo Night
Copyright (c) 2019 enkia — https://github.com/enkia/tokyo-night-vscode-theme Copyright (c) 2019 enkia — https://github.com/enkia/tokyo-night-vscode-theme
Licensed under the MIT licence. The light variant is "Day". Licensed under the MIT license. The light variant is "Day".
### Catppuccin ### Catppuccin
Copyright (c) 2021 Catppuccin — https://github.com/catppuccin/palette Copyright (c) 2021 Catppuccin — https://github.com/catppuccin/palette
Licensed under the MIT licence. "Mocha" is the dark variant and "Latte" the Licensed under the MIT license. "Mocha" is the dark variant and "Latte" the
light one; both are published in that repository's palette.json. light one; both are published in that repository's palette.json.
### Solarized ### Solarized
Copyright (c) 2011 Ethan Schoonover — https://github.com/altercation/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 Licensed under the MIT license. Light and dark are both original to it, and
share one set of accent values by design. share one set of accent values by design.
### Ayu ### Ayu
Copyright (c) Konstantin Pschera — https://github.com/ayu-theme/ayu-colors Copyright (c) Konstantin Pschera — https://github.com/ayu-theme/ayu-colors
Licensed under the MIT licence. The two signature accent colours come from the Licensed under the MIT license. The two signature accent colors come from the
same author's ayu-theme/vscode-ayu, also MIT. same author's ayu-theme/vscode-ayu, also MIT.
### Kanagawa ### Kanagawa
Copyright (c) 2021 Tommaso Laurenzi — https://github.com/rebelot/kanagawa.nvim Copyright (c) 2021 Tommaso Laurenzi — https://github.com/rebelot/kanagawa.nvim
Licensed under the MIT licence. "Wave" is the dark variant and "Lotus" the Licensed under the MIT license. "Wave" is the dark variant and "Lotus" the
light one. The theme takes its name from Hokusai's print. light one. The theme takes its name from Hokusai's print.
### Everforest ### Everforest
Copyright (c) 2019 Sainnhe Park — https://github.com/sainnhe/everforest Copyright (c) 2019 Sainnhe Park — https://github.com/sainnhe/everforest
Licensed under the MIT licence. The medium-contrast variant of each mode is Licensed under the MIT license. The medium-contrast variant of each mode is
the one used here. the one used here.
### Primer ### Primer
Copyright (c) GitHub, Inc. — https://github.com/primer/primitives Copyright (c) GitHub, Inc. — https://github.com/primer/primitives
Licensed under the MIT licence, which covers the colour values. "GitHub" and Licensed under the MIT license, which covers the color values. "GitHub" and
the Invertocat logo are trademarks of GitHub, Inc.; this palette is named the Invertocat logo are trademarks of GitHub, Inc.; this palette is named
"Primer" after the design system and is neither affiliated with nor endorsed "Primer" after the design system and is neither affiliated with nor endorsed
by GitHub. by GitHub.
--- ---
The MIT licence, under which all ten are used: The MIT license, under which all ten are used:
Permission is hereby granted, free of charge, to any person obtaining a Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"), copy of this software and associated documentation files (the "Software"),
+44 -414
View File
@@ -8,7 +8,7 @@
</p> </p>
<p align="center"> <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="LICENSE"><img alt="License: AGPL-3.0-or-later" src="https://img.shields.io/badge/license-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://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://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://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>
@@ -16,14 +16,13 @@
# ihasmail # ihasmail
**Immutable webmail for [Stalwart Mail Server](https://stalw.art) — a container **Immutable webmail for [Stalwart Mail Server](https://stalw.art).** Mail,
with nothing to persist, and a Gmail-class client on top of it.** calendars, contacts, files and filters in one app that works as well on a phone
as on a desktop — and a container with nothing to persist.
Mail, calendars, contacts, files and filters in a responsive single-page app ihasmail talks only JMAP to Stalwart. There is no database, no IMAP or SMTP,
that works equally well on a desktop monitor and a phone. It talks only JMAP and with `IMMUTABLE=1` no writable filesystem either: everything durable,
(plus Stalwart's blob/upload/EventSource endpoints) — no IMAP, no SMTP, no settings included, belongs to Stalwart, so the container is disposable.
database, and with `IMMUTABLE=1` no writable filesystem either. Everything
durable belongs to Stalwart; the container is disposable.
| | | | | |
| --- | --- | | --- | --- |
@@ -33,436 +32,73 @@ durable belongs to Stalwart; the container is disposable.
| 🧪 **[KNOWN-ISSUES.md](KNOWN-ISSUES.md)** | What was verified live, and where Stalwart departs from a spec | | 🧪 **[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 | | 🛣 **[ROADMAP.md](ROADMAP.md)** | What ihasmail does not do, and why |
### Companion tools
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.
## Screenshots ## Screenshots
*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) | | **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) | | **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) | | **Contacts** ![Contacts](docs/screenshots/contacts.jpg) | **Sieve filter builder** ![Filters](docs/screenshots/filters.jpg) |
More, including the mobile layout, on [ihasmail.org](https://ihasmail.org/#screenshots). Taken against the built-in mock with sample data. More, including the phone
layout, on [ihasmail.org](https://ihasmail.org/#screenshots).
## What's in it ## What's in it
- **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 - **Mail** — conversations, labels, search operators, keyboard shortcuts, scheduled and undo send, invitations and RSVP, filters made from a message
- **Calendar** — JMAP Calendars / JSCalendar: month/week/day/agenda, recurrence, attendees and free-busy, colour categories - **Calendar** — month, week, day and agenda views, recurrence, attendees and free-busy
- **Contacts** — JMAP Contacts / JSContact: address books, groups, full editor, vCard import/export - **Contacts** — address books, groups, vCard import and export
- **Files** — JMAP FileNode: browse, upload, download, rename, move, delete - **Files** — browse, upload, move, share
- **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) - **Signature checking** — S/MIME signed mail verified as you read it
- **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 - **Settings that follow the account**, kept in the account's own storage on Stalwart
- **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) - **On a phone** — swipe to archive or delete, pull to refresh, hold to select
- **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 - **Administration** — a dashboard, accounts, groups, mailing lists, roles, tenants and domains, each shown only when the Stalwart role allows it
- **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) - **Ten interface languages and twelve themes** — the nine translations are marked Beta until a native speaker has read them
- **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 - **Platform** — installable PWA, Web Push, `mailto:` handler, no credentials in the browser, strict CSP
- **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
The long version is on [ihasmail.org](https://ihasmail.org/#features); how to The long version is [FEATURES.md](FEATURES.md) and
drive each one is in [Using ihasmail](https://docs.ihasmail.org/using/). [ihasmail.org](https://ihasmail.org/#features).
## Requires Stalwart 0.16 or newer ## Requirements
Sign-in refuses anything older, by name. 0.16 replaced the REST management API **Stalwart 0.16 or newer** — sign-in refuses anything older, by name. Tested
with JMAP registry objects, changed the shape of `FileNode`, split its rights up against 0.16.22; what changed in each release is in
and moved configuration into the store; supporting both generations meant a [KNOWN-ISSUES.md](KNOWN-ISSUES.md).
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.
**Validated against 0.16.22**, released 13 September 2026: the live instance - **No Stalwart yet?** [ihasmail-oneshot](https://github.com/Coffey-Labs/ihasmail-oneshot) deploys a new Stalwart and ihasmail together on one host, in one command.
runs it and the app has been tested against it. Four of its JMAP changes are - **On Stalwart 0.15?** [stalwart-migrator](https://github.com/Coffey-Labs/stalwart-migrator) upgrades it in place, or stay on the [`stalwart-0.15-support`](https://github.com/Coffey-Labs/ihasmail/releases/tag/stalwart-0.15-support) release.
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) ## 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 ```bash
cp .env.example .env cp .env.example .env
# edit: STALWART_URL=https://mail.example.com and APP_SECRET=$(openssl rand -base64 48) # edit: STALWART_URL=https://mail.example.com and APP_SECRET=$(openssl rand -base64 48)
docker compose up --build -d docker compose up --build -d
# → http://localhost:8080 (put Caddy/nginx in front for TLS; see Caddyfile.example / nginx.example.conf) # → http://localhost:8080 put a reverse proxy in front for TLS
``` ```
Users sign in with their Stalwart mailbox credentials. **An account with Or pull the published image, `ghcr.io/coffey-labs/ihasmail`. Releases are
weekly, so it is usually a few days behind `main`.
People sign in with their Stalwart mailbox credentials. **An account with
two-factor authentication needs an app password**, created in Stalwart's own 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 settings.
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: Everything else — TLS, running immutably, several Stalwart servers, settings
[Installing](https://docs.ihasmail.org/install/) · the installation decides, every environment variable — is in
[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
## Architecture
```
browser ──(same-origin /api/*)──► ihasmail server (Node + Hono) ──(JMAP over HTTPS)──► Stalwart
React SPA • session cookie ⇄ Basic auth
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.
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.
## Development
Requirements: Node ≥ 20.19 (26 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
npm run typecheck # tsc for both packages
npm test # vitest (web) + node:test (server)
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 [Installing](https://docs.ihasmail.org/install/) and
[Configuring](https://docs.ihasmail.org/configure/). [Configuring](https://docs.ihasmail.org/configure/).
### The mock ## Development
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`.
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.
### Version numbers
`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.
The date is the commit's own rather than today's, so rebuilding an old commit
gives the version it had the first time.
```bash ```bash
node scripts/version.mjs # the version for the current checkout npm install
docker build --build-arg IHASMAIL_VERSION="$(node scripts/version.mjs)" -t ihasmail:2026.8.30 . npm run dev:mock # built-in mock Stalwart ([email protected] / demo)
npm test
``` ```
`.dockerignore` excludes `.git` deliberately, so an image build cannot work this Architecture, the mock's switches and how versions are numbered are in
out for itself — pass it in. Left out, the build reports `0.0.0`, which is meant [CONTRIBUTING.md](CONTRIBUTING.md#development-setup).
to look wrong: a version with no `+pr` or `+g` means whoever built the image did
not pass one.
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.
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.
### Deploying
[`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.
```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)
```
`--yes` does not override a hold; clearing one means deleting its line.
## Contributing ## Contributing
@@ -471,14 +107,8 @@ container, waits for healthy, then prunes all but the newest
## License ## License
Copyright (C) 2026 Coffey Labs — AGPL-3.0-or-later. See Copyright (C) 2026 Coffey Labs — AGPL-3.0-or-later. See [LICENSE](LICENSE).
[LICENSE](LICENSE).
ihasmail was relicensed from GPL-3.0 to AGPL-3.0 on 2026-08-25: webmail is If you run a modified ihasmail, set `SOURCE_URL` to your own repository: the
nearly always run as a network service rather than handed to anyone as a binary, sign-in page and Settings About both show it. See
and the AGPL's section 13 closes that gap.
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/). [Rebranding](https://docs.ihasmail.org/rebranding/).
+4 -4
View File
@@ -8,13 +8,13 @@ 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. 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. - **More of Stalwart's directory in Administration.** The Administration menu opens on a dashboard and manages accounts, groups, mailing lists, tenants, roles and domains today — see [FEATURES.md](FEATURES.md#administration). DNS and ACME providers 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. The dashboard reads a handful of numbers and stops there. Managing queues, reading logs and changing 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. - **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. - **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. - **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) - 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. - **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. - **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 catalog 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. - **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. - **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.
@@ -26,8 +26,8 @@ See [KNOWN-ISSUES.md](KNOWN-ISSUES.md) for what is built but worth knowing about
**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. **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. **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 weaponized 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. 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 defense, 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. 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.
+1 -1
View File
@@ -128,7 +128,7 @@ const waitFor = async (jsExpr, what, ms = 15000) => {
* capture — twice, silently, producing a "light" screenshot of the dark theme. * capture — twice, silently, producing a "light" screenshot of the dark theme.
* A MutationObserver puts it back faster than anything can take it away. * A MutationObserver puts it back faster than anything can take it away.
* *
* The check is the rendered background colour: the attribute is what lied. * The check is the rendered background color: the attribute is what lied.
*/ */
const themeTest = (want) => want === "light" const themeTest = (want) => want === "light"
? "parseInt(getComputedStyle(document.body).backgroundColor.match(/\\d+/)[0], 10) > 200" ? "parseInt(getComputedStyle(document.body).backgroundColor.match(/\\d+/)[0], 10) > 200"
+396 -538
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -23,11 +23,11 @@
"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": "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\"", "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:coverage": "node scripts/i18n-coverage.mjs",
"i18n:check": "node scripts/i18n-catalog-check.mjs && node scripts/i18n-literals.mjs", "i18n:check": "node scripts/i18n-catalog-check.mjs --check && node scripts/i18n-literals.mjs --check",
"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: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\""
}, },
"devDependencies": { "devDependencies": {
"concurrently": "^9.1.2", "concurrently": "^10.0.5",
"typescript": "^7.0.2", "typescript": "^7.0.2",
"typescript-ast": "npm:typescript@^5.9.3" "typescript-ast": "npm:typescript@^5.9.3"
} }
+1 -1
View File
@@ -59,7 +59,7 @@ export function baseUrlOf(basePath) {
* *
* The comparison is deliberately not `startsWith(base)`: that would let * The comparison is deliberately not `startsWith(base)`: that would let
* `/mailbox` in under a `/mail` mount and serve it the app shell, which is * `/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. * both wrong and a small open door for a neighboring site on the same host.
*/ */
export function stripBasePath(basePath, pathname) { export function stripBasePath(basePath, pathname) {
const base = normalizeBasePath(basePath); const base = normalizeBasePath(basePath);
+22 -22
View File
@@ -2,15 +2,15 @@
""" """
Generate the palette CSS blocks in web/src/styles/app.css. 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 Every color 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 are recorded in .palette-sources/palettes-upstream.md. What this script adds is
the *derivation*: ihasmail needs thirty-odd tokens and these projects publish the *derivation*: ihasmail needs thirty-odd tokens and these projects publish
between twelve and twenty, so the tiers in between are computed rather than 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. guessed, and every text color 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 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 -- 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 Dracula's comment gray 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 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 being true; here it is arithmetic, and the script fails loudly if a token it
emitted would not pass. emitted would not pass.
@@ -30,7 +30,7 @@ BEGIN = "/* === generated palettes: begin === */"
END = "/* === generated palettes: end === */" END = "/* === generated palettes: end === */"
# ---------------------------------------------------------------- colour maths # ---------------------------------------------------------------- color maths
def parse(hex_: str) -> tuple[float, float, float]: def parse(hex_: str) -> tuple[float, float, float]:
h = hex_.lstrip("#") h = hex_.lstrip("#")
@@ -66,18 +66,18 @@ def rgba(hex_: str, alpha: float) -> str:
return f"rgba({r}, {g}, {b}, {alpha})" return f"rgba({r}, {g}, {b}, {alpha})"
def toward_contrast(colour: str, bg: str, target: float, dark_ui: bool) -> str: def toward_contrast(color: str, bg: str, target: float, dark_ui: bool) -> str:
"""Nudge `colour` away from `bg` until it clears `target`. """Nudge `color` away from `bg` until it clears `target`.
Towards white on a dark background and towards black on a light one, so a Toward white on a dark background and toward black on a light one, so a
lifted tier keeps its hue instead of washing out to grey. lifted tier keeps its hue instead of washing out to gray.
""" """
if contrast(colour, bg) >= target: if contrast(color, bg) >= target:
return colour return color
anchor = "#ffffff" if dark_ui else "#000000" anchor = "#ffffff" if dark_ui else "#000000"
best = colour best = color
for i in range(1, 101): for i in range(1, 101):
candidate = mix(colour, anchor, i / 100) candidate = mix(color, anchor, i / 100)
best = candidate best = candidate
if contrast(candidate, bg) >= target: if contrast(candidate, bg) >= target:
return candidate return candidate
@@ -90,7 +90,7 @@ def toward_contrast(colour: str, bg: str, target: float, dark_ui: bool) -> str:
# ihasmail's own palette has a hand-written dark block further up the file -- # 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 # 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 # quietly move colors nobody asked to move. Only its light half is derived
# here, which is why it appears in LIGHT_ONLY. # here, which is why it appears in LIGHT_ONLY.
LIGHT_ONLY = {"ihasmail"} LIGHT_ONLY = {"ihasmail"}
@@ -261,17 +261,17 @@ def build(pid: str, mode: str, src: dict[str, str]) -> tuple[dict[str, str], lis
bg, fg = src["bg"], src["fg"] bg, fg = src["bg"], src["fg"]
notes: list[str] = [] notes: list[str] = []
def lift(name: str, colour: str, target: float) -> str: def lift(name: str, color: str, target: float) -> str:
out = toward_contrast(colour, bg, target, dark) out = toward_contrast(color, bg, target, dark)
if out != colour: if out != color:
notes.append(f"{name} {colour} -> {out} ({contrast(colour, bg):.2f} -> {contrast(out, bg):.2f})") notes.append(f"{name} {color} -> {out} ({contrast(color, bg):.2f} -> {contrast(out, bg):.2f})")
return out return out
# Body text is lifted like every other text tone rather than exempted. # 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 # Most of these palettes publish a body color around 4.5:1 -- their own
# target -- and ihasmail asks 7:1 of the text a reader looks at all day. # 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 # 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 # 2026-09; nudging the published color along its own hue costs nothing a
# reader can name, and the shift is recorded in the header of the # reader can name, and the shift is recorded in the header of the
# generated block like every other one. # generated block like every other one.
fg = lift("fg", fg, TEXT_ON_BG["fg"]) fg = lift("fg", fg, TEXT_ON_BG["fg"])
@@ -365,11 +365,11 @@ def main() -> int:
"/*", "/*",
" * Written by scripts/build-palettes.py -- edit the sources there, not here.", " * 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", " * Every color is from the palette's own project (all MIT); the published",
" * values are recorded in .palette-sources/palettes-upstream.md. The tiers", " * values are recorded in .palette-sources/palettes-upstream.md. The tiers",
" * between them are derived, and every text colour is checked against the", " * between them are derived, and every text color is checked against the",
" * surface it sits on: 4.5:1 for prose, 3:1 for borders and marks. Several", " * 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", " * of these palettes do not meet that as published -- Dracula's comment gray",
" * is about 3.0:1 on its own background -- so those tiers are lifted, which", " * 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.", " * is why this is arithmetic rather than a hand-written block.",
" */", " */",
+13 -13
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env node #!/usr/bin/env node
/* /*
* Check a catalogue against the strings the code actually asks for. * Check a catalog against the strings the code actually asks for.
* *
* Two failures, and only one of them is visible without this. * Two failures, and only one of them is visible without this.
* *
@@ -8,9 +8,9 @@
* as an untranslated word on screen, which somebody will eventually notice. * as an untranslated word on screen, which somebody will eventually notice.
* *
* A *stale* key -- one whose English no longer exists, usually because it was * A *stale* key -- one whose English no longer exists, usually because it was
* mistyped when the catalogue was written -- is silent. The translation sits * mistyped when the catalog was written -- is silent. The translation sits
* in the file looking correct, is never looked up, and the app renders English * 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. * for ever. Nothing warns, because a catalog is only ever read by key.
*/ */
/* /*
* The parser, not the compiler. * The parser, not the compiler.
@@ -32,13 +32,13 @@ import { readFileSync, globSync } from "node:fs";
/* /*
* Two sets, because there are two questions and they need different nets. * Two sets, because there are two questions and they need different nets.
* *
* `wanted` is what a catalogue *owes*: the strings that actually reach t(), * `wanted` is what a catalog *owes*: the strings that actually reach t(),
* tc() or plural(). Coverage is measured against it, so it has to stay strict * 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 * -- widening it would count every CSS class and JMAP method name as an
* untranslated string. * untranslated string.
* *
* `seen` is every string literal in the source, and answers only "is this * `seen` is every string literal in the source, and answers only "is this
* catalogue key still written down anywhere". Stale detection needs the wide * catalog 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 * net: a key reaches t() as a variable often enough that a strict set reports
* mostly false alarms. * mostly false alarms.
*/ */
@@ -70,7 +70,7 @@ for (const file of globSync("web/src/**/*.{ts,tsx}").filter((f) => !f.includes("
if (ts.isJsxText(n)) { const text = n.text.trim(); if (text) seen.add(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 -- * 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 * it reaches t() one render later -- so it stays part of what a catalog
* owes, and out of coverage it would flatter the number. * 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.isPropertyAssignment(n) && n.name.getText(src) === "label" && ts.isStringLiteral(n.initializer)) wanted.add(n.initializer.text);
@@ -81,10 +81,10 @@ for (const file of globSync("web/src/**/*.{ts,tsx}").filter((f) => !f.includes("
if (ts.isCallExpression(n) && ts.isIdentifier(n.expression)) { if (ts.isCallExpression(n) && ts.isIdentifier(n.expression)) {
const fn = n.expression.text, a0 = n.arguments[0]; const fn = n.expression.text, a0 = n.arguments[0];
if ((fn === "t" || fn === "translate" || fn === "tNode") && a0 && ts.isStringLiteral(a0)) wanted.add(a0.text); 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 // tc(context, source) keys the catalog on both, joined by the same
// control character tc() uses. Without this the contextual entries all // control character tc() uses. Without this the contextual entries all
// looked stale, which is the checker's own false alarm rather than a // looked stale, which is the checker's own false alarm rather than a
// catalogue problem. // catalog problem.
if (fn === "tc" && a0 && ts.isStringLiteral(a0) && n.arguments[1] && ts.isStringLiteral(n.arguments[1])) { 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 // Only the contextual key is required. The plain one is tc()'s
// fallback, not a second obligation -- asking for both would report // fallback, not a second obligation -- asking for both would report
@@ -104,8 +104,8 @@ for (const file of globSync("web/src/**/*.{ts,tsx}").filter((f) => !f.includes("
} }
/* /*
* A catalogue and a picker entry are two halves of one thing, and either half * A catalog 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 * alone is dead weight. A catalog with no entry in UI_LANGUAGES never
* reaches a reader -- it builds, it passes every test, and the language simply * 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 * 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 * replacement anchored on a line that did not exist on that branch, so it was
@@ -113,17 +113,17 @@ for (const file of globSync("web/src/**/*.{ts,tsx}").filter((f) => !f.includes("
*/ */
const languagesSrc = readFileSync("web/src/lib/languages.ts", "utf8"); const languagesSrc = readFileSync("web/src/lib/languages.ts", "utf8");
const registered = new Set([...languagesSrc.matchAll(/tag:\s*"([\w-]+)"/g)].map((m) => m[1])); 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", ""))); const catalogs = new Set(globSync("web/src/locales/*.ts").map((f) => f.split("/").pop().replace(".ts", "")));
let failed = false; let failed = false;
for (const tag of catalogues) { for (const tag of catalogs) {
if (!registered.has(tag)) { if (!registered.has(tag)) {
failed = true; failed = true;
console.log(`!! ${tag}.ts exists but is not in UI_LANGUAGES — the language is never offered\n`); console.log(`!! ${tag}.ts exists but is not in UI_LANGUAGES — the language is never offered\n`);
} }
} }
for (const tag of registered) { for (const tag of registered) {
if (tag !== "en" && !catalogues.has(tag)) { if (tag !== "en" && !catalogs.has(tag)) {
failed = true; failed = true;
console.log(`!! UI_LANGUAGES offers ${tag} but there is no ${tag}.ts — it would fall back to English\n`); console.log(`!! UI_LANGUAGES offers ${tag} but there is no ${tag}.ts — it would fall back to English\n`);
} }
+46 -14
View File
@@ -11,11 +11,11 @@
* A string reaches a reader translated if either is true: * A string reaches a reader translated if either is true:
* *
* 1. it is wrapped where it is written -- t(), tc(), tNode(), plural() * 1. it is wrapped where it is written -- t(), tc(), tNode(), plural()
* 2. it is a catalogue key, translated somewhere else * 2. it is a catalog key, translated somewhere else
* *
* The second case is a real convention here, not a loophole: constant tables * 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 * 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 * string that is neither -- one no catalog has a key for, which therefore
* cannot be translated at all, however many languages ship. * cannot be translated at all, however many languages ship.
*/ */
/* /*
@@ -40,7 +40,13 @@ const UI_PROPS = new Set([
"title", "message", "label", "confirmLabel", "cancelLabel", "ariaLabel", "title", "message", "label", "confirmLabel", "cancelLabel", "ariaLabel",
"placeholder", "hint", "occurrenceLabel", "occurrenceHint", "seriesLabel", "seriesHint", "placeholder", "hint", "occurrenceLabel", "occurrenceHint", "seriesLabel", "seriesHint",
]); ]);
const UI_ATTRS = new Set(["title", "aria-label", "placeholder", "alt"]); /*
* A JSX attribute is shown whether it lands on an element or on a component:
* `<MenuItem label="Collapse all">` renders its label as given, exactly as
* `<button title="…">` does. Checking only the DOM spellings let every
* component prop through, so the props are checked here too.
*/
const UI_ATTRS = new Set(["title", "aria-label", "placeholder", "alt", ...UI_PROPS]);
const TOASTS = new Set(["error", "success", "info", "show"]); const TOASTS = new Set(["error", "success", "info", "show"]);
const WRAPPERS = ["t", "tc", "tNode", "translate", "plural"]; const WRAPPERS = ["t", "tc", "tNode", "translate", "plural"];
const EQUALITY = new Set([ const EQUALITY = new Set([
@@ -50,7 +56,7 @@ const EQUALITY = new Set([
/* /*
* Product names, example addresses and URL scaffolding. These reach t() and * Product names, example addresses and URL scaffolding. These reach t() and
* are deliberately absent from every catalogue -- translating "ihasmail" or * are deliberately absent from every catalog -- translating "ihasmail" or
* "[email protected]" would be a bug, not a feature -- so they would otherwise * "[email protected]" would be a bug, not a feature -- so they would otherwise
* be reported for ever. * be reported for ever.
*/ */
@@ -74,8 +80,15 @@ const keys = new Set();
const found = []; const found = [];
for (const file of globSync("web/src/**/*.{ts,tsx}").filter((f) => !f.includes("__tests__") && !f.includes("/locales/"))) { 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 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; * `strict` withdraws the catalog-key exemption. It exists for English held
* in a constant and translated where it renders; a literal written straight
* into a JSX attribute has no later render site to be translated at -- no
* component here passes its props through t() -- so being a key only means
* a translation exists that this string never reaches.
*/
const report = (node, text, strict = false) => {
if (!looksLikeUi(text) || (!strict && keys.has(text)) || NEVER_TRANSLATED.has(text)) return;
const { line } = src.getLineAndCharacterOfPosition(node.getStart(src)); const { line } = src.getLineAndCharacterOfPosition(node.getStart(src));
found.push({ file, line: line + 1, text }); found.push({ file, line: line + 1, text });
}; };
@@ -103,14 +116,33 @@ for (const file of globSync("web/src/**/*.{ts,tsx}").filter((f) => !f.includes("
mark(src); mark(src);
const wrapped = exempt; const wrapped = exempt;
/*
* English assembled around values: `aria-label={`Remove ${email}`}`.
*
* The literal cannot be a catalog key as written, so whether it is a key is
* not asked. Neither is looksLikeUi, which reads the opening of a sentence:
* `${name} — shared by ${owner}` opens with a value and its words come after.
* Any run of letters between the values counts. The only template literals
* that reach a UI attribute and are not prose are pure punctuation around
* values, like `${name} (${size})`, and those have none.
*/
const reportTemplate = (x) => {
const parts = ts.isNoSubstitutionTemplateLiteral(x) ? [x.text] : [x.head.text, ...x.templateSpans.map((s) => s.literal.text)];
if (!/[A-Za-z]{2,}/.test(parts.join(""))) return;
const { line } = src.getLineAndCharacterOfPosition(x.getStart(src));
found.push({ file, line: line + 1, text: parts.join("{}") });
};
const isTemplate = (x) => ts.isTemplateExpression(x) || ts.isNoSubstitutionTemplateLiteral(x);
const visit = (n) => { const visit = (n) => {
if (ts.isPropertyAssignment(n) && ts.isStringLiteral(n.initializer) && !wrapped.has(n.initializer) if (ts.isPropertyAssignment(n) && UI_PROPS.has(n.name.getText(src).replace(/['"]/g, ""))) {
&& UI_PROPS.has(n.name.getText(src).replace(/['"]/g, ""))) { if (ts.isStringLiteral(n.initializer) && !wrapped.has(n.initializer)) report(n.initializer, n.initializer.text);
report(n.initializer, n.initializer.text); if (isTemplate(n.initializer)) reportTemplate(n.initializer);
} }
if (ts.isJsxAttribute(n) && n.initializer && UI_ATTRS.has(n.name.getText(src))) { if (ts.isJsxAttribute(n) && n.initializer && UI_ATTRS.has(n.name.getText(src))) {
const walk = (x) => { const walk = (x) => {
if (ts.isStringLiteral(x) && !wrapped.has(x)) report(x, x.text); if (isTemplate(x)) reportTemplate(x);
if (ts.isStringLiteral(x) && !wrapped.has(x)) report(x, x.text, true);
if (!ts.isCallExpression(x)) ts.forEachChild(x, walk); if (!ts.isCallExpression(x)) ts.forEachChild(x, walk);
}; };
walk(n.initializer); walk(n.initializer);
@@ -119,7 +151,7 @@ for (const file of globSync("web/src/**/*.{ts,tsx}").filter((f) => !f.includes("
&& n.expression.expression.getText(src) === "toast" && TOASTS.has(n.expression.name.text)) { && n.expression.expression.getText(src) === "toast" && TOASTS.has(n.expression.name.text)) {
const a0 = n.arguments[0]; const a0 = n.arguments[0];
if (a0 && ts.isStringLiteral(a0) && !wrapped.has(a0)) report(a0, a0.text); 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. */ /* A template literal cannot be a catalog key at all, so it is always a find. */
if (a0 && ts.isTemplateExpression(a0)) report(a0, a0.head.text + "{}"); if (a0 && ts.isTemplateExpression(a0)) report(a0, a0.head.text + "{}");
} }
ts.forEachChild(n, visit); ts.forEachChild(n, visit);
@@ -128,11 +160,11 @@ for (const file of globSync("web/src/**/*.{ts,tsx}").filter((f) => !f.includes("
} }
if (!found.length) { if (!found.length) {
console.log("i18n literals: none -- every user-visible string is wrapped or has a catalogue key"); console.log("i18n literals: none -- every user-visible string is wrapped or has a catalog key");
process.exit(0); process.exit(0);
} }
console.log(`${found.length} user-visible string(s) the extractor cannot see and no catalogue can translate:\n`); console.log(`${found.length} user-visible string(s) the extractor cannot see and no catalog can translate:\n`);
for (const f of found) console.log(` ${f.file}:${f.line}\n ${JSON.stringify(f.text)}`); 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("\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."); console.log("translated where it renders -- make sure the English is a catalog key.");
process.exit(process.argv.includes("--check") ? 1 : 0); process.exit(process.argv.includes("--check") ? 1 : 0);
+3 -3
View File
@@ -1,10 +1,10 @@
#!/usr/bin/env node #!/usr/bin/env node
/* /*
* Every source string a catalogue needs, straight out of the calls. * Every source string a catalog needs, straight out of the calls.
* *
* The English text is the key, so the catalogue's keys are not a list somebody * The English text is the key, so the catalog's keys are not a list somebody
* maintains -- they are whatever t(), tNode() and plural() are actually asked * 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 * for. Reading them from the code means a catalog can never drift out of
* step with the app in the one direction that matters: a key that no longer * 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 * exists is dead weight, but a call with no key is an untranslated string
* nobody noticed. * nobody noticed.
+1 -1
View File
@@ -156,7 +156,7 @@ test("with 2FA on, a password change needs the current code too", async () => {
test("2FA is switched off with the password and a current code", async () => { test("2FA is switched off with the password and a current code", async () => {
const state = await call("/api/account/security"); const state = await call("/api/account/security");
assert.equal(state.body.otpEnabled, true); assert.equal(state.body.otpEnabled, true);
// The enrolment secret is known only to the client, so disabling uses a code // The enrollment secret is known only to the client, so disabling uses a code
// from the authenticator - here, the one the mock stored. // from the authenticator - here, the one the mock stored.
const stored = (mock as { account: { otpUrl: string | null } }).account.otpUrl; const stored = (mock as { account: { otpUrl: string | null } }).account.otpUrl;
const params = parseOtpauthUrl(stored!); const params = parseOtpauthUrl(stored!);
+4 -4
View File
@@ -169,10 +169,10 @@ export async function revokeAppPassword(ctx: Ctx, id: string): Promise<void> {
} }
/** /**
* Start enrolment: mint a secret and hand back the URL to show as a QR code. * Start enrollment: mint a secret and hand back the URL to show as a QR code.
* Nothing is stored until the user proves they can produce a code from it. * Nothing is stored until the user proves they can produce a code from it.
*/ */
export function beginOtpEnrolment(ctx: Ctx): { secret: string; url: string } { export function beginOtpEnrollment(ctx: Ctx): { secret: string; url: string } {
const secret = generateSecret(); const secret = generateSecret();
return { secret, url: otpauthUrl({ secret, account: ctx.username, issuer: config.appName || "ihasmail" }) }; return { secret, url: otpauthUrl({ secret, account: ctx.username, issuer: config.appName || "ihasmail" }) };
} }
@@ -184,7 +184,7 @@ export function beginOtpEnrolment(ctx: Ctx): { secret: string; url: string } {
* the new secret, so without this an authenticator that was mistyped or out of * the new secret, so without this an authenticator that was mistyped or out of
* step would lock the user out of their mailbox at the next sign-in. * step would lock the user out of their mailbox at the next sign-in.
*/ */
export function assertEnrolmentCode(url: string, code: string): void { export function assertEnrollmentCode(url: string, code: string): void {
const params = parseOtpauthUrl(url); const params = parseOtpauthUrl(url);
if (!params) throw new AccountError("That two-factor secret is not usable.", 400, "bad_otp_url"); if (!params) throw new AccountError("That two-factor secret is not usable.", 400, "bad_otp_url");
if (!verifyTotp(params, code)) { if (!verifyTotp(params, code)) {
@@ -193,7 +193,7 @@ 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(ctx: Ctx, opts: { url: string; code: string; current: string }): Promise<void> {
assertEnrolmentCode(opts.url, opts.code); assertEnrollmentCode(opts.url, opts.code);
const res = await jmap(ctx, [ const res = await jmap(ctx, [
[ [
"x:AccountPassword/set", "x:AccountPassword/set",
+3 -3
View File
@@ -73,14 +73,14 @@ test("no capabilities at all is treated the same way", async () => {
const STALWART = "urn:stalwart:jmap"; const STALWART = "urn:stalwart:jmap";
const baseCaps = { "urn:ietf:params:jmap:core": {}, "urn:ietf:params:jmap:mail": {} }; const baseCaps = { "urn:ietf:params:jmap:core": {}, "urn:ietf:params:jmap:mail": {} };
test("a 0.16 server is recognised from primaryAccounts, where it advertises itself", () => { test("a 0.16 server is recognized from primaryAccounts, where it advertises itself", () => {
assert.equal( assert.equal(
hasStalwartRegistry({ capabilities: baseCaps, accounts: {}, primaryAccounts: { [STALWART]: "a1" } }), hasStalwartRegistry({ capabilities: baseCaps, accounts: {}, primaryAccounts: { [STALWART]: "a1" } }),
true, true,
); );
}); });
test("a 0.16 server is recognised from an account's capabilities", () => { test("a 0.16 server is recognized from an account's capabilities", () => {
assert.equal( assert.equal(
hasStalwartRegistry({ hasStalwartRegistry({
capabilities: baseCaps, capabilities: baseCaps,
@@ -100,7 +100,7 @@ test("a server that advertises it nowhere is one we do not support", () => {
assert.equal(hasStalwartRegistry(undefined), false); assert.equal(hasStalwartRegistry(undefined), false);
}); });
test("a shared account carrying the capability is enough to recognise the server", () => { test("a shared account carrying the capability is enough to recognize the server", () => {
assert.equal( assert.equal(
hasStalwartRegistry({ hasStalwartRegistry({
capabilities: baseCaps, capabilities: baseCaps,
+6 -1
View File
@@ -57,7 +57,12 @@ test("administration needs both the installation and a device marked as the pers
test("an account counts as an administrator by the same test the menu makes", () => { test("an account counts as an administrator by the same test the menu makes", () => {
assert.equal(grantsAdministration(["sysAccountQuery", "sysAccountGet"]), true); assert.equal(grantsAdministration(["sysAccountQuery", "sysAccountGet"]), true);
assert.equal(grantsAdministration(["sysDomainQuery", "sysDomainGet"]), true); assert.equal(grantsAdministration(["sysDomainQuery", "sysDomainGet"]), true);
assert.equal(grantsAdministration(["sysAccountQuery", "sysDomainGet"]), false); // The dashboard opens on less than a list: a count is only a query.
assert.equal(grantsAdministration(["sysAccountQuery"]), true);
assert.equal(grantsAdministration(["sysQueuedMessageQuery"]), true);
assert.equal(grantsAdministration(["sysMetricQuery", "sysMetricGet"]), true);
assert.equal(grantsAdministration(["sysMetricQuery"]), false);
assert.equal(grantsAdministration(["sysAccountGet", "sysDomainGet"]), false);
assert.equal(grantsAdministration(["jmapEmailGet", "sysAccountSettingsGet"]), false); assert.equal(grantsAdministration(["jmapEmailGet", "sysAccountSettingsGet"]), false);
}); });
+8 -3
View File
@@ -13,7 +13,7 @@
* An allowlist rather than a list of administrative objects, because the * An allowlist rather than a list of administrative objects, because the
* registry has dozens of them -- listeners, stores, tracers, system settings -- * 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 * and a new release adds more. An object not named here is refused, which errs
* towards the operator's decision. * toward the operator's decision.
* *
* The standard JMAP methods (mail, calendars, contacts, files, sharing) are not * The standard JMAP methods (mail, calendars, contacts, files, sharing) are not
* touched: they act on what the account can already reach. * touched: they act on what the account can already reach.
@@ -41,10 +41,15 @@ export function administrationAllowed(enabled: boolean, remember: boolean): bool
* Whether an account's permissions would put Administration in its menu -- * 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 * the same test the client makes, so the server can say why it is missing
* without handing over the permissions themselves. * without handing over the permissions themselves.
*
* The client's test is whether any section opens, and the dashboard opens on
* less than a list does: a count needs only the query, the metric history its
* query and get. The account and domain lists need more than their counts, so
* they add nothing here.
*/ */
export function grantsAdministration(permissions: readonly string[]): boolean { export function grantsAdministration(permissions: readonly string[]): boolean {
const has = new Set(permissions); const has = new Set(permissions);
return (has.has("sysAccountQuery") && has.has("sysAccountGet")) || (has.has("sysDomainQuery") && has.has("sysDomainGet")); return has.has("sysAccountQuery") || has.has("sysDomainQuery") || has.has("sysQueuedMessageQuery") || (has.has("sysMetricQuery") && has.has("sysMetricGet"));
} }
/** /**
@@ -60,7 +65,7 @@ export function mayNameRegistryMethod(raw: string): boolean {
/** /**
* Check a JMAP request body. On success, hands back the body to forward -- * 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 * serialized from what was inspected, so the server can never be sent
* something different from what was checked (a duplicate key, say, read one * something different from what was checked (a duplicate key, say, read one
* way here and another way there). * way here and another way there).
*/ */
+75
View File
@@ -0,0 +1,75 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const dir = mkdtempSync(join(tmpdir(), "ihasmail-servers-"));
const file = join(dir, "servers.json");
writeFileSync(
file,
JSON.stringify({
_comment: ["A note, as the example file has."],
"plain.test": "https://mail.plain.test/",
"Linked.Test.": { url: "https://mail.linked.test", adminUrl: "https://admin.linked.test/" },
}),
);
process.env.STALWART_URL = "https://default.example";
process.env.STALWART_ADMIN_URL = "https://admin.default.example/";
process.env.STALWART_SERVERS_FILE = file;
const { adminPrefixFrom, adminUrlFor, advertisedOrigin, upstreamFor } = await import("./upstream.js");
const { config, parseStalwartServers } = await import("./config.js");
/**
* Where the dashboard's "Open Stalwart admin" points. STALWART_URL is how this
* server reaches Stalwart; STALWART_ADMIN_URL is where a browser opens its
* administration, and follows the same domain routing.
*/
test("a servers file entry may name its administration as well as its server, and a note is not a domain", () => {
assert.deepEqual(config.stalwartServers, { "plain.test": "https://mail.plain.test", "linked.test": "https://mail.linked.test" });
assert.deepEqual(config.stalwartAdminUrls, { "linked.test": "https://admin.linked.test" });
assert.equal(upstreamFor("[email protected]"), "https://mail.linked.test");
});
test("an unmapped domain and a bare username open the default administration", () => {
assert.equal(adminUrlFor("[email protected]"), "https://admin.default.example");
assert.equal(adminUrlFor("demo"), "https://admin.default.example");
});
test("a routed domain opens its own server's administration, and never the default's", () => {
assert.equal(adminUrlFor("[email protected]"), "https://admin.linked.test");
// Routed away, with no adminUrl of its own and nothing found: no link rather than the wrong server.
assert.equal(adminUrlFor("[email protected]"), null);
});
test("what the operator configured wins over what was found, and what was found fills the gap", () => {
assert.equal(adminUrlFor("[email protected]", "https://found.example/admin/"), "https://admin.default.example");
assert.equal(adminUrlFor("[email protected]", "https://found.example/admin/"), "https://admin.linked.test");
// The routed domain without an adminUrl takes what its own server said.
assert.equal(adminUrlFor("[email protected]", "https://mail.plain.test/admin/"), "https://mail.plain.test/admin/");
});
/** Finding the administration on the server itself, as production's answered on 2026-09-15. */
test("the web interface's prefix is read from the applications Stalwart has installed", () => {
const got = (list: unknown[]) => adminPrefixFrom([["x:Application/query", { ids: ["a"] }, "q"], ["x:Application/get", { list }, "g"]]);
assert.equal(got([{ enabled: true, description: "Stalwart Web Interface", urlPrefix: { "/admin": true, "/account": true } }]), "/admin");
assert.equal(got([{ enabled: false, urlPrefix: { "/admin": true } }]), null);
assert.equal(got([{ enabled: true, urlPrefix: { "/console": true } }]), null);
assert.equal(got([]), null);
// May not read applications: not an answer, so Stalwart's own default.
assert.equal(adminPrefixFrom([["error", { type: "forbidden" }, "q"], ["error", { type: "forbidden" }, "g"]]), "/admin");
});
test("the origin is the one Stalwart advertises, even when it is reached on a private address", () => {
assert.equal(advertisedOrigin({ apiUrl: "https://mail.example.com/jmap/", baseUrl: "http://127.0.0.1:8080" }), "https://mail.example.com");
assert.equal(advertisedOrigin({ apiUrl: "/jmap/", baseUrl: "https://mail.example.com" }), "https://mail.example.com");
});
test("the shipped example loads through the parser that reads it", () => {
const example = new URL("../../stalwart-servers.example.json", import.meta.url);
const parsed = parseStalwartServers(JSON.parse(readFileSync(example, "utf8")), "example");
assert.ok(Object.keys(parsed.urls).length > 0);
assert.ok(!("_comment" in parsed.urls));
assert.equal(Object.keys(parsed.adminUrls).length, 1);
});
+43 -8
View File
@@ -8,6 +8,7 @@ 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 { attach as pushAttach, attachRelay as pushAttachRelay, prepare as pushPrepare, receive as pushReceive, pushStatus } from "./push.js";
import { getConnInfo } from "@hono/node-server/conninfo"; import { getConnInfo } from "@hono/node-server/conninfo";
import { config } from "./config.js"; import { config } from "./config.js";
import { fetchPermissions } from "./permissionSchema.js";
import { administrationAllowed, gateAdministration, grantsAdministration } from "./adminGate.js"; import { administrationAllowed, gateAdministration, grantsAdministration } from "./adminGate.js";
import { SessionStore, type SessionBackend, type LiveSession } from "./sessions.js"; import { SessionStore, type SessionBackend, type LiveSession } from "./sessions.js";
import { RateLimiter } from "./ratelimit.js"; import { RateLimiter } from "./ratelimit.js";
@@ -23,12 +24,13 @@ import {
getAccountInfo, getAccountInfo,
getUpstreamSession, getUpstreamSession,
upstreamFor, upstreamFor,
adminUrlFor,
localizeSession, localizeSession,
} from "./upstream.js"; } from "./upstream.js";
import { import {
AccountError, AccountError,
assertEnrolmentCode, assertEnrollmentCode,
beginOtpEnrolment, beginOtpEnrollment,
changePassword, changePassword,
createAppPassword, createAppPassword,
disableOtp, disableOtp,
@@ -402,7 +404,7 @@ export function createApp(basePath = config.basePath): Hono<Env> {
); );
} }
/* /*
* A 401 is a judgement about the password and stays counted. Anything * A 401 is a judgment about the password and stays counted. Anything
* else -- refused, timed out, DNS, TLS -- is the upstream failing to * else -- refused, timed out, DNS, TLS -- is the upstream failing to
* answer, which says nothing about the credentials and must not spend * answer, which says nothing about the credentials and must not spend
* somebody's attempts while they wait for it to come back (#239). * somebody's attempts while they wait for it to come back (#239).
@@ -557,7 +559,7 @@ export function createApp(basePath = config.basePath): Hono<Env> {
api.post("/account/2fa/begin", requireSession, async (c) => { api.post("/account/2fa/begin", requireSession, async (c) => {
try { try {
// Nothing is stored yet; the client hands the URL back to confirm. // Nothing is stored yet; the client hands the URL back to confirm.
return c.json(beginOtpEnrolment(await accountCtx(c))); return c.json(beginOtpEnrollment(await accountCtx(c)));
} catch (err) { } catch (err) {
return accountFailure(c, err); return accountFailure(c, err);
} }
@@ -582,7 +584,7 @@ export function createApp(basePath = config.basePath): Hono<Env> {
* the moment 2FA is enabled this session can no longer authenticate at all. * the moment 2FA is enabled this session can no longer authenticate at all.
*/ */
try { try {
assertEnrolmentCode(body.url, code); assertEnrollmentCode(body.url, code);
} catch (err) { } catch (err) {
return accountFailure(c, err); return accountFailure(c, err);
} }
@@ -687,6 +689,30 @@ export function createApp(basePath = config.basePath): Hono<Env> {
} }
}); });
// ---------- Administration: Stalwart's permission list ----------
/*
* The one administration read that is not a JMAP call: the labeled list of
* permissions from Stalwart's schema, for the Roles picker. Behind the same
* two gates as the registry methods, so a session that may not administer
* learns nothing from it.
*/
api.get("/admin/permissions", requireSession, apiRateLimited, async (c) => {
const session = c.get("session");
if (!administrationAllowed(config.administration, session.remember)) {
return config.administration
? c.json({ error: "administration_needs_own_device" }, 403)
: c.json({ error: "administration_disabled" }, 403);
}
try {
const upstream = await getUpstreamSession(session.id, session.authorization, upstreamFor(session.username));
const permissions = await fetchPermissions(session.authorization, upstream.baseUrl);
if (!permissions) return c.json({ error: "upstream_error" }, 502);
return c.json({ permissions });
} catch (err) {
return upstreamFailure(c, err);
}
});
// ---------- Blob upload ---------- // ---------- Blob upload ----------
api.post("/upload/:accountId", requireSession, async (c) => { api.post("/upload/:accountId", requireSession, async (c) => {
const session = c.get("session"); const session = c.get("session");
@@ -865,8 +891,17 @@ function sessionExtras(session: LiveSession, info: AccountInfo = { locale: null,
remember: session.remember, remember: session.remember,
/** Locale configured for the account in Stalwart's directory, if readable. */ /** Locale configured for the account in Stalwart's directory, if readable. */
userLocale: info.locale, userLocale: info.locale,
/** What the upstream server would tell us about itself. */ /**
server: { edition: info.edition }, * What the upstream server would tell us about itself, and -- for a
* session that may administer -- where the operator says its own
* administration is.
*/
server: {
edition: info.edition,
adminUrl: administrationAllowed(config.administration, session.remember) ? adminUrlFor(session.username, info.adminUrl ?? null) : null,
/** SHOW_ENTERPRISE_NOTICES: say "Enterprise feature" on Enterprise too, as the demo does. */
enterpriseNotices: config.showEnterpriseNotices,
},
/** /**
* Whether this session may administer: the installation offers it * Whether this session may administer: the installation offers it
* (ADMINISTRATION) and the person signed in on a device marked as their own. * (ADMINISTRATION) and the person signed in on a device marked as their own.
@@ -915,7 +950,7 @@ const PASSTHROUGH_HEADERS = new Set(["content-type", "content-disposition", "con
* small IncomingMessage/ServerResponse pair. * small IncomingMessage/ServerResponse pair.
* *
* Returns a Response Hono treats as already sent: the raw bindings are * Returns a Response Hono treats as already sent: the raw bindings are
* written to directly, and the returned value is never serialised. * written to directly, and the returned value is never serialized.
*/ */
const SSE_HEADERS = { const SSE_HEADERS = {
"content-type": "text/event-stream", "content-type": "text/event-stream",
+1 -1
View File
@@ -77,7 +77,7 @@ test("junk in the chain is discarded rather than used as a key", () => {
assert.equal(resolveClientIp("127.0.0.1", { forwardedFor: "" }, cfg), "127.0.0.1"); assert.equal(resolveClientIp("127.0.0.1", { forwardedFor: "" }, cfg), "127.0.0.1");
}); });
test("bracketed and IPv4-mapped forms are normalised", () => { test("bracketed and IPv4-mapped forms are normalized", () => {
assert.equal(resolveClientIp("::1", { forwardedFor: "[2001:db8::5]" }, cfg), "2001:db8::5"); assert.equal(resolveClientIp("::1", { forwardedFor: "[2001:db8::5]" }, cfg), "2001:db8::5");
assert.equal(resolveClientIp("::1", { forwardedFor: "::ffff:198.51.100.7" }, cfg), "198.51.100.7"); assert.equal(resolveClientIp("::1", { forwardedFor: "::ffff:198.51.100.7" }, cfg), "198.51.100.7");
}); });
+55 -17
View File
@@ -202,9 +202,9 @@ function readSettingsPolicy(): { defaults: Record<string, unknown>; enforced: Re
* having an outage would take the other four down with it. What happens when * 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. * one is unreachable is a sign-in question, answered in #239.
*/ */
function readStalwartServers(): Record<string, string> { function readStalwartServers(): { urls: Record<string, string>; adminUrls: Record<string, string> } {
const file = process.env.STALWART_SERVERS_FILE; const file = process.env.STALWART_SERVERS_FILE;
if (!file) return {}; if (!file) return { urls: {}, adminUrls: {} };
if (!existsSync(file)) throw new Error(`STALWART_SERVERS_FILE does not exist: ${file}`); if (!existsSync(file)) throw new Error(`STALWART_SERVERS_FILE does not exist: ${file}`);
let raw: unknown; let raw: unknown;
@@ -213,33 +213,55 @@ function readStalwartServers(): Record<string, string> {
} catch (err) { } catch (err) {
throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): ${(err as Error).message}`); throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): ${(err as Error).message}`);
} }
return parseStalwartServers(raw, file);
}
/** The servers file's contents, checked. Exported so the shipped example is tested by the parser that reads it. */
export function parseStalwartServers(raw: unknown, file: string): { urls: Record<string, string>; adminUrls: Record<string, string> } {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) { if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): expected an object of domain to URL`); throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): expected an object of domain to URL`);
} }
const out: Record<string, string> = {}; const out: Record<string, string> = {};
for (const [rawDomain, rawUrl] of Object.entries(raw as Record<string, unknown>)) { const adminUrls: Record<string, string> = {};
for (const [rawDomain, rawValue] of Object.entries(raw as Record<string, unknown>)) {
/* The example file explains itself in a `_comment` key, and a copy of it
used to stop the server as "not a URL". No mail domain starts with an
underscore, so a key that does is a note, not a mapping. */
if (rawDomain.startsWith("_")) continue;
/* Lower-cased and stripped of the root dot, because that is how a domain /* 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 taken off a username will arrive and comparing them any other way means
a mapping that silently never matches. */ a mapping that silently never matches. */
const domain = rawDomain.trim().toLowerCase().replace(/\.$/, ""); const domain = rawDomain.trim().toLowerCase().replace(/\.$/, "");
if (!domain) throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): a domain key is empty`); 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 (domain in out) throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): "${domain}" appears twice once normalized`);
if (typeof rawUrl !== "string") throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): "${domain}" is not a URL`); /* A domain's value is its server's URL, or an object that also names where
let parsed: URL; that server's own administration is: `{"url": …, "adminUrl": …}`. */
try { const value = rawValue && typeof rawValue === "object" && !Array.isArray(rawValue) ? (rawValue as Record<string, unknown>) : { url: rawValue };
parsed = new URL(rawUrl); if (typeof value.url !== "string") throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): "${domain}" is not a URL`);
} catch { out[domain] = httpUrl(value.url, `STALWART_SERVERS_FILE (${file}): "${domain}"`);
throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): "${domain}" is not an absolute URL`); if (value.adminUrl !== undefined) {
if (typeof value.adminUrl !== "string") throw new Error(`Invalid STALWART_SERVERS_FILE (${file}): "${domain}" adminUrl is not a URL`);
adminUrls[domain] = httpUrl(value.adminUrl, `STALWART_SERVERS_FILE (${file}): "${domain}" adminUrl`);
} }
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; return { urls: out, adminUrls };
} }
/** An absolute http(s) URL without its trailing slash, or a startup error naming where it came from. */
function httpUrl(raw: string, where: string): string {
let parsed: URL;
try {
parsed = new URL(raw);
} catch {
throw new Error(`Invalid ${where}: not an absolute URL`);
}
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`Invalid ${where}: must be http or https`);
return raw.replace(/\/+$/, "");
}
const stalwartServers = readStalwartServers();
export const config = { export const config = {
isProd, isProd,
appName: env("APP_NAME", "ihasmail"), appName: env("APP_NAME", "ihasmail"),
@@ -275,7 +297,23 @@ export const config = {
*/ */
basePath: normalizeBasePath(process.env.BASE_PATH), basePath: normalizeBasePath(process.env.BASE_PATH),
stalwartUrl, stalwartUrl,
stalwartServers: readStalwartServers(), stalwartServers: stalwartServers.urls,
/**
* Where an administrator reaches Stalwart's own administration, for the
* pointer on ihasmail's dashboard. Optional, and separate from STALWART_URL,
* which is how *this server* reaches Stalwart -- often an address no browser
* can open. Unset, the dashboard names Stalwart's administration without a
* link. A domain routed elsewhere takes its server's `adminUrl` instead.
*/
stalwartAdminUrl: process.env.STALWART_ADMIN_URL ? httpUrl(process.env.STALWART_ADMIN_URL, "STALWART_ADMIN_URL") : "",
stalwartAdminUrls: stalwartServers.adminUrls,
/**
* Say that an Enterprise-only section is Enterprise-only even on an
* Enterprise server. Off, as a real installation wants it; the public demo
* turns it on, because it reports Enterprise to show those sections and
* should not suggest they come without the license.
*/
showEnterpriseNotices: bool("SHOW_ENTERPRISE_NOTICES", false),
appSecret, appSecret,
trustProxy: bool("TRUST_PROXY", true), trustProxy: bool("TRUST_PROXY", true),
/** /**
@@ -318,7 +356,7 @@ export const config = {
compressJmap: process.env.COMPRESS_JMAP !== "0", compressJmap: process.env.COMPRESS_JMAP !== "0",
/* /*
* How push reaches the browser. "relay" holds one upstream stream per tab * How push reaches the browser. "relay" holds one upstream stream per tab
* (today's behaviour). "subscribe" registers one JMAP PushSubscription per * (today's behavior). "subscribe" registers one JMAP PushSubscription per
* account and fans Stalwart's POSTs out to that account's tabs, holding no * 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 * upstream connection at all -- see push.ts. It needs PUSH_URL: the https
* origin Stalwart can reach ihasmail at, with a certificate it trusts. * origin Stalwart can reach ihasmail at, with a certificate it trusts.
+1 -1
View File
@@ -45,7 +45,7 @@ test("an unmapped domain still goes to the default while others are mapped", ()
}); });
test("the domain is matched however it was typed", () => { test("the domain is matched however it was typed", () => {
// Keys are normalised on load; the username has to be normalised the same // Keys are normalized on load; the username has to be normalized the same
// way or a mapping silently never matches. // way or a mapping silently never matches.
config.stalwartServers["mapped.test"] = "https://mail.mapped.test"; config.stalwartServers["mapped.test"] = "https://mail.mapped.test";
try { try {
+1 -1
View File
@@ -15,7 +15,7 @@ const { createApp } = await import("./app.js");
* it is pointed at. * it is pointed at.
*/ */
test("addresses we must never reach are recognised", () => { test("addresses we must never reach are recognized", () => {
for (const a of [ for (const a of [
"127.0.0.1", "10.1.2.3", "172.16.0.1", "172.31.255.255", "192.168.1.1", "127.0.0.1", "10.1.2.3", "172.16.0.1", "172.31.255.255", "192.168.1.1",
"169.254.169.254", // cloud metadata, the classic SSRF target "169.254.169.254", // cloud metadata, the classic SSRF target
+192 -1
View File
@@ -6,7 +6,7 @@ class Refused extends Error {
constructor(readonly type: string, description?: string) { super(description ?? type); } 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) }); const make = (role: MockRole, extra: { metricsOff?: boolean; now?: Date } = {}) => createDirectory({ accountId: "a1", user: "[email protected]", locale: "en_US", role, fail: (t, d) => new Refused(t, d), ...extra });
/** /**
* The mock stands in for a server that decides what each account may do, so * The mock stands in for a server that decides what each account may do, so
@@ -109,3 +109,194 @@ test("the domain validators refuse what the live server refused, in its words",
const updated = set({ update: { d2: { catchAllAddress: "postmaster" } } }) as { notUpdated?: Record<string, { type: string; description: string }> }; 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"]); assert.deepEqual([updated.notUpdated?.d2?.type, updated.notUpdated?.d2?.description], ["invalidPatch", "Invalid email address"]);
}); });
/** The dashboard's feeds: counts, the queue, and the metric history. */
test("counts come back with no ids when the client asks for a total and no page", () => {
const dir = make("admin");
const r = dir.handlers["x:QueuedMessage/query"]!({ limit: 0, calculateTotal: true }) as { ids: string[]; total: number };
assert.deepEqual(r.ids, []);
assert.equal(r.total, 9);
});
test("the metric history answers the filter the dashboard sends, newest first", () => {
const dir = make("admin", { now: new Date("2026-09-15T14:25:00Z") });
const q = dir.handlers["x:Metric/query"]!({
filter: { timestampIsGreaterThanOrEqual: "2026-09-14T14:25:00Z", metric: ["server.memory"] },
sort: [{ property: "timestamp", isAscending: false }],
}) as { ids: string[] };
const { list } = dir.handlers["x:Metric/get"]!({ ids: q.ids }) as { list: Array<{ metric: string; timestamp: string }> };
assert.equal(list.length, 24);
assert.ok(list.every((m) => m.metric === "server.memory"));
const newest = (dir.handlers["x:Metric/get"]!({ ids: [q.ids[0]] }) as { list: Array<{ timestamp: string }> }).list[0]!;
const next = (dir.handlers["x:Metric/get"]!({ ids: [q.ids[1]] }) as { list: Array<{ timestamp: string }> }).list[0]!;
assert.equal(newest.timestamp, "2026-09-15T14:00:00Z");
assert.ok(newest.timestamp > next.timestamp);
// A bare timestamp is what a live server refuses.
assert.throws(() => dir.handlers["x:Metric/query"]!({ filter: { timestamp: "2026-09-15T00:00:00Z" } }), (e: Refused) => e.type === "unsupportedFilter");
});
test("a tenant administrator gets the queue but not the history, and Community refuses the history", () => {
const tenant = make("tenant-admin");
assert.equal((tenant.handlers["x:QueuedMessage/query"]!({ calculateTotal: true }) as { total: number }).total, 9);
assert.throws(() => tenant.handlers["x:Metric/query"]!({}), (e: Refused) => e.type === "forbidden");
const community = make("admin", { metricsOff: true });
assert.throws(() => community.handlers["x:Metric/query"]!({}), (e: Refused) => e.type === "forbidden" && /Enterprise/.test(e.message));
});
test("helpdesk may count domains, which is what the demo's helpdesk may do", () => {
assert.ok(permissionsFor("helpdesk").includes("sysDomainQuery"));
assert.ok(!permissionsFor("helpdesk").includes("sysMetricQuery"));
});
/** Groups: accounts of type Group, whose members carry the membership. */
test("a group's members are the users whose memberships name it", () => {
const dir = make("admin");
const r = dir.handlers["x:Account/query"]!({ filter: { "@type": "User", memberGroupIds: "g2" }, calculateTotal: true }) as { ids: string[]; total: number };
assert.ok(r.total >= 2);
const { list } = dir.handlers["x:Account/get"]!({ ids: r.ids, properties: ["memberGroupIds"] }) as { list: Array<{ memberGroupIds: Record<string, boolean> }> };
assert.ok(list.every((a) => a.memberGroupIds.g2));
});
test("a membership pointer moves only that membership, and a group cannot join one", () => {
const dir = make("admin");
const [ada] = (dir.handlers["x:Account/query"]!({ filter: { "@type": "User", text: "lovelace" } }) as { ids: string[] }).ids;
dir.handlers["x:Account/set"]!({ update: { [ada!]: { "memberGroupIds/g1": true } } });
const read = () => ((dir.handlers["x:Account/get"]!({ ids: [ada], properties: ["memberGroupIds"] }) as { list: Array<{ memberGroupIds: Record<string, boolean> }> }).list[0]!.memberGroupIds);
assert.deepEqual(Object.keys(read()).sort(), ["g1", "g2"]);
dir.handlers["x:Account/set"]!({ update: { [ada!]: { "memberGroupIds/g2": null } } });
assert.deepEqual(Object.keys(read()), ["g1"]);
const nested = dir.handlers["x:Account/set"]!({ update: { g1: { "memberGroupIds/g2": true } } }) as { notUpdated?: Record<string, { type: string }> };
assert.equal(nested.notUpdated?.g1?.type, "invalidProperties");
const bogus = dir.handlers["x:Account/set"]!({ update: { [ada!]: { "memberGroupIds/u1": true } } }) as { notUpdated?: Record<string, { type: string }> };
assert.equal(bogus.notUpdated?.[ada!]?.type, "invalidForeignKey");
});
test("a group is kept while members name it, and goes once they are out", () => {
const dir = make("admin");
const refused = dir.handlers["x:Account/set"]!({ destroy: ["g2"] }) as { notDestroyed?: Record<string, { type: string; linkedObjects: Array<{ object: string }> }> };
assert.equal(refused.notDestroyed?.g2?.type, "objectIsLinked");
assert.ok(refused.notDestroyed!.g2!.linkedObjects.every((l) => l.object === "Account"));
const members = (dir.handlers["x:Account/query"]!({ filter: { "@type": "User", memberGroupIds: "g2" } }) as { ids: string[] }).ids;
dir.handlers["x:Account/set"]!({ update: Object.fromEntries(members.map((id) => [id, { "memberGroupIds/g2": null }])) });
const done = dir.handlers["x:Account/set"]!({ destroy: ["g2"] }) as { destroyed: string[] };
assert.deepEqual(done.destroyed, ["g2"]);
});
test("a group is created without a password, with Default roles", () => {
const dir = make("admin");
const r = dir.handlers["x:Account/set"]!({ create: { n: { "@type": "Group", name: "sales", domainId: "d1", roles: { "@type": "Default" }, permissions: { "@type": "Inherit" }, quotas: {}, aliases: {} } } }) as { created: Record<string, { id: string }> };
const id = r.created.n!.id;
const { list } = dir.handlers["x:Account/get"]!({ ids: [id] }) as { list: Array<Record<string, unknown>> };
assert.equal(list[0]!["@type"], "Group");
assert.ok(!("memberGroupIds" in list[0]!));
});
/** Mailing lists: their own object, with a set of recipient addresses. */
test("a list is created, found by text, and read back with its address", () => {
const dir = make("admin");
const r = dir.handlers["x:MailingList/set"]!({ create: { n: { name: "team", domainId: "d1", recipients: { "[email protected]": true }, aliases: {} } } }) as { created: Record<string, { id: string }> };
const id = r.created.n!.id;
const q = dir.handlers["x:MailingList/query"]!({ filter: { text: "team" }, calculateTotal: true }) as { ids: string[] };
assert.deepEqual(q.ids, [id]);
const { list } = dir.handlers["x:MailingList/get"]!({ ids: [id] }) as { list: Array<{ emailAddress: string; recipients: Record<string, boolean> }> };
assert.match(list[0]!.emailAddress, /^team@/);
assert.deepEqual(list[0]!.recipients, { "[email protected]": true });
});
test("a recipient pointer moves one address, and a bad one is refused", () => {
const dir = make("admin");
dir.handlers["x:MailingList/set"]!({ update: { l2: { "recipients/[email protected]": true, "recipients/[email protected]": null } } });
const read = () => (dir.handlers["x:MailingList/get"]!({ ids: ["l2"] }) as { list: Array<{ recipients: Record<string, boolean> }> }).list[0]!.recipients;
assert.deepEqual(Object.keys(read()).sort(), ["[email protected]", "[email protected]"]);
const bad = dir.handlers["x:MailingList/set"]!({ update: { l2: { "recipients/not-an-address": true } } }) as { notUpdated?: Record<string, { type: string }> };
assert.equal(bad.notUpdated?.l2?.type, "invalidPatch");
});
test("a list's address cannot be one an account already has, and a role without the permission is refused", () => {
const dir = make("admin");
const clash = dir.handlers["x:MailingList/set"]!({ create: { n: { name: "demo", domainId: "d1" } } }) as { notCreated?: Record<string, { type: string }> };
assert.equal(clash.notCreated?.n?.type, "primaryKeyViolation");
assert.throws(() => make("helpdesk").handlers["x:MailingList/query"]!({}), (e: Refused) => e.type === "forbidden");
});
/** Roles: Stalwart's grant check, loops, and a role still in use. */
test("a role is refused a permission the caller does not hold, directly or through a base", () => {
const helpdesk = make("helpdesk");
// Helpdesk cannot create roles at all.
assert.throws(() => helpdesk.handlers["x:Role/set"]!({ create: { n: { description: "x" } } }), (e: Refused) => e.type === "forbidden");
const tenant = make("tenant-admin");
const direct = tenant.handlers["x:Role/set"]!({ create: { n: { description: "Too much", enabledPermissions: { sysTenantCreate: true } } } }) as { notCreated?: Record<string, { type: string; description: string }> };
assert.equal(direct.notCreated?.n?.type, "forbidden");
assert.match(direct.notCreated!.n!.description, /not authorized to grant/);
const fine = tenant.handlers["x:Role/set"]!({ create: { n: { description: "Accounts only", enabledPermissions: { sysAccountGet: true }, roleIds: { r1: true } } } }) as { created: Record<string, { id: string }> };
assert.ok(fine.created.n!.id);
});
test("a role cannot build on itself through another, and one in use is kept", () => {
const dir = make("admin");
const loop = dir.handlers["x:Role/set"]!({ update: { r1: { "roleIds/r3": true } } }) as { notUpdated?: Record<string, { type: string }> };
assert.equal(loop.notUpdated?.r1?.type, "invalidPatch");
const inUse = dir.handlers["x:Role/set"]!({ destroy: ["r1"] }) as { notDestroyed?: Record<string, { type: string; linkedObjects: Array<{ object: string }> }> };
assert.equal(inUse.notDestroyed?.r1?.type, "objectIsLinked");
assert.deepEqual([...new Set(inUse.notDestroyed!.r1!.linkedObjects.map((l) => l.object))].sort(), ["Authentication", "Role"]);
const free = dir.handlers["x:Role/set"]!({ destroy: ["r4"] }) as { destroyed: string[] };
assert.deepEqual(free.destroyed, ["r4"]);
});
test("the default roles are read from the authentication settings", () => {
const { list } = make("admin").handlers["x:Authentication/get"]!({ ids: ["singleton"] }) as { list: Array<{ defaultUserRoleIds: Record<string, boolean> }> };
assert.deepEqual(list[0]!.defaultUserRoleIds, { r1: true });
assert.throws(() => make("tenant-admin").handlers["x:Authentication/get"]!({}), (e: Refused) => e.type === "forbidden");
});
test("a permission name Stalwart does not know fails the whole change", () => {
const dir = make("admin");
const r = dir.handlers["x:Role/set"]!({ update: { r4: { "enabledPermissions/notARealPermission": true, description: "Renamed" } } }) as { notUpdated?: Record<string, { type: string; properties: string[] }> };
assert.equal(r.notUpdated?.r4?.type, "invalidPatch");
assert.deepEqual(r.notUpdated!.r4!.properties, ["enabledPermissions/notARealPermission"]);
});
/** Tenants: what they hold is whatever names them, and only an administrator outside one may move things in. */
test("a tenant's members are found by memberTenantId, and it is kept while it has any", () => {
const dir = make("admin");
const accounts = dir.handlers["x:Account/query"]!({ filter: { "@type": "User", memberTenantId: "t1" }, calculateTotal: true, limit: 0 }) as { total: number };
const domains = dir.handlers["x:Domain/query"]!({ filter: { memberTenantId: "t1" }, calculateTotal: true }) as { ids: string[] };
assert.equal(accounts.total, 1);
assert.deepEqual(domains.ids, ["d3"]);
const refused = dir.handlers["x:Tenant/set"]!({ destroy: ["t1"] }) as { notDestroyed?: Record<string, { type: string; linkedObjects: Array<{ object: string }> }> };
assert.equal(refused.notDestroyed?.t1?.type, "objectIsLinked");
assert.deepEqual([...new Set(refused.notDestroyed!.t1!.linkedObjects.map((l) => l.object))].sort(), ["Account", "Domain"]);
});
test("a tenant is created with quotas, a domain moves into it, and an empty one is deleted", () => {
const dir = make("admin");
const c = dir.handlers["x:Tenant/set"]!({ create: { n: { name: "Globex", quotas: { maxAccounts: 5, maxDiskQuota: 1024 } } } }) as { created: Record<string, { id: string }> };
const id = c.created.n!.id;
const bad = dir.handlers["x:Tenant/set"]!({ update: { [id]: { "quotas/maxWidgets": 3 } } }) as { notUpdated?: Record<string, { type: string }> };
assert.equal(bad.notUpdated?.[id]?.type, "invalidPatch");
dir.handlers["x:Domain/set"]!({ update: { d4: { memberTenantId: id } } });
assert.equal((dir.handlers["x:Domain/query"]!({ filter: { memberTenantId: id }, calculateTotal: true }) as { total: number }).total, 1);
dir.handlers["x:Domain/set"]!({ update: { d4: { memberTenantId: null } } });
assert.deepEqual((dir.handlers["x:Tenant/set"]!({ destroy: [id] }) as { destroyed: string[] }).destroyed, [id]);
});
test("a tenant administrator cannot move anything into a tenant", () => {
const dir = make("tenant-admin");
const r = dir.handlers["x:Domain/set"]!({ update: { d4: { memberTenantId: "t1" } } }) as { notUpdated?: Record<string, { type: string; description: string }> };
assert.equal(r.notUpdated?.d4?.type, "invalidPatch");
assert.match(r.notUpdated!.d4!.description, /memberTenantId/);
});
test("something in a tenant has to be on a domain in it, and something in none may be anywhere", () => {
const dir = make("admin");
const outside = dir.handlers["x:MailingList/set"]!({ create: { n: { name: "stray", domainId: "d1", memberTenantId: "t1" } } }) as { notCreated?: Record<string, { type: string; objectId: { object: string } }> };
assert.equal(outside.notCreated?.n?.type, "invalidForeignKey");
assert.equal(outside.notCreated!.n!.objectId.object, "Domain");
const inside = dir.handlers["x:MailingList/set"]!({ create: { n: { name: "team", domainId: "d3", memberTenantId: "t1" } } }) as { created?: Record<string, { id: string }> };
assert.ok(inside.created?.n?.id);
const none = dir.handlers["x:MailingList/set"]!({ create: { n: { name: "open", domainId: "d3" } } }) as { created?: Record<string, { id: string }> };
assert.ok(none.created?.n?.id);
const [someone] = (dir.handlers["x:Account/query"]!({ filter: { "@type": "User", domainId: "d1" } }) as { ids: string[] }).ids;
const move = dir.handlers["x:Account/set"]!({ update: { [someone!]: { memberTenantId: "t1" } } }) as { notUpdated?: Record<string, { type: string }> };
assert.equal(move.notUpdated?.[someone!]?.type, "invalidForeignKey");
});
+332 -24
View File
@@ -13,8 +13,16 @@
* credential's own pointer, `credentials/<index>/secret`; * credential's own pointer, `credentials/<index>/secret`;
* - `x:Account/query` understands AND and nothing else. * - `x:Account/query` understands AND and nothing else.
* *
* What it does not reproduce is tenancy: every caller sees every record. The * It also answers the two feeds Administration's dashboard reads: a short
* real server scopes a tenant administrator's queries, and nothing in the client * outbound queue (`x:QueuedMessage`) and a day and a bit of hourly metric
* history (`x:Metric`), dated from when the mock started. MOCK_METRICS=off
* refuses the history the way a Community server does.
*
* Tenants are there for a system administrator to manage -- one tenant holding a
* domain and an account, `memberTenantId` filters on the queries, and the rule
* that only an administrator outside every tenant may move things into one. What
* it does not reproduce is a tenant administrator's scoping: every caller sees
* every record. The real server scopes those queries, and nothing in the client
* relies on seeing more or less than it is given. * relies on seeing more or less than it is given.
* *
* MOCK_ROLE picks who the demo user is: `admin` (the default), `tenant-admin`, * MOCK_ROLE picks who the demo user is: `admin` (the default), `tenant-admin`,
@@ -22,24 +30,36 @@
* delete them) or `user`. * delete them) or `user`.
*/ */
import { readFileSync } from "node:fs";
type Obj = Record<string, unknown>; type Obj = Record<string, unknown>;
/** Every permission Stalwart 0.16.22 knows, from the snapshot the translations are checked against. */
const KNOWN_PERMISSIONS = new Set(
(JSON.parse(readFileSync(new URL("../../../web/src/locales/permissions/source.json", import.meta.url), "utf8")) as { permissions: Array<{ name: string }> }).permissions.map((p) => p.name),
);
export type MockRole = "admin" | "tenant-admin" | "helpdesk" | "user"; export type MockRole = "admin" | "tenant-admin" | "helpdesk" | "user";
const OPS = ["Get", "Query", "Create", "Update", "Destroy"] as const; const OPS = ["Get", "Query", "Create", "Update", "Destroy"] as const;
const all = (...objects: string[]) => objects.flatMap((o) => OPS.map((op) => `sys${o}${op}`)); const all = (...objects: string[]) => objects.flatMap((o) => OPS.map((op) => `sys${o}${op}`));
/** What the dashboard reads beyond the directory. */
const READ_SERVER = ["sysQueuedMessageGet", "sysQueuedMessageQuery", "sysMetricGet", "sysMetricQuery", "sysApplicationGet", "sysApplicationQuery"];
/** A few of the ordinary ones, so the list looks like what a server sends. */ /** A few of the ordinary ones, so the list looks like what a server sends. */
const USER_PERMISSIONS = ["jmapEmailGet", "jmapEmailSet", "jmapMailboxGet", "sysAccountSettingsGet"]; const USER_PERMISSIONS = ["jmapEmailGet", "jmapEmailUpdate", "jmapMailboxGet", "sysAccountSettingsGet"];
export function permissionsFor(role: MockRole): string[] { export function permissionsFor(role: MockRole): string[] {
switch (role) { switch (role) {
case "admin": case "admin":
return [...USER_PERMISSIONS, ...all("Account", "Domain", "Role", "MailingList", "DkimSignature", "DnsServer", "Tenant"), "impersonate"]; return [...USER_PERMISSIONS, ...all("Account", "Domain", "Role", "MailingList", "DkimSignature", "DnsServer", "Tenant"), ...READ_SERVER, "sysAuthenticationGet", "impersonate"];
case "tenant-admin": case "tenant-admin":
return [...USER_PERMISSIONS, ...all("Account", "Domain", "Role", "MailingList", "DkimSignature", "DnsServer")]; // The queue but not the metric history: Stalwart scopes the one to a
// tenant's domains, and the other has no tenant to scope it by.
return [...USER_PERMISSIONS, ...all("Account", "Domain", "Role", "MailingList", "DkimSignature", "DnsServer"), "sysQueuedMessageGet", "sysQueuedMessageQuery"];
case "helpdesk": case "helpdesk":
return [...USER_PERMISSIONS, "sysAccountGet", "sysAccountQuery", "sysAccountUpdate"]; return [...USER_PERMISSIONS, "sysAccountGet", "sysAccountQuery", "sysAccountUpdate", "sysDomainGet", "sysDomainQuery"];
default: default:
return USER_PERMISSIONS; return USER_PERMISSIONS;
} }
@@ -61,6 +81,10 @@ interface Options {
role: MockRole; role: MockRole;
/** Build the error a method fails with; the mock server owns the type. */ /** Build the error a method fails with; the mock server owns the type. */
fail: (type: string, description?: string) => Error; fail: (type: string, description?: string) => Error;
/** Refuse the metric history, as a Community server does. */
metricsOff?: boolean;
/** When the history ends; the newest hour is the one this falls in. */
now?: Date;
} }
export function createDirectory(opts: Options) { export function createDirectory(opts: Options) {
@@ -81,14 +105,15 @@ export function createDirectory(opts: Options) {
const domains: Obj[] = [ const domains: Obj[] = [
domain("d1", userDomain, { ...managed(true, true, true), aliases: { [`mail.${userDomain}`]: true }, description: "Main domain" }), 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("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: "..." } }), domain("d3", "old-brand.example", { ...managed(false, false, false), description: "No longer used", subAddressing: { "@type": "Custom", customRule: "..." }, memberTenantId: "t1" }),
domain("d4", "spare.example", { description: "Waiting for a tenant" }),
]; ];
const dkimKeys: Obj[] = [ 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: "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: "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 }, { 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. */ /** What Stalwart's BIND serializer writes, including a TXT long enough to be split. */
const zoneFile = (d: Obj): string => { const zoneFile = (d: Obj): string => {
const n = String(d.name); const n = String(d.name);
const lines = [ const lines = [
@@ -119,16 +144,19 @@ export function createDirectory(opts: Options) {
}; };
const roles: Obj[] = [ const roles: Obj[] = [
{ id: "r1", description: "User", enabledPermissions: flags(USER_PERMISSIONS), disabledPermissions: {}, roleIds: {} }, { id: "r1", description: "User", enabledPermissions: flags(USER_PERMISSIONS), disabledPermissions: {}, roleIds: {}, memberTenantId: null },
{ id: "r2", description: "Helpdesk", enabledPermissions: flags(permissionsFor("helpdesk").filter((p) => p.startsWith("sys"))), disabledPermissions: {}, roleIds: { r1: true } }, { 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 } }, { id: "r3", description: "Directory manager", enabledPermissions: flags(all("Account")), disabledPermissions: {}, roleIds: { r1: true } },
{ id: "r4", description: "Read-only auditor", enabledPermissions: flags(["sysAccountGet", "sysAccountQuery", "sysDomainGet", "sysDomainQuery", "sysLogGet"]), disabledPermissions: flags(["jmapEmailUpdate"]), roleIds: { r1: true } },
]; ];
/** Stalwart's defaults: which roles an account gets when it is given no others. */
const authentication: Record<string, Obj> = { defaultUserRoleIds: { r1: true }, defaultGroupRoleIds: {}, defaultTenantRoleIds: {}, defaultAdminRoleIds: {} };
const ownRoles = opts.role === "admin" || opts.role === "tenant-admin" ? { "@type": "Admin" } : opts.role === "helpdesk" ? { "@type": "Custom", roleIds: { r2: true } } : { "@type": "User" }; 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 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 user = (o: { id?: string; name: string; domain?: string; description: string; roles?: Obj; used?: number; quota?: number; aliases?: string[]; groups?: string[]; password?: boolean; tenant?: string }) => {
const domainId = o.domain === "d2" ? "d2" : "d1"; const domainId = o.domain === "d2" || o.domain === "d3" ? o.domain : "d1";
const row: Obj = { const row: Obj = {
id: o.id ?? `u${counter++}`, id: o.id ?? `u${counter++}`,
"@type": "User", "@type": "User",
@@ -138,7 +166,7 @@ export function createDirectory(opts: Options) {
credentials: o.password === false ? {} : { "0": { "@type": "Password", credentialId: "0", secret: MASKED, otpAuth: null, expiresAt: null, allowedIps: {} } }, 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"), createdAt: new Date(Date.now() - counter * 86_400_000).toISOString().replace(/\.\d{3}Z$/, "Z"),
memberGroupIds: flags(o.groups ?? []), memberGroupIds: flags(o.groups ?? []),
memberTenantId: null, memberTenantId: o.tenant ?? null,
roles: o.roles ?? { "@type": "User" }, roles: o.roles ?? { "@type": "User" },
permissions: { "@type": "Inherit" }, permissions: { "@type": "Inherit" },
quotas: o.quota ? { maxDiskQuota: o.quota * GIB } : {}, quotas: o.quota ? { maxDiskQuota: o.quota * GIB } : {},
@@ -150,14 +178,16 @@ export function createDirectory(opts: Options) {
accounts.push(row); accounts.push(row);
return row; return row;
}; };
// A group's roles are Default or Custom, not a person's User or Admin.
const group = (id: string, name: string, description: string) => 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: {} }); accounts.push({ id, "@type": "Group", name, domainId: "d1", description, memberTenantId: null, roles: { "@type": "Default" }, permissions: { "@type": "Inherit" }, quotas: {}, usedDiskQuota: 0, aliases: {}, createdAt: "2026-08-01T09:00:00Z" });
group("g1", "support", "Support"); group("g1", "support", "Support");
group("g2", "office", "Office"); 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({ 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: "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: "grace", domain: "d2", description: "Grace Hopper", used: 4.7, quota: 5, groups: ["g2"] });
user({ name: "wile", domain: "d3", description: "Wile E. Coyote", roles: { "@type": "Admin" }, used: 2.1, quota: 5, tenant: "t1" });
user({ name: "alan", domain: "d2", description: "Alan Turing", roles: { "@type": "Custom", roleIds: { r2: true } }, used: 0.8, quota: 5, groups: ["g1"] }); 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: "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: "katherine", description: "Katherine Johnson", roles: { "@type": "Custom", roleIds: { r3: true } }, used: 0.4, quota: 5 });
@@ -168,18 +198,82 @@ export function createDirectory(opts: Options) {
user({ name, domain: i % 3 === 0 ? "d2" : "d1", description, used: (i % 7) * 0.6, quota: i % 4 === 0 ? 0 : 5 }); user({ name, domain: i % 3 === 0 ? "d2" : "d1", description, used: (i % 7) * 0.6, quota: i % 4 === 0 ? 0 : 5 });
}); });
// Nine messages waiting, which is what a small live server had queued on the
// day this was written: a few retries and the odd report.
const queue: Obj[] = Array.from({ length: 9 }, (_, i) => ({ id: `q${i + 1}`, createdAt: new Date(Date.UTC(2026, 8, 15, 6 + i)).toISOString(), size: 2400 + i * 310, priority: 0, flags: {} }));
/**
* Thirty hours of history ending in the current hour: a Counter per hour for
* what was queued, and a memory Gauge. Counters that would be zero are left
* out, as Stalwart leaves them out.
*/
const metrics: Obj[] = [];
{
const hour = 3600_000;
const end = Math.floor((opts.now ?? new Date()).getTime() / hour) * hour;
for (let h = 29; h >= 0; h--) {
const at = end - h * hour;
const timestamp = new Date(at).toISOString().replace(/\.\d{3}Z$/, "Z");
const seq = (29 - h) * 10;
const push = (n: number, type: string, metric: string, count: number) => {
if (type === "Counter" && !count) return;
metrics.push({ id: `m${String(seq + n).padStart(4, "0")}`, "@type": type, metric, count, timestamp });
};
push(0, "Gauge", "server.memory", 360_000_000 + ((h * 7_919_000) % 40_000_000));
push(1, "Counter", "queue.message-queued", (h * 5 + 3) % 9);
push(2, "Counter", "queue.authenticated-message-queued", h % 3);
push(3, "Counter", "queue.dsn-queued", h % 11 === 0 ? 1 : 0);
push(4, "Counter", "queue.report-queued", h % 4 === 1 ? 2 : 0);
}
}
const applications: Obj[] = [{ id: "app1", description: "Stalwart Web Interface", enabled: true, urlPrefix: { "/admin": true, "/account": true } }];
/** Tenants: a name, limits, and whatever names them in its memberTenantId. */
const tenants: Obj[] = [
{ id: "t1", name: "Acme Corp", logo: null, roles: { "@type": "Default" }, permissions: { "@type": "Inherit" }, quotas: { maxAccounts: 25, maxDomains: 2, maxDiskQuota: 50 * GIB }, createdAt: "2026-07-01T09:00:00Z" },
];
const tenantUsage = (id: string) => accounts.filter((x) => x.memberTenantId === id).reduce((n, x) => n + Number(x.usedDiskQuota ?? 0), 0);
/**
* Something in a tenant has to be on a domain in that tenant; something in no
* tenant may be on anyone's domain. Both as the live server answered
* (2026-09-15), including the shape of the refusal.
*/
const domainTenantRefused = (o: Obj): Obj | null => {
const tenant = o.memberTenantId ?? null;
const domain = domains.find((d) => d.id === o.domainId);
if (!tenant || !domain || (domain.memberTenantId ?? null) === tenant) return null;
return { type: "invalidForeignKey", objectId: { object: "Domain", id: domain.id } };
};
/** Only an administrator outside every tenant may put things in one; Stalwart refuses anyone else. */
const tenantRefused = (patch: Obj): Obj | null =>
"memberTenantId" in patch && opts.role !== "admin" ? setError("invalidPatch", "Cannot modify memberTenantId property", ["memberTenantId"]) : null;
const refuseMetrics = () => {
if (opts.metricsOff) throw opts.fail("forbidden", "This feature is only available in the Enterprise edition of Stalwart.");
};
/**
* Mailing lists: an address and the addresses it passes mail on to. The
* recipient set's shape is the live server's (2026-09-15).
*/
const lists: Obj[] = [
{ id: "l1", name: "announce", domainId: "d1", description: "Announcements", recipients: flags([opts.user, "[email protected]", "[email protected]", "[email protected]"]), aliases: {}, memberTenantId: null },
{ id: "l2", name: "board", domainId: "d2", description: "Board", recipients: flags(["[email protected]", "[email protected]"]), aliases: {}, memberTenantId: null },
];
const addressOk = (a: unknown) => typeof a === "string" && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(a);
const demand = (perm: string) => { const demand = (perm: string) => {
if (!permissions.has(perm)) throw opts.fail("forbidden", `You do not have the ${perm} permission.`); 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 domainName = (id: unknown) => domains.find((d) => d.id === id)?.name as string | undefined;
const addressOf = (o: Obj) => `${o.name}@${domainName(o.domainId) ?? "invalid"}`; const addressOf = (o: Obj) => `${o.name}@${domainName(o.domainId) ?? "invalid"}`;
/** Every address in use, primary and alias, across accounts. */ /** Every address in use, primary and alias, across accounts and mailing lists. */
const addressTaken = (address: string, except?: string) => 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))); [...accounts, ...lists].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 view = (o: Obj, properties: unknown): Obj => {
const full: Obj = { ...o }; const full: Obj = { ...o };
if (accounts.includes(o)) full.emailAddress = addressOf(o); if (accounts.includes(o) || lists.includes(o)) full.emailAddress = addressOf(o);
if (domains.includes(o)) full.dnsZoneFile = zoneFile(o); if (domains.includes(o)) full.dnsZoneFile = zoneFile(o);
if (full.credentials) { if (full.credentials) {
full.credentials = Object.fromEntries(Object.entries(full.credentials as Obj).map(([k, c]) => [k, { ...(c as Obj), secret: MASKED }])); full.credentials = Object.fromEntries(Object.entries(full.credentials as Obj).map(([k, c]) => [k, { ...(c as Obj), secret: MASKED }]));
@@ -255,7 +349,9 @@ export function createDirectory(opts: Options) {
const handlers: Record<string, (a: Obj) => Obj> = { const handlers: Record<string, (a: Obj) => Obj> = {
"x:Account/get": get(accounts, "sysAccountGet"), "x:Account/get": get(accounts, "sysAccountGet"),
"x:Account/query": query(() => accounts, "sysAccountQuery", ["text", "@type", "domainId", "externalId", "memberGroupIds", "memberTenantId", "name"], (o, f) => "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)), (f["@type"] === undefined || o["@type"] === f["@type"]) && (f.domainId === undefined || o.domainId === f.domainId) &&
(f.memberGroupIds === undefined || Boolean((o.memberGroupIds as Obj | undefined)?.[f.memberGroupIds as string])) &&
(f.memberTenantId === undefined || o.memberTenantId === f.memberTenantId) && matchText(o, f.text) && matchText(o, f.name)),
"x:Account/set": (a) => { "x:Account/set": (a) => {
const created: Obj = {}; const created: Obj = {};
const notCreated: Obj = {}; const notCreated: Obj = {};
@@ -271,11 +367,15 @@ export function createDirectory(opts: Options) {
if (addressTaken(`${o.name}@${domainName(o.domainId)}`)) { notCreated[cid] = setError("primaryKeyViolation", "An account or alias with this email address already exists."); 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); const refused = grantRefused(o.roles);
if (refused) { notCreated[cid] = setError("forbidden", refused); continue; } if (refused) { notCreated[cid] = setError("forbidden", refused); continue; }
if (o.memberTenantId) {
const refusedTenant = tenantRefused(o) ?? domainTenantRefused(o);
if (refusedTenant) { notCreated[cid] = refusedTenant; continue; }
}
const password = Object.values((o.credentials as Obj) ?? {})[0] as Obj | undefined; const password = Object.values((o.credentials as Obj) ?? {})[0] as Obj | undefined;
const weak = password ? weakPassword(password.secret) : null; const weak = password ? weakPassword(password.secret) : null;
if (weak) { notCreated[cid] = setError("invalidProperties", weak, ["secret"]); continue; } if (weak) { notCreated[cid] = setError("invalidProperties", weak, ["secret"]); continue; }
const id = `u${counter++}`; 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 }); accounts.push({ ...(o["@type"] === "Group" ? {} : { 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)}` }; created[cid] = { id, emailAddress: `${o.name}@${domainName(o.domainId)}` };
} }
for (const [id, raw] of Object.entries((a.update as Obj) ?? {})) { for (const [id, raw] of Object.entries((a.update as Obj) ?? {})) {
@@ -284,7 +384,7 @@ export function createDirectory(opts: Options) {
if (!target) { notUpdated[id] = setError("notFound", "Account not found."); continue; } if (!target) { notUpdated[id] = setError("notFound", "Account not found."); continue; }
const patch = raw as Obj; const patch = raw as Obj;
const next = structuredClone(target); const next = structuredClone(target);
let failure: Obj | null = null; let failure: Obj | null = tenantRefused(patch);
for (const [path, value] of Object.entries(patch)) { 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 === "id" || path === "@type" || path === "usedDiskQuota" || path === "emailAddress") { failure = setError("invalidProperties", `Property ${path} cannot be changed.`, [path]); break; }
if (path.endsWith("/secret")) { if (path.endsWith("/secret")) {
@@ -297,6 +397,12 @@ export function createDirectory(opts: Options) {
} }
setPointer(next, path, value); setPointer(next, path, value);
} }
// Memberships name groups, and only a person has them: groups do not nest.
if (!failure && Object.keys(patch).some((p) => p === "memberGroupIds" || p.startsWith("memberGroupIds/"))) {
if (target["@type"] === "Group") failure = setError("invalidProperties", "Groups cannot be members of other groups.", ["memberGroupIds"]);
else if (Object.keys((next.memberGroupIds as Obj) ?? {}).some((g) => accounts.find((x) => x.id === g)?.["@type"] !== "Group")) failure = setError("invalidForeignKey", "Group does not exist.", ["memberGroupIds"]);
}
if (!failure && "memberTenantId" in patch) failure = domainTenantRefused(next);
if (!failure && ("roles" in patch || "permissions" in patch)) { if (!failure && ("roles" in patch || "permissions" in patch)) {
const refused = grantRefused(next.roles); const refused = grantRefused(next.roles);
if (refused) failure = setError("forbidden", refused); if (refused) failure = setError("forbidden", refused);
@@ -319,7 +425,10 @@ export function createDirectory(opts: Options) {
const i = accounts.findIndex((x) => x.id === id); const i = accounts.findIndex((x) => x.id === id);
if (i < 0) { notDestroyed[id] = setError("notFound", "Account not found."); continue; } 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])) { if (accounts[i]!["@type"] === "Group" && accounts.some((x) => (x.memberGroupIds as Obj | undefined)?.[id])) {
notDestroyed[id] = { ...setError("objectIsLinked", "Group still has members."), linkedObjects: {} }; // Every member's memberGroupIds names the group, which is a link the
// registry will not delete through. The shape is the live server's,
// from a throwaway group on 2026-09-15.
notDestroyed[id] = { type: "objectIsLinked", objectId: { object: "Account", id }, linkedObjects: accounts.filter((x) => (x.memberGroupIds as Obj | undefined)?.[id]).map((x) => ({ object: "Account", id: x.id })) };
continue; continue;
} }
accounts.splice(i, 1); accounts.splice(i, 1);
@@ -328,7 +437,7 @@ export function createDirectory(opts: Options) {
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 } : {}) }; 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/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/query": query(() => domains, "sysDomainQuery", ["text", "aliases", "memberTenantId", "name"], (o, f) => (f.memberTenantId === undefined || o.memberTenantId === f.memberTenantId) && matchText(o, f.text) && matchText(o, f.name)),
"x:Domain/set": (a) => { "x:Domain/set": (a) => {
const created: Obj = {}; const created: Obj = {};
const notCreated: Obj = {}; const notCreated: Obj = {};
@@ -355,6 +464,9 @@ export function createDirectory(opts: Options) {
demand("sysDomainUpdate"); demand("sysDomainUpdate");
const target = domains.find((d) => d.id === id); const target = domains.find((d) => d.id === id);
if (!target) { notUpdated[id] = setError("notFound", "Domain not found."); continue; } if (!target) { notUpdated[id] = setError("notFound", "Domain not found."); continue; }
const refusedTenant = tenantRefused(raw as Obj);
if (refusedTenant) { notUpdated[id] = refusedTenant; continue; }
if ((raw as Obj).memberTenantId && !tenants.some((x) => x.id === (raw as Obj).memberTenantId)) { notUpdated[id] = setError("invalidForeignKey", "Tenant does not exist.", ["memberTenantId"]); continue; }
const next = structuredClone(target); const next = structuredClone(target);
for (const [path, value] of Object.entries(raw as Obj)) setPointer(next, path, value); 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. // Live on 2026-09-13: a catch-all that is not a whole address.
@@ -379,7 +491,8 @@ export function createDirectory(opts: Options) {
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 } : {}) }; 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/get": get(dkimKeys, "sysDkimSignatureGet"),
"x:DkimSignature/query": query(() => dkimKeys, "sysDkimSignatureQuery", ["domainId", "memberTenantId"], (o, f) => f.domainId === undefined || o.domainId === f.domainId), "x:DkimSignature/query": query(() => dkimKeys, "sysDkimSignatureQuery", ["domainId", "memberTenantId"], (o, f) =>
(f.domainId === undefined || o.domainId === f.domainId) && (f.memberTenantId === undefined || (o.memberTenantId ?? null) === f.memberTenantId)),
"x:DkimSignature/set": (a) => { "x:DkimSignature/set": (a) => {
const destroyed: string[] = []; const destroyed: string[] = [];
for (const id of (a.destroy as string[]) ?? []) { for (const id of (a.destroy as string[]) ?? []) {
@@ -394,8 +507,200 @@ export function createDirectory(opts: Options) {
demand("sysDnsServerGet"); 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: [] }; 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:QueuedMessage/get": get(queue, "sysQueuedMessageGet"),
"x:QueuedMessage/query": query(() => queue, "sysQueuedMessageQuery", [], () => true),
"x:Metric/get": (a) => {
refuseMetrics();
return get(metrics, "sysMetricGet")(a);
},
// Ids sort the way timestamps do, so the helper's newest-first order is the
// `timestamp` descending the dashboard asks for.
"x:Metric/query": (a) => {
refuseMetrics();
return query(() => metrics, "sysMetricQuery", ["timestampIsGreaterThanOrEqual", "timestampIsLessThanOrEqual", "metric"], (o, f) =>
(f.timestampIsGreaterThanOrEqual === undefined || String(o.timestamp) >= String(f.timestampIsGreaterThanOrEqual)) &&
(f.timestampIsLessThanOrEqual === undefined || String(o.timestamp) <= String(f.timestampIsLessThanOrEqual)) &&
(!Array.isArray(f.metric) || (f.metric as string[]).includes(o.metric as string)))(a);
},
"x:MailingList/get": get(lists, "sysMailingListGet"),
"x:MailingList/query": query(() => lists, "sysMailingListQuery", ["text", "memberTenantId"], (o, f) => (f.memberTenantId === undefined || o.memberTenantId === f.memberTenantId) && matchText(o, f.text)),
"x:MailingList/set": (a) => {
const created: Obj = {};
const notCreated: Obj = {};
const updated: Obj = {};
const notUpdated: Obj = {};
const destroyed: string[] = [];
const notDestroyed: Obj = {};
const check = (o: Obj, id?: string): Obj | null => {
if (typeof o.name !== "string" || !/^[a-z0-9._-]+$/i.test(o.name)) return setError("invalidProperties", "Invalid email local part", ["name"]);
if (!domainName(o.domainId)) return setError("invalidForeignKey", "Domain does not exist.", ["domainId"]);
if (addressTaken(`${o.name}@${domainName(o.domainId)}`, id)) return setError("primaryKeyViolation", "An account or alias with this email address already exists.");
if (Object.keys((o.recipients as Obj) ?? {}).some((r) => !addressOk(r))) return setError("invalidProperties", "Invalid email address", ["recipients"]);
return null;
};
for (const [cid, raw] of Object.entries((a.create as Obj) ?? {})) {
demand("sysMailingListCreate");
const o: Obj = { recipients: {}, aliases: {}, description: null, ...(raw as Obj) };
const failure = check(o) ?? (o.memberTenantId ? (tenantRefused(o) ?? domainTenantRefused(o)) : null);
if (failure) { notCreated[cid] = failure; continue; }
const id = `l${counter++}`;
lists.push({ memberTenantId: null, ...o, id });
created[cid] = { id, emailAddress: `${o.name}@${domainName(o.domainId)}` };
}
for (const [id, raw] of Object.entries((a.update as Obj) ?? {})) {
demand("sysMailingListUpdate");
const target = lists.find((x) => x.id === id);
if (!target) { notUpdated[id] = setError("notFound", "Mailing list not found."); continue; }
const next = structuredClone(target);
for (const [path, value] of Object.entries(raw as Obj)) setPointer(next, path, value);
const failure = check(next, id);
if (failure) { notUpdated[id] = { ...failure, type: failure.type === "invalidProperties" ? "invalidPatch" : failure.type }; continue; }
Object.assign(target, next);
updated[id] = null;
}
for (const id of (a.destroy as string[]) ?? []) {
demand("sysMailingListDestroy");
const i = lists.findIndex((x) => x.id === id);
if (i < 0) { notDestroyed[id] = setError("notFound", "Mailing list not found."); continue; }
lists.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 } : {}) };
},
// Which roles Stalwart hands out by default. Its own settings object; the
// Roles screen reads it to warn before a default role is changed.
"x:Authentication/get": (a) => {
demand("sysAuthenticationGet");
const ids = (a.ids as string[] | null | undefined) ?? ["singleton"];
return { accountId: opts.accountId, state: "1", list: ids.filter((id) => id === "singleton").map((id) => ({ id, ...authentication })), notFound: ids.filter((id) => id !== "singleton") };
},
"x:Role/set": (a) => {
const created: Obj = {};
const notCreated: Obj = {};
const updated: Obj = {};
const notUpdated: Obj = {};
const destroyed: string[] = [];
const notDestroyed: Obj = {};
/** Stalwart refuses a role whose permissions -- its own or inherited -- the caller does not hold. */
const check = (o: Obj, id?: string): Obj | null => {
if (typeof o.description !== "string" || !o.description.trim()) return setError("invalidProperties", "String cannot be empty", ["description"]);
const seen = new Set<string>();
const walk = (rid: string): boolean => {
if (rid === id) return false;
if (seen.has(rid)) return true;
seen.add(rid);
const r = roles_(rid);
return !!r && Object.keys((r.roleIds as Obj) ?? {}).every(walk);
};
if (!Object.keys((o.roleIds as Obj) ?? {}).every(walk)) return setError("invalidProperties", "A role cannot inherit from itself or from a role that does not exist.", ["roleIds"]);
// A name that is not a permission fails the whole change, as the live server does.
for (const set of ["enabledPermissions", "disabledPermissions"]) {
const bad = Object.keys((o[set] as Obj) ?? {}).find((p) => !KNOWN_PERMISSIONS.has(p));
if (bad) return setError("invalidProperties", "Invalid value for object property", [`${set}/${bad}`]);
}
const granted = new Set(Object.keys((o.enabledPermissions as Obj) ?? {}));
for (const rid of seen) for (const p of Object.keys((roles_(rid)!.enabledPermissions as Obj) ?? {})) granted.add(p);
const missing = [...granted].filter((p) => !permissions.has(p));
if (missing.length) return setError("forbidden", `You are not authorized to grant permissions: ${missing.slice(0, 5).join(", ")}.`);
return null;
};
for (const [cid, raw] of Object.entries((a.create as Obj) ?? {})) {
demand("sysRoleCreate");
const o: Obj = { enabledPermissions: {}, disabledPermissions: {}, roleIds: {}, ...(raw as Obj) };
const failure = check(o);
if (failure) { notCreated[cid] = failure; continue; }
const id = `r${counter++}`;
roles.push({ ...o, id, memberTenantId: null });
created[cid] = { id };
}
for (const [id, raw] of Object.entries((a.update as Obj) ?? {})) {
demand("sysRoleUpdate");
const target = roles_(id);
if (!target) { notUpdated[id] = setError("notFound", "Role not found."); continue; }
const next = structuredClone(target);
for (const [path, value] of Object.entries(raw as Obj)) setPointer(next, path, value);
const failure = check(next, id);
if (failure) { notUpdated[id] = failure.type === "invalidProperties" ? { ...failure, type: "invalidPatch" } : failure; continue; }
Object.assign(target, next);
updated[id] = null;
}
for (const id of (a.destroy as string[]) ?? []) {
demand("sysRoleDestroy");
if (!roles_(id)) { notDestroyed[id] = setError("notFound", "Role not found."); continue; }
const linked = [
...accounts.filter((x) => ((x.roles as Obj | undefined)?.roleIds as Obj | undefined)?.[id]).map((x) => ({ object: "Account", id: x.id })),
...roles.filter((x) => (x.roleIds as Obj | undefined)?.[id]).map((x) => ({ object: "Role", id: x.id })),
...(Object.values(authentication).some((set) => (set as Obj)[id]) ? [{ object: "Authentication", id: "singleton" }] : []),
];
if (linked.length) { notDestroyed[id] = { type: "objectIsLinked", objectId: { object: "Role", id }, linkedObjects: linked }; continue; }
roles.splice(roles.findIndex((x) => x.id === id), 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:Tenant/get": (a) => {
demand("sysTenantGet");
for (const x of tenants) x.usedDiskQuota = tenantUsage(x.id as string);
return get(tenants, "sysTenantGet")(a);
},
"x:Tenant/query": query(() => tenants, "sysTenantQuery", ["text"], (o, f) => matchText(o, f.text)),
"x:Tenant/set": (a) => {
const created: Obj = {};
const notCreated: Obj = {};
const updated: Obj = {};
const notUpdated: Obj = {};
const destroyed: string[] = [];
const notDestroyed: Obj = {};
const check = (o: Obj): Obj | null => {
if (typeof o.name !== "string" || !o.name.trim()) return setError("invalidProperties", "String cannot be empty", ["name"]);
for (const [k, v] of Object.entries((o.quotas as Obj) ?? {})) {
if (!["maxAccounts", "maxGroups", "maxDomains", "maxMailingLists", "maxRoles", "maxOauthClients", "maxDkimKeys", "maxDnsServers", "maxDirectories", "maxAcmeProviders", "maxDiskQuota"].includes(k) || typeof v !== "number" || v < 0) {
return setError("invalidProperties", "Invalid value for object property", [`quotas/${k}`]);
}
}
return grantRefused(o.roles) ? setError("forbidden", grantRefused(o.roles)!) : null;
};
for (const [cid, raw] of Object.entries((a.create as Obj) ?? {})) {
demand("sysTenantCreate");
const o: Obj = { logo: null, roles: { "@type": "Default" }, permissions: { "@type": "Inherit" }, quotas: {}, ...(raw as Obj) };
const failure = check(o);
if (failure) { notCreated[cid] = failure; continue; }
const id = `t${counter++}`;
tenants.push({ ...o, id, createdAt: new Date().toISOString().replace(/\.\d{3}Z$/, "Z") });
created[cid] = { id };
}
for (const [id, raw] of Object.entries((a.update as Obj) ?? {})) {
demand("sysTenantUpdate");
const target = tenants.find((x) => x.id === id);
if (!target) { notUpdated[id] = setError("notFound", "Tenant not found."); continue; }
const next = structuredClone(target);
for (const [path, value] of Object.entries(raw as Obj)) setPointer(next, path, value);
const failure = check(next);
if (failure) { notUpdated[id] = failure.type === "invalidProperties" ? { ...failure, type: "invalidPatch" } : failure; continue; }
Object.assign(target, next);
updated[id] = null;
}
for (const id of (a.destroy as string[]) ?? []) {
demand("sysTenantDestroy");
if (!tenants.some((x) => x.id === id)) { notDestroyed[id] = setError("notFound", "Tenant not found."); continue; }
const linked = [
...accounts.filter((x) => x.memberTenantId === id).map((x) => ({ object: "Account", id: x.id })),
...domains.filter((x) => x.memberTenantId === id).map((x) => ({ object: "Domain", id: x.id })),
...lists.filter((x) => x.memberTenantId === id).map((x) => ({ object: "MailingList", id: x.id })),
...roles.filter((x) => x.memberTenantId === id).map((x) => ({ object: "Role", id: x.id })),
];
if (linked.length) { notDestroyed[id] = { type: "objectIsLinked", objectId: { object: "Tenant", id }, linkedObjects: linked }; continue; }
tenants.splice(tenants.findIndex((x) => x.id === id), 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 } : {}) };
},
// Stalwart's web interface is an installed application; ihasmail reads its
// prefix to link the dashboard to it.
"x:Application/query": query(() => applications, "sysApplicationQuery", ["text"], () => true),
"x:Application/get": get(applications, "sysApplicationGet"),
"x:Role/get": get(roles, "sysRoleGet"), "x:Role/get": get(roles, "sysRoleGet"),
"x:Role/query": query(() => roles, "sysRoleQuery", ["text", "description", "memberTenantId"], (o, f) => matchText(o, f.description)), "x:Role/query": query(() => roles, "sysRoleQuery", ["text", "description", "memberTenantId"], (o, f) => (f.memberTenantId === undefined || (o.memberTenantId ?? null) === f.memberTenantId) && matchText(o, f.description)),
}; };
return { handlers, permissions: [...permissions], accounts }; return { handlers, permissions: [...permissions], accounts };
@@ -422,6 +727,9 @@ function setPointer(obj: Obj, path: string, value: unknown): void {
node = node[part] as Obj; node = node[part] as Obj;
} }
const last = parts[parts.length - 1]!; const last = parts[parts.length - 1]!;
if (value === null) delete node[last]; // A top-level property set to null reads back as null -- deleting it here
// would leave the old value in place when the change is merged back. A
// nested pointer to null takes the entry out of its set or map.
if (value === null && parts.length > 1) delete node[last];
else node[last] = value; else node[last] = value;
} }
+23 -9
View File
@@ -10,6 +10,10 @@ import { eventGetView, expandOccurrences, occurrenceAt, occurrenceView, parseSyn
import { parseOtpauthUrl, verifyTotp } from "../totp.js"; import { parseOtpauthUrl, verifyTotp } from "../totp.js";
import { holdUntilOf, undoStatusOf } from "./futurerelease.js"; import { holdUntilOf, undoStatusOf } from "./futurerelease.js";
import { createDirectory, mockRole } from "./directory.js"; import { createDirectory, mockRole } from "./directory.js";
import { readFileSync } from "node:fs";
import { gzipSync } from "node:zlib";
const PERMISSION_SNAPSHOT = (JSON.parse(readFileSync(new URL("../../../web/src/locales/permissions/source.json", import.meta.url), "utf8")) as { permissions: Array<{ name: string; label: string }> }).permissions;
const PORT = Number(process.env.MOCK_PORT ?? 8788); const PORT = Number(process.env.MOCK_PORT ?? 8788);
/** /**
@@ -20,7 +24,7 @@ const PORT = Number(process.env.MOCK_PORT ?? 8788);
*/ */
const NO_REGISTRY = process.env.MOCK_NO_REGISTRY === "1"; const NO_REGISTRY = process.env.MOCK_NO_REGISTRY === "1";
/** /**
* Stalwart advertises FUTURERELEASE in the session but only honours it when * Stalwart advertises FUTURERELEASE in the session but only honors it when
* the MTA's own `futureRelease` setting is on -- and that setting defaults to * the MTA's own `futureRelease` setting is on -- and that setting defaults to
* off, in which case the hold is dropped without a word and the message goes * off, in which case the hold is dropped without a word and the message goes
* out at once. Set MOCK_NO_FUTURE_RELEASE=1 to reproduce that trap. * out at once. Set MOCK_NO_FUTURE_RELEASE=1 to reproduce that trap.
@@ -41,6 +45,8 @@ const SHARED_CAPS: Obj = {
const USER = process.env.MOCK_USER ?? "[email protected]"; const USER = process.env.MOCK_USER ?? "[email protected]";
/** Locale the fake directory reports for the account (POSIX style, as Stalwart does). */ /** Locale the fake directory reports for the account (POSIX style, as Stalwart does). */
const MOCK_LOCALE = process.env.MOCK_LOCALE ?? "en_US"; const MOCK_LOCALE = process.env.MOCK_LOCALE ?? "en_US";
/** What /api/account reports. Tenants are managed only on "enterprise"; MOCK_EDITION=enterprise to develop them. */
const MOCK_EDITION = process.env.MOCK_EDITION ?? "oss";
const PASS = process.env.MOCK_PASS ?? "demo"; const PASS = process.env.MOCK_PASS ?? "demo";
/** /**
* Credential state, mutable so the self-service flows can be exercised against * Credential state, mutable so the self-service flows can be exercised against
@@ -194,7 +200,7 @@ function addSignedEmail(o: { which: keyof typeof SIGNED_MESSAGES; from: [string,
* A marketing template of the shape #290 was reported against. * A marketing template of the shape #290 was reported against.
* *
* Nothing in it is unusual an outer 600px wrapper on `bgcolor="#ffffff"`, a * Nothing in it is unusual an outer 600px wrapper on `bgcolor="#ffffff"`, a
* `<style>` block, a coloured call to action, a grey footer and that is the * `<style>` block, a colored call to action, a gray footer and that is the
* point. Every one of those is enough to make `htmlDeclaresColors` true, so a * point. Every one of those is enough to make `htmlDeclaresColors` true, so a
* mock without one could not show what "apply the theme to messages too" does * mock without one could not show what "apply the theme to messages too" does
* to the mail people actually receive: nothing at all. * to the mail people actually receive: nothing at all.
@@ -700,7 +706,7 @@ function genericSet(list: Obj[], prefix: string, onCreate?: (o: Obj) => void) {
* answer. One event still comes back as a bare object, the shape this returned * answer. One event still comes back as a bare object, the shape this returned
* when an invitation was all it had to handle. * when an invitation was all it had to handle.
* *
* The synthetic organiser and attendee only go on events that arrived with a * The synthetic organizer and attendee only go on events that arrived with a
* METHOD. Those are scheduling messages, which is what the invitation fixtures * METHOD. Those are scheduling messages, which is what the invitation fixtures
* are; a plain export is not addressed to anyone, and inventing participants * are; a plain export is not addressed to anyone, and inventing participants
* for it would make imported events look like invitations nobody sent. * for it would make imported events look like invitations nobody sent.
@@ -892,6 +898,7 @@ const directory = createDirectory({
user: USER, user: USER,
locale: MOCK_LOCALE, locale: MOCK_LOCALE,
role: mockRole(process.env.MOCK_ROLE), role: mockRole(process.env.MOCK_ROLE),
metricsOff: process.env.MOCK_METRICS === "off",
fail: (type, description) => new MethodError(type, description), fail: (type, description) => new MethodError(type, description),
}); });
@@ -913,7 +920,7 @@ const handlers: Record<string, Handler> = {
"Email/query": (a) => { "Email/query": (a) => {
let list = emails.filter((e) => matchFilter(e, a.filter as Obj)); let list = emails.filter((e) => matchFilter(e, a.filter as Obj));
/* /*
* Honour the sort rather than always answering newest-first. This used to * Honor the sort rather than always answering newest-first. This used to
* ignore it entirely, which reproduced a server that silently returns a * ignore it entirely, which reproduced a server that silently returns a
* different order from the one asked for -- the one shape of wrongness a * different order from the one asked for -- the one shape of wrongness a
* client cannot detect. * client cannot detect.
@@ -1033,7 +1040,7 @@ const handlers: Record<string, Handler> = {
return setResp({ updated: { singleton: null } }); return setResp({ updated: { singleton: null } });
}, },
/* /*
* Push subscriptions. The JMAP half can be modelled; delivery cannot -- that * Push subscriptions. The JMAP half can be modeled; delivery cannot -- that
* runs through the browser vendor's real push service, so nothing local will * runs through the browser vendor's real push service, so nothing local will
* ever make a notification appear. * ever make a notification appear.
* *
@@ -1218,7 +1225,7 @@ const handlers: Record<string, Handler> = {
} }
const status = undoStatusOf(sub, Date.now()); const status = undoStatusOf(sub, Date.now());
if (status !== "pending") { if (status !== "pending") {
notUpdated[id] = { type: "cannotUnsend", description: status === "canceled" ? "The message was already cancelled." : "The message has already been sent." }; notUpdated[id] = { type: "cannotUnsend", description: status === "canceled" ? "The message was already canceled." : "The message has already been sent." };
continue; continue;
} }
sub.undoStatus = "canceled"; sub.undoStatus = "canceled";
@@ -1363,7 +1370,7 @@ function checkAuth(req: IncomingMessage): boolean {
const u = raw.slice(0, sep); const u = raw.slice(0, sep);
const p = raw.slice(sep + 1); const p = raw.slice(sep + 1);
if (u !== USER) return false; if (u !== USER) return false;
// App passwords are recognised by shape and skip the second factor, which is // App passwords are recognized by shape and skip the second factor, which is
// exactly what lets a webmail session survive 2FA being switched on. // exactly what lets a webmail session survive 2FA being switched on.
if (account.appPasswords.some((a) => a.secret === p)) return true; if (account.appPasswords.some((a) => a.secret === p)) return true;
if (!account.otpUrl) return p === account.password; if (!account.otpUrl) return p === account.password;
@@ -1425,7 +1432,14 @@ export const server = createServer(async (req, res) => {
// The account info endpoint; the only place a server reports its edition. // The account info endpoint; the only place a server reports its edition.
if (url.pathname === "/api/account" && req.method === "GET") { if (url.pathname === "/api/account" && req.method === "GET") {
res.writeHead(200, { "content-type": "application/json" }); res.writeHead(200, { "content-type": "application/json" });
return res.end(JSON.stringify({ permissions: directory.permissions, edition: "oss", locale: MOCK_LOCALE })); return res.end(JSON.stringify({ permissions: directory.permissions, edition: MOCK_EDITION, locale: MOCK_LOCALE }));
}
// The registry schema, cut down to the permission list the Roles picker
// reads. Gzipped as the real file is, from the 0.16.22 snapshot the
// translations are checked against.
if (url.pathname === "/api/schema" && req.method === "GET") {
res.writeHead(200, { "content-type": "application/json", "content-encoding": "gzip" });
return res.end(gzipSync(JSON.stringify({ enums: { Permission: PERMISSION_SNAPSHOT } })));
} }
if (url.pathname === "/jmap/" && req.method === "POST") { if (url.pathname === "/jmap/" && req.method === "POST") {
const body = JSON.parse((await readBody(req)).toString()) as { methodCalls: [string, Obj, string][]; using?: string[] }; const body = JSON.parse((await readBody(req)).toString()) as { methodCalls: [string, Obj, string][]; using?: string[] };
@@ -1487,7 +1501,7 @@ export const server = createServer(async (req, res) => {
* **Confirmed live on 0.16.21 (2026-09-06):** the interval is in **seconds** * **Confirmed live on 0.16.21 (2026-09-06):** the interval is in **seconds**
* `data: {"interval": 30}` where up to 0.16.20 the same field carried * `data: {"interval": 30}` where up to 0.16.20 the same field carried
* milliseconds. The server floors it at 30 s (asking for 1, 2 or 5 all * milliseconds. The server floors it at 30 s (asking for 1, 2 or 5 all
* answered 30 and pinged every 30 s) and honours anything above (45 pinged * answered 30 and pinged every 30 s) and honors anything above (45 pinged
* at 45 s and said 45, 60 at 60 and said 60). `ping=0` disables pings * at 45 s and said 45, 60 at 60 and said 60). `ping=0` disables pings
* altogether; a value that is not a number at all `abc`, or empty is a * altogether; a value that is not a number at all `abc`, or empty is a
* 400 before the stream opens. * 400 before the stream opens.
+1 -1
View File
@@ -38,7 +38,7 @@ describe("expandOccurrences", () => {
assert.equal(out[0]!.index, 0); assert.equal(out[0]!.index, 0);
}); });
it("honours count", () => { it("honors count", () => {
const ev = { ...series(), recurrenceRule: { ...WEEKDAYS, count: 3 } }; const ev = { ...series(), recurrenceRule: { ...WEEKDAYS, count: 3 } };
const [a, b] = week("2026-09-07T00:00:00", "2026-10-01T00:00:00"); const [a, b] = week("2026-09-07T00:00:00", "2026-10-01T00:00:00");
assert.equal(expandOccurrences(ev, a, b).length, 3); assert.equal(expandOccurrences(ev, a, b).length, 3);
+1 -1
View File
@@ -171,7 +171,7 @@ const SERIES_ONLY = ["recurrenceRule", "recurrenceRules", "excludedRecurrenceRul
* The object a `CalendarEvent/get` returns for one occurrence. * The object a `CalendarEvent/get` returns for one occurrence.
* *
* The rule is stripped, `recurrenceId` is set, and `baseEventId` points at the * The rule is stripped, `recurrenceId` is set, and `baseEventId` points at the
* master so an occurrence is recognisable by its `recurrenceId` and by * master so an occurrence is recognizable by its `recurrenceId` and by
* nothing else, which is the shape `isRecurring` was written against. * nothing else, which is the shape `isRecurring` was written against.
*/ */
export function occurrenceView(base: Obj, occ: Occurrence): Obj { export function occurrenceView(base: Obj, occ: Occurrence): Obj {
+1 -1
View File
@@ -4,7 +4,7 @@
* These are not hand-written. Each was produced by `openssl smime -sign` with a * 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 * 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, * 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 * and a stray line-ending normalization would turn a working fixture into a
* broken one for reasons invisible in a diff. * broken one for reasons invisible in a diff.
* *
* The same files back the unit tests, in web/src/lib/smime/__tests__/fixtures. * The same files back the unit tests, in web/src/lib/smime/__tests__/fixtures.
+28
View File
@@ -0,0 +1,28 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { gzipSync } from "node:zlib";
import { extractPermissions, parseSchemaBody } from "./permissionSchema.js";
/** Stalwart's permission list, out of the registry schema it serves at /api/schema. */
test("the permission list is enums.Permission, names and labels, once each", () => {
const schema = { objects: {}, enums: { Permission: [
{ name: "sysAccountGet", label: "Accounts Management: Get accounts" },
{ name: "authenticate", label: "" },
{ name: "sysAccountGet", label: "a repeat" },
{ label: "no name" },
"not an object",
] } };
assert.deepEqual(extractPermissions(schema), [
{ name: "sysAccountGet", label: "Accounts Management: Get accounts" },
{ name: "authenticate", label: "authenticate" },
]);
assert.deepEqual(extractPermissions({ enums: {} }), []);
assert.deepEqual(extractPermissions(null), []);
});
test("the schema reads whether or not the transport already inflated it", () => {
const doc = { enums: { Permission: [{ name: "impersonate", label: "Act on behalf of another user" }] } };
const plain = new TextEncoder().encode(JSON.stringify(doc));
assert.deepEqual(parseSchemaBody(plain), doc);
assert.deepEqual(parseSchemaBody(new Uint8Array(gzipSync(plain))), doc);
});
+63
View File
@@ -0,0 +1,63 @@
import { gunzipSync } from "node:zlib";
import { config } from "./config.js";
/**
* Stalwart's list of permissions, for the Roles screen's picker.
*
* Stalwart publishes its whole registry schema at `GET /api/schema` to any
* signed-in account -- objects, forms, layouts and `enums.Permission`, a label
* for each permission. Its own administration interface is built from it. The
* browser cannot fetch it (no credentials there, and another origin), so this
* fetches it as the signed-in account and hands back the one part the client
* needs: a list of names and English labels, a few dozen kilobytes rather than
* the whole document.
*
* Held in memory for an hour per server, because it changes only when Stalwart
* is upgraded. Nothing is written anywhere.
*/
export interface PermissionInfo {
name: string;
label: string;
}
const CACHE_MS = 60 * 60 * 1000;
const cache = new Map<string, { at: number; list: PermissionInfo[] }>();
/** The permission list out of a schema document, or an empty list if it is not where 0.16 keeps it. */
export function extractPermissions(schema: unknown): PermissionInfo[] {
const list = (schema as { enums?: { Permission?: unknown } } | null)?.enums?.Permission;
if (!Array.isArray(list)) return [];
const out: PermissionInfo[] = [];
const seen = new Set<string>();
for (const item of list) {
const { name, label } = (item ?? {}) as { name?: unknown; label?: unknown };
if (typeof name !== "string" || !name || seen.has(name)) continue;
seen.add(name);
out.push({ name, label: typeof label === "string" && label ? label : name });
}
return out;
}
/**
* The schema's bytes as JSON. The file is shipped gzipped; whether the server
* says so in Content-Encoding (so fetch has already inflated it) or serves the
* .gz as it is, the magic number settles which this is.
*/
export function parseSchemaBody(bytes: Uint8Array): unknown {
const raw = bytes[0] === 0x1f && bytes[1] === 0x8b ? gunzipSync(bytes) : Buffer.from(bytes);
return JSON.parse(raw.toString("utf8"));
}
export async function fetchPermissions(authorization: string, baseUrl: string): Promise<PermissionInfo[] | null> {
const hit = cache.get(baseUrl);
if (hit && Date.now() - hit.at < CACHE_MS) return hit.list;
const res = await fetch(`${baseUrl}/api/schema`, {
headers: { authorization, accept: "application/json" },
signal: AbortSignal.timeout(config.upstreamTimeout),
});
if (!res.ok) return null;
const list = extractPermissions(parseSchemaBody(new Uint8Array(await res.arrayBuffer())));
if (list.length) cache.set(baseUrl, { at: Date.now(), list });
return list;
}
+1 -1
View File
@@ -12,7 +12,7 @@ test("the account's permissions are kept alongside the edition", () => {
}); });
test("permission names read the same whichever case the server uses", () => { test("permission names read the same whichever case the server uses", () => {
// The source serialises camelCase; the documentation shows kebab-case. // The source serializes camelCase; the documentation shows kebab-case.
assert.equal(normalizePermission("sys-account-get"), "sysAccountGet"); assert.equal(normalizePermission("sys-account-get"), "sysAccountGet");
assert.equal(normalizePermission("sysAccountGet"), "sysAccountGet"); assert.equal(normalizePermission("sysAccountGet"), "sysAccountGet");
assert.equal(normalizePermission("sys-dkim-signature-create"), "sysDkimSignatureCreate"); assert.equal(normalizePermission("sys-dkim-signature-create"), "sysDkimSignatureCreate");
+1 -1
View File
@@ -75,7 +75,7 @@ export interface CreateSessionParams {
* other sessions" button: `app.ts` also calls it when the password or the app * 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 * password changes, so it carries the guarantee that changing a credential
* invalidates the sessions still holding the old one. A stateless backend * 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 * cannot honor that alone; the plan is for OAuth to hand the job to
* Stalwart's own token registry, which can already answer both questions. * Stalwart's own token registry, which can already answer both questions.
*/ */
export interface SessionBackend { export interface SessionBackend {
+10 -4
View File
@@ -72,11 +72,17 @@ test("every entry in the example mapping is a domain and an http(s) URL", () =>
if (key.startsWith("_")) continue; if (key.startsWith("_")) continue;
const domain = key.trim().toLowerCase().replace(/\.$/, ""); const domain = key.trim().toLowerCase().replace(/\.$/, "");
assert.ok(domain, "a domain key is empty"); assert.ok(domain, "a domain key is empty");
assert.ok(!seen.has(domain), `${domain} appears twice once normalised`); assert.ok(!seen.has(domain), `${domain} appears twice once normalized`);
seen.add(domain); seen.add(domain);
assert.equal(typeof value, "string", `${domain} is not a string`); // A URL, or an object naming the server's URL and its administration's.
const url = new URL(value as string); const entry = value && typeof value === "object" ? (value as Record<string, unknown>) : { url: value };
assert.ok(url.protocol === "http:" || url.protocol === "https:", `${domain} must be http or https`); for (const [field, v] of Object.entries(entry)) {
assert.ok(field === "url" || field === "adminUrl", `${domain} has an unknown field ${field}`);
assert.equal(typeof v, "string", `${domain} ${field} is not a string`);
const url = new URL(v as string);
assert.ok(url.protocol === "http:" || url.protocol === "https:", `${domain} ${field} must be http or https`);
}
assert.equal(typeof entry.url, "string", `${domain} has no url`);
} }
assert.ok(seen.size > 0, "the example should show at least one mapping"); assert.ok(seen.size > 0, "the example should show at least one mapping");
}); });
+2 -2
View File
@@ -88,7 +88,7 @@ export function staticHandler(root: string, basePath = ""): Handler {
* already being read here, so checking what it asks for costs one substring * 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. * 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 * A warning rather than a refusal: this reads a built artifact to guess at a
* misconfiguration, and a wrong guess that stops the server from starting is * misconfiguration, and a wrong guess that stops the server from starting is
* worse than the problem it is describing. * worse than the problem it is describing.
*/ */
@@ -128,7 +128,7 @@ export function staticHandler(root: string, basePath = ""): Handler {
* comes off once, here. Anything outside it is a 404 and not the app * 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 * shell: under `/mail` this process shares a hostname with whatever else
* the proxy serves, and answering `/` or `/other-app/thing` with our * the proxy serves, and answering `/` or `/other-app/thing` with our
* index would shadow a neighbour rather than let it 404 honestly. * index would shadow a neighbor rather than let it 404 honestly.
*/ */
const fullPath = decodeURIComponent(new URL(c.req.url).pathname); const fullPath = decodeURIComponent(new URL(c.req.url).pathname);
const urlPath = stripBasePath(basePath, fullPath); const urlPath = stripBasePath(basePath, fullPath);
+2 -2
View File
@@ -1,13 +1,13 @@
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
/** /**
* TOTP (RFC 6238) just enough to enrol a second factor safely. * TOTP (RFC 6238) just enough to enroll a second factor safely.
* *
* Stalwart stores the otpauth:// URL and checks codes at login, but it does * Stalwart stores the otpauth:// URL and checks codes at login, but it does
* *not* check the new secret when 2FA is switched on: it verifies the * *not* check the new secret when 2FA is switched on: it verifies the
* credentials that are already on the account. A user whose authenticator was * credentials that are already on the account. A user whose authenticator was
* mistyped or whose clock has drifted would be locked out of their mailbox at * mistyped or whose clock has drifted would be locked out of their mailbox at
* the next sign-in. So ihasmail proves the enrolment itself, before asking the * the next sign-in. So ihasmail proves the enrollment itself, before asking the
* server to store anything. * server to store anything.
*/ */
+94 -4
View File
@@ -1,4 +1,5 @@
import { config } from "./config.js"; import { config } from "./config.js";
import { grantsAdministration } from "./adminGate.js";
export interface UpstreamSession { export interface UpstreamSession {
capabilities: Record<string, unknown>; capabilities: Record<string, unknown>;
@@ -54,6 +55,87 @@ export function upstreamFor(username: string): string {
return config.stalwartServers[domain] ?? config.stalwartUrl; return config.stalwartServers[domain] ?? config.stalwartUrl;
} }
/**
* Where the administrator signed in as `username` opens Stalwart's own
* administration.
*
* What the operator configured wins -- STALWART_ADMIN_URL for the default
* server, a servers file entry's `adminUrl` for a routed domain -- and what was
* found on the account's own server (`detected`) is used otherwise. Routing is
* the same as `upstreamFor`: a routed domain is never pointed at the default
* server's administration, and `detected` already came from its own server.
*/
export function adminUrlFor(username: string, detected: string | null = null): string | null {
const at = username.lastIndexOf("@");
const domain = at < 0 ? "" : username.slice(at + 1).trim().toLowerCase().replace(/\.$/, "");
if (domain && domain in config.stalwartServers) return config.stalwartAdminUrls[domain] ?? detected;
return config.stalwartAdminUrl || detected;
}
/** Stalwart's own default for its web interface, written at first boot (`manager/defaults.rs`). */
const DEFAULT_ADMIN_PREFIX = "/admin";
/**
* The prefix Stalwart's administration is served under, from the `x:Application`
* answers: "/admin" if an enabled application claims it, null if the server
* says there is none (disabled, removed, or moved to another prefix). A refusal
* -- the account may not read applications -- is not an answer, and gets
* Stalwart's default.
*/
export function adminPrefixFrom(responses: [string, Record<string, unknown>, string][]): string | null {
const get = responses.find(([name]) => name === "x:Application/get" || name === "error");
if (!get || get[0] === "error") return DEFAULT_ADMIN_PREFIX;
const list = (get[1].list as Array<{ enabled?: unknown; urlPrefix?: unknown }> | undefined) ?? [];
const claims = list.some((app) => app.enabled !== false && app.urlPrefix && typeof app.urlPrefix === "object" && DEFAULT_ADMIN_PREFIX in (app.urlPrefix as object));
return claims ? DEFAULT_ADMIN_PREFIX : null;
}
/**
* The public origin a Stalwart session belongs to: the host it advertises in
* its own URLs, which is the address people reach it at even when this server
* talks to it on a private one (STALWART_URL=http://127.0.0.1:…). A relative
* URL falls back to the configured base.
*/
export function advertisedOrigin(session: Pick<UpstreamSession, "apiUrl" | "baseUrl">): string | null {
try {
return new URL(session.apiUrl, session.baseUrl).origin;
} catch {
return null;
}
}
/**
* Where this session's server serves its own administration, found from the
* server itself: its advertised origin, and the prefix its web interface
* application is installed under. Null when the server says it has none.
*/
async function detectAdminUrl(authorization: string, session: UpstreamSession): Promise<string | null> {
const origin = advertisedOrigin(session);
const accountId = session.primaryAccounts?.[STALWART_CAP];
if (!origin) return null;
let prefix: string | null = DEFAULT_ADMIN_PREFIX;
if (accountId) {
try {
const res = await fetch(absoluteUpstream(session.apiUrl, session.baseUrl), {
method: "POST",
headers: { authorization, "content-type": "application/json", accept: "application/json" },
body: JSON.stringify({
using: [JMAP_CORE, STALWART_CAP],
methodCalls: [
["x:Application/query", { accountId }, "q"],
["x:Application/get", { accountId, "#ids": { resultOf: "q", name: "x:Application/query", path: "/ids" }, properties: ["enabled", "urlPrefix"] }, "g"],
],
}),
signal: AbortSignal.timeout(config.upstreamTimeout),
});
if (res.ok) prefix = adminPrefixFrom(((await res.json()) as { methodResponses?: [string, Record<string, unknown>, string][] }).methodResponses ?? []);
} catch {
/* unreachable is not "none": keep the default */
}
}
return prefix ? `${origin}${prefix}/` : null;
}
export function wellKnownUrl(base: string = config.stalwartUrl): string { export function wellKnownUrl(base: string = config.stalwartUrl): string {
return `${base}/.well-known/jmap`; return `${base}/.well-known/jmap`;
} }
@@ -142,6 +224,11 @@ export interface AccountInfo {
* access. * access.
*/ */
permissions: string[]; permissions: string[];
/**
* Where this server's own administration is, found rather than configured:
* see `detectAdminUrl`. Only looked for when the account administers.
*/
adminUrl?: string | null;
} }
const infoCache = new Map<string, { info: AccountInfo; fetchedAt: number }>(); const infoCache = new Map<string, { info: AccountInfo; fetchedAt: number }>();
@@ -163,7 +250,7 @@ const SCRIPT_MODIFIERS: Record<string, string> = {
}; };
/** /**
* Normalise a POSIX-style locale ("de_DE.UTF-8@euro") into a BCP-47 tag * Normalize a POSIX-style locale ("de_DE.UTF-8@euro") into a BCP-47 tag
* ("de-DE"). Returns null for the locale-less values ("C", "POSIX") and for * ("de-DE"). Returns null for the locale-less values ("C", "POSIX") and for
* anything that does not look like a language tag. * anything that does not look like a language tag.
*/ */
@@ -249,10 +336,10 @@ function localeOf(call: [string, Record<string, unknown>, string] | undefined):
} }
/** /**
* Permission names in the form the source serialises them. * Permission names in the form the source serializes them.
* *
* Stalwart 0.16 builds `/api/account`'s list from the same enum as everything * Stalwart 0.16 builds `/api/account`'s list from the same enum as everything
* else, which serialises as camelCase (`sysAccountGet`). Its documentation and * else, which serializes as camelCase (`sysAccountGet`). Its documentation and
* OpenAPI example show kebab-case (`sys-account-get`) instead. Until a live * 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 * server settles which is true, both are read as the one form, so a check
* written against `sysAccountGet` holds either way. * written against `sysAccountGet` holds either way.
@@ -294,6 +381,9 @@ export async function getAccountInfo(sessionId: string, authorization: string, s
try { try {
info = await fetchAccountInfo(authorization, session); info = await fetchAccountInfo(authorization, session);
info = { ...info, ...(await fetchServerAccount(authorization, session.baseUrl)) }; info = { ...info, ...(await fetchServerAccount(authorization, session.baseUrl)) };
// Only an administrator is shown the link, so only an administrator's
// server is asked where it is.
if (grantsAdministration(info.permissions)) info = { ...info, adminUrl: await detectAdminUrl(authorization, session) };
} catch { } catch {
/* all of this is a nicety - never fail the session over it */ /* all of this is a nicety - never fail the session over it */
} }
@@ -336,7 +426,7 @@ export function localizeSession(s: UpstreamSession, extras: Record<string, unkno
* So by default only the path and query are taken from the advertised URL; * 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 * 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. * should have done all along -- the operator named the route on purpose.
* STALWART_FOLLOW_ADVERTISED_URLS=1 restores the old behaviour for a setup * STALWART_FOLLOW_ADVERTISED_URLS=1 restores the old behavior for a setup
* that genuinely needs to reach Stalwart at a different origin than the one * that genuinely needs to reach Stalwart at a different origin than the one
* it was given. * it was given.
*/ */
+7 -1
View File
@@ -17,9 +17,15 @@
"JSON, a duplicate domain, or a value that is not an http(s) URL stops the", "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.", "server at startup rather than failing quietly at somebody's sign-in.",
"", "",
"ihasmail's Administration dashboard links to each server's own",
"administration, found from the server. A value may instead be an object",
"that overrides where it is: {\"url\": ..., \"adminUrl\": ...}.",
"STALWART_ADMIN_URL is the same for the default server. A listed domain is",
"never pointed at the default server's administration.",
"",
"Docs: https://docs.ihasmail.org/configure/#several-stalwart-servers" "Docs: https://docs.ihasmail.org/configure/#several-stalwart-servers"
], ],
"example.com": "https://mail.example.com", "example.com": "https://mail.example.com",
"customer-b.test": "https://jmap.customer-b.test" "customer-b.test": { "url": "https://jmap.customer-b.test", "adminUrl": "https://admin.customer-b.test" }
} }
+1 -1
View File
@@ -9,7 +9,7 @@
theme, which a media query cannot do — it only knows what the OS prefers, 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 not what the user picked here. There used to be two, both with media
attributes, which meant the selector in applyTheme (:not([media])) matched attributes, which meant the selector in applyTheme (:not([media])) matched
neither and the colour never moved off whatever the OS implied. neither and the color never moved off whatever the OS implied.
The initial value is the default theme's background, so the browser chrome 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. is right from the first paint rather than only once JS has run.
+4 -4
View File
@@ -12,9 +12,9 @@
"test": "vitest run" "test": "vitest run"
}, },
"dependencies": { "dependencies": {
"@tanstack/react-virtual": "^3.13.2", "@tanstack/react-virtual": "^3.14.12",
"dompurify": "^3.4.15", "dompurify": "^3.4.15",
"lucide-react": "^0.477.0", "lucide-react": "^1.45.0",
"marked": "^18.0.11", "marked": "^18.0.11",
"qrcode-generator": "^2.0.4", "qrcode-generator": "^2.0.4",
"react": "^19.0.0", "react": "^19.0.0",
@@ -26,9 +26,9 @@
"@types/react": "^19.0.10", "@types/react": "^19.0.10",
"@types/react-dom": "^19.2.7", "@types/react-dom": "^19.2.7",
"@vitejs/plugin-react": "^6.1.1", "@vitejs/plugin-react": "^6.1.1",
"jsdom": "^26.0.0", "jsdom": "^30.0.1",
"typescript": "^7.0.2", "typescript": "^7.0.2",
"vite": "^8.3.0", "vite": "^8.3.0",
"vitest": "^4.1.11" "vitest": "^5.0.0"
} }
} }
+10 -10
View File
@@ -44,7 +44,7 @@ export function App() {
* knowing its strings just changed. Rather than make every one of the * knowing its strings just changed. Rather than make every one of the
* thousand call sites a subscriber -- which would turn extracting a string * 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 * 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 * away and rebuilt when the catalog changes. Picking a language is a
* once-in-an-account event; paying for it there is far cheaper than paying * once-in-an-account event; paying for it there is far cheaper than paying
* for it on every render everywhere. * for it on every render everywhere.
*/ */
@@ -54,9 +54,9 @@ export function App() {
}, [bootstrap]); }, [bootstrap]);
/* /*
* Wait for the catalogue before the first paint. * Wait for the catalog before the first paint.
* *
* The tree is rebuilt when a catalogue lands, so components recover on * The tree is rebuilt when a catalog lands, so components recover on
* their own -- but a string computed in an effect does not. A toast fired * 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 * 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 otherwise not. The wait costs nothing visible: the session bootstrap
@@ -129,7 +129,7 @@ function AuthedApp() {
* or the sign-out that every deploy causes -- the first frame is the * or the sign-out that every deploy causes -- the first frame is the
* defaults, and the defaults are English. Rendering then means anything * defaults, and the defaults are English. Rendering then means anything
* computed before the settings land is computed in the wrong language: not * computed before the settings land is computed in the wrong language: not
* the interface, which is rebuilt when the catalogue arrives, but a string * the interface, which is rebuilt when the catalog arrives, but a string
* emitted once, like a toast. That is why the stale-folder toast came out * emitted once, like a toast. That is why the stale-folder toast came out
* in English on an otherwise German screen. * in English on an otherwise German screen.
* *
@@ -148,14 +148,14 @@ function AuthedApp() {
setReady(true); setReady(true);
return; return;
} }
let cancelled = false; let canceled = false;
void (async () => { void (async () => {
/* Before the account's own settings, so both the seeding below and the /* Before the account's own settings, so both the seeding below and the
enforcement inside `hydrate` have something to apply. */ enforcement inside `hydrate` have something to apply. */
await loadSettingsPolicy(); await loadSettingsPolicy();
if (cancelled) return; if (canceled) return;
const remote = await loadRemoteSettings(); const remote = await loadRemoteSettings();
if (cancelled) return; if (canceled) return;
if (remote) useSettings.getState().hydrate(remote); if (remote) useSettings.getState().hydrate(remote);
// No settings file: this account has never had settings of its own, so // No settings file: this account has never had settings of its own, so
// the installation's defaults are what it starts on rather than // the installation's defaults are what it starts on rather than
@@ -174,10 +174,10 @@ function AuthedApp() {
other: "Your administrator changed {n} settings", other: "Your administrator changed {n} settings",
}), { action: { label: t("Settings"), onClick: () => { window.location.href = withBase("/settings/general"); } } }); }), { action: { label: t("Settings"), onClick: () => { window.location.href = withBase("/settings/general"); } } });
} }
// The catalogue for whatever language that turned out to be. Hydrating // The catalog for whatever language that turned out to be. Hydrating
// asks for it; this is waiting for the answer. // asks for it; this is waiting for the answer.
await whenLanguageReady(); await whenLanguageReady();
if (cancelled) return; if (canceled) return;
setReady(true); setReady(true);
// Pushes were held back until now so they could not race the load. A // 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. // change made while it was in flight was kept, and goes out here.
@@ -187,7 +187,7 @@ function AuthedApp() {
if (!remote && settingsSyncAvailable()) queueSettingsPush(syncedPart(useSettings.getState().settings)); if (!remote && settingsSyncAvailable()) queueSettingsPush(syncedPart(useSettings.getState().settings));
})(); })();
return () => { return () => {
cancelled = true; canceled = true;
}; };
}, [accountId]); }, [accountId]);
+1 -1
View File
@@ -321,7 +321,7 @@ export class JmapClient {
else reject(new ApiError(xhr.status, (xhr.response as ApiErrorBody)?.error ?? "upload_failed", (xhr.response as ApiErrorBody)?.message ?? "Upload failed")); else reject(new ApiError(xhr.status, (xhr.response as ApiErrorBody)?.error ?? "upload_failed", (xhr.response as ApiErrorBody)?.message ?? "Upload failed"));
}; };
xhr.onerror = () => reject(new ApiError(0, "network_error", "Network error during upload")); xhr.onerror = () => reject(new ApiError(0, "network_error", "Network error during upload"));
xhr.onabort = () => reject(new ApiError(0, "aborted", "Upload cancelled")); xhr.onabort = () => reject(new ApiError(0, "aborted", "Upload canceled"));
opts.signal?.addEventListener("abort", () => xhr.abort()); opts.signal?.addEventListener("abort", () => xhr.abort());
xhr.send(data); xhr.send(data);
}); });
+4
View File
@@ -38,6 +38,10 @@ export interface JmapSession {
server?: { server?: {
/** "oss" | "community" | "enterprise". Stalwart publishes no version. */ /** "oss" | "community" | "enterprise". Stalwart publishes no version. */
edition?: string | null; edition?: string | null;
/** Where Stalwart's own administration is (STALWART_ADMIN_URL), for a session that may administer. */
adminUrl?: string | null;
/** SHOW_ENTERPRISE_NOTICES: an Enterprise-only section says so even on Enterprise. */
enterpriseNotices?: boolean;
}; };
/** /**
* False when this session may not administer: the operator turned it off, * False when this session may not administer: the operator turned it off,
+18 -7
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { ADMIN_BASELINE, adminSections, can, canGrantRole, generatePassword, hasAdministration, outranks, permissionSet, resolveRoles, type RoleDef } from "@/lib/adminAccess"; import { ADMIN_BASELINE, adminSections, can, dashboardCards, canGrantRole, generatePassword, hasAdministration, outranks, permissionSet, resolveRoles, type RoleDef } from "@/lib/adminAccess";
const set = (...p: string[]) => permissionSet(p); const set = (...p: string[]) => permissionSet(p);
const everything = set(...ADMIN_BASELINE, "sysTenantGet", "jmapEmailGet", "impersonate"); const everything = set(...ADMIN_BASELINE, "sysTenantGet", "jmapEmailGet", "impersonate");
@@ -12,17 +12,28 @@ const roles = new Map<string, RoleDef>([
]); ]);
describe("who is offered administration", () => { describe("who is offered administration", () => {
it("needs both halves of reading the account list", () => { it("needs both halves of reading the account list to list accounts", () => {
expect(hasAdministration(set("sysAccountQuery", "sysAccountGet"))).toBe(true); // Groups are accounts to the server, so they come with the same two permissions.
expect(hasAdministration(set("sysAccountQuery"))).toBe(false); expect(adminSections(set("sysAccountQuery", "sysAccountGet"))).toEqual(["dashboard", "accounts", "groups"]);
// A query alone is a count on the dashboard, not a list.
expect(adminSections(set("sysAccountQuery"))).toEqual(["dashboard"]);
expect(hasAdministration(set("sysAccountGet"))).toBe(false); expect(hasAdministration(set("sysAccountGet"))).toBe(false);
expect(hasAdministration(permissionSet(undefined))).toBe(false); expect(hasAdministration(permissionSet(undefined))).toBe(false);
}); });
it("offers each section only with both halves of reading it", () => { it("offers each section only with both halves of reading it", () => {
expect(adminSections(set("sysDomainQuery", "sysDomainGet"))).toEqual(["domains"]); expect(adminSections(set("sysDomainQuery", "sysDomainGet"))).toEqual(["dashboard", "domains"]);
expect(hasAdministration(set("sysDomainQuery", "sysDomainGet"))).toBe(true); expect(hasAdministration(set("sysDomainQuery", "sysDomainGet"))).toBe(true);
expect(adminSections(set("sysAccountQuery", "sysAccountGet", "sysDomainQuery"))).toEqual(["accounts"]); expect(adminSections(set("sysAccountQuery", "sysAccountGet", "sysDomainQuery"))).toEqual(["dashboard", "accounts", "groups"]);
});
it("gives the dashboard a card for each number the role can read", () => {
expect(dashboardCards(set("sysAccountQuery", "sysAccountGet", "sysDomainQuery", "sysDomainGet"))).toEqual(["users", "domains"]);
expect(dashboardCards(set("sysQueuedMessageQuery"))).toEqual(["pending"]);
// The history takes its get as well: the query only finds the records.
expect(dashboardCards(set("sysMetricQuery"))).toEqual([]);
expect(dashboardCards(set("sysMetricQuery", "sysMetricGet"))).toEqual(["memory", "received", "sent"]);
expect(adminSections(set("jmapEmailGet"))).toEqual([]);
}); });
it("reads one permission per object and operation", () => { it("reads one permission per object and operation", () => {
@@ -83,7 +94,7 @@ describe("generated passwords", () => {
expect(p).not.toMatch(/[01lIO]/); expect(p).not.toMatch(/[01lIO]/);
}); });
it("skip bytes that would favour the start of the alphabet", () => { it("skip bytes that would favor the start of the alphabet", () => {
// 256 % 55 leaves 36 byte values over; a plain modulo would hand those to // 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 // 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. // and more are drawn, so a batch of nothing but those costs a draw.
@@ -0,0 +1,87 @@
import { describe, expect, it, vi } from "vitest";
import { client, JmapMethodError } from "@/jmap/client";
import { balancedColumns, countObjects, isRefused, loadMetrics, summarizeMetrics, type MetricRecord } from "@/lib/adminDashboard";
const counter = (metric: string, count: number, timestamp = "2026-09-15T14:00:00Z"): MetricRecord => ({ "@type": "Counter", metric, count, timestamp });
describe("the dashboard's message numbers", () => {
it("adds received and sent up over the metric names Stalwart's own dashboard uses", () => {
const stats = summarizeMetrics([
counter("queue.message-queued", 6),
counter("queue.message-queued", 4, "2026-09-15T13:00:00Z"),
counter("queue.authenticated-message-queued", 2),
counter("queue.dsn-queued", 1),
counter("queue.report-queued", 3),
// Recorded, but not either number.
counter("message-ingest.ham", 50),
]);
expect(stats.received).toBe(10);
expect(stats.sent).toBe(6);
});
it("reads memory from the newest gauge, not the first one listed", () => {
const stats = summarizeMetrics([
{ "@type": "Gauge", metric: "server.memory", count: 100, timestamp: "2026-09-15T12:00:00Z" },
{ "@type": "Gauge", metric: "server.memory", count: 300, timestamp: "2026-09-15T14:00:00Z" },
{ "@type": "Gauge", metric: "queue.count", count: 7, timestamp: "2026-09-15T15:00:00Z" },
]);
expect(stats.memory).toEqual({ bytes: 300, at: "2026-09-15T14:00:00Z" });
});
it("tells a history that records nothing from a quiet day", () => {
expect(summarizeMetrics([]).recorded).toBe(false);
const quiet = summarizeMetrics([{ "@type": "Gauge", metric: "server.memory", count: 1, timestamp: "2026-09-15T14:00:00Z" }]);
expect(quiet).toMatchObject({ recorded: true, received: 0, sent: 0 });
});
});
describe("the dashboard's queries", () => {
it("counts users rather than accounts, and asks for no ids", async () => {
const call = vi.spyOn(client, "call").mockResolvedValue({ ids: [], total: 5 });
expect(await countObjects("Account")).toBe(5);
expect(call).toHaveBeenCalledWith("x:Account/query", { filter: { "@type": "User" }, limit: 0, calculateTotal: true });
await countObjects("QueuedMessage");
expect(call).toHaveBeenLastCalledWith("x:QueuedMessage/query", { limit: 0, calculateTotal: true });
call.mockRestore();
});
it("filters the history with Stalwart's comparison names, and pages the gets", async () => {
// A bare `timestamp` or `after` is unsupportedFilter on a live server.
vi.spyOn(client, "maxObjectsInGet", "get").mockReturnValue(2);
const call = vi.spyOn(client, "call").mockImplementation(async (method, args) => {
if (method === "x:Metric/query") return (args as { position: number }).position === 0 ? { ids: ["a", "b"] } : { ids: ["c"] };
return { list: ((args as { ids: string[] }).ids).map((id) => counter("queue.message-queued", 1, id)) };
});
const records = await loadMetrics(new Date("2026-09-14T15:30:00.123Z"));
expect(records).toHaveLength(3);
expect(call.mock.calls[0]).toEqual([
"x:Metric/query",
{
filter: { timestampIsGreaterThanOrEqual: "2026-09-14T15:30:00Z", metric: ["queue.message-queued", "queue.authenticated-message-queued", "queue.dsn-queued", "queue.report-queued", "server.memory"] },
sort: [{ property: "timestamp", isAscending: false }],
position: 0,
limit: 2,
},
]);
vi.restoreAllMocks();
});
it("treats only a forbidden answer as the server refusing", () => {
expect(isRefused(new JmapMethodError("x:Metric/query", { type: "forbidden" }))).toBe(true);
expect(isRefused(new JmapMethodError("x:Metric/query", { type: "serverFail" }))).toBe(false);
expect(isRefused(new Error("offline"))).toBe(false);
});
});
describe("the card grid", () => {
it("never leaves a row short when the cards can be divided evenly", () => {
for (const n of [1, 2, 3, 4, 6]) {
const { wide, mid } = balancedColumns(n);
expect(n % wide, `${n} cards across ${wide}`).toBe(0);
expect(n % mid, `${n} cards across ${mid}`).toBe(0);
expect(wide).toBeLessThanOrEqual(4);
}
expect(balancedColumns(6)).toEqual({ wide: 3, mid: 2 });
expect(balancedColumns(3)).toEqual({ wide: 3, mid: 1 });
});
});
+1 -1
View File
@@ -62,7 +62,7 @@ describe("the account query", () => {
* live server gave, or one its source says it gives. * live server gave, or one its source says it gives.
*/ */
describe("refusals in the reader's language", () => { describe("refusals in the reader's language", () => {
it("recognises the registry's validators and says it again, without the server's words", () => { it("recognizes 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. // 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"); const domain = describeDirectoryError(new DirectoryError("invalidPatch", "Invalid domain name", ["name"]), "domain");
expect(domain).toMatch(/isn't a valid domain name/); expect(domain).toMatch(/isn't a valid domain name/);
+4 -4
View File
@@ -1,10 +1,10 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { describeLinked, dkimAlgorithm, looksLikeDomain, normaliseDomain, parseZoneFile } from "@/lib/adminDomains"; import { describeLinked, dkimAlgorithm, looksLikeDomain, normalizeDomain, parseZoneFile } from "@/lib/adminDomains";
/** /**
* Written the way Stalwart's BIND serialiser writes it (dns-update's * Written the way Stalwart's BIND serializer writes it (dns-update's
* `BindSerializer`): `name IN TYPE value`, and a TXT over 255 bytes as a * `BindSerializer`): `name IN TYPE value`, and a TXT over 255 bytes as a
* parenthesised run of quoted chunks. * parenthesized run of quoted chunks.
*/ */
const long = "v=DKIM1; k=rsa; h=sha256; p=" + "A".repeat(400); const long = "v=DKIM1; k=rsa; h=sha256; p=" + "A".repeat(400);
const zone = [ const zone = [
@@ -46,7 +46,7 @@ describe("reading the zone file", () => {
describe("domain names", () => { describe("domain names", () => {
it("are written back lower-case without the root dot", () => { it("are written back lower-case without the root dot", () => {
expect(normaliseDomain(" Example.COM. ")).toBe("example.com"); expect(normalizeDomain(" Example.COM. ")).toBe("example.com");
}); });
it("are checked loosely before the server decides", () => { it("are checked loosely before the server decides", () => {
+66
View File
@@ -0,0 +1,66 @@
import { describe, expect, it, vi } from "vitest";
import { client } from "@/jmap/client";
import { countMembers, createGroup, destroyGroup, groupRoleKey, groupRolesFromKey, membershipPatch } from "@/lib/adminGroups";
describe("group membership", () => {
it("is a patch to each member, one pointer each, so no other membership moves", () => {
// Stalwart's set patch adds a key on `true` and removes it on `null`, and
// leaves every other key in the set as it was.
expect(membershipPatch(["u1", "u2"], "g1", true)).toEqual({ u1: { "memberGroupIds/g1": true }, u2: { "memberGroupIds/g1": true } });
expect(membershipPatch(["u1"], "g1", false)).toEqual({ u1: { "memberGroupIds/g1": null } });
});
it("counts members as users whose memberships name the group, asking for no ids", async () => {
const call = vi.spyOn(client, "call").mockResolvedValue({ ids: [], total: 4 });
expect(await countMembers(["g1"])).toEqual(new Map([["g1", 4]]));
expect(call).toHaveBeenCalledWith("x:Account/query", { filter: { "@type": "User", memberGroupIds: "g1" }, limit: 0, calculateTotal: true });
call.mockRestore();
});
it("leaves a count out rather than showing a failed one as none", async () => {
const call = vi.spyOn(client, "call").mockRejectedValue(new Error("offline"));
expect(await countMembers(["g1"])).toEqual(new Map());
call.mockRestore();
});
});
describe("creating and deleting a group", () => {
it("creates an account of type Group, with nothing a person needs to sign in", async () => {
const call = vi.spyOn(client, "call").mockResolvedValue({ created: { n: { id: "g9" } } });
expect(await createGroup({ name: " sales ", domainId: "d1", description: "", roles: { "@type": "Default" }, diskQuotaBytes: null })).toBe("g9");
const create = (call.mock.calls[0]![1] as { create: { n: Record<string, unknown> } }).create.n;
expect(create).toMatchObject({ "@type": "Group", name: "sales", domainId: "d1", description: null, roles: { "@type": "Default" }, permissions: { "@type": "Inherit" }, quotas: {} });
expect(create).not.toHaveProperty("credentials");
expect(create).not.toHaveProperty("encryptionAtRest");
expect(create).not.toHaveProperty("memberGroupIds");
call.mockRestore();
});
it("takes the members out before deleting, and deletes nothing if that fails", async () => {
const call = vi.spyOn(client, "call").mockResolvedValueOnce({ updated: { u1: null } }).mockResolvedValueOnce({ destroyed: ["g1"] });
await destroyGroup("g1", ["u1"]);
expect(call.mock.calls.map((c) => [c[0], Object.keys(c[1] as object)])).toEqual([
["x:Account/set", ["update"]],
["x:Account/set", ["destroy"]],
]);
call.mockReset();
call.mockResolvedValueOnce({ notUpdated: { u1: { type: "forbidden" } } });
await expect(destroyGroup("g1", ["u1"])).rejects.toMatchObject({ type: "forbidden" });
expect(call).toHaveBeenCalledTimes(1);
call.mockRestore();
});
it("goes straight to the delete for a group with no members", async () => {
const call = vi.spyOn(client, "call").mockResolvedValue({ destroyed: ["g1"] });
await destroyGroup("g1", []);
expect(call).toHaveBeenCalledTimes(1);
expect(call).toHaveBeenCalledWith("x:Account/set", { destroy: ["g1"] });
call.mockRestore();
});
it("round-trips a group's roles, which are Default or Custom", () => {
for (const roles of [{ "@type": "Default" } as const, { "@type": "Custom", roleIds: { r1: true, r2: true } } as const]) {
expect(groupRolesFromKey(groupRoleKey(roles))).toEqual(roles);
}
});
});
+48
View File
@@ -0,0 +1,48 @@
import { describe, expect, it, vi } from "vitest";
import { client } from "@/jmap/client";
import { createList, parseAddresses, queryLists, recipientsPatch } from "@/lib/adminLists";
describe("a mailing list's recipients", () => {
it("are saved as what was added and removed, one pointer each", () => {
// The live server adds a set key on `true`, removes it on `null`, and
// leaves the rest -- so a recipient added elsewhere meanwhile survives.
expect(recipientsPatch(["[email protected]", "[email protected]"], ["[email protected]", "[email protected]"])).toEqual({
"recipients/[email protected]": null,
"recipients/[email protected]": true,
});
expect(recipientsPatch(["[email protected]"], ["[email protected]"])).toEqual({});
});
it("compare without regard to case, and escape what a pointer cannot hold", () => {
expect(recipientsPatch(["[email protected]"], ["[email protected]"])).toEqual({});
expect(recipientsPatch([], ["odd/[email protected]"])).toEqual({ "recipients/[email protected]": true });
});
it("come out of a paste of names, commas and angle brackets, and keep what isn't an address", () => {
expect(parseAddresses('Ada Lovelace <[email protected]>, [email protected]; "Alan" [email protected]\[email protected] mailto:[email protected]')).toEqual({
addresses: ["[email protected]", "[email protected]", "[email protected]", "[email protected]"],
rejected: [],
});
expect(parseAddresses("ada@, @example.org, someone@nowhere")).toEqual({ addresses: [], rejected: ["ada@", "@example.org", "someone@nowhere"] });
});
});
describe("the list calls", () => {
it("search on text, and leave the filter out when there is none", async () => {
const call = vi.spyOn(client, "call").mockResolvedValue({ ids: [], total: 0 });
await queryLists({ text: " board ", position: 50, limit: 50 });
expect(call).toHaveBeenLastCalledWith("x:MailingList/query", { filter: { text: "board" }, position: 50, limit: 50, calculateTotal: true });
await queryLists({});
expect(call).toHaveBeenLastCalledWith("x:MailingList/query", { position: 0, calculateTotal: true });
call.mockRestore();
});
it("create one with its recipients as a set", async () => {
const call = vi.spyOn(client, "call").mockResolvedValue({ created: { n: { id: "l9" } } });
expect(await createList({ name: "team", domainId: "d1", description: " ", recipients: ["[email protected]", "[email protected]"] })).toBe("l9");
expect(call).toHaveBeenCalledWith("x:MailingList/set", {
create: { n: { name: "team", domainId: "d1", description: null, recipients: { "[email protected]": true, "[email protected]": true }, aliases: {} } },
});
call.mockRestore();
});
});
+41
View File
@@ -0,0 +1,41 @@
import { describe, expect, it } from "vitest";
import { permissionSet } from "@/lib/adminAccess";
import { canBuildOn, effectivePermissions, inherited, roleOutranks, setPatch, type DirectoryRole } from "@/lib/adminRoles";
const flags = (...n: string[]) => Object.fromEntries(n.map((x) => [x, true]));
const roles = new Map<string, DirectoryRole>([
["user", { id: "user", description: "User", enabledPermissions: flags("jmapEmailGet", "jmapEmailUpdate") }],
["help", { id: "help", description: "Helpdesk", enabledPermissions: flags("sysAccountGet"), disabledPermissions: flags("jmapEmailUpdate"), roleIds: flags("user") }],
["lead", { id: "lead", description: "Lead", enabledPermissions: flags("sysAccountUpdate"), roleIds: flags("help") }],
]);
describe("what a role holds", () => {
it("follows every base, and a denial anywhere in the tree wins", () => {
// Stalwart unions enabled with enabled and disabled with disabled across
// the tree, then takes the disabled away (permissions.rs).
expect([...effectivePermissions(roles.get("lead")!, roles, "lead")].sort()).toEqual(["jmapEmailGet", "sysAccountGet", "sysAccountUpdate"]);
const { granted, denied } = inherited(["help"], roles, "lead");
expect(granted.get("jmapEmailGet")).toBe("help");
expect(denied.get("jmapEmailUpdate")).toBe("help");
});
it("changes a set one pointer at a time", () => {
expect(setPatch("enabledPermissions", ["a", "b"], new Set(["b", "c"]))).toEqual({ "enabledPermissions/a": null, "enabledPermissions/c": true });
expect(setPatch("roleIds", [], [])).toEqual({});
});
it("will not build on itself, or on a role already built on it", () => {
expect(canBuildOn("help", "help", roles)).toBe(false);
expect(canBuildOn("help", "lead", roles)).toBe(false);
expect(canBuildOn("lead", "user", roles)).toBe(true);
expect(canBuildOn(null, "lead", roles)).toBe(true);
});
it("is read-only to a viewer missing anything enabled in its tree, denied or not", () => {
const viewer = permissionSet(["jmapEmailGet", "sysAccountGet", "sysAccountUpdate"]);
// jmapEmailUpdate is denied on Helpdesk but enabled on User beneath it: a
// grant Stalwart would check, and a delete it would not.
expect(roleOutranks(viewer, roles.get("lead")!, roles)).toBe(true);
expect(roleOutranks(permissionSet([...viewer, "jmapEmailUpdate"]), roles.get("lead")!, roles)).toBe(false);
});
});
@@ -0,0 +1,49 @@
import { describe, expect, it, vi } from "vitest";
import { client } from "@/jmap/client";
import { countTenantMembers, drawableLogo, quotasPatch, setDomainTenant } from "@/lib/adminTenants";
describe("a tenant's limits", () => {
it("change one pointer each, leaving the quotas ihasmail does not offer alone", () => {
const before = { maxAccounts: 25, maxDomains: 2, maxOauthClients: 7 };
expect(quotasPatch(before, { maxAccounts: 30, maxDomains: null, maxGroups: 5, maxRoles: null })).toEqual({
"quotas/maxAccounts": 30,
"quotas/maxDomains": null,
"quotas/maxGroups": 5,
});
expect(quotasPatch(before, { maxAccounts: 25 })).toEqual({});
});
});
describe("what a tenant holds", () => {
it("is counted with a memberTenantId filter per kind, users and groups apart", async () => {
const call = vi.spyOn(client, "call").mockImplementation(async (method, args) => {
const f = (args as { filter: Record<string, unknown> }).filter;
if (method === "x:Role/query") throw new Error("forbidden");
return { total: method === "x:Account/query" && f["@type"] === "Group" ? 2 : 1 };
});
expect(await countTenantMembers("t1")).toEqual({ accounts: 1, groups: 2, lists: 1, domains: 1, dkimKeys: 1 });
expect(call).toHaveBeenCalledWith("x:Account/query", { filter: { "@type": "User", memberTenantId: "t1" }, limit: 0, calculateTotal: true });
expect(call).toHaveBeenCalledWith("x:Domain/query", { filter: { memberTenantId: "t1" }, limit: 0, calculateTotal: true });
call.mockRestore();
});
it("moves a domain in and out by its memberTenantId", async () => {
const call = vi.spyOn(client, "call").mockResolvedValue({ updated: { d4: null } });
await setDomainTenant("d4", "t1");
expect(call).toHaveBeenLastCalledWith("x:Domain/set", { update: { d4: { memberTenantId: "t1" } } });
await setDomainTenant("d4", null);
expect(call).toHaveBeenLastCalledWith("x:Domain/set", { update: { d4: { memberTenantId: null } } });
call.mockRestore();
});
});
describe("a tenant's logo", () => {
it("is drawn only from https or an image data URL", () => {
expect(drawableLogo("https://example.com/logo.png")).toBe("https://example.com/logo.png");
expect(drawableLogo("data:image/png;base64,AAAA")).toBe("data:image/png;base64,AAAA");
expect(drawableLogo("http://example.com/logo.png")).toBeNull();
expect(drawableLogo("javascript:alert(1)")).toBeNull();
expect(drawableLogo("data:text/html;base64,AAAA")).toBeNull();
expect(drawableLogo(null)).toBeNull();
});
});
@@ -34,7 +34,7 @@ describe("the span an availability bar covers", () => {
expect(w.span).toBeGreaterThan(0); expect(w.span).toBeGreaterThan(0);
}); });
it("marks a single day every three hours, labelling every six", () => { it("marks a single day every three hours, labeling every six", () => {
const w = availabilityWindow(at("2026-09-02T09:00:00"), at("2026-09-02T10:00:00")); const w = availabilityWindow(at("2026-09-02T09:00:00"), at("2026-09-02T10:00:00"));
expect(w.scale).toBe("hours"); 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(hours(w)).toEqual(["2@0", "2@3", "2@6", "2@9", "2@12", "2@15", "2@18", "2@21"]);
+2 -2
View File
@@ -73,7 +73,7 @@ describe("birthdaysInRange", () => {
expect(birthdaysInRange([card("c2", "", { month: 6, day: 15 })], 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", () => { it("falls back to a name built from components, then to the organization", () => {
const [s, e] = range("2026-01-01", "2027-01-01"); const [s, e] = range("2026-01-01", "2027-01-01");
const parts = { const parts = {
id: "c1", id: "c1",
@@ -115,7 +115,7 @@ describe("birthdaysInRange", () => {
expect(out.map((b) => b.name)).toEqual(["Amy", "Zoe"]); expect(out.map((b) => b.name)).toEqual(["Amy", "Zoe"]);
}); });
it("gives each occurrence a stable, unique id that marks it as synthesised", () => { it("gives each occurrence a stable, unique id that marks it as synthesized", () => {
const [s, e] = range("2025-01-01", "2027-01-01"); const [s, e] = range("2025-01-01", "2027-01-01");
const out = birthdaysInRange([card("c1", "Ada", { month: 6, day: 15 })], s, e); 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(new Set(out.map((b) => b.id)).size).toBe(out.length);
+1 -1
View File
@@ -6,7 +6,7 @@ import { DEFAULT_APP_NAME } from "@/lib/brand";
* *
* `APP_NAME` is a runtime variable, so every place showing the name has to ask * `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 * 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 * neighbor): it fetched `/api/config`, received the name and used only
* `sourceUrl`, so a rebranded instance still said "ihasmail" on the page a new * `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. * user meets first. These pin the shape of the answer rather than the name.
*/ */
+2 -2
View File
@@ -97,14 +97,14 @@ describe("explicit date formats", () => {
}); });
describe("clock preference", () => { describe("clock preference", () => {
it("honours 24-hour regardless of locale", () => { it("honors 24-hour regardless of locale", () => {
setDateTimePrefs({ locale: "en-US", timeFormat: "24" }); setDateTimePrefs({ locale: "en-US", timeFormat: "24" });
expect(formatClock(SAMPLE)).toBe("18:23"); expect(formatClock(SAMPLE)).toBe("18:23");
expect(uses24Hour()).toBe(true); expect(uses24Hour()).toBe(true);
expect(formatHourLabel(13)).toBe("13"); expect(formatHourLabel(13)).toBe("13");
expect(formatHourLabel(9)).toBe("09"); expect(formatHourLabel(9)).toBe("09");
}); });
it("honours 12-hour regardless of locale", () => { it("honors 12-hour regardless of locale", () => {
setDateTimePrefs({ locale: "de-DE", timeFormat: "12" }); setDateTimePrefs({ locale: "de-DE", timeFormat: "12" });
expect(formatClock(SAMPLE)).toBe("6:23 PM"); expect(formatClock(SAMPLE)).toBe("6:23 PM");
expect(uses24Hour()).toBe(false); expect(uses24Hour()).toBe(false);
+5 -5
View File
@@ -2,7 +2,7 @@
* The two sentence builders, which had no tests while they were building * The two sentence builders, which had no tests while they were building
* English by concatenation -- and no test would have caught the thing wrong * English by concatenation -- and no test would have caught the thing wrong
* with them, since the English output was correct. These pin the two * with them, since the English output was correct. These pin the two
* properties that matter now: every fragment goes through the catalogue, and * properties that matter now: every fragment goes through the catalog, and
* the joining is Intl's rather than a hardcoded " and ". * the joining is Intl's rather than a hardcoded " and ".
*/ */
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
@@ -12,7 +12,7 @@ import { setUiLanguageForFormatting } from "../datetime";
import { setCatalog } from "../i18n"; import { setCatalog } from "../i18n";
describe("sieve describeRule", () => { describe("sieve describeRule", () => {
it("names the header and operator through the catalogue", () => { it("names the header and operator through the catalog", () => {
const s = describeSieve({ const s = describeSieve({
id: "1", name: "r", join: "allof", enabled: true, id: "1", name: "r", join: "allof", enabled: true,
tests: [{ type: "header", header: "subject", op: "contains", value: "invoice" }], tests: [{ type: "header", header: "subject", op: "contains", value: "invoice" }],
@@ -50,7 +50,7 @@ describe("recurrence describeRule", () => {
expect(describeRecurrence({ "@type": "RecurrenceRule", frequency: "daily", interval: 3 } as never)).toBe("Every 3 days"); expect(describeRecurrence({ "@type": "RecurrenceRule", frequency: "daily", interval: 3 } as never)).toBe("Every 3 days");
}); });
it("recognises Monday to Friday as every weekday", () => { it("recognizes Monday to Friday as every weekday", () => {
const rule = { const rule = {
"@type": "RecurrenceRule", frequency: "weekly", "@type": "RecurrenceRule", frequency: "weekly",
byDay: ["mo", "tu", "we", "th", "fr"].map((day) => ({ "@type": "NDay", day })), byDay: ["mo", "tu", "we", "th", "fr"].map((day) => ({ "@type": "NDay", day })),
@@ -80,12 +80,12 @@ describe("recurrence describeRule", () => {
expect(names[0]).toBe("Montag"); expect(names[0]).toBe("Montag");
expect(names).toHaveLength(7); expect(names).toHaveLength(7);
// The narrow forms collide in English ("T" for both Tuesday and Thursday), // 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. // which is why they cannot be catalog keys and come from Intl instead.
expect(weekdayOptions().map((w) => w.short)).toHaveLength(7); expect(weekdayOptions().map((w) => w.short)).toHaveLength(7);
setUiLanguageForFormatting(null); setUiLanguageForFormatting(null);
}); });
it("renders a translated rule through the catalogue", () => { it("renders a translated rule through the catalog", () => {
setCatalog("de", { strings: { Daily: "Täglich" }, plurals: {} }); setCatalog("de", { strings: { Daily: "Täglich" }, plurals: {} });
expect(describeRecurrence({ "@type": "RecurrenceRule", frequency: "daily" } as never)).toBe("Täglich"); expect(describeRecurrence({ "@type": "RecurrenceRule", frequency: "daily" } as never)).toBe("Täglich");
setCatalog("en", { strings: {}, plurals: {} }); setCatalog("en", { strings: {}, plurals: {} });
+27 -3
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { canDropFolder, descendantIds, folderColor, movable } from "../folderMove"; import { canDropFolder, canMoveFolderTo, descendantIds, folderColor, movable } from "../folderMove";
import type { Id, Mailbox } from "@/jmap/types"; import type { Id, Mailbox } from "@/jmap/types";
const mb = (id: string, name: string, parentId: string | null, role: Mailbox["role"] = null): Mailbox => const mb = (id: string, name: string, parentId: string | null, role: Mailbox["role"] = null): Mailbox =>
@@ -68,15 +68,39 @@ describe("canDropFolder", () => {
}); });
}); });
describe("canMoveFolderTo", () => {
const rights = (r: Partial<Mailbox["myRights"]>) => ({ mayRename: true, mayCreateChild: true, ...r }) as Mailbox["myRights"];
const owned: Record<Id, Mailbox> = Object.fromEntries(Object.values(tree).map((m) => [m.id, { ...m, myRights: rights({}) }]));
it("agrees with a drop when every right is granted", () => {
expect(canMoveFolderTo(owned, "news", "work")).toBe(true);
expect(canMoveFolderTo(owned, "eu", null)).toBe(true);
expect(canMoveFolderTo(owned, "work", "eu")).toBe(false);
expect(canMoveFolderTo(owned, "news", null)).toBe(false);
});
it("refuses a folder the user may not rename, top level included", () => {
const locked = { ...owned, eu: { ...owned.eu!, myRights: rights({ mayRename: false }) } };
expect(canMoveFolderTo(locked, "eu", "news")).toBe(false);
expect(canMoveFolderTo(locked, "eu", null)).toBe(false);
});
it("refuses a destination that may not hold new subfolders", () => {
const closed = { ...owned, work: { ...owned.work!, myRights: rights({ mayCreateChild: false }) } };
expect(canMoveFolderTo(closed, "news", "work")).toBe(false);
expect(canMoveFolderTo(closed, "eu", null)).toBe(true);
});
});
describe("folderColor", () => { describe("folderColor", () => {
it("returns the colour chosen for that folder, and null for the rest", () => { it("returns the color chosen for that folder, and null for the rest", () => {
const colors = { work: "#7c3aed" }; const colors = { work: "#7c3aed" };
expect(folderColor(colors, "work")).toBe("#7c3aed"); expect(folderColor(colors, "work")).toBe("#7c3aed");
expect(folderColor(colors, "news")).toBeNull(); expect(folderColor(colors, "news")).toBeNull();
expect(folderColor({}, "work")).toBeNull(); expect(folderColor({}, "work")).toBeNull();
}); });
it("is keyed by id, so a renamed folder keeps its colour", () => { it("is keyed by id, so a renamed folder keeps its color", () => {
// The id is stable across a rename; the name and path are not. // The id is stable across a rename; the name and path are not.
expect(folderColor({ mb1: "#0f766e" }, "mb1")).toBe("#0f766e"); expect(folderColor({ mb1: "#0f766e" }, "mb1")).toBe("#0f766e");
}); });
+22 -22
View File
@@ -34,7 +34,7 @@ describe("sanitizeEmailHtml", () => {
}); });
describe("htmlDeclaresColors", () => { describe("htmlDeclaresColors", () => {
it("is false for mail that brings no colours", () => { it("is false for mail that brings no colors", () => {
expect(htmlDeclaresColors("<p>Hi there</p>")).toBe(false); expect(htmlDeclaresColors("<p>Hi there</p>")).toBe(false);
expect(htmlDeclaresColors("<div><b>bold</b> and <i>italic</i></div>", "font-family:Arial")).toBe(false); expect(htmlDeclaresColors("<div><b>bold</b> and <i>italic</i></div>", "font-family:Arial")).toBe(false);
expect(htmlDeclaresColors('<a href="https://x.io/?color=red">link</a>')).toBe(false); expect(htmlDeclaresColors('<a href="https://x.io/?color=red">link</a>')).toBe(false);
@@ -54,9 +54,9 @@ describe("htmlDeclaresColors", () => {
/** /**
* Forcing the theme onto mail that styles itself issue #290. * Forcing the theme onto mail that styles itself issue #290.
* *
* The switch above it leaves nearly all HTML mail alone, because one colour * The switch above it leaves nearly all HTML mail alone, because one color
* anywhere opts a message out. What this half has to get right is telling a * anywhere opts a message out. What this half has to get right is telling a
* sheet the design sits on from a surface painted on top of it: neutralise the * sheet the design sits on from a surface painted on top of it: neutralize the
* first and the white card goes away, keep the second and a button keeps a * first and the white card goes away, keep the second and a button keeps a
* label you can still read. * label you can still read.
*/ */
@@ -70,15 +70,15 @@ describe("relativeLuminance", () => {
expect(relativeLuminance("rgba(255,255,255,0.5)")).toBeCloseTo(1, 5); expect(relativeLuminance("rgba(255,255,255,0.5)")).toBeCloseTo(1, 5);
}); });
it("has nothing to say about a colour it cannot read", () => { it("has nothing to say about a color it cannot read", () => {
// Not a failure: the caller treats null as "no deliberate surface", which // Not a failure: the caller treats null as "no deliberate surface", which
// is the safe way round — an unreadable colour must not keep a white sheet. // is the safe way round — an unreadable color must not keep a white sheet.
expect(relativeLuminance("color-mix(in srgb, red, blue)")).toBeNull(); expect(relativeLuminance("color-mix(in srgb, red, blue)")).toBeNull();
expect(relativeLuminance("var(--brand)")).toBeNull(); expect(relativeLuminance("var(--brand)")).toBeNull();
expect(relativeLuminance("")).toBeNull(); expect(relativeLuminance("")).toBeNull();
}); });
it("treats a fully transparent colour as painting nothing", () => { it("treats a fully transparent color as painting nothing", () => {
expect(relativeLuminance("rgba(0,0,0,0)")).toBeNull(); expect(relativeLuminance("rgba(0,0,0,0)")).toBeNull();
expect(relativeLuminance("transparent")).toBeNull(); expect(relativeLuminance("transparent")).toBeNull();
}); });
@@ -100,21 +100,21 @@ describe("markKeptSurfaces", () => {
* Marking is only half of it the other half is the rule in EMAIL_BASE_CSS * Marking is only half of it the other half is the rule in EMAIL_BASE_CSS
* that reads the marks, and #310 was a bug in that half rather than in the * that reads the marks, and #310 was a bug in that half rather than in the
* marking. So these assert what the reader actually sees: does the * marking. So these assert what the reader actually sees: does the
* neutraliser hit this element? The selector is lifted out of the stylesheet * neutralizer hit this element? The selector is lifted out of the stylesheet
* rather than copied, so a test cannot quietly drift from the rule it checks. * rather than copied, so a test cannot quietly drift from the rule it checks.
*/ */
const NEUTRALISER = (() => { const NEUTRALIZER = (() => {
const m = EMAIL_BASE_CSS.match( const m = EMAIL_BASE_CSS.match(
/\.ihm-email-root\.forced\s+(\*:not\([^{]*?)\s*\{\s*color: inherit/, /\.ihm-email-root\.forced\s+(\*:not\([^{]*?)\s*\{\s*color: inherit/,
); );
if (!m) throw new Error("could not find the neutraliser rule in EMAIL_BASE_CSS"); if (!m) throw new Error("could not find the neutralizer rule in EMAIL_BASE_CSS");
return m[1]!.trim(); return m[1]!.trim();
})(); })();
/** True when the theme is forced onto this element rather than leaving it alone. */ /** True when the theme is forced onto this element rather than leaving it alone. */
const neutralised = (el: Element) => el.matches(NEUTRALISER); const neutralized = (el: Element) => el.matches(NEUTRALIZER);
it("keeps a coloured button and drops the white sheet around it", () => { it("keeps a colored button and drops the white sheet around it", () => {
// The shape reported in #290: a Shopify/Klaviyo template whose outer 600px // The shape reported in #290: a Shopify/Klaviyo template whose outer 600px
// wrapper carries bgcolor="#ffffff" and whose CTA carries bgcolor="#1155CC". // wrapper carries bgcolor="#ffffff" and whose CTA carries bgcolor="#1155CC".
const d = frag('<table bgcolor="#ffffff"><tr><td bgcolor="#1155CC"><a style="color:#FFFFFF">Buy</a></td></tr></table>'); const d = frag('<table bgcolor="#ffffff"><tr><td bgcolor="#1155CC"><a style="color:#FFFFFF">Buy</a></td></tr></table>');
@@ -127,7 +127,7 @@ describe("markKeptSurfaces", () => {
expect(d.querySelector("a")!.hasAttribute("data-ihm-in-keep")).toBe(true); expect(d.querySelector("a")!.hasAttribute("data-ihm-in-keep")).toBe(true);
}); });
it("neutralises a light panel nested inside a dark painted card", () => { it("neutralizes a light panel nested inside a dark painted card", () => {
// The shape reported in #310: a dark Klaviyo campaign whose 600px cards // The shape reported in #310: a dark Klaviyo campaign whose 600px cards
// are dark enough to be marked, with light content tables inside them. // are dark enough to be marked, with light content tables inside them.
// Those tables used to inherit the card's exemption and render as beige // Those tables used to inherit the card's exemption and render as beige
@@ -153,11 +153,11 @@ describe("markKeptSurfaces", () => {
// The fix, stated the way the reader experiences it: the nested sheet is // The fix, stated the way the reader experiences it: the nested sheet is
// themed, and so is the copy inside it. Before #310 both were exempt for // themed, and so is the copy inside it. Before #310 both were exempt for
// being descendants of the card. // being descendants of the card.
expect(neutralised(nested)).toBe(true); expect(neutralized(nested)).toBe(true);
expect(neutralised(d.querySelector("td")!)).toBe(true); expect(neutralized(d.querySelector("td")!)).toBe(true);
// The card itself is still left alone, and the page surround still goes. // The card itself is still left alone, and the page surround still goes.
expect(neutralised(card)).toBe(false); expect(neutralized(card)).toBe(false);
expect(neutralised(surround)).toBe(true); expect(neutralized(surround)).toBe(true);
}); });
it("still keeps a button that sits inside a nested light panel", () => { it("still keeps a button that sits inside a nested light panel", () => {
@@ -172,11 +172,11 @@ describe("markKeptSurfaces", () => {
'</div>', '</div>',
); );
expect(markKeptSurfaces(d)).toBe(2); expect(markKeptSurfaces(d)).toBe(2);
expect(neutralised(d.querySelector("table")!)).toBe(true); expect(neutralized(d.querySelector("table")!)).toBe(true);
expect(neutralised(d.querySelector("td")!)).toBe(false); expect(neutralized(d.querySelector("td")!)).toBe(false);
// The label keeps its white, which is the thing #294 bought and this must // The label keeps its white, which is the thing #294 bought and this must
// not spend. // not spend.
expect(neutralised(d.querySelector("a")!)).toBe(false); expect(neutralized(d.querySelector("a")!)).toBe(false);
}); });
it("leaves no light panel exempt across the whole reported specimen", () => { it("leaves no light panel exempt across the whole reported specimen", () => {
@@ -201,7 +201,7 @@ describe("markKeptSurfaces", () => {
expect(panels.length).toBe(21); expect(panels.length).toBe(21);
expect(markKeptSurfaces(d)).toBe(7); expect(markKeptSurfaces(d)).toBe(7);
expect(panels.filter((p) => !neutralised(p))).toHaveLength(0); expect(panels.filter((p) => !neutralized(p))).toHaveLength(0);
}); });
it("reads an inline background as well as the attribute", () => { it("reads an inline background as well as the attribute", () => {
@@ -233,7 +233,7 @@ describe("markKeptSurfaces", () => {
* The control that actually stops it is layout containment on an ancestor of * The control that actually stops it is layout containment on an ancestor of
* the shadow host, which mail CSS has no selector for; that lives in app.css * the shadow host, which mail CSS has no selector for; that lives in app.css
* and is asserted at the bottom of this file, because jsdom does no layout and * and is asserted at the bottom of this file, because jsdom does no layout and
* cannot prove it here. These cover the second line of defence. * cannot prove it here. These cover the second line of defense.
*/ */
describe("mail CSS cannot climb out of its card", () => { describe("mail CSS cannot climb out of its card", () => {
const render = (html: string) => sanitizeEmailHtml(html).html; const render = (html: string) => sanitizeEmailHtml(html).html;
@@ -271,7 +271,7 @@ describe("mail CSS cannot climb out of its card", () => {
describe("the containment that mail CSS cannot override", () => { describe("the containment that mail CSS cannot override", () => {
it("is still applied to the message body container", async () => { it("is still applied to the message body container", async () => {
// jsdom does no layout, so this asserts the control is present rather than // jsdom does no layout, so this asserts the control is present rather than
// that it works; the behaviour was verified in a real browser. Without it, // that it works; the behavior was verified in a real browser. Without it,
// a message can cover the viewport regardless of what the sanitizer does. // a message can cover the viewport regardless of what the sanitizer does.
const { readFile } = await import("node:fs/promises"); const { readFile } = await import("node:fs/promises");
const { join } = await import("node:path"); const { join } = await import("node:path");
@@ -36,7 +36,7 @@ describe("deciding whether a message has an HTML alternative", () => {
expect(hasHtmlAlternative({ type: "text/htmlish" }, "<p>Hi</p>")).toBe(false); expect(hasHtmlAlternative({ type: "text/htmlish" }, "<p>Hi</p>")).toBe(false);
}); });
it("matches the type case-insensitively, since a header may be capitalised", () => { it("matches the type case-insensitively, since a header may be capitalized", () => {
expect(hasHtmlAlternative({ type: "TEXT/HTML" }, "<p>Hi</p>")).toBe(true); expect(hasHtmlAlternative({ type: "TEXT/HTML" }, "<p>Hi</p>")).toBe(true);
}); });
+5 -5
View File
@@ -29,12 +29,12 @@ describe("t", () => {
expect(currentLanguage()).toBe("en"); expect(currentLanguage()).toBe("en");
}); });
it("translates once a catalogue is in force", () => { it("translates once a catalog is in force", () => {
setCatalog("de", de); setCatalog("de", de);
expect(t("Archive")).toBe("Archivieren"); expect(t("Archive")).toBe("Archivieren");
}); });
it("falls back per string, not per catalogue", () => { it("falls back per string, not per catalog", () => {
setCatalog("de", de); setCatalog("de", de);
expect(t("Report spam")).toBe("Report spam"); expect(t("Report spam")).toBe("Report spam");
}); });
@@ -60,7 +60,7 @@ describe("interpolation", () => {
describe("plural", () => { describe("plural", () => {
const FORMS = { one: "{n} message", other: "{n} messages" }; const FORMS = { one: "{n} message", other: "{n} messages" };
it("picks the English form without a catalogue", () => { it("picks the English form without a catalog", () => {
expect(plural(1, FORMS)).toBe("1 message"); expect(plural(1, FORMS)).toBe("1 message");
expect(plural(0, FORMS)).toBe("0 messages"); expect(plural(0, FORMS)).toBe("0 messages");
expect(plural(5, FORMS)).toBe("5 messages"); expect(plural(5, FORMS)).toBe("5 messages");
@@ -73,7 +73,7 @@ describe("plural", () => {
expect(plural(7, FORMS)).toBe("7 сообщений"); // many expect(plural(7, FORMS)).toBe("7 сообщений"); // many
}); });
it("falls back to `other` when the catalogue lacks the category", () => { it("falls back to `other` when the catalog lacks the category", () => {
setCatalog("de", de); setCatalog("de", de);
// German has no "few"; asking for 3 must not render undefined. // German has no "few"; asking for 3 must not render undefined.
expect(plural(3, FORMS)).toBe("3 Nachrichten"); expect(plural(3, FORMS)).toBe("3 Nachrichten");
@@ -95,7 +95,7 @@ describe("tNode", () => {
it("lets a translator move the element", () => { it("lets a translator move the element", () => {
// Splitting the sentence into two t() calls could not do this: the // Splitting the sentence into two t() calls could not do this: the
// fragments would render in the English order whatever the catalogue said. // fragments would render in the English order whatever the catalog said.
setCatalog("de", de); setCatalog("de", de);
expect(render(tNode("Open {scheme} links here", { scheme: <code>mailto:</code> }))) expect(render(tNode("Open {scheme} links here", { scheme: <code>mailto:</code> })))
.toBe("<code>mailto:</code>-Links hier öffnen"); .toBe("<code>mailto:</code>-Links hier öffnen");
+1 -1
View File
@@ -111,7 +111,7 @@ describe("parseIcsDuration", () => {
}); });
describe("looksLikeCalendar", () => { describe("looksLikeCalendar", () => {
it("recognises a calendar and rejects an error page", () => { it("recognizes a calendar and rejects an error page", () => {
expect(looksLikeCalendar("BEGIN:VCALENDAR\r\nEND:VCALENDAR")).toBe(true); expect(looksLikeCalendar("BEGIN:VCALENDAR\r\nEND:VCALENDAR")).toBe(true);
expect(looksLikeCalendar("<!doctype html><title>404</title>")).toBe(false); expect(looksLikeCalendar("<!doctype html><title>404</title>")).toBe(false);
}); });
+3 -3
View File
@@ -30,7 +30,7 @@ const find = (e: JSCalendarEvent[], prefix: string) => eventLines(e).filter((l)
const one = (e: JSCalendarEvent, prefix: string) => find([e], prefix)[0]; const one = (e: JSCalendarEvent, prefix: string) => find([e], prefix)[0];
describe("the document around the events", () => { describe("the document around the events", () => {
it("is a calendar a reader will recognise", () => { it("is a calendar a reader will recognize", () => {
const l = lines([base]); const l = lines([base]);
expect(l[0]).toBe("BEGIN:VCALENDAR"); expect(l[0]).toBe("BEGIN:VCALENDAR");
expect(l).toContain("VERSION:2.0"); expect(l).toContain("VERSION:2.0");
@@ -105,7 +105,7 @@ describe("recurrence", () => {
expect(one(e, "RRULE")).toBe("RRULE:FREQ=MONTHLY;BYDAY=-1TH"); expect(one(e, "RRULE")).toBe("RRULE:FREQ=MONTHLY;BYDAY=-1TH");
}); });
it("turns a cancelled occurrence into an EXDATE", () => { it("turns a canceled occurrence into an EXDATE", () => {
const e = { ...weekly, recurrenceOverrides: { "2026-09-09T09:00:00": null } }; const e = { ...weekly, recurrenceOverrides: { "2026-09-09T09:00:00": null } };
expect(one(e, "EXDATE")).toBe("EXDATE;TZID=Europe/Berlin:20260909T090000"); expect(one(e, "EXDATE")).toBe("EXDATE;TZID=Europe/Berlin:20260909T090000");
expect(find([e], "BEGIN:VEVENT")).toHaveLength(1); expect(find([e], "BEGIN:VEVENT")).toHaveLength(1);
@@ -166,7 +166,7 @@ describe("the rest of an event", () => {
expect(one(e, "TRANSP")).toBe("TRANSP:TRANSPARENT"); expect(one(e, "TRANSP")).toBe("TRANSP:TRANSPARENT");
}); });
it("writes the organiser and the guests, with what each answered", () => { it("writes the organizer and the guests, with what each answered", () => {
const e = { const e = {
...base, ...base,
organizerCalendarAddress: "mailto:[email protected]", organizerCalendarAddress: "mailto:[email protected]",
@@ -0,0 +1,42 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { comboOf, keyboard } from "@/lib/keyboard";
/*
* A "keydown" that carries no key. Chrome's password autofill dispatches one
* as a plain Event when a saved login is picked, and comboOf read `key.length`
* off it -- an uncaught TypeError in the console on every sign-in.
*/
let pop: (() => void) | null = null;
afterEach(() => {
pop?.();
pop = null;
});
describe("a keydown with no key", () => {
it("has no combo", () => {
expect(comboOf(new Event("keydown") as KeyboardEvent)).toBeNull();
});
it("reaches no binding and throws nothing", () => {
const handler = vi.fn();
pop = keyboard.pushScope("test", [{ keys: "e", description: "Archive", group: "Mail", handler }]);
const errors: unknown[] = [];
const onError = (ev: ErrorEvent) => errors.push(ev.error);
window.addEventListener("error", onError);
try {
window.dispatchEvent(new Event("keydown", { bubbles: true }));
} finally {
window.removeEventListener("error", onError);
}
expect(errors).toEqual([]);
expect(handler).not.toHaveBeenCalled();
});
it("leaves real keys alone", () => {
expect(comboOf(new KeyboardEvent("keydown", { key: "e" }))).toBe("e");
expect(comboOf(new KeyboardEvent("keydown", { key: "E", shiftKey: true }))).toBe("E");
expect(comboOf(new KeyboardEvent("keydown", { key: "Enter", ctrlKey: true }))).toMatch(/enter$/);
});
});
+4 -4
View File
@@ -19,7 +19,7 @@ describe("resolveUiLanguage", () => {
}); });
it("refuses a language whose strings are not shipped", () => { it("refuses a language whose strings are not shipped", () => {
// The account travels between machines and can outlive a catalogue. A // The account travels between machines and can outlive a catalog. A
// page that says lang="fr" while rendering English is worse than one that // page that says lang="fr" while rendering English is worse than one that
// admits to English: it stops the reader translating it themselves. // admits to English: it stops the reader translating it themselves.
// Derived rather than named, so shipping another language does not turn // Derived rather than named, so shipping another language does not turn
@@ -30,7 +30,7 @@ describe("resolveUiLanguage", () => {
}); });
it("carries the Beta flag until a person has signed the language off", () => { it("carries the Beta flag until a person has signed the language off", () => {
// Not a completeness measure. A catalogue can be word-for-word finished // Not a completeness measure. A catalog can be word-for-word finished
// and still read like a machine wrote it, which is what this marks. // and still read like a machine wrote it, which is what this marks.
// Every shipped language except English is unreviewed, and stays marked // Every shipped language except English is unreviewed, and stays marked
// until a person says otherwise. // until a person says otherwise.
@@ -40,12 +40,12 @@ describe("resolveUiLanguage", () => {
} }
}); });
it("honours one that is", () => { it("honors one that is", () => {
for (const l of UI_LANGUAGES) expect(resolveUiLanguage(l.tag)).toBe(l.tag); for (const l of UI_LANGUAGES) expect(resolveUiLanguage(l.tag)).toBe(l.tag);
}); });
it("only offers languages that resolve to themselves", () => { it("only offers languages that resolve to themselves", () => {
// Guards the ordering mistake: adding a picker entry before its catalogue. // Guards the ordering mistake: adding a picker entry before its catalog.
for (const l of UI_LANGUAGES) { for (const l of UI_LANGUAGES) {
expect(resolveUiLanguage(l.tag)).toBe(l.tag); expect(resolveUiLanguage(l.tag)).toBe(l.tag);
expect(l.name.trim()).not.toBe(""); expect(l.name.trim()).not.toBe("");
+1 -1
View File
@@ -94,7 +94,7 @@ describe("comparatorsFor, custom levels", () => {
}); });
describe("optional sorts, which a server is allowed to refuse", () => { describe("optional sorts, which a server is allowed to refuse", () => {
it("recognises the keyword properties", () => { it("recognizes the keyword properties", () => {
expect(isOptionalSort({ property: "hasKeyword", keyword: "$seen" })).toBe(true); expect(isOptionalSort({ property: "hasKeyword", keyword: "$seen" })).toBe(true);
expect(isOptionalSort({ property: "someInThreadHaveKeyword", keyword: "$flagged" })).toBe(true); expect(isOptionalSort({ property: "someInThreadHaveKeyword", keyword: "$flagged" })).toBe(true);
expect(isOptionalSort({ property: "receivedAt" })).toBe(false); expect(isOptionalSort({ property: "receivedAt" })).toBe(false);
+7 -7
View File
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it } from "vitest"; import { afterEach, describe, expect, it } from "vitest";
import { isLocalisedName, mailboxDisplayName, mailboxDisplayPath } from "@/lib/mailboxName"; import { isLocalizedName, mailboxDisplayName, mailboxDisplayPath } from "@/lib/mailboxName";
import { setCatalog, type Catalog } from "@/lib/i18n"; import { setCatalog, type Catalog } from "@/lib/i18n";
import type { Mailbox } from "@/jmap/types"; import type { Mailbox } from "@/jmap/types";
@@ -19,7 +19,7 @@ const mb = (id: string, name: string, role: string | null = null, parentId: stri
afterEach(() => setCatalog("en", { strings: {}, plurals: {} })); afterEach(() => setCatalog("en", { strings: {}, plurals: {} }));
describe("mailboxDisplayName", () => { describe("mailboxDisplayName", () => {
it("is the server's name until a catalogue says otherwise", () => { it("is the server's name until a catalog says otherwise", () => {
expect(mailboxDisplayName(mb("1", "Deleted Items", "trash"))).toBe("Deleted Items"); expect(mailboxDisplayName(mb("1", "Deleted Items", "trash"))).toBe("Deleted Items");
}); });
@@ -43,18 +43,18 @@ describe("mailboxDisplayName", () => {
}); });
}); });
describe("isLocalisedName", () => { describe("isLocalizedName", () => {
it("tells an editor when the name on screen is not the server's", () => { it("tells an editor when the name on screen is not the server's", () => {
// A rename box prefilled with "Papierkorb" would rename the folder to that // A rename box prefilled with "Papierkorb" would rename the folder to that
// the moment somebody pressed Save — a real change made by accident. // the moment somebody pressed Save — a real change made by accident.
expect(isLocalisedName(mb("1", "Deleted Items", "trash"))).toBe(true); expect(isLocalizedName(mb("1", "Deleted Items", "trash"))).toBe(true);
expect(isLocalisedName(mb("2", "Newsletters"))).toBe(false); expect(isLocalizedName(mb("2", "Newsletters"))).toBe(false);
expect(isLocalisedName(mb("3", "Work", "subscribed"))).toBe(false); expect(isLocalizedName(mb("3", "Work", "subscribed"))).toBe(false);
}); });
}); });
describe("mailboxDisplayPath", () => { describe("mailboxDisplayPath", () => {
it("localises each part that has a role and leaves the rest", () => { it("localizes each part that has a role and leaves the rest", () => {
setCatalog("de", de); setCatalog("de", de);
const all = { a: mb("a", "Inbox", "inbox"), b: mb("b", "Projects", null, "a") }; const all = { a: mb("a", "Inbox", "inbox"), b: mb("b", "Projects", null, "a") };
expect(mailboxDisplayPath(all.b!, all)).toBe("Posteingang / Projects"); expect(mailboxDisplayPath(all.b!, all)).toBe("Posteingang / Projects");
+1 -1
View File
@@ -35,7 +35,7 @@ describe("renderMarkdown", () => {
/* /*
* Markdown passes raw HTML through by design, and the file came from * Markdown passes raw HTML through by design, and the file came from
* somewhere else -- an upload, or a share from another account. Every one of * somewhere else -- an upload, or a share from another account. Every one of
* these renders as a script tag without a sanitiser. * these renders as a script tag without a sanitizer.
*/ */
it("takes out anything that would execute", () => { it("takes out anything that would execute", () => {
const html = renderMarkdown("<script>alert(1)</script>\n\n<img src=x onerror=alert(1)>\n\n<iframe src='https://evil.example'></iframe>\n"); const html = renderMarkdown("<script>alert(1)</script>\n\n<img src=x onerror=alert(1)>\n\n<iframe src='https://evil.example'></iframe>\n");
+1 -1
View File
@@ -85,7 +85,7 @@ describe("the rest of the schema", () => {
expect(phones).toContainEqual(expect.objectContaining({ number: "3", features: { pager: true } })); expect(phones).toContainEqual(expect.objectContaining({ number: "3", features: { pager: true } }));
}); });
it("reads the organisation, its units and the job title", () => { it("reads the organization, its units and the job title", () => {
const c = card("dn: cn=X\ncn: X\no: Example Corp\nou: Research\nou: Optics\ntitle: Lens Grinder\n")!; const c = card("dn: cn=X\ncn: X\no: Example Corp\nou: Research\nou: Optics\ntitle: Lens Grinder\n")!;
expect(values(c.organizations)[0]).toMatchObject({ expect(values(c.organizations)[0]).toMatchObject({
name: "Example Corp", name: "Example Corp",
+2 -2
View File
@@ -5,7 +5,7 @@ describe("the palettes themselves", () => {
it("has a light and a dark half for every one of them", () => { it("has a light and a dark half for every one of them", () => {
// The reason there is no "this palette is dark only" machinery: there is // The reason there is no "this palette is dark only" machinery: there is
// no such palette. ihasmail's own gained a light half, and the override, // no such palette. ihasmail's own gained a light half, and the override,
// the toggle's memory and a greyed-out control all went with it. // the toggle's memory and a grayed-out control all went with it.
expect(PALETTES.map((p) => p.id)).toEqual([ expect(PALETTES.map((p) => p.id)).toEqual([
"default", "ihasmail", "dracula", "gruvbox", "rose-pine", "tokyo-night", "default", "ihasmail", "dracula", "gruvbox", "rose-pine", "tokyo-night",
"catppuccin", "solarized", "ayu", "kanagawa", "everforest", "primer", "catppuccin", "solarized", "ayu", "kanagawa", "everforest", "primer",
@@ -75,7 +75,7 @@ describe("legacyTheme, read by a device still on an older build", () => {
}); });
describe("toggleTarget", () => { describe("toggleTarget", () => {
it("flips the mode and keeps the colours, whatever the palette", () => { it("flips the mode and keeps the colors, whatever the palette", () => {
for (const palette of ["default", "ihasmail", "gruvbox", "dracula", "rose-pine", "tokyo-night"] as const) { for (const palette of ["default", "ihasmail", "gruvbox", "dracula", "rose-pine", "tokyo-night"] as const) {
expect(toggleTarget({ palette, mode: "dark" }, false)).toEqual({ palette, mode: "light" }); expect(toggleTarget({ palette, mode: "dark" }, false)).toEqual({ palette, mode: "light" });
expect(toggleTarget({ palette, mode: "light" }, false)).toEqual({ palette, mode: "dark" }); expect(toggleTarget({ palette, mode: "light" }, false)).toEqual({ palette, mode: "dark" });
@@ -0,0 +1,54 @@
import { describe, expect, it } from "vitest";
import source from "../../locales/permissions/source.json";
import { describePermissions, splitLabel, type PermissionCatalog } from "@/lib/permissionLabels";
import { UI_LANGUAGES } from "@/lib/languages";
describe("permission labels", () => {
it("split Stalwart's label into its heading and action", () => {
expect(splitLabel("Accounts Management: Create accounts")).toEqual({ categoryKey: "Accounts Management", action: "Create accounts" });
expect(splitLabel("Action: Reload: TLS certificates")).toEqual({ categoryKey: "Action", action: "Reload: TLS certificates" });
expect(splitLabel("Act on behalf of another user")).toEqual({ categoryKey: "General", action: "Act on behalf of another user" });
});
it("fall back to Stalwart's English for a permission a language does not have yet", () => {
const catalog: PermissionCatalog = { categories: { "Accounts Management": "Kontenverwaltung" }, labels: { sysAccountGet: "Konten abrufen" } };
expect(describePermissions([
{ name: "sysAccountGet", label: "Accounts Management: Get accounts" },
{ name: "sysBrandNewThing", label: "Novelties: Do something new" },
{ name: "impersonate", label: "Act on behalf of another user" },
], catalog, "Allgemein")).toEqual([
{ name: "sysAccountGet", categoryKey: "Accounts Management", category: "Kontenverwaltung", action: "Konten abrufen" },
{ name: "sysBrandNewThing", categoryKey: "Novelties", category: "Novelties", action: "Do something new" },
{ name: "impersonate", categoryKey: "General", category: "Allgemein", action: "Act on behalf of another user" },
]);
});
});
/**
* Every language covers every permission the snapshot has, and nothing it
* does not: a missing one would show English in the middle of a translated
* picker, and a stale one would never be looked up.
*/
describe("the permission catalogs", () => {
const modules = import.meta.glob<{ permissionCatalog: PermissionCatalog }>("../../locales/permissions/*.ts");
const tagOf = (path: string) => path.split("/").pop()!.replace(/\.ts$/, "");
const languages = UI_LANGUAGES.map((l) => l.tag).filter((tag) => tag !== "en");
const names = new Set(source.permissions.map((p) => p.name));
const categories = new Set(source.permissions.map((p) => splitLabel(p.label).categoryKey).filter((c) => c !== "General"));
it("exist for every language the interface ships", () => {
expect(Object.keys(modules).map(tagOf).sort()).toEqual([...languages].sort());
});
for (const tag of languages) {
it(`${tag} names every permission and heading, and nothing else`, async () => {
const load = Object.entries(modules).find(([path]) => tagOf(path) === tag)?.[1];
expect(load, `locales/permissions/${tag}.ts`).toBeTruthy();
const { permissionCatalog } = await load!();
expect(Object.keys(permissionCatalog.labels).filter((n) => !names.has(n))).toEqual([]);
expect([...names].filter((n) => !permissionCatalog.labels[n]?.trim())).toEqual([]);
expect(Object.keys(permissionCatalog.categories).sort()).toEqual([...categories].sort());
});
}
});
+2 -2
View File
@@ -7,7 +7,7 @@ import { settingsAlreadyLoadedFor, stopSettingsSync } from "../settingsSync";
* Settings used to live only in localStorage, so nothing followed the user * Settings used to live only in localStorage, so nothing followed the user
* between devices issue #54, whose sharpest case is the default identity: * between devices issue #54, whose sharpest case is the default identity:
* with none set, the address that sorts first wins, so mail goes out from an * with none set, the address that sorts first wins, so mail goes out from an
* address the recipient may not recognise. * address the recipient may not recognize.
* *
* The split is written as a list of exceptions, which means the interesting * The split is written as a list of exceptions, which means the interesting
* test is not "does this key sync" but "does a key added later sync without * test is not "does this key sync" but "does a key added later sync without
@@ -25,7 +25,7 @@ describe("which settings follow the account", () => {
const synced = syncedPart(DEFAULT_SETTINGS); const synced = syncedPart(DEFAULT_SETTINGS);
// A pane width picked on a monitor is wrong on a laptop, and the // A pane width picked on a monitor is wrong on a laptop, and the
// notification toggles track a per-browser permission grant. // notification toggles track a per-browser permission grant.
for (const key of ["listPaneWidth", "listPaneHeight", "density", "fontSize", "sidebarCollapsed", "desktopNotifications", "notificationSound"]) { for (const key of ["listPaneWidth", "listPaneHeight", "contactsListWidth", "sidebarWidth", "density", "fontSize", "sidebarCollapsed", "desktopNotifications", "notificationSound"]) {
expect(synced, key).not.toHaveProperty(key); expect(synced, key).not.toHaveProperty(key);
} }
}); });
+1 -1
View File
@@ -109,7 +109,7 @@ describe("sharing a file", () => {
await expect(shareFile(aFile())).resolves.toBe("unsupported"); await expect(shareFile(aFile())).resolves.toBe("unsupported");
}); });
it("raises anything it does not recognise, so a real fault is still reported", async () => { it("raises anything it does not recognize, so a real fault is still reported", async () => {
stubNavigator({ stubNavigator({
share: vi.fn(async () => { throw new DOMException("boom", "DataError"); }), share: vi.fn(async () => { throw new DOMException("boom", "DataError"); }),
canShare: (() => true) as unknown as Navigator["canShare"], canShare: (() => true) as unknown as Navigator["canShare"],
+1 -1
View File
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import { buildMarkerSignature, byteLength, compactHtml, markerOf, signatureTooLong, SIGNATURE_LIMIT } from "../signatureHtml"; import { buildMarkerSignature, byteLength, compactHtml, markerOf, signatureTooLong, SIGNATURE_LIMIT } from "../signatureHtml";
describe("signature compaction", () => { describe("signature compaction", () => {
it("strips office cruft and non-essential styles but keeps colours and links", () => { it("strips office cruft and non-essential styles but keeps colors and links", () => {
const src = `<!--[if gte mso 9]><xml>x</xml><![endif]--><div class="WordSection1" style="mso-margin-top-alt:auto;line-height:115%;font-family:'Calibri',sans-serif;color:windowtext"><p class="MsoNormal" style="margin:0cm;font-size:11pt"><span lang="EN-US" style="font-size:12pt;color:#1F4E79;mso-fareast-language:EN-US"><b>John Coffey</b></span><o:p></o:p></p><p><span></span></p><a href="https://linuxexpert.org" target="_blank" data-x="1">linuxexpert.org</a><img src="https://x/y.png" width="100" style="mso-foo:bar"></div>`; const src = `<!--[if gte mso 9]><xml>x</xml><![endif]--><div class="WordSection1" style="mso-margin-top-alt:auto;line-height:115%;font-family:'Calibri',sans-serif;color:windowtext"><p class="MsoNormal" style="margin:0cm;font-size:11pt"><span lang="EN-US" style="font-size:12pt;color:#1F4E79;mso-fareast-language:EN-US"><b>John Coffey</b></span><o:p></o:p></p><p><span></span></p><a href="https://linuxexpert.org" target="_blank" data-x="1">linuxexpert.org</a><img src="https://x/y.png" width="100" style="mso-foo:bar"></div>`;
const out = compactHtml(src); const out = compactHtml(src);
expect(out).not.toContain("mso-"); expect(out).not.toContain("mso-");
+3 -3
View File
@@ -6,8 +6,8 @@ import { catalog as de } from "@/locales/de";
/** /**
* The briefing is the only thing standing between a notification action and a * The briefing is the only thing standing between a notification action and a
* button labelled in a language the reader does not use the worker is plain * button labeled in a language the reader does not use the worker is plain
* JavaScript outside the bundle and cannot reach a catalogue. * JavaScript outside the bundle and cannot reach a catalog.
* *
* It is also the only place the archive mailbox is named, and getting that * It is also the only place the archive mailbox is named, and getting that
* wrong does not fail visibly: a message would be filed somewhere, just not * wrong does not fail visibly: a message would be filed somewhere, just not
@@ -45,7 +45,7 @@ describe("the worker's briefing", () => {
}); });
it("carries the worker's text in the language the tab is in", async () => { it("carries the worker's text in the language the tab is in", async () => {
// The worker has no catalogue. Everything it will say has to be said here // The worker has no catalog. Everything it will say has to be said here
// first, or a German reader gets English buttons on their lock screen. // first, or a German reader gets English buttons on their lock screen.
setCatalog("de", de); setCatalog("de", de);
const { store } = fakeCaches(); const { store } = fakeCaches();
+1 -1
View File
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import { SWIPE_CHOICES, describeSwipe, type SwipeAction } from "../swipe"; import { SWIPE_CHOICES, describeSwipe, type SwipeAction } from "../swipe";
/** /**
* A swipe names what it is about to do on a coloured strip the reader sees for * A swipe names what it is about to do on a colored strip the reader sees for
* about a third of a second before letting go. These check that the name is * about a third of a second before letting go. These check that the name is
* true in the folder it is being read in which is the whole reason the * true in the folder it is being read in which is the whole reason the
* descriptor exists rather than a fixed label per setting. * descriptor exists rather than a fixed label per setting.
+1 -1
View File
@@ -138,7 +138,7 @@ describe("remembering the palette you were on", () => {
expect(toggleTarget(away, false)).toEqual({ palette: "ihasmail", mode: "dark" }); expect(toggleTarget(away, false)).toEqual({ palette: "ihasmail", mode: "dark" });
}); });
it("keeps the colours when the palette has both sides", () => { it("keeps the colors when the palette has both sides", () => {
const away = toggleTarget({ palette: "gruvbox", mode: "dark" }, false); const away = toggleTarget({ palette: "gruvbox", mode: "dark" }, false);
expect(away.palette).toBe("gruvbox"); expect(away.palette).toBe("gruvbox");
expect(away.mode).toBe("light"); expect(away.mode).toBe("light");
+1 -1
View File
@@ -65,7 +65,7 @@ const file = (name: string, body: string, extra: Attr[] = []): Attr[] => [
const text = (a: Uint8Array) => new TextDecoder().decode(a); const text = (a: Uint8Array) => new TextDecoder().decode(a);
describe("isTnef", () => { describe("isTnef", () => {
it("recognises the types and the filename", () => { it("recognizes the types and the filename", () => {
expect(isTnef("application/ms-tnef", null)).toBe(true); expect(isTnef("application/ms-tnef", null)).toBe(true);
expect(isTnef("application/vnd.ms-tnef; name=winmail.dat", null)).toBe(true); expect(isTnef("application/vnd.ms-tnef; name=winmail.dat", null)).toBe(true);
expect(isTnef("application/octet-stream", "winmail.dat")).toBe(true); expect(isTnef("application/octet-stream", "winmail.dat")).toBe(true);
+1 -1
View File
@@ -27,7 +27,7 @@ describe("lockAxis", () => {
expect(lockAxis(30, 25)).toBe("y"); expect(lockAxis(30, 25)).toBe("y");
}); });
it("counts distance on either axis towards committing", () => { it("counts distance on either axis toward committing", () => {
expect(lockAxis(0, AXIS_SLOP)).toBe("y"); expect(lockAxis(0, AXIS_SLOP)).toBe("y");
expect(lockAxis(AXIS_SLOP, 0)).toBe("x"); expect(lockAxis(AXIS_SLOP, 0)).toBe("x");
}); });
@@ -5,7 +5,7 @@ import { createRoot, type Root } from "react-dom/client";
/* /*
* The guard's answers, and which of them the dialog leans on. * The guard's answers, and which of them the dialog leans on.
* *
* It shipped with "Discard changes" as the only choice carrying a colour, which * It shipped with "Discard changes" as the only choice carrying a color, which
* made losing the work the easy thing to click on a dialog whose entire purpose * made losing the work the easy thing to click on a dialog whose entire purpose
* is to stop that (#175). The emphasis belongs on the safe answer; the * is to stop that (#175). The emphasis belongs on the safe answer; the
* destructive one stays legible as destructive without being the loudest thing * destructive one stays legible as destructive without being the loudest thing
+1 -1
View File
@@ -42,7 +42,7 @@ const advertises = (account: AccountLike | undefined, cap: string): boolean =>
Boolean(account && cap in (account.accountCapabilities ?? {})); Boolean(account && cap in (account.accountCapabilities ?? {}));
/** /**
* The account to read and write for this capability, honouring the switcher. * The account to read and write for this capability, honoring the switcher.
* *
* Use for anything the reader is looking at: their mail, a shared calendar, * Use for anything the reader is looking at: their mail, a shared calendar,
* somebody's files. Not for anything of the reader's own see below. * somebody's files. Not for anything of the reader's own see below.
+31 -4
View File
@@ -14,7 +14,7 @@
* for a check Stalwart does not make. See there. * for a check Stalwart does not make. See there.
*/ */
export type AdminObject = "Account" | "Domain" | "Role" | "MailingList" | "DkimSignature" | "DnsServer" | "Tenant"; export type AdminObject = "Account" | "Domain" | "Role" | "MailingList" | "DkimSignature" | "DnsServer" | "Tenant" | "QueuedMessage" | "Metric";
export type AdminOp = "Get" | "Query" | "Create" | "Update" | "Destroy"; export type AdminOp = "Get" | "Query" | "Create" | "Update" | "Destroy";
export type Permissions = ReadonlySet<string>; export type Permissions = ReadonlySet<string>;
@@ -27,17 +27,44 @@ export function can(perms: Permissions, object: AdminObject, op: AdminOp): boole
return perms.has(`sys${object}${op}`); return perms.has(`sys${object}${op}`);
} }
export type AdminSection = "accounts" | "domains"; export type AdminSection = "dashboard" | "accounts" | "groups" | "lists" | "tenants" | "roles" | "domains";
export type DashboardCard = "users" | "domains" | "pending" | "memory" | "received" | "sent";
/**
* The dashboard's cards an account may see.
*
* A count is a query with `calculateTotal`, so a query alone earns one. The
* three read from the metric history need the get as well, since the query
* only finds the records. Stalwart scopes the first three to a tenant
* administrator's own tenancy; the metric history has no tenant in it at all,
* and the Tenant Administrator role Stalwart creates does not hold it -- which
* is how a tenant's dashboard comes to show only what is theirs.
*/
export function dashboardCards(perms: Permissions): DashboardCard[] {
const out: DashboardCard[] = [];
if (can(perms, "Account", "Query")) out.push("users");
if (can(perms, "Domain", "Query")) out.push("domains");
if (can(perms, "QueuedMessage", "Query")) out.push("pending");
if (can(perms, "Metric", "Query") && can(perms, "Metric", "Get")) out.push("memory", "received", "sent");
return out;
}
/** /**
* The sections an account may open, in the order they are listed. * The sections an account may open, in the order they are listed.
* *
* A list that cannot be read is not worth an entry, so each takes both halves * A list that cannot be read is not worth an entry, so each takes both halves
* of reading one: the query that finds the objects and the get that shows them. * of reading one: the query that finds the objects and the get that shows them.
* The dashboard comes first, and is there whenever it has a card to show.
*/ */
export function adminSections(perms: Permissions): AdminSection[] { export function adminSections(perms: Permissions): AdminSection[] {
const out: AdminSection[] = []; const out: AdminSection[] = [];
if (can(perms, "Account", "Query") && can(perms, "Account", "Get")) out.push("accounts"); if (dashboardCards(perms).length) out.push("dashboard");
// Groups are accounts to the server, behind the same two permissions.
if (can(perms, "Account", "Query") && can(perms, "Account", "Get")) out.push("accounts", "groups");
if (can(perms, "MailingList", "Query") && can(perms, "MailingList", "Get")) out.push("lists");
if (can(perms, "Tenant", "Query") && can(perms, "Tenant", "Get")) out.push("tenants");
if (can(perms, "Role", "Query") && can(perms, "Role", "Get")) out.push("roles");
if (can(perms, "Domain", "Query") && can(perms, "Domain", "Get")) out.push("domains"); if (can(perms, "Domain", "Query") && can(perms, "Domain", "Get")) out.push("domains");
return out; return out;
} }
@@ -80,7 +107,7 @@ export interface RoleDef {
* more rights than its own and sign in as it. ihasmail refuses to offer that, * more rights than its own and sign in as it. ihasmail refuses to offer that,
* and treats such an account as read-only. * and treats such an account as read-only.
* *
* It errs towards refusing. A role that cannot be read -- the viewer lacks * It errs toward refusing. A role that cannot be read -- the viewer lacks
* `sysRoleGet`, or the id is not in the list -- counts as outranking, because * `sysRoleGet`, or the id is not in the list -- counts as outranking, because
* an unknown grant is not a grant the viewer can be shown to hold. What it * an unknown grant is not a grant the viewer can be shown to hold. What it
* cannot see is tenancy: an "Administrator" account is a tenant administrator * cannot see is tenancy: an "Administrator" account is a tenant administrator
+128
View File
@@ -0,0 +1,128 @@
import { client, JmapMethodError } from "@/jmap/client";
/**
* The numbers on Administration's dashboard, over the ordinary JMAP proxy.
*
* Counts are queries with `calculateTotal` and `limit: 0`: Stalwart lifts its
* own limit when asked for a total, so the number is the whole count, and no
* ids come back to be thrown away. For a tenant administrator the server scopes
* all three to the tenancy -- accounts and domains to its members, the queue to
* messages touching its domains.
*
* The rest is read from `x:Metric`, the history Stalwart records once per
* collection interval (hourly by default): a Counter holds what happened in
* that interval, a Gauge the reading at its end. Received and sent are the sums
* Stalwart's own dashboard shows, over the same metric names. The history is
* Enterprise-only and has to be switched on (`x:MetricsStore`); a Community
* server refuses the query as `forbidden`, and one that records nothing
* answers with nothing -- the two cases the dashboard tells apart.
*/
export const RECEIVED_METRICS = ["queue.message-queued"] as const;
export const SENT_METRICS = ["queue.authenticated-message-queued", "queue.dsn-queued", "queue.report-queued"] as const;
export const MEMORY_METRIC = "server.memory";
/** The window received and sent cover. */
export const DASHBOARD_WINDOW_MS = 24 * 60 * 60 * 1000;
export interface MetricRecord {
"@type": "Counter" | "Gauge" | "Histogram";
metric: string;
count: number;
timestamp: string;
sum?: number;
}
export interface MessageStats {
received: number;
sent: number;
/** The latest memory reading, or null when none was recorded in the window. */
memory: { bytes: number; at: string } | null;
/**
* Whether the server recorded anything in the window. Memory is written every
* interval, so a window with no records at all is a history that is switched
* off -- not a quiet day, which would still say zero.
*/
recorded: boolean;
}
export function summarizeMetrics(records: readonly MetricRecord[]): MessageStats {
let received = 0;
let sent = 0;
let memory: MessageStats["memory"] = null;
const receivedNames = new Set<string>(RECEIVED_METRICS);
const sentNames = new Set<string>(SENT_METRICS);
for (const r of records) {
if (r["@type"] === "Counter") {
if (receivedNames.has(r.metric)) received += r.count;
else if (sentNames.has(r.metric)) sent += r.count;
} else if (r["@type"] === "Gauge" && r.metric === MEMORY_METRIC) {
if (!memory || r.timestamp > memory.at) memory = { bytes: r.count, at: r.timestamp };
}
}
return { received, sent, memory, recorded: records.length > 0 };
}
type CountedObject = "Account" | "Domain" | "QueuedMessage";
/** How many there are. Accounts are counted as users: groups are accounts too. */
export async function countObjects(object: CountedObject): Promise<number> {
const res = await client.call<{ total?: number; ids?: string[] }>(`x:${object}/query`, {
...(object === "Account" ? { filter: { "@type": "User" } } : {}),
limit: 0,
calculateTotal: true,
});
return res.total ?? res.ids?.length ?? 0;
}
/**
* Every record of the dashboard's metrics since `since`, newest first.
*
* The filter keys are Stalwart's comparison names for the property -- a bare
* `timestamp` is `unsupportedFilter`. A day at the default hourly interval is
* well under one page; the paging is for a server that collects far more often.
*/
export async function loadMetrics(since: Date): Promise<MetricRecord[]> {
const filter = {
timestampIsGreaterThanOrEqual: since.toISOString().replace(/\.\d{3}Z$/, "Z"),
metric: [...RECEIVED_METRICS, ...SENT_METRICS, MEMORY_METRIC],
};
const step = client.maxObjectsInGet;
const out: MetricRecord[] = [];
for (let position = 0; ; position += step) {
const q = await client.call<{ ids?: string[] }>("x:Metric/query", { filter, sort: [{ property: "timestamp", isAscending: false }], position, limit: step });
const ids = q.ids ?? [];
if (ids.length) out.push(...(await client.call<{ list: MetricRecord[] }>("x:Metric/get", { ids })).list);
if (ids.length < step) return out;
}
}
/**
* How many columns the cards take, so no row is left short.
*
* `wide` is the most that divides the cards evenly without going past four;
* `mid` is what they drop to when that no longer fits, again only a count the
* cards divide into -- three cards go to one column rather than two and one.
* Five is the one count nothing divides, and takes three over two. A phone
* always gets one column, which the stylesheet decides.
*/
export function balancedColumns(cards: number): { wide: number; mid: number } {
switch (cards) {
case 0:
case 1:
return { wide: 1, mid: 1 };
case 2:
return { wide: 2, mid: 2 };
case 3:
return { wide: 3, mid: 1 };
case 4:
return { wide: 4, mid: 2 };
default:
return { wide: 3, mid: 2 };
}
}
/** A refusal from the server itself, as opposed to a failure to reach it. */
export function isRefused(err: unknown): boolean {
return err instanceof JmapMethodError && err.error.type === "forbidden";
}
+37 -8
View File
@@ -54,6 +54,8 @@ export interface DirectoryAccount {
usedDiskQuota?: number; usedDiskQuota?: number;
aliases?: Record<string, EmailAlias>; aliases?: Record<string, EmailAlias>;
memberGroupIds?: Record<string, boolean>; memberGroupIds?: Record<string, boolean>;
/** The tenant the account belongs to; only ever read back to an administrator outside every tenant. */
memberTenantId?: string | null;
credentials?: Record<string, Credential>; credentials?: Record<string, Credential>;
createdAt?: string; createdAt?: string;
} }
@@ -61,11 +63,13 @@ export interface DirectoryAccount {
export interface DirectoryDomain { export interface DirectoryDomain {
id: string; id: string;
name: string; name: string;
/** The tenant the domain is in: an account can be in a tenant only on one of its domains. */
memberTenantId?: string | null;
} }
const ACCOUNT_PROPERTIES = [ const ACCOUNT_PROPERTIES = [
"@type", "name", "domainId", "emailAddress", "description", "roles", "permissions", "quotas", "@type", "name", "domainId", "emailAddress", "description", "roles", "permissions", "quotas",
"usedDiskQuota", "aliases", "memberGroupIds", "credentials", "createdAt", "usedDiskQuota", "aliases", "memberGroupIds", "memberTenantId", "credentials", "createdAt",
]; ];
/** The one quota ihasmail edits; the others keep whatever they had. */ /** The one quota ihasmail edits; the others keep whatever they had. */
@@ -119,7 +123,7 @@ async function all<T>(object: "Domain" | "Role", properties: string[]): Promise<
return res.list; return res.list;
} }
export const listDomains = () => all<DirectoryDomain>("Domain", ["name"]); export const listDomains = () => all<DirectoryDomain>("Domain", ["name", "memberTenantId"]);
export const listRoles = () => all<RoleDef>("Role", ["description", "enabledPermissions", "roleIds"]); export const listRoles = () => all<RoleDef>("Role", ["description", "enabledPermissions", "roleIds"]);
export async function listGroups(): Promise<DirectoryAccount[]> { export async function listGroups(): Promise<DirectoryAccount[]> {
@@ -143,6 +147,8 @@ export interface NewAccount {
password: string; password: string;
roles: UserRoles; roles: UserRoles;
diskQuotaBytes: number | null; diskQuotaBytes: number | null;
/** Put the account in a tenant; only an administrator outside every tenant may. */
memberTenantId?: string | null;
} }
export async function createAccount(input: NewAccount): Promise<string> { export async function createAccount(input: NewAccount): Promise<string> {
@@ -159,6 +165,7 @@ export async function createAccount(input: NewAccount): Promise<string> {
quotas: input.diskQuotaBytes ? { [DISK_QUOTA]: input.diskQuotaBytes } : {}, quotas: input.diskQuotaBytes ? { [DISK_QUOTA]: input.diskQuotaBytes } : {},
aliases: {}, aliases: {},
memberGroupIds: {}, memberGroupIds: {},
...(input.memberTenantId ? { memberTenantId: input.memberTenantId } : {}),
// Required on create. Turning it on is one-way and not offered here. // Required on create. Turning it on is one-way and not offered here.
encryptionAtRest: { "@type": "Disabled" }, encryptionAtRest: { "@type": "Disabled" },
}, },
@@ -229,7 +236,7 @@ const VALIDATOR_MESSAGES: Record<string, () => string> = {
}; };
/** What kind of thing a refusal was about, where the wording has to differ. */ /** What kind of thing a refusal was about, where the wording has to differ. */
export type DirectoryObject = "account" | "domain"; export type DirectoryObject = "account" | "domain" | "group" | "list" | "role" | "tenant";
/** /**
* Say what went wrong in terms of the person's own action, in their language. * Say what went wrong in terms of the person's own action, in their language.
@@ -237,7 +244,7 @@ export type DirectoryObject = "account" | "domain";
* Stalwart explains a refusal in English, and its words are never shown as * Stalwart explains a refusal in English, and its words are never shown as
* they are: an interface in German that answers in English reads as broken * they are: an interface in German that answers in English reads as broken
* even when the English is exact. Every type the registry returns has its * even when the English is exact. Every type the registry returns has its
* own message, and a value a validator refused is recognised by the * own message, and a value a validator refused is recognized by the
* validator's wording and said again here. * validator's wording and said again here.
* *
* One exception, on purpose. A password policy is the server's to set -- a * One exception, on purpose. A password policy is the server's to set -- a
@@ -261,9 +268,11 @@ export function describeDirectoryError(err: unknown, object: DirectoryObject = "
const description = err.description ?? ""; const description = err.description ?? "";
switch (err.type) { switch (err.type) {
case "forbidden": case "forbidden":
if (/not authorized to grant/i.test(description)) return t("You can't give an account permissions your own role doesn't have."); if (/not authorized to grant/i.test(description)) {
return object === "role" ? t("You can't give a role permissions your own role doesn't have.") : t("You can't give an account permissions your own role doesn't have.");
}
if (/external directory/i.test(description)) return t("This account signs in through an external directory, so its password can't be set here."); if (/external directory/i.test(description)) return t("This account signs in through an external directory, so its password can't be set here.");
if (/licen[cs]ed account limit/i.test(description)) return t("The server's licence allows no more accounts."); if (/licen[cs]ed account limit/i.test(description)) return t("The server's license allows no more accounts.");
return t("The mail server refused this. Your role may not allow it."); return t("The mail server refused this. Your role may not allow it.");
case "primaryKeyViolation": case "primaryKeyViolation":
return object === "domain" return object === "domain"
@@ -272,11 +281,31 @@ export function describeDirectoryError(err: unknown, object: DirectoryObject = "
case "invalidForeignKey": case "invalidForeignKey":
return t("One of the chosen domain, role or group can't be used for this account."); return t("One of the chosen domain, role or group can't be used for this account.");
case "overQuota": case "overQuota":
return object === "domain" ? t("Your organisation has reached the number of domains it is allowed.") : t("Your organisation has reached the number of accounts it is allowed."); return object === "domain"
? t("Your organization has reached the number of domains it is allowed.")
: object === "group"
? t("Your organization has reached the number of groups it is allowed.")
: object === "list"
? t("Your organization has reached the number of mailing lists it is allowed.")
: object === "role"
? t("Your organization has reached the number of roles it is allowed.")
: object === "tenant"
? t("The server allows no more tenants.")
: t("Your organization has reached the number of accounts it is allowed.");
case "objectIsLinked": case "objectIsLinked":
return t("Something still depends on this, so the server kept it."); return t("Something still depends on this, so the server kept it.");
case "notFound": case "notFound":
return object === "domain" ? t("This domain no longer exists. Someone may have removed it.") : t("This account no longer exists. Someone may have deleted it."); return object === "domain"
? t("This domain no longer exists. Someone may have removed it.")
: object === "group"
? t("This group no longer exists. Someone may have deleted it.")
: object === "list"
? t("This mailing list no longer exists. Someone may have deleted it.")
: object === "role"
? t("This role no longer exists. Someone may have deleted it.")
: object === "tenant"
? t("This tenant no longer exists. Someone may have deleted it.")
: t("This account no longer exists. Someone may have deleted it.");
case "rateLimit": case "rateLimit":
return t("Too many attempts. Please wait a few minutes and try again."); return t("Too many attempts. Please wait a few minutes and try again.");
case "tooLarge": case "tooLarge":
+8 -5
View File
@@ -127,18 +127,18 @@ export async function namesOf(object: "Tenant" | "DnsServer", ids: string[]): Pr
} }
/** Lower-case, no surrounding space or root dot: how a domain is written back. */ /** Lower-case, no surrounding space or root dot: how a domain is written back. */
export function normaliseDomain(name: string): string { export function normalizeDomain(name: string): string {
return name.trim().toLowerCase().replace(/\.$/, ""); return name.trim().toLowerCase().replace(/\.$/, "");
} }
/** Enough of a check to catch a typo before the server does; the server decides. */ /** Enough of a check to catch a typo before the server does; the server decides. */
export function looksLikeDomain(name: string): boolean { export function looksLikeDomain(name: string): boolean {
return /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9-]{2,63}$/.test(normaliseDomain(name)); return /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9-]{2,63}$/.test(normalizeDomain(name));
} }
export async function createDomain(input: { name: string; description: string }): Promise<string> { export async function createDomain(input: { name: string; description: string }): Promise<string> {
const res = await client.call<SetResponse>("x:Domain/set", { const res = await client.call<SetResponse>("x:Domain/set", {
create: { n: { name: normaliseDomain(input.name), description: input.description.trim() || null } }, create: { n: { name: normalizeDomain(input.name), description: input.description.trim() || null } },
}); });
refused(res, "notCreated"); refused(res, "notCreated");
const id = (res.created?.n as { id?: string } | undefined)?.id; const id = (res.created?.n as { id?: string } | undefined)?.id;
@@ -179,8 +179,8 @@ export interface DnsRecord {
/** /**
* Read the zone file Stalwart computes for a domain. * Read the zone file Stalwart computes for a domain.
* *
* Its serialiser writes one record per line as `name IN TYPE value`, and a TXT * Its serializer writes one record per line as `name IN TYPE value`, and a TXT
* record longer than 255 bytes as a parenthesised run of quoted strings, one * record longer than 255 bytes as a parenthesized run of quoted strings, one
* per line. A DNS provider's form wants the whole value, so the strings are * per line. A DNS provider's form wants the whole value, so the strings are
* joined and unescaped; the original lines are kept for anyone pasting into a * joined and unescaped; the original lines are kept for anyone pasting into a
* zone. Anything that does not parse is kept too, as its own row, rather than * zone. Anything that does not parse is kept too, as its own row, rather than
@@ -227,6 +227,9 @@ export function describeLinked(linked: string[]): string {
if (kind === "Account") parts.push(plural(n, { one: "{n} account", other: "{n} accounts" })); if (kind === "Account") parts.push(plural(n, { one: "{n} account", other: "{n} accounts" }));
else if (kind === "MailingList") parts.push(plural(n, { one: "{n} mailing list", other: "{n} mailing lists" })); else if (kind === "MailingList") parts.push(plural(n, { one: "{n} mailing list", other: "{n} mailing lists" }));
else if (kind === "DkimSignature") parts.push(plural(n, { one: "{n} DKIM key", other: "{n} DKIM keys" })); else if (kind === "DkimSignature") parts.push(plural(n, { one: "{n} DKIM key", other: "{n} DKIM keys" }));
else if (kind === "Role") parts.push(plural(n, { one: "{n} role", other: "{n} roles" }));
else if (kind === "Domain") parts.push(plural(n, { one: "{n} domain", other: "{n} domains" }));
else if (kind === "Authentication") parts.push(t("the default roles"));
else parts.push(plural(n, { one: "{n} other item", other: "{n} other items" })); else parts.push(plural(n, { one: "{n} other item", other: "{n} other items" }));
} }
return parts.join(", "); return parts.join(", ");
+172
View File
@@ -0,0 +1,172 @@
import { client } from "@/jmap/client";
import { t } from "@/lib/i18n";
import type { PermissionsMode, UserRoles } from "@/lib/adminAccess";
import { DirectoryError, DISK_QUOTA, queryAccounts, type EmailAlias } from "@/lib/adminDirectory";
/**
* Groups, from Stalwart 0.16's directory.
*
* A group is not an object of its own: it is an `x:Account` whose `@type` is
* `Group`, read and written with the same methods and the same `sysAccount*`
* permissions as a person. What differs, from the 0.16.22 source:
*
* - **Membership lives on the member.** A group has no list of members; each
* user carries `memberGroupIds`, and a group's members are the users whose set
* names it. Adding or removing one is a patch to that user --
* `memberGroupIds/<group>: true`, or `null` to take it out -- which touches
* nothing else in the set. Groups do not nest: a group has no memberships.
* - **Membership is access, not permission.** A user's permissions come from
* their own roles only. What a group gives its members is whatever has been
* shared with the group -- a mailbox, a calendar.
* - **Roles are `Default` or `Custom`,** not a person's `User`/`Admin`/`Custom`.
* A group has no credentials and cannot sign in.
*/
export type GroupRoles = { "@type": "Default" } | { "@type": "Custom"; roleIds: Record<string, boolean> };
export interface DirectoryGroup {
id: string;
"@type": "Group";
name: string;
domainId: string;
emailAddress?: string;
description?: string | null;
roles?: GroupRoles;
permissions?: PermissionsMode;
quotas?: Record<string, number>;
usedDiskQuota?: number;
aliases?: Record<string, EmailAlias>;
createdAt?: string;
}
/** A member as the group's panel shows them, with what `outranks` and `isSelf` need. */
export interface GroupMember {
id: string;
name: string;
emailAddress?: string;
description?: string | null;
roles?: UserRoles;
permissions?: PermissionsMode;
}
const GROUP_PROPERTIES = ["@type", "name", "domainId", "emailAddress", "description", "roles", "permissions", "quotas", "usedDiskQuota", "aliases", "createdAt"];
const MEMBER_PROPERTIES = ["name", "emailAddress", "description", "roles", "permissions"];
type SetResponse = Record<string, Record<string, { type: string; description?: string; properties?: string[] } | null> | undefined> & {
created?: Record<string, { id: string }>;
};
function throwIfRefused(res: SetResponse, key: "notCreated" | "notUpdated" | "notDestroyed"): void {
const first = Object.values(res[key] ?? {})[0];
if (first) throw new DirectoryError(first.type, first.description, first.properties);
}
export const queryGroups = (opts: { text?: string; position?: number; limit?: number }) => queryAccounts({ type: "Group", ...opts });
export async function getGroups(ids: string[]): Promise<DirectoryGroup[]> {
if (!ids.length) return [];
const res = await client.call<{ list: DirectoryGroup[] }>("x:Account/get", { ids, properties: GROUP_PROPERTIES });
const byId = new Map(res.list.map((g) => [g.id, g]));
return ids.map((id) => byId.get(id)).filter((g): g is DirectoryGroup => Boolean(g));
}
/** The filter that finds a group's members: users whose memberships name it. */
export const memberFilter = (groupId: string) => ({ "@type": "User", memberGroupIds: groupId });
/** How many members each group has. A count that fails is left out rather than shown as none. */
export async function countMembers(groupIds: string[]): Promise<Map<string, number>> {
const out = new Map<string, number>();
await Promise.all(
groupIds.map(async (id) => {
try {
const res = await client.call<{ total?: number }>("x:Account/query", { filter: memberFilter(id), limit: 0, calculateTotal: true });
if (typeof res.total === "number") out.set(id, res.total);
} catch {
/* the column shows a dash */
}
}),
);
return out;
}
/** A group's members, as many as one get allows, newest first as the server orders them. */
export async function listMembers(groupId: string): Promise<{ members: GroupMember[]; total: number }> {
const q = await client.call<{ ids?: string[]; total?: number }>("x:Account/query", { filter: memberFilter(groupId), limit: client.maxObjectsInGet, calculateTotal: true });
const ids = q.ids ?? [];
if (!ids.length) return { members: [], total: q.total ?? 0 };
const res = await client.call<{ list: GroupMember[] }>("x:Account/get", { ids, properties: MEMBER_PROPERTIES });
return { members: res.list, total: q.total ?? res.list.length };
}
/** People to offer when adding a member, by name or address. */
export async function searchUsers(text: string, limit = 8): Promise<GroupMember[]> {
const q = await queryAccounts({ type: "User", text, limit });
if (!q.ids.length) return [];
const res = await client.call<{ list: GroupMember[] }>("x:Account/get", { ids: q.ids, properties: MEMBER_PROPERTIES });
return res.list;
}
export interface NewGroup {
name: string;
domainId: string;
description: string;
roles: GroupRoles;
diskQuotaBytes: number | null;
}
export async function createGroup(input: NewGroup): Promise<string> {
const res = await client.call<SetResponse>("x:Account/set", {
create: {
n: {
"@type": "Group",
name: input.name.trim(),
domainId: input.domainId,
description: input.description.trim() || null,
roles: input.roles,
permissions: { "@type": "Inherit" },
quotas: input.diskQuotaBytes ? { [DISK_QUOTA]: input.diskQuotaBytes } : {},
aliases: {},
},
},
});
throwIfRefused(res, "notCreated");
const id = res.created?.n?.id;
if (!id) throw new DirectoryError("serverFail", t("The server did not say whether the group was created."));
return id;
}
/** The patch that puts users into a group or takes them out, one pointer each so no other membership moves. */
export function membershipPatch(userIds: readonly string[], groupId: string, member: boolean): Record<string, Record<string, true | null>> {
return Object.fromEntries(userIds.map((id) => [id, { [`memberGroupIds/${groupId}`]: member ? true : null }]));
}
export async function setMembership(userIds: readonly string[], groupId: string, member: boolean): Promise<void> {
if (!userIds.length) return;
const res = await client.call<SetResponse>("x:Account/set", { update: membershipPatch(userIds, groupId, member) });
throwIfRefused(res, "notUpdated");
}
/**
* Delete a group, taking its members out of it first.
*
* Stalwart keeps an object that others still name, and every member's
* `memberGroupIds` names the group -- the same reason a domain's keys go
* before the domain. The two are separate calls: if the memberships cannot be
* changed, nothing has been deleted.
*/
export async function destroyGroup(groupId: string, memberIds: readonly string[]): Promise<void> {
await setMembership(memberIds, groupId, false);
const res = await client.call<SetResponse>("x:Account/set", { destroy: [groupId] });
throwIfRefused(res, "notDestroyed");
}
/** A group's roles as one select value: "Default", or "custom:<ids>". */
export function groupRoleKey(roles: GroupRoles | undefined): string {
if (!roles || roles["@type"] === "Default") return "Default";
return `custom:${Object.keys(roles.roleIds ?? {}).sort().join(",")}`;
}
export function groupRolesFromKey(key: string): GroupRoles {
if (key.startsWith("custom:")) return { "@type": "Custom", roleIds: Object.fromEntries(key.slice(7).split(",").filter(Boolean).map((id) => [id, true])) };
return { "@type": "Default" };
}
+141
View File
@@ -0,0 +1,141 @@
import { client } from "@/jmap/client";
import { t } from "@/lib/i18n";
import { DirectoryError, type EmailAlias } from "@/lib/adminDirectory";
/**
* Mailing lists, from Stalwart 0.16's directory.
*
* A list is its own registry object, `x:MailingList`, behind `sysMailingList*`.
* It is an address and the addresses it passes mail on to, and nothing more:
* there are no owners, no moderation and no posting policy to set. Shapes, as
* the live server answered them (2026-09-15):
*
* - `recipients` is a set of addresses, `{"[email protected]": true}`, on this
* server or anywhere else. One is added with `recipients/<address>: true` and
* taken out with `null`, which leaves the rest of the set alone.
* - `emailAddress` is computed from `name` and `domainId`, as an account's is.
* - The query filters on `text`; the default order is newest first.
*/
export interface DirectoryList {
id: string;
name: string;
domainId: string;
emailAddress?: string;
description?: string | null;
recipients?: Record<string, boolean>;
aliases?: Record<string, EmailAlias>;
}
const LIST_PROPERTIES = ["name", "domainId", "emailAddress", "description", "recipients", "aliases"];
type SetResponse = Record<string, Record<string, { type: string; description?: string; properties?: string[] } | null> | undefined> & {
created?: Record<string, { id: string }>;
};
function throwIfRefused(res: SetResponse, key: "notCreated" | "notUpdated" | "notDestroyed"): void {
const first = Object.values(res[key] ?? {})[0];
if (first) throw new DirectoryError(first.type, first.description, first.properties);
}
export async function queryLists(opts: { text?: string; position?: number; limit?: number }): Promise<{ ids: string[]; total: number }> {
const res = await client.call<{ ids?: string[]; total?: number }>("x:MailingList/query", {
...(opts.text?.trim() ? { filter: { text: opts.text.trim() } } : {}),
position: opts.position ?? 0,
...(opts.limit ? { limit: opts.limit } : {}),
calculateTotal: true,
});
return { ids: res.ids ?? [], total: res.total ?? res.ids?.length ?? 0 };
}
export async function getLists(ids: string[]): Promise<DirectoryList[]> {
if (!ids.length) return [];
const res = await client.call<{ list: DirectoryList[] }>("x:MailingList/get", { ids, properties: LIST_PROPERTIES });
const byId = new Map(res.list.map((l) => [l.id, l]));
return ids.map((id) => byId.get(id)).filter((l): l is DirectoryList => Boolean(l));
}
export interface NewList {
name: string;
domainId: string;
description: string;
recipients: string[];
}
export async function createList(input: NewList): Promise<string> {
const res = await client.call<SetResponse>("x:MailingList/set", {
create: {
n: {
name: input.name.trim(),
domainId: input.domainId,
description: input.description.trim() || null,
recipients: Object.fromEntries(input.recipients.map((r) => [r, true])),
aliases: {},
},
},
});
throwIfRefused(res, "notCreated");
const id = res.created?.n?.id;
if (!id) throw new DirectoryError("serverFail", t("The server did not say whether the list was created."));
return id;
}
export async function updateList(id: string, patch: Record<string, unknown>): Promise<void> {
if (!Object.keys(patch).length) return;
const res = await client.call<SetResponse>("x:MailingList/set", { update: { [id]: patch } });
throwIfRefused(res, "notUpdated");
}
export async function destroyList(id: string): Promise<void> {
const res = await client.call<SetResponse>("x:MailingList/set", { destroy: [id] });
throwIfRefused(res, "notDestroyed");
}
/** An address as one step of a JSON pointer: `~` and `/` escaped, as RFC 6901 has it. */
const pointerKey = (address: string) => address.replace(/~/g, "~0").replace(/\//g, "~1");
/**
* The recipient changes between two lists of addresses, one pointer each.
*
* Only what changed is sent, so a recipient someone else added while this panel
* was open is not taken out by saving it. Addresses compare without regard to
* case, the way mail is delivered to them.
*/
export function recipientsPatch(before: readonly string[], after: readonly string[]): Record<string, true | null> {
const lower = (list: readonly string[]) => new Map(list.map((a) => [a.toLowerCase(), a]));
const was = lower(before);
const now = lower(after);
const patch: Record<string, true | null> = {};
for (const [key, address] of was) if (!now.has(key)) patch[`recipients/${pointerKey(address)}`] = null;
for (const [key, address] of now) if (!was.has(key)) patch[`recipients/${pointerKey(address)}`] = true;
return patch;
}
/** A plausible address: one @, something either side, a dot in the domain. Stalwart has the last word. */
export function looksLikeAddress(value: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
}
/**
* Addresses out of whatever was typed or pasted: a line from a spreadsheet, a
* list separated by commas, `Name <address>`. Words with no @ in them are the
* names around the addresses and are passed over; something with an @ that is
* not an address is returned, so it can be shown rather than dropped.
*/
export function parseAddresses(text: string): { addresses: string[]; rejected: string[] } {
const addresses: string[] = [];
const rejected: string[] = [];
const seen = new Set<string>();
for (const raw of text.split(/[\s,;]+/)) {
const token = raw.replace(/^["'(<]+|[>"')]+$/g, "").replace(/^mailto:/i, "");
if (!token.includes("@")) continue;
if (!looksLikeAddress(token)) {
rejected.push(token);
continue;
}
if (seen.has(token.toLowerCase())) continue;
seen.add(token.toLowerCase());
addresses.push(token);
}
return { addresses, rejected };
}
+180
View File
@@ -0,0 +1,180 @@
import { apiFetch, client } from "@/jmap/client";
import { t } from "@/lib/i18n";
import type { Permissions, RoleDef } from "@/lib/adminAccess";
import { DirectoryError } from "@/lib/adminDirectory";
import { DomainError } from "@/lib/adminDomains";
import type { PermissionInfo } from "@/lib/permissionLabels";
/**
* Roles, from Stalwart 0.16's directory.
*
* `x:Role` behind `sysRole*`. A role has a `description` -- which is its name;
* there is no other -- the roles it builds on (`roleIds`, followed all the way
* down), and two sets of permissions: `enabledPermissions` it adds and
* `disabledPermissions` it takes away, which wins over anything enabled or
* inherited. The four a new server starts with (User, Group, Tenant
* Administrator, System Administrator) are ordinary rows, editable like any
* other, written once at first boot.
*
* Stalwart refuses to create or change a role that would carry a permission
* the caller does not hold, which is what the picker's locked rows show ahead
* of time. It does not check a delete.
*/
export interface DirectoryRole extends RoleDef {
description?: string | null;
enabledPermissions?: Record<string, boolean>;
disabledPermissions?: Record<string, boolean>;
roleIds?: Record<string, boolean>;
}
/** Which roles Stalwart gives an account that has been given none of its own. */
export interface RoleDefaults {
user: string[];
group: string[];
tenant: string[];
admin: string[];
}
const ROLE_PROPERTIES = ["description", "enabledPermissions", "disabledPermissions", "roleIds"];
type SetResponse = Record<string, Record<string, { type: string; description?: string; properties?: string[] } | null> | undefined> & {
created?: Record<string, { id: string }>;
};
/** A refusal, carrying what the server says still uses the role -- a delete's usual answer. */
function throwIfRefused(res: SetResponse, key: "notCreated" | "notUpdated" | "notDestroyed"): void {
const first = Object.values(res[key] ?? {})[0] as ({ type: string; description?: string; properties?: string[]; linkedObjects?: Array<{ object?: string; id?: string }> } | null | undefined);
if (first) throw new DomainError(first);
}
/** Every role, sorted by name. There are few enough to hold at once; the server caps a get anyway. */
export async function listAllRoles(): Promise<DirectoryRole[]> {
const q = await client.call<{ ids?: string[] }>("x:Role/query", { limit: client.maxObjectsInGet });
if (!q.ids?.length) return [];
const res = await client.call<{ list: DirectoryRole[] }>("x:Role/get", { ids: q.ids, properties: ROLE_PROPERTIES });
return res.list.sort((a, b) => (a.description ?? a.id).localeCompare(b.description ?? b.id));
}
/** The default roles, or null when the viewer may not read the authentication settings. */
export async function loadRoleDefaults(): Promise<RoleDefaults | null> {
try {
const res = await client.call<{ list: Array<Record<string, Record<string, boolean> | undefined>> }>("x:Authentication/get", {
ids: ["singleton"],
properties: ["defaultUserRoleIds", "defaultGroupRoleIds", "defaultTenantRoleIds", "defaultAdminRoleIds"],
});
const s = res.list[0];
if (!s) return null;
const ids = (k: string) => Object.keys(s[k] ?? {});
return { user: ids("defaultUserRoleIds"), group: ids("defaultGroupRoleIds"), tenant: ids("defaultTenantRoleIds"), admin: ids("defaultAdminRoleIds") };
} catch {
return null;
}
}
/** Stalwart's labeled permission list, through ihasmail's server. */
export async function loadPermissionList(): Promise<PermissionInfo[]> {
const res = await apiFetch<{ permissions: PermissionInfo[] }>("/api/admin/permissions");
return res.permissions;
}
export interface NewRole {
description: string;
roleIds: string[];
enabled: string[];
disabled: string[];
}
const set = (names: readonly string[]) => Object.fromEntries(names.map((n) => [n, true]));
export async function createRole(input: NewRole): Promise<string> {
const res = await client.call<SetResponse>("x:Role/set", {
create: { n: { description: input.description.trim(), roleIds: set(input.roleIds), enabledPermissions: set(input.enabled), disabledPermissions: set(input.disabled) } },
});
throwIfRefused(res, "notCreated");
const id = res.created?.n?.id;
if (!id) throw new DirectoryError("serverFail", t("The server did not say whether the role was created."));
return id;
}
export async function updateRole(id: string, patch: Record<string, unknown>): Promise<void> {
if (!Object.keys(patch).length) return;
const res = await client.call<SetResponse>("x:Role/set", { update: { [id]: patch } });
throwIfRefused(res, "notUpdated");
}
export async function destroyRole(id: string): Promise<void> {
const res = await client.call<SetResponse>("x:Role/set", { destroy: [id] });
throwIfRefused(res, "notDestroyed");
}
/** A set property's changes as one pointer per name, so nothing else in the set is touched. */
export function setPatch(property: string, before: Iterable<string>, after: Iterable<string>): Record<string, true | null> {
const was = new Set(before);
const now = new Set(after);
const patch: Record<string, true | null> = {};
for (const n of was) if (!now.has(n)) patch[`${property}/${n}`] = null;
for (const n of now) if (!was.has(n)) patch[`${property}/${n}`] = true;
return patch;
}
/** What a permission is, on the role being edited. */
export type PermissionState = "allow" | "deny" | "none";
/**
* What a role's bases grant and take away, and which base each came through.
*
* Stalwart unions every role in the tree -- enabled with enabled, disabled with
* disabled -- and then takes the disabled set away (`permissions.rs`), so a
* denial on a base role holds on every role built on it.
*/
export function inherited(roleIds: readonly string[], roles: ReadonlyMap<string, DirectoryRole>, exclude?: string): { granted: Map<string, string>; denied: Map<string, string> } {
const granted = new Map<string, string>();
const denied = new Map<string, string>();
const seen = new Set<string>(exclude ? [exclude] : []);
const walk = (id: string, via: string) => {
if (seen.has(id)) return;
seen.add(id);
const role = roles.get(id);
if (!role) return;
for (const p of Object.keys(role.enabledPermissions ?? {})) if (!granted.has(p)) granted.set(p, via);
for (const p of Object.keys(role.disabledPermissions ?? {})) if (!denied.has(p)) denied.set(p, via);
for (const child of Object.keys(role.roleIds ?? {})) walk(child, via);
};
for (const id of roleIds) walk(id, id);
return { granted, denied };
}
/** The roles a role may build on: not itself, and none that already builds on it. */
export function canBuildOn(roleId: string | null, candidate: string, roles: ReadonlyMap<string, DirectoryRole>): boolean {
if (!roleId) return roles.has(candidate);
if (candidate === roleId) return false;
const seen = new Set<string>();
const reaches = (id: string): boolean => {
if (id === roleId) return true;
if (seen.has(id)) return false;
seen.add(id);
return Object.keys(roles.get(id)?.roleIds ?? {}).some(reaches);
};
return !reaches(candidate);
}
/** Everything a role grants once its bases are followed and every denial in the tree taken away. */
export function effectivePermissions(role: Pick<DirectoryRole, "enabledPermissions" | "disabledPermissions" | "roleIds">, roles: ReadonlyMap<string, DirectoryRole>, self?: string): Set<string> {
const base = inherited(Object.keys(role.roleIds ?? {}), roles, self);
const out = new Set<string>([...base.granted.keys(), ...Object.keys(role.enabledPermissions ?? {})]);
for (const p of [...base.denied.keys(), ...Object.keys(role.disabledPermissions ?? {})]) out.delete(p);
return out;
}
/**
* Whether a role carries a permission the viewer does not hold, which makes it
* read-only to them. Everything enabled anywhere in its tree counts, denied or
* not: that is what Stalwart checks a grant against, and what a delete -- which
* it does not check -- would otherwise let someone take away.
*/
export function roleOutranks(viewer: Permissions, role: DirectoryRole, roles: ReadonlyMap<string, DirectoryRole>): boolean {
const granted = new Set<string>([...inherited(Object.keys(role.roleIds ?? {}), roles, role.id).granted.keys(), ...Object.keys(role.enabledPermissions ?? {})]);
for (const p of granted) if (!viewer.has(p)) return true;
return false;
}
+188
View File
@@ -0,0 +1,188 @@
import { client } from "@/jmap/client";
import { t } from "@/lib/i18n";
import { DirectoryError } from "@/lib/adminDirectory";
import { DomainError } from "@/lib/adminDomains";
/**
* Tenants, from Stalwart 0.16's directory.
*
* `x:Tenant` behind `sysTenant*`, an Enterprise feature: on a Community server
* the objects exist, but anyone inside a tenant is held to a plain user's
* permissions. A tenant is a name, an optional logo, the roles its members may
* at most have, and quotas. It holds no list of what is in it -- membership
* runs the other way, as `memberTenantId` on accounts, groups, domains,
* mailing lists, roles and DKIM keys.
*
* Only an account outside every tenant may set `memberTenantId` (Stalwart
* refuses "Cannot modify memberTenantId property" to anyone else), and inside a
* tenant the server scopes every query to it and fills it in on create. Shapes
* from the 0.16.22 schema:
*
* - `quotas` is a map from a `TenantStorageQuota` name to a number: counts for
* accounts, groups, domains and the rest, bytes for `maxDiskQuota`. A quota
* that is absent is no limit.
* - `logo` is a URL or a data URL, or null.
*/
export type TenantRoles = { "@type": "Default" } | { "@type": "Custom"; roleIds: Record<string, boolean> };
export interface DirectoryTenant {
id: string;
name: string;
logo?: string | null;
roles?: TenantRoles;
quotas?: Record<string, number>;
usedDiskQuota?: number;
createdAt?: string;
}
/** The quotas ihasmail offers, in the order they are shown. Disk space is bytes; the rest are counts. */
export const TENANT_QUOTAS = ["maxAccounts", "maxGroups", "maxMailingLists", "maxDomains", "maxRoles", "maxDkimKeys", "maxDiskQuota"] as const;
export type TenantQuota = (typeof TENANT_QUOTAS)[number];
/** What belongs to a tenant, and how each is counted. */
export const TENANT_MEMBERS = [
{ key: "accounts", method: "x:Account/query", filter: { "@type": "User" }, quota: "maxAccounts" },
{ key: "groups", method: "x:Account/query", filter: { "@type": "Group" }, quota: "maxGroups" },
{ key: "lists", method: "x:MailingList/query", filter: {}, quota: "maxMailingLists" },
{ key: "domains", method: "x:Domain/query", filter: {}, quota: "maxDomains" },
{ key: "roles", method: "x:Role/query", filter: {}, quota: "maxRoles" },
// A domain's keys join the tenant it was created in, and keep it there.
{ key: "dkimKeys", method: "x:DkimSignature/query", filter: {}, quota: "maxDkimKeys" },
] as const;
export type TenantMemberKind = (typeof TENANT_MEMBERS)[number]["key"];
const TENANT_PROPERTIES = ["name", "logo", "roles", "quotas", "usedDiskQuota", "createdAt"];
type SetResponse = Record<string, Record<string, { type: string; description?: string; properties?: string[]; linkedObjects?: Array<{ object?: string; id?: string }> } | null> | undefined> & {
created?: Record<string, { id: string }>;
};
function throwIfRefused(res: SetResponse, key: "notCreated" | "notUpdated" | "notDestroyed"): void {
const first = Object.values(res[key] ?? {})[0];
if (first) throw new DomainError(first);
}
export async function queryTenants(opts: { text?: string; position?: number; limit?: number }): Promise<{ ids: string[]; total: number }> {
const res = await client.call<{ ids?: string[]; total?: number }>("x:Tenant/query", {
...(opts.text?.trim() ? { filter: { text: opts.text.trim() } } : {}),
position: opts.position ?? 0,
...(opts.limit ? { limit: opts.limit } : {}),
calculateTotal: true,
});
return { ids: res.ids ?? [], total: res.total ?? res.ids?.length ?? 0 };
}
export async function getTenants(ids: string[]): Promise<DirectoryTenant[]> {
if (!ids.length) return [];
const res = await client.call<{ list: DirectoryTenant[] }>("x:Tenant/get", { ids, properties: TENANT_PROPERTIES });
const byId = new Map(res.list.map((x) => [x.id, x]));
return ids.map((id) => byId.get(id)).filter((x): x is DirectoryTenant => Boolean(x));
}
/** Every tenant's id and name, for pickers. */
export async function listTenantNames(): Promise<Array<{ id: string; name: string }>> {
const q = await client.call<{ ids?: string[] }>("x:Tenant/query", { limit: client.maxObjectsInGet });
if (!q.ids?.length) return [];
const res = await client.call<{ list: Array<{ id: string; name: string }> }>("x:Tenant/get", { ids: q.ids, properties: ["name"] });
return res.list.sort((a, b) => a.name.localeCompare(b.name));
}
/**
* How many of each kind of thing a tenant holds. A count that fails -- the
* viewer may not read that kind at all -- is left out rather than shown as
* none, which would read as "safe to delete".
*/
export async function countTenantMembers(tenantId: string): Promise<Partial<Record<TenantMemberKind, number>>> {
const out: Partial<Record<TenantMemberKind, number>> = {};
await Promise.all(
TENANT_MEMBERS.map(async (m) => {
try {
const res = await client.call<{ total?: number }>(m.method, { filter: { ...m.filter, memberTenantId: tenantId }, limit: 0, calculateTotal: true });
if (typeof res.total === "number") out[m.key] = res.total;
} catch {
/* left out */
}
}),
);
return out;
}
/** The domains in a tenant, and those in none, which are the ones that can be added. */
export async function tenantDomains(tenantId: string): Promise<{ inTenant: Array<{ id: string; name: string }>; unassigned: Array<{ id: string; name: string }> }> {
const q = await client.call<{ ids?: string[] }>("x:Domain/query", { limit: client.maxObjectsInGet });
if (!q.ids?.length) return { inTenant: [], unassigned: [] };
const res = await client.call<{ list: Array<{ id: string; name: string; memberTenantId?: string | null }> }>("x:Domain/get", { ids: q.ids, properties: ["name", "memberTenantId"] });
const sorted = res.list.sort((a, b) => a.name.localeCompare(b.name));
return {
inTenant: sorted.filter((d) => d.memberTenantId === tenantId).map(({ id, name }) => ({ id, name })),
unassigned: sorted.filter((d) => !d.memberTenantId).map(({ id, name }) => ({ id, name })),
};
}
/**
* How many of a tenant's accounts and groups are on a domain.
*
* Stalwart lets a domain leave a tenant while the tenant still has accounts on
* it (live, 2026-09-15), leaving them in a tenant on a domain outside it --
* which it refuses to create. The panel asks this before it offers the move.
*/
export async function tenantAccountsOnDomain(tenantId: string, domainId: string): Promise<number> {
const res = await client.call<{ total?: number }>("x:Account/query", { filter: { domainId, memberTenantId: tenantId }, limit: 0, calculateTotal: true });
return res.total ?? 0;
}
/** Put a domain in a tenant, or take it out with null. */
export async function setDomainTenant(domainId: string, tenantId: string | null): Promise<void> {
const res = await client.call<SetResponse>("x:Domain/set", { update: { [domainId]: { memberTenantId: tenantId } } });
throwIfRefused(res, "notUpdated");
}
export interface NewTenant {
name: string;
logo: string | null;
roles: TenantRoles;
quotas: Record<string, number>;
}
export async function createTenant(input: NewTenant): Promise<string> {
const res = await client.call<SetResponse>("x:Tenant/set", {
create: { n: { name: input.name.trim(), logo: input.logo, roles: input.roles, permissions: { "@type": "Inherit" }, quotas: input.quotas } },
});
throwIfRefused(res, "notCreated");
const id = res.created?.n?.id;
if (!id) throw new DirectoryError("serverFail", t("The server did not say whether the tenant was created."));
return id;
}
export async function updateTenant(id: string, patch: Record<string, unknown>): Promise<void> {
if (!Object.keys(patch).length) return;
const res = await client.call<SetResponse>("x:Tenant/set", { update: { [id]: patch } });
throwIfRefused(res, "notUpdated");
}
export async function destroyTenant(id: string): Promise<void> {
const res = await client.call<SetResponse>("x:Tenant/set", { destroy: [id] });
throwIfRefused(res, "notDestroyed");
}
/**
* The quota changes as one pointer each, so a quota ihasmail does not offer
* (OAuth clients, DNS servers, directories, ACME providers) keeps its value.
*/
export function quotasPatch(before: Record<string, number> | undefined, after: Partial<Record<TenantQuota, number | null>>): Record<string, number | null> {
const patch: Record<string, number | null> = {};
for (const key of TENANT_QUOTAS) {
if (!(key in after)) continue;
const next = after[key] ?? null;
const was = before?.[key] ?? null;
if (next !== was) patch[`quotas/${key}`] = next;
}
return patch;
}
/** A logo worth showing: an https or data image URL. Anything else is kept but not drawn. */
export function drawableLogo(logo: string | null | undefined): string | null {
if (!logo) return null;
return /^https:\/\//i.test(logo) || /^data:image\/(png|jpe?g|gif|webp|svg\+xml);/i.test(logo) ? logo : null;
}
+2 -2
View File
@@ -53,8 +53,8 @@ function bodyText(email: Email): string {
* Everyone the message was between, as guests: the sender and the people it * Everyone the message was between, as guests: the sender and the people it
* was addressed to. * was addressed to.
* *
* The reader's own addresses come out -- they are the organiser, and an * The reader's own addresses come out -- they are the organizer, and an
* organiser listed among their own guests is an event that invites you to your * organizer listed among their own guests is an event that invites you to your
* own appointment. Bcc stays out too, on a message the reader sent themselves: * own appointment. Bcc stays out too, on a message the reader sent themselves:
* a blind recipient added to a guest list is visible to every other guest, and * a blind recipient added to a guest list is visible to every other guest, and
* turning a hidden copy into a public one is not something a menu item should * turning a hidden copy into a public one is not something a menu item should
+1 -1
View File
@@ -3,7 +3,7 @@
* *
* `import.meta.env.BASE_URL` is Vite's own copy of the `base` it built with, * `import.meta.env.BASE_URL` is Vite's own copy of the `base` it built with,
* and `vite.config.ts` sets that from `BASE_PATH` through the shared * and `vite.config.ts` sets that from `BASE_PATH` through the shared
* normaliser -- so this is the same answer the server reached, not a second * normalizer -- so this is the same answer the server reached, not a second
* guess at it. Reading it here rather than re-deriving it from * guess at it. Reading it here rather than re-deriving it from
* `window.location` matters because the app is a SPA: at `/mail/inbox/abc` * `window.location` matters because the app is a SPA: at `/mail/inbox/abc`
* there is nothing in the address that says how much of it is the mount. * there is nothing in the address that says how much of it is the mount.
+1 -1
View File
@@ -23,7 +23,7 @@ export interface Birthday {
age: number | null; age: number | null;
} }
/** The prefix marking a synthesised event, so nothing tries to save one. */ /** The prefix marking a synthesized event, so nothing tries to save one. */
export const BIRTHDAY_ID_PREFIX = "ihm-birthday:"; export const BIRTHDAY_ID_PREFIX = "ihm-birthday:";
/** The virtual calendar's id. Not a JMAP id, and deliberately unlike one. */ /** The virtual calendar's id. Not a JMAP id, and deliberately unlike one. */
+5 -5
View File
@@ -64,7 +64,7 @@ export function withPrefs<T>(over: Partial<DateTimePrefs>, fn: () => T): T {
} }
} }
/** Locale reported by Stalwart for this account (normalised), or null. */ /** Locale reported by Stalwart for this account (normalized), or null. */
export function setServerLocale(raw: string | null | undefined): void { export function setServerLocale(raw: string | null | undefined): void {
serverLocale = normalizeLocale(raw); serverLocale = normalizeLocale(raw);
} }
@@ -193,7 +193,7 @@ function num(value: number, digits: number): string {
return f.format(value); return f.format(value);
} }
/** Time-of-day options honouring the 12h/24h preference. */ /** Time-of-day options honoring the 12h/24h preference. */
export function timeOptions(): Intl.DateTimeFormatOptions { export function timeOptions(): Intl.DateTimeFormatOptions {
switch (prefs.timeFormat) { switch (prefs.timeFormat) {
case "24": case "24":
@@ -562,13 +562,13 @@ export function localeOptions(): LocaleOption[] {
* Weekday names in the reader's locale, indexed by JSCalendar's two-letter day. * Weekday names in the reader's locale, indexed by JSCalendar's two-letter day.
* *
* These used to be a table of English strings with a `short` of "M", "T", "W" * These used to be a table of English strings with a `short` of "M", "T", "W"
* which could not become catalogue entries at all: "T" is both Tuesday and * which could not become catalog entries at all: "T" is both Tuesday and
* Thursday and "S" is both Saturday and Sunday, so the key collides with * Thursday and "S" is both Saturday and Sunday, so the key collides with
* itself. A catalogue cannot hold two translations under one key, and no * itself. A catalog cannot hold two translations under one key, and no
* amount of translating fixes that the data was wrong, not the wiring. * amount of translating fixes that the data was wrong, not the wiring.
* *
* Intl has the names already, in every locale, in three widths, and gets the * Intl has the names already, in every locale, in three widths, and gets the
* plural and capitalisation conventions right without anybody maintaining a * plural and capitalization conventions right without anybody maintaining a
* list. 2026-06-01 is a Monday; the rest follow from it. * list. 2026-06-01 is a Monday; the rest follow from it.
*/ */
export type WeekdayKey = "mo" | "tu" | "we" | "th" | "fr" | "sa" | "su"; export type WeekdayKey = "mo" | "tu" | "we" | "th" | "fr" | "sa" | "su";
+1 -1
View File
@@ -27,7 +27,7 @@ function unsafe(ch: string): boolean {
} }
/** /**
* Long enough to stay recognisable, short enough to survive a 255-*byte* limit * Long enough to stay recognizable, short enough to survive a 255-*byte* limit
* once a CJK subject is three bytes a character. * once a CJK subject is three bytes a character.
*/ */
const MAX = 80; const MAX = 80;
+1 -1
View File
@@ -54,7 +54,7 @@ export function isShared(node: Pick<FileNode, "shareWith">): boolean {
* legal moves behind a disabled drop. The server refuses those with a message * legal moves behind a disabled drop. The server refuses those with a message
* of its own, which is a better answer than a silent one. * of its own, which is a better answer than a silent one.
*/ */
/** The MIME a dragged node is offered under, so a target can recognise it. */ /** The MIME a dragged node is offered under, so a target can recognize it. */
export const NODE_MIME = "application/x-ihasmail-filenode"; export const NODE_MIME = "application/x-ihasmail-filenode";
/** /**

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