Compare commits

...
3 Commits
Author SHA1 Message Date
zemion c31f9b69cb docs: complete German structured documentation
Module Package Release / publish-packages (push) Successful in 11s
2026-08-24 01:15:35 +02:00
zemion 1cbf4acaf4 feat(mail): add governed JMAP mailbox sync and search
Module Package Release / publish-packages (push) Successful in 12s
2026-08-22 17:09:05 +02:00
zemion fd808336bc docs(mail): complete German help coverage
Module Package Release / publish-packages (push) Successful in 11s
2026-08-22 05:44:34 +02:00
33 changed files with 3002 additions and 195 deletions
+15 -12
View File
@@ -4,7 +4,7 @@
**Repository type:** module (domain). **Repository type:** module (domain).
<!-- govoplan-repository-type:end --> <!-- govoplan-repository-type:end -->
GovOPlaN Mail is the mail transport module. It owns reusable SMTP/IMAP profile management, an explicitly enabled legacy POP3 import path, mail profile policy enforcement, mock mail infrastructure, and the mail WebUI package. GovOPlaN Mail is the mail transport module. It owns reusable SMTP/IMAP/JMAP profile management, an explicitly enabled legacy POP3 import path, mail profile policy enforcement, mock mail infrastructure, and the mail WebUI package.
## Ownership ## Ownership
@@ -12,7 +12,7 @@ This repository owns:
- backend module manifest `mail` - backend module manifest `mail`
- mail permissions such as `mail:profile:read`, `mail:profile:write_own`, `mail:profile:write`, `mail:profile:use`, `mail:profile:test`, and `mail:mailbox:read` - mail permissions such as `mail:profile:read`, `mail:profile:write_own`, `mail:profile:write`, `mail:profile:use`, `mail:profile:test`, and `mail:mailbox:read`
- SMTP/IMAP profile models, dedicated legacy POP3 sources, policy checks, encrypted credential storage, and profile resolution - SMTP/IMAP/JMAP profile models, dedicated legacy POP3 sources, policy checks, encrypted credential storage, and profile resolution
- SMTP send and IMAP append adapters, including mock transports for development - SMTP send and IMAP append adapters, including mock transports for development
- development mock mailbox endpoints used by test-send flows - development mock mailbox endpoints used by test-send flows
- WebUI package `@govoplan/mail-webui` with profile management, policy management, read-only mailbox components, and governed POP3 import - WebUI package `@govoplan/mail-webui` with profile management, policy management, read-only mailbox components, and governed POP3 import
@@ -21,7 +21,7 @@ Core owns auth, tenants, RBAC evaluation, database/session primitives, secret he
Mail publishes `privacy.dsar.mail` for Core's governed data-subject-request Mail publishes `privacy.dsar.mail` for Core's governed data-subject-request
workflow. It isolates matching mailbox header parties and returns bounded index, workflow. It isolates matching mailbox header parties and returns bounded index,
personal-profile, delivery, reconciliation, bounce, and imported-message metadata. SMTP/IMAP/POP3 personal-profile, delivery, reconciliation, bounce, and imported-message metadata. SMTP/IMAP/JMAP/POP3
configuration and credentials, encrypted messages and envelopes, source UIDL configuration and credentials, encrypted messages and envelopes, source UIDL
and folder/UID and folder/UID
locators, worker and idempotency state, diagnostics, and opaque evidence are locators, worker and idempotency state, diagnostics, and opaque evidence are
@@ -31,7 +31,7 @@ provider does not perform direct erasure.
## Profile and credential ownership ## Profile and credential ownership
Mail profiles are separate governed definitions. Mail owns their SMTP/IMAP Mail profiles are separate governed definitions. Mail owns their SMTP/IMAP/JMAP
endpoints, encrypted credentials, tests, scope, and policy. Consumers such as endpoints, encrypted credentials, tests, scope, and policy. Consumers such as
Campaign store only a stable profile identifier and resolve the authorized, Campaign store only a stable profile identifier and resolve the authorized,
active profile through `mail.campaign_delivery`; they never copy or override active profile through `mail.campaign_delivery`; they never copy or override
@@ -87,7 +87,7 @@ closed with guidance to store those credentials on a Mail profile and enable
inheritance. inheritance.
Deleting a profile deactivates its non-secret tombstone metadata and scrubs Deleting a profile deactivates its non-secret tombstone metadata and scrubs
both encrypted SMTP and IMAP passwords immediately in the same transaction as its encrypted SMTP, IMAP, JMAP, and POP3 credentials immediately in the same transaction as
a non-secret audit event. Destructive module retirement applies the same rule a non-secret audit event. Destructive module retirement applies the same rule
to every remaining profile before any Mail table is dropped; a scrub or audit to every remaining profile before any Mail table is dropped; a scrub or audit
failure blocks retirement. failure blocks retirement.
@@ -144,13 +144,16 @@ Development mailbox routes are registered by the mail module only when the
core runtime is in `dev` mode and `dev_mailbox_api_enabled` is enabled. Core core runtime is in `dev` mode and `dev_mailbox_api_enabled` is enabled. Core
does not contribute these routes directly. does not contribute these routes directly.
JMAP remains deferred. The explicitly enabled POP3 slice is limited to bounded, JMAP is available as an opt-in, read-only mailbox transport after the stable
encrypted, duplicate-safe legacy import; preview and ordinary import are IMAP baseline. It discovers RFC 8620/8621 capabilities, lists folders,
non-destructive, while source deletion requires separate endpoint policy, performs server-side message search and pagination, reads bounded message
permission, confirmation, and audit evidence. The protocol decision is bodies and attachment metadata, and exposes bounded incremental Email changes.
documented in [docs/MAIL_PROTOCOL_ROADMAP.md](docs/MAIL_PROTOCOL_ROADMAP.md): IMAP behavior is unchanged, and SMTP remains the send transport. JMAP Session
prefer JMAP for future modern mailbox sync/search and keep POP3 out of normal and advertised API origins are governed independently and credentials stay in
mailbox browsing. The same roadmap records the Mail's encrypted envelopes. The explicitly enabled POP3 slice remains limited
to bounded, encrypted, duplicate-safe legacy import. The protocol boundary is
documented in [docs/MAIL_PROTOCOL_ROADMAP.md](docs/MAIL_PROTOCOL_ROADMAP.md).
The same roadmap records the
approved S/MIME-first, OpenPGP-additional message-protection profile and its approved S/MIME-first, OpenPGP-additional message-protection profile and its
no-silent-downgrade requirement. no-silent-downgrade requirement.
+38 -20
View File
@@ -23,12 +23,12 @@ See also [Mail protocol roadmap](MAIL_PROTOCOL_ROADMAP.md) and the Campaign
Mail owns: Mail owns:
- reusable SMTP/IMAP profile definitions, dedicated legacy POP3 sources, and scope; - reusable SMTP/IMAP/JMAP profile definitions, dedicated legacy POP3 sources, and scope;
- encrypted SMTP/IMAP/POP3 credentials and safe credential replacement; - encrypted SMTP/IMAP/JMAP/POP3 credentials and safe credential replacement;
- effective profile policy and visibility/authorization decisions; - effective profile policy and visibility/authorization decisions;
- connection tests and protocol adapters; - connection tests and protocol adapters;
- SMTP send and IMAP append operations exposed to consumers; - SMTP send and IMAP append operations exposed to consumers;
- read-only mailbox folder/message access, bounded indexes, and encrypted - read-only IMAP/JMAP mailbox folder/message access, bounded indexes, and encrypted
pending-review records imported from legacy POP3 sources; and pending-review records imported from legacy POP3 sources; and
- the transport sanitization boundary and throttling behavior. A general - the transport sanitization boundary and throttling behavior. A general
Mail-owned provider-attempt/diagnostic ledger remains planned. Mail-owned provider-attempt/diagnostic ledger remains planned.
@@ -94,7 +94,7 @@ deactivating a profile may scrub Mail-owned credentials as described below.
### Profile ### Profile
A profile is a reusable, named delivery identity with optional SMTP and IMAP A profile is a reusable, named delivery identity with optional SMTP and IMAP
configuration. It can additionally own a dedicated POP3 endpoint for an configuration and one or more opt-in JMAP mailbox endpoints. It can additionally own a dedicated POP3 endpoint for an
explicit legacy-import workflow. It has a stable id, lifecycle state, scope, explicit legacy-import workflow. It has a stable id, lifecycle state, scope,
owner context, and non-secret connection metadata. Passwords are write-only owner context, and non-secret connection metadata. Passwords are write-only
encrypted values and are never returned through list/read/capability responses. encrypted values and are never returned through list/read/capability responses.
@@ -114,14 +114,14 @@ operation: using, testing, managing, and managing secrets are separate rights.
### Policy ### Policy
Mail policy controls approved profile ids, which lower scopes may define Mail policy controls approved profile ids, which lower scopes may define
profiles, allowed/denied hosts and addressing patterns, credential inheritance, profiles, allowed/denied SMTP/IMAP/JMAP hosts and addressing patterns, credential inheritance,
and lower-level limits. The effective result is assembled from applicable and lower-level limits. The effective result is assembled from applicable
system, tenant, user/group, and campaign context. Denials and locked parent system, tenant, user/group, and campaign context. Denials and locked parent
limits cannot be relaxed by a lower scope. limits cannot be relaxed by a lower scope.
### Transport identity and revision ### Transport identity and revision
Mail owns opaque random revisions for relevant SMTP/IMAP identity and Mail owns opaque random revisions for relevant SMTP/IMAP/JMAP identity and
configuration. They are concurrency tokens, not deterministic hashes that a configuration. They are concurrency tokens, not deterministic hashes that a
consumer could use to guess a host or account. Credentials are excluded. A consumer could use to guess a host or account. Credentials are excluded. A
consumer can freeze these revisions at build time and ask Mail to require the consumer can freeze these revisions at build time and ask Mail to require the
@@ -164,7 +164,7 @@ new idempotency key and links it to the prior command.
2. Choose from the profiles visible and authorized for the current tenant, 2. Choose from the profiles visible and authorized for the current tenant,
owner, group, and task context. Never enter or copy a profile id manually owner, group, and task context. Never enter or copy a profile id manually
when the UI can present a picker. when the UI can present a picker.
3. Review the safe summary: name, scope, active state, SMTP/IMAP availability, 3. Review the safe summary: name, scope, active state, SMTP/IMAP/JMAP availability,
and policy-relevant sender identity. Credentials and raw provider internals and policy-relevant sender identity. Credentials and raw provider internals
are not visible. are not visible.
4. Save the reference in the consuming module. If ownership or policy changes, 4. Save the reference in the consuming module. If ownership or policy changes,
@@ -177,7 +177,7 @@ permission.
### Test a profile ### Test a profile
An authorized profile test verifies connection and authentication for the An authorized profile test verifies connection and authentication for the
selected active/visible SMTP or IMAP profile using Mail-owned credentials. The selected active/visible SMTP, IMAP, or JMAP profile using Mail-owned credentials. The
consumer-use path evaluates effective Mail policy separately. Use a consumer-use path evaluates effective Mail policy separately. Use a
non-production provider and mailbox first. A successful connection test does non-production provider and mailbox first. A successful connection test does
not prove policy authorization for a later Campaign context, deliverability, not prove policy authorization for a later Campaign context, deliverability,
@@ -194,9 +194,13 @@ ordinary consumers to bypass reusable profiles.
### Read a mailbox ### Read a mailbox
The current mailbox UI and API are read-only. An authorized user can list IMAP The current mailbox UI and API are read-only. An authorized user can list IMAP
folders, page through messages, and inspect a bounded full message. Folder or JMAP folders, page through messages, and inspect a bounded full message.
names are parsed and quoted defensively; Sent-folder discovery uses provider IMAP folder names are parsed and quoted defensively; Sent-folder discovery uses
flags and common names. The list exposes the provider's `Seen` flag as a provider flags and common names. JMAP discovers the Session and Mail account,
uses `Mailbox/get` hierarchy and roles, runs text search with `Email/query`, and
uses `Email/get` for bounded summaries/details. `Email/changes` exposes a
bounded incremental cursor; an expired state tells the caller to perform a full
refresh. The list exposes the provider's `Seen`/`$seen` state as a
read/unread indicator without changing it. It also labels whether the current read/unread indicator without changing it. It also labels whether the current
page came directly from the provider, from the bounded mailbox index, or from page came directly from the provider, from the bounded mailbox index, or from
an index while a refresh is in progress, including the index timestamp when an index while a refresh is in progress, including the index timestamp when
@@ -210,9 +214,16 @@ silently interpreted as an empty message.
Mailbox access requires both `mail:mailbox:read` and `mail:profile:use`. It must Mailbox access requires both `mail:mailbox:read` and `mail:profile:use`. It must
not mutate read/unread, delete, move, or reply state. Message responses are not mutate read/unread, delete, move, or reply state. Message responses are
bounded by the deployment response policy; ordinary UI should avoid loading a bounded by the endpoint response/body policy; ordinary UI should avoid loading a
whole large mailbox or attachment merely to show a list. whole large mailbox or attachment merely to show a list.
JMAP is opt-in per server endpoint. Its authenticated Session URL is governed
by `jmap_hosts`; an advertised API URL on another origin fails closed unless
that origin is explicitly listed for the endpoint. Bearer tokens or Basic
credentials are stored only in Mail credential envelopes. This slice does not
send through JMAP, mutate provider state, download attachment binaries, or add
calendar/contact/thread features.
### Import a legacy POP3 mailbox ### Import a legacy POP3 mailbox
POP3 is available only for bounded migration from a legacy server that cannot POP3 is available only for bounded migration from a legacy server that cannot
@@ -253,6 +264,12 @@ split `mail:pop3:delete` when operators must never delete provider messages.
Imported records follow configured Mail/records retention and require manual Imported records follow configured Mail/records retention and require manual
review for a data-subject request or deletion decision. review for a data-subject request or deletion decision.
Contextual help is available from the page and from each policy-sensitive
source setting, credential field, size limit, import action, and destructive
confirmation. Press F1 while a control has focus to open the Mail-owned German
reference for the exact POP3 context; the same topic remains available through
the page help action.
## Profile administration ## Profile administration
### Roles ### Roles
@@ -293,21 +310,21 @@ the deletion in the audit log.
The configured Help Center exposes **Create a custom Mail profile** only when The configured Help Center exposes **Create a custom Mail profile** only when
the current actor has broad or self-service profile-write authority and the the current actor has broad or self-service profile-write authority and the
effective user-scope policy permits user profiles. It states the active SMTP/IMAP hostname effective user-scope policy permits user profiles. It states the active SMTP/IMAP/JMAP hostname
allow-list groups and deny rules, plus the actor's separate credential, test, allow-list groups and deny rules, plus the actor's separate credential, test,
use, and approval requirements. The Settings task creates in the current use, and approval requirements. The Settings task creates in the current
account's user scope. Grant `mail:profile:write_own` for self-service; account's user scope. Grant `mail:profile:write_own` for self-service;
`mail:profile:write` remains broad profile administration authority. `mail:profile:write` remains broad profile administration authority.
1. Choose the narrowest suitable scope and a stable, descriptive name/slug. 1. Choose the narrowest suitable scope and a stable, descriptive name/slug.
2. Configure SMTP, optional IMAP, TLS mode, account identity, standard folder 2. Configure SMTP and optional IMAP, or add an optional JMAP Session endpoint after creating the profile. Set TLS mode, account identity, standard folder
mappings, and timeouts. Folder discovery proposes provider-visible Inbox, mappings, and timeouts. Folder discovery proposes provider-visible Inbox,
Sent, Drafts, Trash, Archive, and Junk names without mutating the mailbox. Sent, Drafts, Trash, Archive, and Junk names without mutating the mailbox.
Sender/envelope/recipient constraints belong to Sender/envelope/recipient constraints belong to
effective Mail policy; Campaign rate limits remain delivery configuration. effective Mail policy; Campaign rate limits remain delivery configuration.
3. Enter credentials only in the dedicated credential fields. Returned profile 3. Enter credentials only in the dedicated credential fields. Returned profile
data indicates whether credentials are configured without returning them. data indicates whether credentials are configured without returning them.
4. Save and run SMTP/IMAP tests against a non-production target. 4. Save and run SMTP/IMAP/JMAP tests against a non-production target.
5. Verify the effective policy for every intended consumer context. 5. Verify the effective policy for every intended consumer context.
6. Communicate changes that alter the non-secret transport identity; prepared 6. Communicate changes that alter the non-secret transport identity; prepared
consumer snapshots will deliberately stop until rebuilt. consumer snapshots will deliberately stop until rebuilt.
@@ -319,7 +336,7 @@ credential replacement never depends on reading the old cleartext value back.
Profile deletion is immediate for Mail-owned secrets and audit evidence: Profile deletion is immediate for Mail-owned secrets and audit evidence:
1. Mail clears both encrypted SMTP and IMAP passwords in the same transaction. 1. Mail clears encrypted SMTP, IMAP, JMAP, and POP3 credential envelopes in the same transaction.
2. It deactivates the remaining non-secret tombstone state so historical stable 2. It deactivates the remaining non-secret tombstone state so historical stable
references can fail safely rather than resolve to another profile. references can fail safely rather than resolve to another profile.
3. When owned encrypted secrets existed, it emits 3. When owned encrypted secrets existed, it emits
@@ -340,7 +357,7 @@ Effective policy is contextual. Administrators should document:
- which profile ids are approved globally or for a tenant; - which profile ids are approved globally or for a tenant;
- whether tenant, user, group, or campaign-scoped profiles may be created; - whether tenant, user, group, or campaign-scoped profiles may be created;
- allowed and denied SMTP/IMAP hosts; - allowed and denied SMTP/IMAP/JMAP hosts;
- permitted From, envelope sender (including bounce address), and envelope - permitted From, envelope sender (including bounce address), and envelope
recipient-domain patterns; recipient-domain patterns;
- whether SMTP/IMAP credentials inherit from the reusable profile; and - whether SMTP/IMAP credentials inherit from the reusable profile; and
@@ -493,7 +510,7 @@ mandatory release gate.
Security invariants: Security invariants:
- Decrypted SMTP/IMAP passwords never cross the Mail capability/API boundary. - Decrypted SMTP/IMAP passwords and JMAP/POP3 credentials never cross the Mail capability/API boundary.
- Password fields are write-only and encrypted at rest; safe responses expose - Password fields are write-only and encrypted at rest; safe responses expose
configuration state, not values. configuration state, not values.
- Consumers persist stable profile references, not transport copies. - Consumers persist stable profile references, not transport copies.
@@ -550,8 +567,9 @@ Before claiming a Mail composition is production-ready:
semantics (`govoplan-mail#16`). semantics (`govoplan-mail#16`).
- Final Campaign **test / single send / single resend** semantics; those are a - Final Campaign **test / single send / single resend** semantics; those are a
Campaign business-action contract built on Mail transport operations. Campaign business-action contract built on Mail transport operations.
- JMAP mailbox synchronization/search; it is preferred only after the IMAP MVP - JMAP provider-side mutation, submission, push, thread, calendar, contact,
is stable. attachment-binary, and automatic background-sync support; read-only mailbox
synchronization/search is implemented on the stable IMAP mailbox contract.
- Expanding POP3 beyond the implemented explicit legacy download/import - Expanding POP3 beyond the implemented explicit legacy download/import
workflow; it has no folder, flag, search, or synchronization contract. workflow; it has no folder, flag, search, or synchronization contract.
- A full mail client with compose/reply/move/delete/read-state mutation. - A full mail client with compose/reply/move/delete/read-state mutation.
+33 -15
View File
@@ -1,17 +1,20 @@
# Mail Protocol Roadmap # Mail Protocol Roadmap
GovOPlaN Mail focuses on SMTP sending and IMAP mailbox access. It also provides GovOPlaN Mail uses SMTP for sending and supports read-only mailbox access over
an explicitly enabled, bounded POP3 legacy-import path. JMAP remains deferred IMAP or JMAP. It also provides an explicitly enabled, bounded POP3
until the IMAP mailbox MVP and protocol-neutral mailbox contract are stable. legacy-import path. The first JMAP slice is implemented on the stable,
protocol-neutral mailbox contract.
## Current Baseline ## Current Baseline
- SMTP is the send protocol. - SMTP is the send protocol.
- IMAP is the read/append protocol. - IMAP is the established read/append protocol and remains unchanged.
- JMAP is an opt-in read-only sync/search protocol; it is not used for sending
or append-to-Sent.
- POP3 is an optional legacy migration source, never a general mailbox - POP3 is an optional legacy migration source, never a general mailbox
protocol or default profile endpoint. protocol or default profile endpoint.
- Mail profile policy, encrypted credentials, mailbox folder parsing, test - Mail profile policy, encrypted credentials, connection diagnostics, and the
buttons, and read-only mailbox UI are built around SMTP and IMAP. read-only mailbox UI cover SMTP/IMAP/JMAP endpoints as applicable.
This baseline matches the first production use case: send campaign mail, append This baseline matches the first production use case: send campaign mail, append
sent copies when configured, and inspect mailboxes read-only. sent copies when configured, and inspect mailboxes read-only.
@@ -40,8 +43,8 @@ the S/MIME profile is stable.
## JMAP ## JMAP
JMAP is the preferred future sync/search protocol where target mail servers JMAP is the preferred sync/search protocol where target mail servers support
support it. RFC 8620 Core and RFC 8621 Mail capabilities.
Reasons: Reasons:
@@ -50,12 +53,25 @@ Reasons:
- modern search and thread models - modern search and thread models
- better fit for browser-facing mailbox UX through a server proxy - better fit for browser-facing mailbox UX through a server proxy
JMAP should be added only after: The implemented first slice provides:
- the IMAP mailbox MVP has stable folder/message pagination behavior - authenticated Session discovery with Bearer or Basic credentials;
- mail profile policy can express protocol-specific availability - explicit account selection or primary Mail-account selection;
- mailbox UI can handle protocol-neutral folder/message DTOs - folder hierarchy projection through `Mailbox/get`;
- test infrastructure includes at least one reliable JMAP server target - server-side text search and pagination through `Email/query` plus bounded
summaries and details through `Email/get`;
- incremental state through bounded `Email/changes`, with an explicit full
refresh when the provider can no longer calculate changes;
- per-endpoint response and body-value bounds;
- a dedicated JMAP hostname policy and fail-closed cross-origin API discovery;
and
- protocol-neutral folder/message DTOs and mailbox UI selection while keeping
the IMAP path unchanged.
The current boundary is read-only. JMAP submission, mailbox/message mutation,
threads, calendars, contacts, push subscriptions, binary attachment download,
and automatic background synchronization are deferred until a separately
governed slice needs them.
## POP3 ## POP3
@@ -84,5 +100,7 @@ legacy source rollout is an explicit operational action.
## Decision ## Decision
Keep the implemented POP3 surface limited to governed legacy import. Do not Keep the implemented POP3 surface limited to governed legacy import. Do not
expand it into mailbox browsing. Design protocol-neutral mailbox DTOs and expand it into mailbox browsing. Keep the protocol-neutral mailbox DTOs and
prefer JMAP for future modern synchronization/search support. use the implemented JMAP path for modern synchronization/search support when
an administrator explicitly configures it. Keep SMTP for sending and POP3
limited to governed legacy import.
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "@govoplan/mail-webui", "name": "@govoplan/mail-webui",
"version": "0.1.20", "version": "0.1.23",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@govoplan/mail-webui", "name": "@govoplan/mail-webui",
"version": "0.1.20", "version": "0.1.23",
"peerDependencies": { "peerDependencies": {
"@govoplan/core-webui": "^0.1.18", "@govoplan/core-webui": "^0.1.18",
"lucide-react": "^1.23.0", "lucide-react": "^1.23.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@govoplan/mail-webui", "name": "@govoplan/mail-webui",
"version": "0.1.20", "version": "0.1.23",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "webui/src/index.ts", "main": "webui/src/index.ts",
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "govoplan-mail" name = "govoplan-mail"
version = "0.1.20" version = "0.1.23"
description = "GovOPlaN mail module with backend and WebUI integration." description = "GovOPlaN mail module with backend and WebUI integration."
readme = "README.md" readme = "README.md"
requires-python = ">=3.12" requires-python = ">=3.12"
+73
View File
@@ -1,5 +1,8 @@
from __future__ import annotations from __future__ import annotations
import urllib.parse
from typing import Literal
from pydantic import Field, model_validator from pydantic import Field, model_validator
from govoplan_core.mail.config import ( from govoplan_core.mail.config import (
@@ -51,10 +54,80 @@ class Pop3Config(Pop3ServerConfig):
username: str | None = None username: str | None = None
password: str | None = None password: str | None = None
class JmapServerConfig(StrictModel):
"""Server-only settings for an RFC 8620/8621 mailbox endpoint."""
session_url: str
account_id: str | None = Field(default=None, max_length=255)
auth_scheme: Literal["bearer", "basic"] = "bearer"
timeout_seconds: int = Field(default=20, ge=1, le=120)
max_response_bytes: int = Field(
default=5 * 1024 * 1024,
ge=64 * 1024,
le=25 * 1024 * 1024,
)
max_body_value_bytes: int = Field(
default=1 * 1024 * 1024,
ge=1_024,
le=5 * 1024 * 1024,
)
allowed_api_origins: list[str] = Field(default_factory=list, max_length=10)
@model_validator(mode="after")
def validate_urls(self) -> "JmapServerConfig":
self.session_url = _absolute_http_url(self.session_url, label="JMAP session URL")
session_origin = _http_origin(self.session_url)
origins: list[str] = []
for value in self.allowed_api_origins:
normalized = _http_origin(
_absolute_http_url(value, label="JMAP allowed API origin")
)
if normalized != session_origin and normalized not in origins:
origins.append(normalized)
self.allowed_api_origins = origins
if self.account_id is not None:
self.account_id = self.account_id.strip() or None
return self
class JmapConfig(JmapServerConfig):
username: str | None = Field(default=None, max_length=320)
password: str | None = None
@model_validator(mode="after")
def validate_credentials(self) -> "JmapConfig":
if self.auth_scheme == "basic" and not (self.username and self.password):
raise ValueError("JMAP Basic authentication requires username and password")
if self.auth_scheme == "bearer" and not self.password:
raise ValueError("JMAP Bearer authentication requires an access token")
return self
def _absolute_http_url(value: str, *, label: str) -> str:
parsed = urllib.parse.urlsplit(str(value or "").strip())
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
raise ValueError(f"{label} must be an absolute HTTP(S) URL")
if parsed.username or parsed.password:
raise ValueError(f"{label} must not include embedded credentials")
if parsed.fragment:
raise ValueError(f"{label} must not include a fragment")
return urllib.parse.urlunsplit(parsed)
def _http_origin(value: str) -> str:
parsed = urllib.parse.urlsplit(value)
port = parsed.port or (443 if parsed.scheme == "https" else 80)
default_port = 443 if parsed.scheme == "https" else 80
suffix = "" if port == default_port else f":{port}"
return f"{parsed.scheme.lower()}://{(parsed.hostname or '').lower()}{suffix}"
__all__ = [ __all__ = [
"ImapConfig", "ImapConfig",
"ImapFolderMappings", "ImapFolderMappings",
"ImapServerConfig", "ImapServerConfig",
"JmapConfig",
"JmapServerConfig",
"Pop3Config", "Pop3Config",
"Pop3ServerConfig", "Pop3ServerConfig",
"SmtpConfig", "SmtpConfig",
+13 -13
View File
@@ -26,7 +26,7 @@ MAIL_SECRET_MANAGE_SCOPE = "mail:secret:manage" # noqa: S105 # nosec B105
MAIL_SECRET_MANAGE_OWN_SCOPE = "mail:secret:manage_own" # noqa: S105 # nosec B105 MAIL_SECRET_MANAGE_OWN_SCOPE = "mail:secret:manage_own" # noqa: S105 # nosec B105
MAIL_PROFILE_TEST_SCOPE = "mail:profile:test" MAIL_PROFILE_TEST_SCOPE = "mail:profile:test"
MAIL_PROFILE_USE_SCOPE = "mail:profile:use" MAIL_PROFILE_USE_SCOPE = "mail:profile:use"
_HOST_POLICY_FIELDS = (("SMTP", "smtp_hosts"), ("IMAP", "imap_hosts")) _HOST_POLICY_FIELDS = (("SMTP", "smtp_hosts"), ("IMAP", "imap_hosts"), ("JMAP", "jmap_hosts"))
def documentation_topics(context: DocumentationContext) -> tuple[DocumentationTopic, ...]: def documentation_topics(context: DocumentationContext) -> tuple[DocumentationTopic, ...]:
@@ -233,7 +233,7 @@ def _custom_mail_profile_topic(context: DocumentationContext) -> DocumentationTo
title="Create a custom Mail profile", title="Create a custom Mail profile",
summary=( summary=(
"Create a reusable profile in the current account's user-scoped Settings view, " "Create a reusable profile in the current account's user-scoped Settings view, "
"within the active SMTP and IMAP hostname policy." "within the active SMTP, IMAP, and JMAP hostname policy."
), ),
body="\n".join(authority_lines), body="\n".join(authority_lines),
layer="configured", layer="configured",
@@ -345,12 +345,12 @@ def _custom_profile_authority_lines(
approval_required: bool, approval_required: bool,
) -> tuple[str, ...]: ) -> tuple[str, ...]:
credentials = ( credentials = (
"Credential authority: you may save or replace Mail-owned SMTP/IMAP passwords." "Credential authority: you may save or replace Mail-owned SMTP/IMAP passwords and JMAP tokens or Basic credentials."
if can_manage_credentials if can_manage_credentials
else "Credential authority: you may define the profile, but you cannot save or replace passwords; an actor with both profile-write and secret-management authority must do that when authentication requires one." else "Credential authority: you may define the profile, but you cannot save or replace passwords; an actor with both profile-write and secret-management authority must do that when authentication requires one."
) )
testing = ( testing = (
"Test authority: you may run the profile's SMTP/IMAP connection tests after saving it as active." "Test authority: you may run the profile's SMTP/IMAP/JMAP connection tests after saving it as active."
if can_test_profile if can_test_profile
else "Test authority: creating the profile does not let you run connection tests; ask an actor with both profile-test and profile-use authority to verify an active profile." else "Test authority: creating the profile does not let you run connection tests; ask an actor with both profile-test and profile-use authority to verify an active profile."
) )
@@ -376,18 +376,18 @@ def _custom_profile_steps(
) -> tuple[str, ...]: ) -> tuple[str, ...]:
steps = [ steps = [
"Open Settings, choose Mail profiles, and select Add profile in the current account's user-scoped view.", "Open Settings, choose Mail profiles, and select Add profile in the current account's user-scoped view.",
"Enter a stable name and configure SMTP plus optional IMAP hostnames that satisfy every host-policy statement shown above.", "Enter a stable name and configure SMTP plus optional IMAP settings; add an optional JMAP server after the profile exists. Every endpoint must satisfy the host-policy statements shown above.",
] ]
steps.append( steps.append(
"Enter the required SMTP/IMAP credentials in the dedicated password fields." "Enter the required SMTP/IMAP credentials, or link an encrypted bearer token or Basic credential to the JMAP server."
if can_manage_credentials if can_manage_credentials
else "Save the non-secret profile definition, then ask an actor with both profile-write and secret-management authority to add credentials if the server requires authentication." else "Save the non-secret profile definition, then ask an actor with both profile-write and secret-management authority to add credentials if the server requires authentication."
) )
steps.append("Save the profile; Mail validates the effective user-scope host policy again on the server.") steps.append("Save the profile; Mail validates the effective user-scope host policy again on the server.")
steps.append( steps.append(
"Save the profile as active, then run the available SMTP and IMAP connection tests." "Save the profile as active, then run the available SMTP, IMAP, and JMAP connection tests."
if can_test_profile if can_test_profile
else "Ask an actor with both profile-test and profile-use authority to run the SMTP and IMAP connection tests after the profile is active." else "Ask an actor with both profile-test and profile-use authority to run the SMTP, IMAP, and JMAP connection tests after the profile is active."
) )
if approval_required: if approval_required:
steps.append("Ask a Mail administrator to add the new profile to the active approved-profile list.") steps.append("Ask a Mail administrator to add the new profile to the active approved-profile list.")
@@ -402,9 +402,9 @@ def _custom_profile_steps(
def _custom_profile_verification(*, can_test_profile: bool, can_use_profile: bool, approval_required: bool) -> str: def _custom_profile_verification(*, can_test_profile: bool, can_use_profile: bool, approval_required: bool) -> str:
checks = ["Reopen My Mail profiles and confirm the saved profile remains in the current account's user-scoped view."] checks = ["Reopen My Mail profiles and confirm the saved profile remains in the current account's user-scoped view."]
checks.append( checks.append(
"Confirm the authorized SMTP/IMAP tests succeed." "Confirm the authorized SMTP/IMAP/JMAP tests succeed."
if can_test_profile if can_test_profile
else "Have an authorized tester confirm the SMTP/IMAP tests succeed." else "Have an authorized tester confirm the SMTP/IMAP/JMAP tests succeed."
) )
if approval_required: if approval_required:
checks.append("Confirm an administrator approved the generated profile reference before expecting it in a picker.") checks.append("Confirm an administrator approved the generated profile reference before expecting it in a picker.")
@@ -424,7 +424,7 @@ def _mail_policy_admin_text(policy: dict[str, Any], *, source_count: int) -> tup
locked_limit_count = sum(1 for value in _lower_limit_values(policy) if value is False) locked_limit_count = sum(1 for value in _lower_limit_values(policy) if value is False)
if approved_profile_limit and not lower_scopes: if approved_profile_limit and not lower_scopes:
summary = "This tenant is in approved-profile mode: users can choose configured mail profiles, but lower scopes cannot bring arbitrary SMTP or IMAP servers." summary = "This tenant is in approved-profile mode: users can choose configured mail profiles, but lower scopes cannot bring arbitrary SMTP, IMAP, or JMAP servers."
elif approved_profile_limit: elif approved_profile_limit:
summary = "This tenant limits mail sending to approved profile ids, while selected lower scopes can still define profiles within policy limits." summary = "This tenant limits mail sending to approved profile ids, while selected lower scopes can still define profiles within policy limits."
elif lower_scopes: elif lower_scopes:
@@ -451,10 +451,10 @@ def _mail_policy_user_text(policy: dict[str, Any]) -> tuple[str, str]:
body = "This is set by tenant policy. If the mail server you need is not offered, ask an administrator to add it as an approved mail profile." body = "This is set by tenant policy. If the mail server you need is not offered, ask an administrator to add it as an approved mail profile."
elif approved_profile_limit: elif approved_profile_limit:
summary = "You can use approved Mail profiles. Some scopes may also define additional reusable profiles." summary = "You can use approved Mail profiles. Some scopes may also define additional reusable profiles."
body = "The available profiles are limited by tenant policy. Campaigns select one profile by reference; SMTP/IMAP settings and credentials remain managed in Mail." body = "The available profiles are limited by tenant policy. Campaigns select one profile by reference; SMTP/IMAP/JMAP settings and credentials remain managed in Mail."
elif lower_scopes: elif lower_scopes:
summary = "You may be able to define reusable Mail profiles in selected scopes, subject to tenant rules." summary = "You may be able to define reusable Mail profiles in selected scopes, subject to tenant rules."
body = "GovOPlaN checks each profile before use. Campaigns reference an available profile and never store its SMTP/IMAP settings or credentials." body = "GovOPlaN checks each profile before use. Campaigns reference an available profile and never store its SMTP/IMAP/JMAP settings or credentials."
else: else:
summary = "Mail servers are managed centrally for this tenant." summary = "Mail servers are managed centrally for this tenant."
body = "You cannot add a personal, group, or campaign mail server here. Choose one of the configured options or ask an administrator to add another approved profile." body = "You cannot add a personal, group, or campaign mail server here. Choose one of the configured options or ask an administrator to add another approved profile."
@@ -0,0 +1,214 @@
"""German translations for public structured documentation metadata."""
from __future__ import annotations
from typing import Any
GERMAN_STRUCTURED_TRANSLATIONS: dict[str, dict[str, Any]] = {'mail.bounce-processing': {'verification': 'Senden Sie eine Nachricht mit einer eindeutigen '
'Message-ID, nehmen Sie zweimal einen DSN auf und '
'überprüfen Sie eine korrelierte Beobachtung, während '
'die SMTP-Akzeptanz intakt bleibt.'},
'mail.privacy.data-subject-requests': {'limitations': ['Verschlüsselte ausgehende Nutzlasten '
'können vom Empfänger nicht ohne eine '
'unabhängig bestätigte '
'Mail-Befehlsreferenz durchsucht werden.',
'Die externe Mailbox-Löschung befindet '
'sich außerhalb des DSAR-Anbieters und '
'muss mit dem konfigurierten Anbieter '
'koordiniert werden.'],
'steps': ['Führen Sie die Mail-Provider-Suche und '
'Überprüfung von Mailbox-Index, POP3-Import, '
'Profil, Lieferung, Abgleich und '
'Bounce-Dispositionen aus.',
'Bewahren Sie den unveränderlichen '
'Transportnachweis mit seinem Grund auf.',
'Koordinieren Sie die genehmigte '
'Mailbox-Inhaltelöschung mit der autoritativen '
'externen Mailbox und aktualisieren Sie dann den '
'abgeleiteten Index.',
'Verwenden Sie '
'E-Mail-Profillebenszykluskontrollen für '
'genehmigte Änderungen des persönlichen Profils; '
'Bearbeiten Sie nicht direkt verschlüsselte '
'Nutzlast- oder Beweiszeilen.']},
'mail.profile-standard-folder-mappings': {'steps': ['Öffnen Sie einen editierbaren IMAP-Server in '
'einem wiederverwendbaren Mail-Profil.',
'Wählen Sie Ordner erkennen, um die vom '
'Anbieter sichtbaren Ordnernamen zu laden, '
'oder geben Sie genaue Namen manuell ein.',
'Wenden Sie die erkannten Zuordnungen an, '
'überprüfen Sie jede Rolle und lassen Sie '
'unsichere Rollen für automatisches Verhalten '
'leer.',
'Speichern Sie das Profil und laden Sie es '
'neu, um zu überprüfen, ob die Zuordnungen '
'beibehalten wurden.'],
'verification': 'Bestätigen Sie, dass ältere '
'Sent-only-Profile das gleiche '
'effektive Sent-Mapping zeigen, und '
'bestätigen Sie, dass ein '
'kampagnenlokaler Sent-Override '
'unverändert bleibt.'},
'mail.reference.campaign-delivery-contract': {'verification': 'Nachweisen Sie, dass veraltete '
'Revisionen vor der Entschlüsselung '
'fehlschlagen, der Batch-Preflight '
'vor DATA fehlschlägt, zwei '
'Nachrichten eine gesunde '
'Verbindung wiederverwenden, eine '
'veraltete Verbindung vor der '
'nächsten Nachricht wieder '
'verbunden wird, die Trennung nach '
'der DATA nie wiedergegeben wird, '
'systemische Ausfälle verbleibende '
'Jobs anhalten, Anbieterdetails '
'werden gelöscht und das Interface '
'/ Versionsgate wird übergeben.'},
'mail.reference.credentials-egress-retirement': {'verification': 'Testen Sie DNS-Rebinding und '
'verweigerte Adressen, beweisen '
'Sie, dass der verbundene Peer '
'angeheftet ist, injizieren Sie '
'Credential-Scrub- und '
'Auditfehler, wiederholen Sie '
'die Löschung für Idempotenz und '
'führen Sie den '
'Ruhestands-Preflight gegen '
'einen Snapshot aus.'},
'mail.workflow.choose-and-test-profile': {'outcome': 'Die verbrauchende Aufgabe verweist auf ein '
'verfügbares Mail-eigenes Profil und enthält '
'keine kopierte Transportkonfiguration oder '
'Anmeldeinformationen.',
'prerequisites': ['Mail ist installiert und Sie können '
'Profile lesen, verwenden und testen, '
'die im aktuellen Kontext sichtbar '
'sind.',
'Ein Profiladministrator hat '
'Anmeldeinformationen und effektive '
'Richtlinien konfiguriert.'],
'steps': ['Öffnen Sie Mail-Profile und wählen Sie ein '
'sichtbares aktives Profil.',
'Überprüfen Sie den Sicherheitsumfang, die '
'Verfügbarkeit von SMTP/IMAP/JMAP und die '
'Absenderidentität, ohne Anmeldewerte zu '
'erwarten.',
'Führen Sie den entsprechenden SMTP-, IMAP- '
'oder '
'JMAP-Konnektivitäts-/Authentifizierungstest '
'zuerst gegen ein Nicht-Produktionsziel aus.',
'Kehren Sie zur verbrauchenden Aufgabe zurück '
'und wählen Sie dasselbe Profil über den '
'Picker aus.'],
'verification': 'Laden Sie beide Oberflächen neu, '
'bestätigen Sie, dass nur die stabile '
'Referenz vom Verbraucher beibehalten '
'wird, und führen Sie die eigene '
'kontextbezogene Richtlinienvalidierung '
'des Verbrauchers durch.'},
'mail.workflow.legacy-pop3-import': {'fields': [{'label': 'Verkehrssicherheit',
'user_description': 'Verwenden Sie TLS oder '
'STARTTLS; unverschlüsselter '
'Transport unterliegt '
'weiterhin der '
'Deployment-Egress-Richtlinie '
'und ist nicht der sichere '
'Standard.'},
{'label': 'Grenzwerte für Nachrichten und Chargen',
'user_description': 'Bound sowohl jede '
'heruntergeladene Nachricht '
'als auch die gesamte '
'importierte Charge, bevor '
'der Anbieterinhalt in den '
'lokalen verschlüsselten '
'Speicher gelangt.'},
{'label': 'Ausdrücklich Legacy Import ermöglichen',
'user_description': 'Hält die Quelle inaktiv, '
'bis die Endpunktmetadaten '
'und ihre verschlüsselten '
'Anmeldeinformationen beide '
'gespeichert wurden.'},
{'label': 'Anträge auf Löschung nach Einfuhr',
'user_description': 'Erlaubt, aber wählt niemals '
'die separat autorisierte '
'destruktive Anforderung '
'aus; jede Charge benötigt '
'noch eine explizite '
'Bestätigung.'}],
'limitations': ['Ein POP3-Server muss stabile '
'UIDL-Identifikatoren bereitstellen; '
'ansonsten ist eine sichere doppelte '
'Verhinderung nicht verfügbar und der Import '
'wird abgelehnt.',
'POP3 hat keine Ordner- oder Flag-Semantik '
'und ist nicht das empfohlene Protokoll für '
'den laufenden Mailbox-Zugriff.',
'Die Quelllöschung kann nicht zurückgesetzt '
'werden und hat möglicherweise ein '
'unbekanntes Ergebnis, wenn die Verbindung '
'fehlschlägt, während QUIT Löschungen '
'festlegt.'],
'operational_consequences': ['Durch das Ändern von Host-, '
'Port-, Sicherheits-, '
'Kontoidentitäts- oder '
'Importlimits wird die '
'Transportrevision geändert und '
'veraltete Previews ungültig '
'gemacht.',
'Durch das Ermöglichen des '
'Löschens von Quellen entsteht '
'eine irreversible Grenze für '
'externe Effekte; unbekannte '
'QUIT-Ergebnisse erfordern eine '
'Versöhnung statt eines blinden '
'Wiederholens.',
'Die Deaktivierung von '
'Legacy-Importen führt zu '
'regulierten lokalen Importen '
'und deren Nachweisen, die zur '
'Überprüfung zur Verfügung '
'stehen, während der Zugang '
'neuer Anbieter verhindert '
'wird.'],
'steps': ['Bitten Sie einen Mail-Administrator, eine '
'dedizierte POP3-Altquelle zu konfigurieren und '
'explizit zu aktivieren.',
'Testen Sie die Quelle und aktualisieren Sie eine '
'begrenzte Vorschau; Es werden keine '
'Nachrichtenflags oder Löschstatus geändert.',
'Wählen Sie Nachrichten aus und importieren Sie '
'sie in verschlüsselte Pending-Review-Datensätze.',
'Verwenden Sie delete-after-import nur, wenn '
'Richtlinien und eine separate destruktive '
'Berechtigung dies zulassen, und versöhnen Sie '
'dann fehlgeschlagene oder unbekannte Ergebnisse.'],
'verification': 'Nachweisen Sie deaktivierte Richtlinien, '
'TLS- und Authentifizierungsdiagnostik, '
'zerstörungsfreie Vorschau / Import, '
'UIDL-Duplikate-Verhinderung, verschlüsselte '
'Rohdatenspeicherung, separate '
'Löschberechtigung, '
'Import-Vor-Löschen-Auditbestellung und '
'fehlgeschlagene oder ergebnisunbekannte '
'Löschnachweise.'},
'mail.workflow.read-mailbox': {'outcome': 'Die erforderliche Nachricht wurde inspiziert, ohne den '
'Status der Provider-Mailbox zu ändern.',
'prerequisites': ['Ein aktives sichtbares Profil hat IMAP oder '
'JMAP konfiguriert.',
'Sie können beide dieses profil verwenden und '
'seine mailbox lesen.'],
'steps': ['Öffnen Sie Mail und wählen Sie ein autorisiertes IMAP- '
'oder JMAP-fähiges Profil.',
'Wählen Sie einen Ordner aus, überprüfen Sie das '
'Live/Cache-Synchronisationslabel und stellen Sie den '
'begrenzten Nachrichtenindex auf die Seite; JMAP-Suchen '
'werden beim Anbieter ausgeführt.',
'Verwenden Sie den vom Anbieter abgeleiteten '
'Read/Unread-Indikator und öffnen Sie dann nur die für '
'die Aufgabe benötigte Nachricht.',
'Wechseln Sie bei Bedarf zwischen sicheren Klartext- und '
'isolierten HTML-Ansichten und überprüfen Sie die '
'Anhang- oder Nichtverfügbarkeitsangaben, bevor Sie die '
'Vorschau schließen.'],
'verification': 'Aktualisieren Sie das Provider-Postfach '
'unabhängig und bestätigen Sie, dass keine Lese-, '
'Verschiebe-, Lösch-, Antwort- oder Flag-Mutation '
'durch GovOPlaN verursacht wurde.'}}
+15 -3
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import fnmatch import fnmatch
import json import json
import re import re
import urllib.parse
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Any, Iterable, Mapping from typing import Any, Iterable, Mapping
@@ -33,7 +34,7 @@ class MailProfileError(RuntimeError):
MAIL_PROFILE_POLICY_SETTINGS_KEY = "mail_profile_policy" MAIL_PROFILE_POLICY_SETTINGS_KEY = "mail_profile_policy"
PROFILE_SCOPE_TYPES = {"system", "tenant", "user", "group", "campaign"} PROFILE_SCOPE_TYPES = {"system", "tenant", "user", "group", "campaign"}
PROFILE_PATTERN_KEYS = ("smtp_hosts", "imap_hosts", "envelope_senders", "from_headers", "recipient_domains") PROFILE_PATTERN_KEYS = ("smtp_hosts", "imap_hosts", "jmap_hosts", "envelope_senders", "from_headers", "recipient_domains")
PROFILE_SCOPE_ORDER = {"system": 0, "tenant": 1, "user": 2, "group": 2, "campaign": 3} PROFILE_SCOPE_ORDER = {"system": 0, "tenant": 1, "user": 2, "group": 2, "campaign": 3}
MAIL_POLICY_LIMIT_KEYS = ( MAIL_POLICY_LIMIT_KEYS = (
"allowed_profile_ids", "allowed_profile_ids",
@@ -44,11 +45,13 @@ MAIL_POLICY_LIMIT_KEYS = (
"imap_credentials.inherit", "imap_credentials.inherit",
"whitelist.smtp_hosts", "whitelist.smtp_hosts",
"whitelist.imap_hosts", "whitelist.imap_hosts",
"whitelist.jmap_hosts",
"whitelist.envelope_senders", "whitelist.envelope_senders",
"whitelist.from_headers", "whitelist.from_headers",
"whitelist.recipient_domains", "whitelist.recipient_domains",
"blacklist.smtp_hosts", "blacklist.smtp_hosts",
"blacklist.imap_hosts", "blacklist.imap_hosts",
"blacklist.jmap_hosts",
"blacklist.envelope_senders", "blacklist.envelope_senders",
"blacklist.from_headers", "blacklist.from_headers",
"blacklist.recipient_domains", "blacklist.recipient_domains",
@@ -711,11 +714,19 @@ def _domain_from_email(value: str | None) -> str | None:
return text.rsplit("@", 1)[1] or None return text.rsplit("@", 1)[1] or None
def _assert_transport_values_allowed(policy: EffectiveMailProfilePolicy, smtp: SmtpConfig | dict[str, Any] | None, imap: ImapConfig | dict[str, Any] | None) -> None: def _assert_transport_values_allowed(
policy: EffectiveMailProfilePolicy,
smtp: SmtpConfig | dict[str, Any] | None,
imap: ImapConfig | dict[str, Any] | None,
jmap: dict[str, Any] | None = None,
) -> None:
smtp_host = smtp.host if isinstance(smtp, SmtpConfig) else smtp.get("host") if isinstance(smtp, dict) else None smtp_host = smtp.host if isinstance(smtp, SmtpConfig) else smtp.get("host") if isinstance(smtp, dict) else None
imap_host = imap.host if isinstance(imap, ImapConfig) else imap.get("host") if isinstance(imap, dict) else None imap_host = imap.host if isinstance(imap, ImapConfig) else imap.get("host") if isinstance(imap, dict) else None
jmap_url = jmap.get("session_url") if isinstance(jmap, dict) else None
jmap_host = urllib.parse.urlsplit(str(jmap_url)).hostname if jmap_url else None
_assert_policy_value(policy, "smtp_hosts", str(smtp_host) if smtp_host else None) _assert_policy_value(policy, "smtp_hosts", str(smtp_host) if smtp_host else None)
_assert_policy_value(policy, "imap_hosts", str(imap_host) if imap_host else None) _assert_policy_value(policy, "imap_hosts", str(imap_host) if imap_host else None)
_assert_policy_value(policy, "jmap_hosts", str(jmap_host) if jmap_host else None)
def assert_mail_policy_allows_transport( def assert_mail_policy_allows_transport(
@@ -724,6 +735,7 @@ def assert_mail_policy_allows_transport(
tenant_id: str, tenant_id: str,
smtp: SmtpConfig | dict[str, Any] | None, smtp: SmtpConfig | dict[str, Any] | None,
imap: ImapConfig | dict[str, Any] | None = None, imap: ImapConfig | dict[str, Any] | None = None,
jmap: dict[str, Any] | None = None,
campaign_id: str | None = None, campaign_id: str | None = None,
owner_user_id: str | None = None, owner_user_id: str | None = None,
owner_group_id: str | None = None, owner_group_id: str | None = None,
@@ -735,7 +747,7 @@ def assert_mail_policy_allows_transport(
owner_user_id=owner_user_id, owner_user_id=owner_user_id,
owner_group_id=owner_group_id, owner_group_id=owner_group_id,
) )
_assert_transport_values_allowed(policy, smtp, imap) _assert_transport_values_allowed(policy, smtp, imap, jmap)
def assert_mail_policy_allows_send( def assert_mail_policy_allows_send(
+302 -23
View File
@@ -1,5 +1,8 @@
from __future__ import annotations from __future__ import annotations
from govoplan_core.core.modules import with_documentation_structured_translations
from govoplan_mail.backend.german_structured_documentation import GERMAN_STRUCTURED_TRANSLATIONS
from dataclasses import replace from dataclasses import replace
from pathlib import Path from pathlib import Path
@@ -50,9 +53,11 @@ from govoplan_mail.backend.documentation import (
) )
from govoplan_mail.backend.provider_state import ( from govoplan_mail.backend.provider_state import (
IMAP_PROVIDER_ID, IMAP_PROVIDER_ID,
JMAP_PROVIDER_ID,
POP3_PROVIDER_ID, POP3_PROVIDER_ID,
SMTP_PROVIDER_ID, SMTP_PROVIDER_ID,
imap_provider_states, imap_provider_states,
jmap_provider_states,
pop3_provider_states, pop3_provider_states,
smtp_provider_states, smtp_provider_states,
) )
@@ -97,7 +102,7 @@ def _mail_retirement_provider(session: object | None, module_id: str):
plan, plan,
destroy_data_warnings=( destroy_data_warnings=(
*plan.destroy_data_warnings, *plan.destroy_data_warnings,
"Mail-owned encrypted SMTP/IMAP/POP3 passwords are scrubbed with non-secret audit records immediately before tables are dropped; encrypted POP3 import records are then removed with the Mail tables. Any scrub or audit failure blocks retirement.", "Mail-owned encrypted SMTP/IMAP/JMAP/POP3 credentials are scrubbed with non-secret audit records immediately before tables are dropped; encrypted POP3 import records are then removed with the Mail tables. Any scrub or audit failure blocks retirement.",
), ),
destroy_data_executor=executor, destroy_data_executor=executor,
) )
@@ -132,17 +137,17 @@ def _permission(scope: str, label: str, description: str) -> PermissionDefinitio
PERMISSIONS = ( PERMISSIONS = (
_permission("mail:profile:read", "View mail profiles", "Inspect reusable SMTP/IMAP and governed legacy POP3 profile metadata."), _permission("mail:profile:read", "View mail profiles", "Inspect reusable SMTP/IMAP/JMAP and governed legacy POP3 profile metadata."),
_permission("mail:profile:use", "Use mail profiles", "Select an approved mail profile for delivery."), _permission("mail:profile:use", "Use mail profiles", "Select an approved mail profile for delivery."),
_permission("mail:profile:test", "Test mail profiles", "Run SMTP/IMAP connection tests and explicitly enabled POP3 diagnostics."), _permission("mail:profile:test", "Test mail profiles", "Run SMTP/IMAP/JMAP connection tests and explicitly enabled POP3 diagnostics."),
_permission("mail:mailbox:read", "Read mailboxes", "List IMAP folders and inspect messages without mutating mailbox state."), _permission("mail:mailbox:read", "Read mailboxes", "List IMAP or JMAP folders and inspect messages without mutating mailbox state."),
_permission("mail:profile:write", "Manage mail profiles", "Create and edit reusable mail profiles."), _permission("mail:profile:write", "Manage mail profiles", "Create and edit reusable mail profiles."),
_permission( _permission(
"mail:profile:write_own", "mail:profile:write_own",
"Manage own mail profiles", "Manage own mail profiles",
"Create, edit, and deactivate only the current account's user-scoped mail profiles within effective policy.", "Create, edit, and deactivate only the current account's user-scoped mail profiles within effective policy.",
), ),
_permission("mail:secret:manage", "Manage mail secrets", "Create or replace stored SMTP/IMAP/POP3 credentials."), _permission("mail:secret:manage", "Manage mail secrets", "Create or replace stored SMTP/IMAP/JMAP/POP3 credentials."),
_permission( _permission(
"mail:pop3:manage", "mail:pop3:manage",
"Manage legacy POP3 imports", "Manage legacy POP3 imports",
@@ -349,6 +354,46 @@ IMAP_PROVIDER = ExternalProviderDeclaration(
) )
JMAP_PROVIDER = ExternalProviderDeclaration(
id=JMAP_PROVIDER_ID,
module_id="mail",
label="JMAP mailbox projection",
maturity="read",
operations=("discover", "search", "read", "preview"),
objects=(
ProviderObjectDeclaration(
object_type="mailbox_folder",
field_groups=("identity", "role", "counts", "revision"),
authority_modes=("external_authoritative", "external_mirror"),
default_authority_mode="external_mirror",
),
ProviderObjectDeclaration(
object_type="mailbox_message",
field_groups=("identity", "headers", "body_preview", "flags", "source_metadata"),
authority_modes=("external_authoritative", "external_mirror"),
default_authority_mode="external_mirror",
),
),
behavior=ProviderBehaviorDeclaration(
revision_tokens="JMAP Mailbox and Email state values plus the transport revision identify mailbox observations.",
concurrency="Bounded Email/query, Email/get, and Email/changes calls pin one discovered Session and never mutate provider state.",
freshness="Mailbox and message index timestamps state when the external JMAP account was last observed.",
health="Capability discovery and connection diagnostics remain separate from secret credential fields.",
max_read_items=500,
evidence="Mailbox index rows retain bounded provider identifiers and observation times.",
audit_event_types=("mail.mailbox.read",),
correction="A later JMAP refresh replaces the derived projection while source-owned history remains external.",
reconciliation="An expired Email state requires a bounded full refresh instead of guessing missed changes.",
outage="The last derived index remains readable with stale or unknown freshness where policy permits.",
classifications=("confidential", "personal", "special_category"),
purposes=("mailbox access", "mailbox search"),
retention="Derived mailbox indexes follow Mail retention policy.",
secret_handling="JMAP bearer tokens or Basic credentials remain encrypted and are never returned through mailbox or provider-state APIs.",
),
documentation_topic_ids=("mail.workflow.read-mailbox",),
)
POP3_PROVIDER = ExternalProviderDeclaration( POP3_PROVIDER = ExternalProviderDeclaration(
id=POP3_PROVIDER_ID, id=POP3_PROVIDER_ID,
module_id="mail", module_id="mail",
@@ -400,7 +445,7 @@ POP3_PROVIDER = ExternalProviderDeclaration(
manifest = ModuleManifest( manifest = ModuleManifest(
id="mail", id="mail",
name="Mail", name="Mail",
version="0.1.20", version="0.1.23",
required_capabilities=(CAPABILITY_AUTH_PRINCIPAL_RESOLVER, CAPABILITY_AUTH_PERMISSION_EVALUATOR), required_capabilities=(CAPABILITY_AUTH_PRINCIPAL_RESOLVER, CAPABILITY_AUTH_PERMISSION_EVALUATOR),
optional_dependencies=("campaigns", "addresses", "calendar", "postbox", "search"), optional_dependencies=("campaigns", "addresses", "calendar", "postbox", "search"),
provides_interfaces=( provides_interfaces=(
@@ -615,10 +660,75 @@ manifest = ModuleManifest(
), ),
related_modules=("audit", "records"), related_modules=("audit", "records"),
unlocks=("Governed retirement of legacy POP3 mailboxes without making destructive retrieval the default.",), unlocks=("Governed retirement of legacy POP3 mailboxes without making destructive retrieval the default.",),
translations={
"de": {
"title": "Nachrichten aus einem alten POP3-Postfach importieren",
"summary": "Begrenzt viele POP3-Nachrichten in verschlüsselte lokale Prüfdatensätze übernehmen, ohne die Quelldaten standardmäßig zu löschen.",
"body": (
"POP3 ist ausschließlich ein nachrangiger Migrationsweg und wird niemals stillschweigend aktiviert. "
"Eine Mail-Administration legt eine eigene POP3-Quelle an, aktiviert den Altimport ausdrücklich, "
"hinterlegt Zugangsdaten verschlüsselt, prüft TLS und Anmeldung und entscheidet getrennt, ob das Löschen "
"an der Quelle überhaupt angefordert werden darf. Importberechtigte laden eine begrenzte Live-Vorschau, "
"wählen Nachrichten anhand stabiler UIDL-Kennungen und übernehmen sie als verschlüsselte Datensätze mit "
"ausstehender Prüfung. Wiederholte Importe werden als Duplikate ausgewiesen und nicht erneut gespeichert. "
"Quelldaten bleiben unverändert, solange nicht die Endpunktrichtlinie Löschen nach Import erlaubt, die "
"ausführende Person zusätzlich mail:pop3:delete besitzt und das Löschen für den konkreten Stapel ausdrücklich "
"ausgewählt wird. Mail schreibt und protokolliert zuerst den lokalen Import und versucht erst danach die "
"Löschung beim Anbieter. Eine fehlgeschlagene oder unklare Löschung entfernt deshalb niemals den verwalteten "
"lokalen Datensatz und muss vor einem weiteren destruktiven Versuch abgestimmt werden. Für den laufenden "
"Postfachzugriff sind IMAP oder JMAP vorzuziehen."
),
}
},
metadata={ metadata={
"kind": "workflow", "kind": "workflow",
"route": "/mail/legacy-import", "route": "/mail/legacy-import",
"screen": "Legacy POP3 import", "screen": "Legacy POP3 import",
"help_contexts": [
"mail.pop3",
"mail.pop3.source-editor",
"mail.pop3.action.reload",
"mail.pop3.action.create-source",
"mail.pop3.action.configure-source",
"mail.pop3.action.save-source",
"mail.pop3.action.test",
"mail.pop3.action.preview",
"mail.pop3.action.import",
"mail.pop3.field.profile",
"mail.pop3.field.name",
"mail.pop3.field.host",
"mail.pop3.field.port",
"mail.pop3.field.transport-security",
"mail.pop3.field.timeout",
"mail.pop3.field.max-message-size",
"mail.pop3.field.max-batch-size",
"mail.pop3.field.preview-body-lines",
"mail.pop3.field.username",
"mail.pop3.field.password",
"mail.pop3.field.enabled",
"mail.pop3.field.allow-delete-after-import",
"mail.pop3.field.message-selection",
"mail.pop3.field.delete-after-import",
"mail.pop3.confirm-delete-source",
],
"fields": [
{
"label": "Transport security",
"user_description": "Use TLS or STARTTLS; unencrypted transport remains subject to deployment egress policy and is not the safe default.",
},
{
"label": "Message and batch limits",
"user_description": "Bound both each downloaded message and the total imported batch before provider content enters local encrypted storage.",
},
{
"label": "Explicitly enable legacy import",
"user_description": "Keeps the source inert until endpoint metadata and its encrypted credential have both been stored.",
},
{
"label": "Permit delete-after-import requests",
"user_description": "Allows, but never selects, the separately authorized destructive request; each batch still needs explicit confirmation.",
},
],
"steps": [ "steps": [
"Ask a Mail administrator to configure and explicitly enable a dedicated POP3 legacy source.", "Ask a Mail administrator to configure and explicitly enable a dedicated POP3 legacy source.",
"Test the source and refresh a bounded preview; no message flags or deletion state are changed.", "Test the source and refresh a bounded preview; no message flags or deletion state are changed.",
@@ -630,6 +740,11 @@ manifest = ModuleManifest(
"POP3 has no folder or flag semantics and is not the recommended protocol for ongoing mailbox access.", "POP3 has no folder or flag semantics and is not the recommended protocol for ongoing mailbox access.",
"Source deletion cannot be rolled back and may have an unknown outcome if the connection fails while QUIT commits deletions.", "Source deletion cannot be rolled back and may have an unknown outcome if the connection fails while QUIT commits deletions.",
], ],
"operational_consequences": [
"Changing host, port, security, account identity, or import limits rotates the transport revision and invalidates stale previews.",
"Enabling source deletion creates an irreversible external effect boundary; unknown QUIT outcomes require reconciliation rather than blind retry.",
"Disabling legacy import leaves governed local imports and their evidence available for review while preventing new provider access.",
],
"verification": "Prove disabled policy, TLS and authentication diagnostics, non-destructive preview/import, UIDL duplicate prevention, encrypted raw retention, separate delete authorization, import-before-delete audit ordering, and failed or outcome-unknown deletion evidence.", "verification": "Prove disabled policy, TLS and authentication diagnostics, non-destructive preview/import, UIDL duplicate prevention, encrypted raw retention, separate delete authorization, import-before-delete audit ordering, and failed or outcome-unknown deletion evidence.",
}, },
), ),
@@ -638,7 +753,7 @@ manifest = ModuleManifest(
title="Review Mail data in a data-subject request", title="Review Mail data in a data-subject request",
summary="Collect tenant-scoped Mail metadata while preserving transport evidence and external-mailbox authority.", summary="Collect tenant-scoped Mail metadata while preserving transport evidence and external-mailbox authority.",
body=( body=(
"Mail's DSAR provider searches the effective tenant by normalized header or bounce-recipient email, direct membership references, and namespaced Mail profile, message-index, POP3-import, delivery-command, or bounce references. It isolates only matching From, To, and Cc parties and returns bounded message-index or imported-message content, safe personal-profile metadata, and delivery, attempt, reconciliation, and bounce outcomes. It excludes SMTP/IMAP/POP3 configuration, usernames and credentials, encrypted messages and envelopes, POP3 source UIDLs and revisions, refusal detail, mailbox folders and UIDs, endpoint and credential identifiers, idempotency and worker claims, diagnostics, error text, and opaque evidence. " "Mail's DSAR provider searches the effective tenant by normalized header or bounce-recipient email, direct membership references, and namespaced Mail profile, message-index, POP3-import, delivery-command, or bounce references. It isolates only matching From, To, and Cc parties and returns bounded message-index or imported-message content, safe personal-profile metadata, and delivery, attempt, reconciliation, and bounce outcomes. It excludes SMTP/IMAP/JMAP/POP3 configuration, usernames and credentials, encrypted messages and envelopes, POP3 source UIDLs and revisions, refusal detail, mailbox folders and UIDs, endpoint and credential identifiers, idempotency and worker claims, diagnostics, error text, and opaque evidence. "
"Delivery attempts, reconciliation decisions, and bounce observations remain retained as immutable transport and recovery evidence. Mailbox indexes, encrypted POP3 imports, and personal profiles require manual review through Mail and the authoritative external mailbox. The provider performs no direct erasure because deleting a derived or imported record alone would not establish the state of its external source, while changing a profile or delivery command can affect credentials, other users, and preserved evidence." "Delivery attempts, reconciliation decisions, and bounce observations remain retained as immutable transport and recovery evidence. Mailbox indexes, encrypted POP3 imports, and personal profiles require manual review through Mail and the authoritative external mailbox. The provider performs no direct erasure because deleting a derived or imported record alone would not establish the state of its external source, while changing a profile or delivery command can affect credentials, other users, and preserved evidence."
), ),
layer="configured", layer="configured",
@@ -656,6 +771,27 @@ manifest = ModuleManifest(
DocumentationLink(label="Mail handbook", href="govoplan-mail/docs/MAIL_HANDBOOK.md", kind="repository"), DocumentationLink(label="Mail handbook", href="govoplan-mail/docs/MAIL_HANDBOOK.md", kind="repository"),
), ),
related_modules=("access", "audit", "campaigns", "postbox"), related_modules=("access", "audit", "campaigns", "postbox"),
translations={
"de": {
"title": "Mail-Daten in einer Auskunftsanfrage prüfen",
"summary": "Mandantenbezogene Mail-Metadaten zusammentragen und dabei Transportnachweise sowie die Zuständigkeit des externen Postfachs bewahren.",
"body": (
"Der Mail-Provider für Betroffenenanfragen durchsucht den wirksamen Mandanten anhand normalisierter "
"Absender-, Empfänger- oder Unzustellbarkeitsadressen, direkter Mitgliedschaftsverweise und namensraumgebundener "
"Verweise auf Mail-Profile, Nachrichtenindizes, POP3-Importe, Zustellbefehle oder Rückläufer. Er grenzt nur "
"passende Absender-, An- und Cc-Beteiligte ab und liefert begrenzte Inhalte aus Nachrichtenindex oder Import, "
"sichere Metadaten persönlicher Profile sowie Zustell-, Versuch-, Abstimmungs- und Rückläufergebnisse. "
"Ausgeschlossen bleiben SMTP-, IMAP-, JMAP- und POP3-Konfiguration, Benutzernamen und Zugangsdaten, verschlüsselte "
"Nachrichten und Umschläge, POP3-UIDLs und Quellrevisionen, Ablehnungsdetails, Postfachordner und UIDs, Endpunkt- "
"und Zugangsdatenkennungen, Idempotenz- und Worker-Ansprüche, Diagnosen, Fehlertexte und undurchsichtige Nachweise. "
"Zustellversuche, Abstimmungsentscheidungen und Rückläuferbeobachtungen bleiben als unveränderliche Transport- "
"und Wiederherstellungsnachweise erhalten. Nachrichtenindizes, verschlüsselte POP3-Importe und persönliche Profile "
"müssen in Mail und im maßgeblichen externen Postfach manuell geprüft werden. Der Provider löscht nicht unmittelbar, "
"weil das Entfernen eines abgeleiteten oder importierten Datensatzes den Zustand seiner externen Quelle nicht belegt "
"und Änderungen an Profilen oder Zustellbefehlen Zugangsdaten, andere Personen und aufbewahrte Nachweise betreffen können."
),
}
},
metadata={ metadata={
"kind": "workflow", "kind": "workflow",
"route": "/admin?section=tenant-data-subject-requests", "route": "/admin?section=tenant-data-subject-requests",
@@ -855,13 +991,26 @@ manifest = ModuleManifest(
documentation_types=("admin", "user"), documentation_types=("admin", "user"),
audience=("mail_user", "mail_admin", "administrator"), audience=("mail_user", "mail_admin", "administrator"),
related_modules=("search",), related_modules=("search",),
translations={
"de": {
"title": "Berechtigte Postfachnachrichten durchsuchen",
"summary": "Begrenzte Metadaten und Vorschauen aus dem zwischengespeicherten Postfach für die berechtigungsbewusste Plattformsuche bereitstellen.",
"body": (
"Ist Search installiert, stellt Mail seinen nur lesbaren Postfachzwischenspeicher bereit, niemals Zugangsdaten "
"oder unbegrenzte Rohnachrichten. Ergebnisse erfordern sowohl Leseberechtigung für das Postfach als auch "
"Nutzungsberechtigung für das Profil. Vor jeder Ausgabe werden aktueller Profilbereich, Richtlinie, Aktivität "
"sowie Sichtbarkeit für Mandant, Person, Gruppe oder Campaign erneut geprüft. Postfachaktualisierungen veröffentlichen "
"dauerhafte Indexänderungen; für die Abstimmung bleibt ein vollständiger Neuaufbau verfügbar."
),
}
},
order=39, order=39,
), ),
DocumentationTopic( DocumentationTopic(
id="mail.profiles-and-policy", id="mail.profiles-and-policy",
title="Mail profiles and policy hierarchy", title="Mail profiles and policy hierarchy",
summary="Mail sending is configured through reusable SMTP/IMAP profiles and an effective policy assembled from system, tenant, owner, and campaign scope where applicable.", summary="Mail sending and mailbox access use reusable SMTP/IMAP/JMAP profiles governed by an effective system, tenant, owner, and campaign policy.",
body="The active policy decides whether users can only choose approved profiles or whether user, group, and campaign scopes may define additional reusable profiles. Runtime documentation adds the current tenant posture when the actor may read mail profile policy.", body="The active policy decides whether users can only choose approved profiles or whether user, group, and campaign scopes may define additional reusable profiles. SMTP, IMAP, and JMAP host allow/deny rules are inherited independently. JMAP Session discovery fails closed when its advertised API origin differs unless an administrator explicitly allows that origin. Runtime documentation adds the current tenant posture when the actor may read mail profile policy.",
layer="configured", layer="configured",
documentation_types=("admin",), documentation_types=("admin",),
audience=("tenant_admin", "mail_admin", "campaign_admin"), audience=("tenant_admin", "mail_admin", "campaign_admin"),
@@ -883,6 +1032,19 @@ manifest = ModuleManifest(
related_modules=("campaigns",), related_modules=("campaigns",),
unlocks=("Campaign-local delivery rules become visible when govoplan-campaign is installed.",), unlocks=("Campaign-local delivery rules become visible when govoplan-campaign is installed.",),
configuration_keys=("mail_profile_policy",), configuration_keys=("mail_profile_policy",),
translations={
"de": {
"title": "Mail-Profile und Richtlinienhierarchie",
"summary": "Mail-Versand und Postfachzugriff über wiederverwendbare SMTP-/IMAP-/JMAP-Profile und eine wirksame Richtlinie aus System-, Mandanten-, Eigentümer- und gegebenenfalls Campaign-Ebene steuern.",
"body": (
"Die wirksame Richtlinie entscheidet, ob Personen ausschließlich freigegebene Profile auswählen dürfen "
"oder ob auf Personen-, Gruppen- und Campaign-Ebene zusätzliche wiederverwendbare Profile angelegt werden können. "
"Host-Freigaben und -Sperren für SMTP, IMAP und JMAP werden unabhängig vererbt. Ein von der JMAP-Session "
"angekündigter API-Ursprung muss bei abweichendem Ursprung ausdrücklich freigegeben sein. "
"Die Laufzeitdokumentation ergänzt die aktuelle Lage des Mandanten, wenn die handelnde Person die Mail-Profilrichtlinie lesen darf."
),
}
},
metadata={ metadata={
"kind": "reference", "kind": "reference",
"route": "/settings?section=mail-profiles", "route": "/settings?section=mail-profiles",
@@ -918,6 +1080,21 @@ manifest = ModuleManifest(
DocumentationLink(label="Mail handbook", href="govoplan-mail/docs/MAIL_HANDBOOK.md", kind="repository"), DocumentationLink(label="Mail handbook", href="govoplan-mail/docs/MAIL_HANDBOOK.md", kind="repository"),
), ),
related_modules=("campaigns",), related_modules=("campaigns",),
translations={
"de": {
"title": "Standardordner eines IMAP-Profils zuordnen",
"summary": "Zuordnungen für Posteingang, Gesendet, Entwürfe, Papierkorb, Archiv und Junk am wiederverwendbaren Mail-Profil speichern und durch begrenzte IMAP-Erkennung vorbelegen.",
"body": (
"Ordnernamen sind Metadaten des Profils beziehungsweise Servers und keine Campaign-Einstellungen. Eine berechtigte "
"Profiladministration kann Namen direkt eintragen oder die Ordnererkennung verwenden; leere Zuordnungen behalten "
"das automatische Verhalten bei. Vorhandene Werte aus imap.sent_folder werden als Zuordnung für Gesendet angezeigt "
"und gespeichert, während das Kompatibilitätsfeld für ältere Verbraucher synchron bleibt. Eine Campaign-spezifische "
"Abweichung für den Gesendet-Ordner bleibt für diese Campaign maßgeblich und wird von der Profilerkennung nicht verändert. "
"Die Erkennung listet nur die beim Anbieter sichtbaren Namen auf und legt keine externen Ordner an, benennt sie nicht um, "
"verschiebt sie nicht und löscht sie nicht."
),
}
},
metadata={ metadata={
"kind": "workflow", "kind": "workflow",
"route": "/settings?section=mail-profiles", "route": "/settings?section=mail-profiles",
@@ -958,6 +1135,20 @@ manifest = ModuleManifest(
), ),
), ),
related_modules=("campaigns", "calendar", "audit"), related_modules=("campaigns", "calendar", "audit"),
translations={
"de": {
"title": "Zustellstatus und Rückläufer verarbeiten",
"summary": "Einen berechtigten IMAP-Ordner beobachten und DSN-Ergebnisse mit dauerhaften Mail-Befehlen abgleichen.",
"body": (
"Mail speichert die ausgehende RFC-Message-ID zusammen mit dem dauerhaften Befehl, verarbeitet begrenzte "
"message/delivery-status-Berichte ohne Postfachkennzeichen zu ändern und zeichnet je Empfänger idempotente "
"Beobachtungen auf. Die SMTP-Annahme bleibt von einem späteren Rückläufer getrennt. Nicht zuordenbare Berichte "
"bleiben zur Prüfung sichtbar; Mail speichert nur begrenzte Diagnosen und einen Digest des Rohinhalts, nicht den "
"Rohtext des Rückläufers. Ist Calendar aktiv, leitet derselbe begrenzte Quellscan iCalendar-Teile mit METHOD:REPLY "
"zur idempotenten Abstimmung der Teilnehmenden an Calendar weiter, ohne die Nachricht als Rückläufer einzuordnen."
),
}
},
metadata={ metadata={
"kind": "workflow", "kind": "workflow",
"route": "/mail/bounces", "route": "/mail/bounces",
@@ -996,6 +1187,21 @@ manifest = ModuleManifest(
), ),
related_modules=("campaigns", "access"), related_modules=("campaigns", "access"),
unlocks=("Reusable, governed delivery identities without cross-module secret duplication.",), unlocks=("Reusable, governed delivery identities without cross-module secret duplication.",),
translations={
"de": {
"title": "Mail besitzt Transportprofile und Zugangsdaten",
"summary": "Andere Module wählen berechtigte Mail-Profile über stabile Kennungen aus; sie kopieren weder SMTP-/IMAP-Einstellungen noch Geheimnisse.",
"body": (
"Mail verschlüsselt Zugangsdaten, prüft Verbindungen, bewertet Profilbereich und Richtlinie und führt "
"revisionsgebundene Transportwirkungen aus, ohne die aufgelöste Konfiguration zurückzugeben. Zufällige gespeicherte "
"Revisionen wechseln, wenn sich normalisierte Transportdaten oder die Kontoidentität ändern; eine reine "
"Passwortrotation bleibt für bereits aufgebauten fachlichen Willen transparent. Campaign speichert nur "
"server.mail_profile_id und bereinigte Zustellnachweise. Campaign-lokale Transportfelder werden abgelehnt; "
"ältere Campaign-Datensätze bleiben gesperrt, bis eine ausdrückliche Profilmigration den ursprünglichen "
"Auditdatensatz bewahrt und eine bearbeitbare Version aktualisiert."
),
}
},
metadata={ metadata={
"kind": "reference", "kind": "reference",
"route": "/settings?section=mail-profiles", "route": "/settings?section=mail-profiles",
@@ -1012,7 +1218,7 @@ manifest = ModuleManifest(
DocumentationTopic( DocumentationTopic(
id="mail.workflow.choose-and-test-profile", id="mail.workflow.choose-and-test-profile",
title="Choose and test a reusable Mail profile", title="Choose and test a reusable Mail profile",
summary="Select a profile visible in the current context, test its SMTP or IMAP connection, and let the consuming task store only its stable reference.", summary="Select a profile visible in the current context, test its SMTP, IMAP, or JMAP connection, and let the consuming task store only its stable reference.",
body="Profile tests verify current connection and authentication using Mail-owned credentials. They do not prove later Campaign policy authorization, deliverability, recipient acceptance, or future availability. Use the picker rather than entering identifiers or copying transport settings into another module.", body="Profile tests verify current connection and authentication using Mail-owned credentials. They do not prove later Campaign policy authorization, deliverability, recipient acceptance, or future availability. Use the picker rather than entering identifiers or copying transport settings into another module.",
layer="configured", layer="configured",
documentation_types=("user",), documentation_types=("user",),
@@ -1029,7 +1235,18 @@ manifest = ModuleManifest(
DocumentationLink(label="Mail handbook", href="govoplan-mail/docs/MAIL_HANDBOOK.md", kind="repository"), DocumentationLink(label="Mail handbook", href="govoplan-mail/docs/MAIL_HANDBOOK.md", kind="repository"),
), ),
related_modules=("campaigns",), related_modules=("campaigns",),
unlocks=("Reusable SMTP/IMAP identities that consumers can reference without handling credentials.",), unlocks=("Reusable SMTP/IMAP/JMAP identities that consumers can reference without handling credentials.",),
translations={
"de": {
"title": "Ein wiederverwendbares Mail-Profil auswählen und prüfen",
"summary": "Ein im aktuellen Kontext sichtbares Profil auswählen, seine SMTP-, IMAP- oder JMAP-Verbindung prüfen und im verbrauchenden Vorgang nur den stabilen Verweis speichern.",
"body": (
"Profiltests prüfen die aktuelle Verbindung und Anmeldung mit den von Mail verwalteten Zugangsdaten. Sie belegen "
"weder eine spätere Richtlinienfreigabe in Campaign noch Zustellbarkeit, Empfängerannahme oder künftige Verfügbarkeit. "
"Verwenden Sie die Auswahlkomponente, statt Kennungen einzugeben oder Transporteinstellungen in ein anderes Modul zu kopieren."
),
}
},
metadata={ metadata={
"kind": "workflow", "kind": "workflow",
"route": "/settings?section=mail-profiles", "route": "/settings?section=mail-profiles",
@@ -1041,8 +1258,8 @@ manifest = ModuleManifest(
], ],
"steps": [ "steps": [
"Open Mail profiles and choose a visible active profile.", "Open Mail profiles and choose a visible active profile.",
"Review its safe scope, SMTP/IMAP availability, and sender identity without expecting credential values.", "Review its safe scope, SMTP/IMAP/JMAP availability, and sender identity without expecting credential values.",
"Run the relevant SMTP or IMAP connectivity/authentication test against a non-production target first.", "Run the relevant SMTP, IMAP, or JMAP connectivity/authentication test against a non-production target first.",
"Return to the consuming task and select the same profile through its picker.", "Return to the consuming task and select the same profile through its picker.",
], ],
"outcome": "The consuming task references an available Mail-owned profile and contains no copied transport configuration or credentials.", "outcome": "The consuming task references an available Mail-owned profile and contains no copied transport configuration or credentials.",
@@ -1056,8 +1273,8 @@ manifest = ModuleManifest(
DocumentationTopic( DocumentationTopic(
id="mail.workflow.read-mailbox", id="mail.workflow.read-mailbox",
title="Read a permitted mailbox without changing it", title="Read a permitted mailbox without changing it",
summary="Choose an IMAP-enabled profile, browse synchronized folders, and inspect bounded message content through the read-only mailbox surface.", summary="Choose an IMAP- or JMAP-enabled profile, browse folders, search or page messages, and inspect bounded content through the read-only mailbox surface.",
body="Mailbox access requires both mailbox-read and profile-use authority for a profile visible in the actor's scope. Lists expose provider read/unread flags and live/cache/refresh provenance without mutating them. Message HTML is isolated and sanitized, while attachments, inline references, unavailable content, and provider failures remain explicit. Listing folders or messages must not mark mail read, move it, delete it, or expose unbounded content.", body="Mailbox access requires both mailbox-read and profile-use authority for a profile visible in the actor's scope. IMAP retains its existing bounded list behavior. JMAP adds capability discovery, server-side text search, query-state cursors, and bounded Email/changes synchronization; an expired state explicitly requires a full refresh. Lists expose provider read/unread flags and provenance without mutating them. Message HTML is isolated and sanitized, while attachment metadata, unavailable content, and provider failures remain explicit. Listing folders or messages must not mark mail read, move it, delete it, or expose unbounded content.",
layer="configured", layer="configured",
documentation_types=("user",), documentation_types=("user",),
audience=("mail_user",), audience=("mail_user",),
@@ -1073,18 +1290,33 @@ manifest = ModuleManifest(
DocumentationLink(label="Mail handbook", href="govoplan-mail/docs/MAIL_HANDBOOK.md", kind="repository"), DocumentationLink(label="Mail handbook", href="govoplan-mail/docs/MAIL_HANDBOOK.md", kind="repository"),
), ),
unlocks=("Read-only access to an authorized operational mailbox without broadening profile administration rights.",), unlocks=("Read-only access to an authorized operational mailbox without broadening profile administration rights.",),
translations={
"de": {
"title": "Ein berechtigtes Postfach ohne Änderungen lesen",
"summary": "Ein IMAP- oder JMAP-fähiges Profil auswählen, Ordner durchsuchen und begrenzte Nachrichteninhalte in der nur lesbaren Postfachoberfläche prüfen.",
"body": (
"Der Postfachzugriff erfordert sowohl Leseberechtigung für das Postfach als auch Nutzungsberechtigung für ein "
"im Bereich der handelnden Person sichtbares Profil. IMAP behält sein bisheriges Verhalten; JMAP ergänzt "
"serverseitige Suche, zustandsgebundene Seitennavigation und begrenzte inkrementelle Änderungen. Listen zeigen die vom Anbieter gelieferten Gelesen-/Ungelesen-Kennzeichen "
"und die Herkunft aus Livezugriff, Zwischenspeicher oder Aktualisierung, ohne diese Zustände zu verändern. HTML-Inhalte "
"werden isoliert und bereinigt; Anlagen, Inline-Verweise, nicht verfügbare Inhalte und Providerfehler bleiben ausdrücklich sichtbar. "
"Das Auflisten von Ordnern oder Nachrichten darf keine Nachricht als gelesen markieren, verschieben oder löschen und keine "
"unbegrenzten Inhalte offenlegen."
),
}
},
metadata={ metadata={
"kind": "workflow", "kind": "workflow",
"route": "/mail", "route": "/mail",
"screen": "Mail", "screen": "Mail",
"help_contexts": ["mail.list", "mail.mailbox"], "help_contexts": ["mail.list", "mail.mailbox"],
"prerequisites": [ "prerequisites": [
"An active visible profile has IMAP configured.", "An active visible profile has IMAP or JMAP configured.",
"You may both use that profile and read its mailbox.", "You may both use that profile and read its mailbox.",
], ],
"steps": [ "steps": [
"Open Mail and choose an authorized IMAP-enabled profile.", "Open Mail and choose an authorized IMAP- or JMAP-enabled profile.",
"Select a folder, review the live/cached synchronization label, and page or filter its bounded message index.", "Select a folder, review the live/cached synchronization label, and page its bounded message index; JMAP searches run at the provider.",
"Use the provider-derived read/unread indicator, then open only the message needed for the task.", "Use the provider-derived read/unread indicator, then open only the message needed for the task.",
"Switch between safe plain-text and isolated HTML views as needed, and review attachment or unavailable-content details before closing the preview.", "Switch between safe plain-text and isolated HTML views as needed, and review attachment or unavailable-content details before closing the preview.",
], ],
@@ -1099,8 +1331,8 @@ manifest = ModuleManifest(
DocumentationTopic( DocumentationTopic(
id="mail.reference.credentials-egress-retirement", id="mail.reference.credentials-egress-retirement",
title="Protect Mail credentials, network egress, and retirement", title="Protect Mail credentials, network egress, and retirement",
summary="Keep secrets Mail-owned, pin every SMTP/IMAP/POP3 peer, bound responses, and delete owned credentials immediately with non-secret audit evidence.", summary="Keep secrets Mail-owned, govern every SMTP/IMAP/JMAP/POP3 peer, bound responses, and delete owned credentials immediately with non-secret audit evidence.",
body="Private-network connector access is deployment-wide, but every allowed hostname still resolves to an approved peer that is pinned at socket creation. Unsupported transports fail before connection. Deleting a profile immediately scrubs its owned encrypted SMTP/IMAP/POP3 passwords and records non-secret audit when secrets existed; a scrub or audit failure rolls the action back. Encrypted POP3 import content follows Mail/records retention. Destructive module retirement applies the same secret-scrub rule before all Mail tables, including imports, are dropped.", body="Private-network connector access is deployment-wide, but every allowed hostname still resolves to an approved peer that is pinned at socket creation. JMAP applies the same egress controls to its Session and advertised API URL, permits cross-origin APIs only through an explicit endpoint allow-list, and bounds complete responses and body values. Unsupported capabilities fail before mailbox data is returned. Deleting a profile immediately scrubs its owned encrypted SMTP/IMAP/JMAP/POP3 secrets and records non-secret audit when secrets existed; a scrub or audit failure rolls the action back. Encrypted POP3 import content follows Mail/records retention. Destructive module retirement applies the same secret-scrub rule before all Mail tables, including imports, are dropped.",
layer="evidence", layer="evidence",
documentation_types=("admin",), documentation_types=("admin",),
audience=("mail_admin", "platform_operator", "security_reviewer", "release_reviewer"), audience=("mail_admin", "platform_operator", "security_reviewer", "release_reviewer"),
@@ -1117,6 +1349,22 @@ manifest = ModuleManifest(
), ),
related_modules=("audit",), related_modules=("audit",),
unlocks=("A testable Mail trust boundary with fail-closed egress and auditable secret disposal.",), unlocks=("A testable Mail trust boundary with fail-closed egress and auditable secret disposal.",),
translations={
"de": {
"title": "Mail-Zugangsdaten, Netzausgänge und Außerbetriebnahme schützen",
"summary": "Geheimnisse in Mail belassen, jeden SMTP-/IMAP-/JMAP-/POP3-Gegenpunkt steuern, Antworten begrenzen und eigene Zugangsdaten sofort mit nicht geheimem Auditnachweis löschen.",
"body": (
"Der Zugriff von Konnektoren auf private Netze wird bereitstellungsweit gesteuert; dennoch wird jeder erlaubte "
"Hostname in einen freigegebenen Gegenpunkt aufgelöst und beim Aufbau des Sockets fest gebunden. Nicht unterstützte "
"Transporte scheitern vor dem Verbindungsaufbau. Für JMAP gelten dieselben Netzausgangsregeln; abweichende API-Ursprünge "
"müssen ausdrücklich freigegeben sein und Antworten sowie Inhalte sind begrenzt. Beim Löschen eines Profils werden dessen verschlüsselte SMTP-, IMAP-, JMAP- "
"und POP3-Geheimnisse sofort entfernt und, sofern Geheimnisse vorhanden waren, mit nicht geheimen Angaben protokolliert. "
"Scheitert das Entfernen oder das Audit, wird die Aktion zurückgerollt. Verschlüsselte POP3-Importinhalte folgen der "
"Aufbewahrung von Mail beziehungsweise Records. Bei einer destruktiven Modulaußerbetriebnahme gilt dieselbe Regel: "
"Zuerst werden Geheimnisse entfernt, erst danach alle Mail-Tabellen einschließlich der Importdaten gelöscht."
),
}
},
metadata={ metadata={
"kind": "reference", "kind": "reference",
"route": "/settings?section=mail-profiles", "route": "/settings?section=mail-profiles",
@@ -1152,6 +1400,27 @@ manifest = ModuleManifest(
), ),
related_modules=("campaigns", "audit"), related_modules=("campaigns", "audit"),
unlocks=("Profile-backed campaign delivery without cross-module credential or configuration copies.",), unlocks=("Profile-backed campaign delivery without cross-module credential or configuration copies.",),
translations={
"de": {
"title": "Campaign über den Mail-Zustellvertrag integrieren",
"summary": "Campaign friert Profilverweis und undurchsichtige Revision ein; Mail berechtigt erneut, prüft die Revision, löst Zugangsdaten auf und führt die Wirkung in einem Aufruf aus.",
"body": (
"Der Vertrag mail.campaign_delivery 0.2 gibt niemals entschlüsselte Zugangsdaten oder aufgelöste SMTP-/IMAP-Konfiguration zurück. "
"Mail vergleicht die erwartete zufällige Transportrevision vor dem Entschlüsseln protokollspezifischer Zugangsdaten und liefert "
"nur begrenzte, bereinigte Ergebnisse. Synchrone Stapel berechtigen die vollständige Empfängermenge und prüfen DNS, Netzausgang, "
"Verbindung, TLS und Anmeldung vor der ersten Wirkung. Wenn die Bereitstellungsrichtlinie es erlaubt, verwendet Mail die begrenzte "
"Verbindung erneut, prüft sie zuvor und verbindet vor der nächsten Nachricht neu, sobald sie veraltet ist. Ein Verbindungsverlust nach "
"Beginn von DATA bleibt mit unbekanntem Ergebnis bestehen und wird niemals automatisch wiederholt. Systemische Anmelde-, Absender- oder "
"Verbindungsfehler tragen stabile Ursachencodes, damit Campaign verbleibende Aufträge anhält und Verbindung, Neuverbindung, Fehler und "
"Pausenfortschritt anzeigt. Campaign besitzt gewöhnliche Empfängeraufträge; Berichtsnachrichten nutzen das verschlüsselte, idempotente "
"Zustellbefehls- und Versuchsledger von Mail. Jeder aktuelle SMTP- und Gesendet-Ordner-Versuch übergibt vor dem Providerkontakt eine "
"stabile Wirkungskennung an einen von Mail besessenen Core-Wiederherstellungsvorgang. Der Nachweis des Wirkungsbeginns verhindert blinde "
"Wiederzustellung; unbekannte Ergebnisse erfordern ausdrückliche Abstimmung, und rohe Empfängerablehnungen erfordern Mail-Diagnoseberechtigung. "
"Mail-Ausgangsverarbeitung und Aufbewahrungsläufe werden nach Mandantenberechtigung partitioniert. Das Deaktivieren von Mail lässt bereits "
"angenommene Befehle und Nachweise daher zur Klärung durch den Betrieb unverändert bestehen."
),
}
},
metadata={ metadata={
"kind": "reference", "kind": "reference",
"route": "/campaigns/{campaign_id}/mail-settings", "route": "/campaigns/{campaign_id}/mail-settings",
@@ -1173,7 +1442,7 @@ manifest = ModuleManifest(
resolve=documentation_configuration_states, resolve=documentation_configuration_states,
), ),
), ),
external_providers=(SMTP_PROVIDER, IMAP_PROVIDER, POP3_PROVIDER), external_providers=(SMTP_PROVIDER, IMAP_PROVIDER, JMAP_PROVIDER, POP3_PROVIDER),
external_provider_state_providers=( external_provider_state_providers=(
ExternalProviderStateProviderRegistration( ExternalProviderStateProviderRegistration(
module_id="mail", module_id="mail",
@@ -1185,6 +1454,11 @@ manifest = ModuleManifest(
provider_id=IMAP_PROVIDER_ID, provider_id=IMAP_PROVIDER_ID,
provider=imap_provider_states, provider=imap_provider_states,
), ),
ExternalProviderStateProviderRegistration(
module_id="mail",
provider_id=JMAP_PROVIDER_ID,
provider=jmap_provider_states,
),
ExternalProviderStateProviderRegistration( ExternalProviderStateProviderRegistration(
module_id="mail", module_id="mail",
provider_id=POP3_PROVIDER_ID, provider_id=POP3_PROVIDER_ID,
@@ -1197,7 +1471,7 @@ manifest = ModuleManifest(
maturity="vertical_slice", maturity="vertical_slice",
documentation_ref="docs/MAIL_HANDBOOK.md", documentation_ref="docs/MAIL_HANDBOOK.md",
test_ref="tests/test_delivery_outbox.py", test_ref="tests/test_delivery_outbox.py",
known_limits=("A complete webmail profile and recovery adoption for future provider-side mailbox mutations are not reference-ready; POP3 is supported only as an explicitly enabled, bounded legacy-import path and has no folder or flag semantics.",), known_limits=("Mailbox access is deliberately read-only. JMAP currently covers Mailbox/get, Email/query, Email/get, and Email/changes only; provider-side mutations, threads, calendars, contacts, and JMAP submission are not implemented. POP3 is supported only as an explicitly enabled, bounded legacy-import path and has no folder or flag semantics.",),
supported_authority_modes=( supported_authority_modes=(
"external_authoritative", "external_authoritative",
"external_mirror", "external_mirror",
@@ -1205,7 +1479,7 @@ manifest = ModuleManifest(
), ),
owned_concepts=("mail profile", "mail delivery command", "delivery attempt", "mailbox projection", "governed POP3 import"), owned_concepts=("mail profile", "mail delivery command", "delivery attempt", "mailbox projection", "governed POP3 import"),
non_owned_concepts=("campaign", "notification", "recipient address directory", "external mailbox"), non_owned_concepts=("campaign", "notification", "recipient address directory", "external mailbox"),
target_tested_providers=(SMTP_PROVIDER_ID, IMAP_PROVIDER_ID, POP3_PROVIDER_ID), target_tested_providers=(SMTP_PROVIDER_ID, IMAP_PROVIDER_ID, JMAP_PROVIDER_ID, POP3_PROVIDER_ID),
recovery_docs=("docs/MAIL_HANDBOOK.md",), recovery_docs=("docs/MAIL_HANDBOOK.md",),
security_docs=("docs/MAIL_HANDBOOK.md",), security_docs=("docs/MAIL_HANDBOOK.md",),
operations_docs=("docs/MAIL_HANDBOOK.md",), operations_docs=("docs/MAIL_HANDBOOK.md",),
@@ -1213,5 +1487,10 @@ manifest = ModuleManifest(
) )
manifest = with_documentation_structured_translations(
manifest, locale="de", translations=GERMAN_STRUCTURED_TRANSLATIONS
)
def get_manifest() -> ModuleManifest: def get_manifest() -> ModuleManifest:
return manifest return manifest
+33 -8
View File
@@ -24,6 +24,7 @@ from govoplan_mail.backend.db.models import (
SMTP_PROVIDER_ID = "mail.smtp_delivery" SMTP_PROVIDER_ID = "mail.smtp_delivery"
IMAP_PROVIDER_ID = "mail.imap_mailbox" IMAP_PROVIDER_ID = "mail.imap_mailbox"
JMAP_PROVIDER_ID = "mail.jmap_mailbox"
POP3_PROVIDER_ID = "mail.pop3_legacy_import" POP3_PROVIDER_ID = "mail.pop3_legacy_import"
_CURRENT_INDEX_WINDOW = timedelta(minutes=30) _CURRENT_INDEX_WINDOW = timedelta(minutes=30)
@@ -40,6 +41,12 @@ def imap_provider_states(
return _mail_provider_states(context, protocol="imap") return _mail_provider_states(context, protocol="imap")
def jmap_provider_states(
context: ExternalProviderStateContext,
) -> tuple[ExternalProviderRuntimeState, ...]:
return _mail_provider_states(context, protocol="jmap")
def pop3_provider_states( def pop3_provider_states(
context: ExternalProviderStateContext, context: ExternalProviderStateContext,
) -> tuple[ExternalProviderRuntimeState, ...]: ) -> tuple[ExternalProviderRuntimeState, ...]:
@@ -106,15 +113,28 @@ def _mail_provider_states(
) )
metrics = _imap_metrics(context.session, profile_ids=profile_ids) metrics = _imap_metrics(context.session, profile_ids=profile_ids)
if protocol == "jmap":
metrics = {
profile_id: {
key: value
for key, value in values.items()
if key in {"indexed_folders", "indexed_messages", "last_indexed_at"}
}
for profile_id, values in metrics.items()
}
provider_id = JMAP_PROVIDER_ID if protocol == "jmap" else IMAP_PROVIDER_ID
return tuple( return tuple(
_imap_state( _imap_state(
profile, profile,
endpoints=endpoints_by_profile.get(profile.id, []), endpoints=endpoints_by_profile.get(profile.id, []),
metrics=metrics.get(profile.id, {}), metrics=metrics.get(profile.id, {}),
observed_at=observed_at, observed_at=observed_at,
protocol=protocol,
provider_id=provider_id,
) )
for profile in profiles for profile in profiles
if endpoints_by_profile.get(profile.id) or _legacy_configured(profile, "imap") if endpoints_by_profile.get(profile.id)
or (protocol == "imap" and _legacy_configured(profile, "imap"))
) )
@@ -327,10 +347,13 @@ def _imap_state(
endpoints: list[MailServerEndpoint], endpoints: list[MailServerEndpoint],
metrics: dict[str, Any], metrics: dict[str, Any],
observed_at: datetime, observed_at: datetime,
protocol: str = "imap",
provider_id: str = IMAP_PROVIDER_ID,
) -> ExternalProviderRuntimeState: ) -> ExternalProviderRuntimeState:
protocol_label = protocol.upper()
active = bool(profile.is_active) and ( active = bool(profile.is_active) and (
any(item.is_active for item in endpoints) any(item.is_active for item in endpoints)
or (not endpoints and _legacy_configured(profile, "imap")) or (protocol == "imap" and not endpoints and _legacy_configured(profile, "imap"))
) )
indexed_at = _aware(metrics.get("last_indexed_at")) indexed_at = _aware(metrics.get("last_indexed_at"))
errors = int(metrics.get("bounce_source_errors", 0)) errors = int(metrics.get("bounce_source_errors", 0))
@@ -353,8 +376,8 @@ def _imap_state(
else "unknown" else "unknown"
) )
return ExternalProviderRuntimeState( return ExternalProviderRuntimeState(
provider_id=IMAP_PROVIDER_ID, provider_id=provider_id,
binding_ref=f"mail:profile:{profile.id}:imap", binding_ref=f"mail:profile:{profile.id}:{protocol}",
authority_mode="external_mirror", authority_mode="external_mirror",
observed_at=observed_at, observed_at=observed_at,
configured=True, configured=True,
@@ -371,13 +394,13 @@ def _imap_state(
), ),
last_success_at=indexed_at or _aware(metrics.get("last_bounce_success_at")), last_success_at=indexed_at or _aware(metrics.get("last_bounce_success_at")),
detail=( detail=(
"IMAP mailbox access is disabled." f"{protocol_label} mailbox access is disabled."
if not active if not active
else "IMAP mailbox or bounce-source errors require attention." else f"{protocol_label} mailbox or bounce-source errors require attention."
if errors if errors
else "IMAP mailbox state has not been indexed yet." else f"{protocol_label} mailbox state has not been indexed yet."
if indexed_at is None if indexed_at is None
else "IMAP mailbox index state is available." else f"{protocol_label} mailbox index state is available."
), ),
metrics={ metrics={
"indexed_folders": int(metrics.get("indexed_folders", 0)), "indexed_folders": int(metrics.get("indexed_folders", 0)),
@@ -469,9 +492,11 @@ def _aware(value: object | None) -> datetime | None:
__all__ = [ __all__ = [
"IMAP_PROVIDER_ID", "IMAP_PROVIDER_ID",
"JMAP_PROVIDER_ID",
"POP3_PROVIDER_ID", "POP3_PROVIDER_ID",
"SMTP_PROVIDER_ID", "SMTP_PROVIDER_ID",
"imap_provider_states", "imap_provider_states",
"jmap_provider_states",
"pop3_provider_states", "pop3_provider_states",
"smtp_provider_states", "smtp_provider_states",
] ]
+482 -3
View File
@@ -35,6 +35,7 @@ from govoplan_mail.backend.schemas import (
MailDeliveryReconcileRequest, MailDeliveryReconcileRequest,
MailDeliveryResendRequest, MailDeliveryResendRequest,
MailMailboxBootstrapResponse, MailMailboxBootstrapResponse,
MailMailboxChangesResponse,
MailImapTestRequest, MailImapTestRequest,
MailMailboxAttachmentResponse, MailMailboxAttachmentResponse,
MailMailboxMessageDetailResponse, MailMailboxMessageDetailResponse,
@@ -81,6 +82,7 @@ from govoplan_mail.backend.mailbox_index import (
) )
from govoplan_mail.backend.mail_profiles import ( from govoplan_mail.backend.mail_profiles import (
MailProfileError, MailProfileError,
assert_mail_policy_allows_transport,
campaign_mail_owner_context, campaign_mail_owner_context,
campaign_mail_context_visible_to_actor, campaign_mail_context_visible_to_actor,
create_mail_server_profile, create_mail_server_profile,
@@ -99,7 +101,7 @@ from govoplan_mail.backend.mail_profiles import (
smtp_config_from_profile, smtp_config_from_profile,
update_mail_server_profile, update_mail_server_profile,
) )
from govoplan_mail.backend.config import ImapConfig, Pop3Config, SmtpConfig from govoplan_mail.backend.config import ImapConfig, JmapConfig, Pop3Config, SmtpConfig
from govoplan_mail.backend.db.models import MailPop3Import from govoplan_mail.backend.db.models import MailPop3Import
from govoplan_mail.backend.pop3_imports import ( from govoplan_mail.backend.pop3_imports import (
Pop3ImportError, Pop3ImportError,
@@ -154,6 +156,19 @@ from govoplan_mail.backend.server_hierarchy import (
update_mail_server_endpoint, update_mail_server_endpoint,
) )
from govoplan_mail.backend.sending.imap import ImapAppendError, ImapConfigurationError, get_imap_message, list_imap_folders, list_imap_messages, load_imap_mailbox_bootstrap, test_imap_login from govoplan_mail.backend.sending.imap import ImapAppendError, ImapConfigurationError, get_imap_message, list_imap_folders, list_imap_messages, load_imap_mailbox_bootstrap, test_imap_login
from govoplan_mail.backend.sending.jmap import (
JmapAuthenticationError,
JmapCapabilityError,
JmapConfigurationError,
JmapPermissionError,
JmapProviderError,
get_jmap_email_changes,
get_jmap_message,
list_jmap_folders,
list_jmap_messages,
load_jmap_mailbox_bootstrap,
test_jmap_connection,
)
from govoplan_mail.backend.sending.smtp import test_smtp_login from govoplan_mail.backend.sending.smtp import test_smtp_login
from govoplan_mail.backend.sending.pop3 import ( from govoplan_mail.backend.sending.pop3 import (
Pop3ConfigurationError, Pop3ConfigurationError,
@@ -175,6 +190,7 @@ MAIL_POLICY_RESOURCE = "mail_profile_policy"
MAIL_SERVER_RESOURCE = "mail_server" MAIL_SERVER_RESOURCE = "mail_server"
MAIL_CREDENTIAL_RESOURCE = "mail_credential" MAIL_CREDENTIAL_RESOURCE = "mail_credential"
MAILBOX_MESSAGES_CURSOR_SCOPE = "mail.mailbox.messages.v1" MAILBOX_MESSAGES_CURSOR_SCOPE = "mail.mailbox.messages.v1"
JMAP_MAILBOX_MESSAGES_CURSOR_SCOPE = "mail.mailbox.jmap.messages.v1"
DEFAULT_MAILBOX_MESSAGE_LIMIT = 50 DEFAULT_MAILBOX_MESSAGE_LIMIT = 50
CAPABILITY_ADDRESSES_LOOKUP = "addresses.lookup" CAPABILITY_ADDRESSES_LOOKUP = "addresses.lookup"
CAPABILITY_ADDRESSES_CONTACT_WRITER = "addresses.contact_writer" CAPABILITY_ADDRESSES_CONTACT_WRITER = "addresses.contact_writer"
@@ -1201,6 +1217,105 @@ def _next_mailbox_cursor(
) )
def _jmap_mailbox_cursor_fingerprint(
*,
tenant_id: str,
profile_id: str,
folder: str,
limit: int,
query: str,
) -> str:
return keyset_query_fingerprint(
JMAP_MAILBOX_MESSAGES_CURSOR_SCOPE,
{
"tenant_id": tenant_id,
"profile_id": profile_id,
"folder": folder,
"limit": limit,
"query": query,
"protocol": "jmap",
}
)
def _jmap_mailbox_cursor_position(
cursor: str | None,
*,
fingerprint: str,
offset: int,
) -> tuple[int, str | None]:
if not cursor:
return offset, None
try:
values = decode_keyset_cursor(
JMAP_MAILBOX_MESSAGES_CURSOR_SCOPE,
cursor,
fingerprint=fingerprint,
)
except KeysetCursorError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(exc),
) from exc
raw_offset = values.get("offset")
query_state = values.get("query_state")
if not isinstance(raw_offset, int) or raw_offset < 0:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid JMAP pagination cursor")
if not isinstance(query_state, str) or not query_state:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid JMAP pagination cursor")
return raw_offset, query_state
def _jmap_mailbox_cursor_limit(cursor: str | None, explicit_limit: int | None) -> int:
if explicit_limit is not None:
return explicit_limit
if not cursor:
return DEFAULT_MAILBOX_MESSAGE_LIMIT
try:
values = decode_keyset_cursor(JMAP_MAILBOX_MESSAGES_CURSOR_SCOPE, cursor)
except KeysetCursorError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
raw_limit = values.get("limit")
if not isinstance(raw_limit, int) or raw_limit < 1 or raw_limit > 100:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid JMAP pagination cursor")
return raw_limit
def _next_jmap_mailbox_cursor(
*,
tenant_id: str,
profile_id: str,
folder: str,
limit: int,
offset: int,
total_count: int,
query_state: str,
messages,
query: str,
) -> tuple[str | None, bool]:
next_offset = offset + len(messages)
if next_offset >= total_count or not messages:
return None, True
return (
encode_keyset_cursor(
JMAP_MAILBOX_MESSAGES_CURSOR_SCOPE,
fingerprint=_jmap_mailbox_cursor_fingerprint(
tenant_id=tenant_id,
profile_id=profile_id,
folder=folder,
limit=limit,
query=query,
),
values={
"offset": next_offset,
"limit": limit,
"query_state": query_state,
},
),
True,
)
def _mailbox_folder_response( def _mailbox_folder_response(
result, result,
*, *,
@@ -1209,12 +1324,14 @@ def _mailbox_folder_response(
indexed_at=None, indexed_at=None,
) -> MailImapFolderListResponse: ) -> MailImapFolderListResponse:
folders = [MailImapFolderResponse(name=item.name, flags=item.flags, message_count=item.message_count, unseen_count=item.unseen_count) for item in result.folders] folders = [MailImapFolderResponse(name=item.name, flags=item.flags, message_count=item.message_count, unseen_count=item.unseen_count) for item in result.folders]
protocol = getattr(result, "protocol", "imap")
return MailImapFolderListResponse( return MailImapFolderListResponse(
ok=True, ok=True,
protocol=protocol,
host=result.host, host=result.host,
port=result.port, port=result.port,
security=result.security, security=result.security,
message=f"Found {len(folders)} IMAP folder(s).", message=f"Found {len(folders)} {protocol.upper()} folder(s).",
folders=folders, folders=folders,
detected_sent_folder=result.detected_sent_folder, detected_sent_folder=result.detected_sent_folder,
detected_folder_mappings=getattr(result, "detected_folder_mappings", None) or {}, detected_folder_mappings=getattr(result, "detected_folder_mappings", None) or {},
@@ -1337,6 +1454,85 @@ def _imap_config_for_principal(
raise MailProfileError(str(exc)) from exc raise MailProfileError(str(exc)) from exc
def _jmap_config_for_principal(
session: Session,
*,
principal: ApiPrincipal,
profile_id: str,
server_id: str | None = None,
credential_id: str | None = None,
campaign_id: str | None = None,
) -> JmapConfig:
profile = _get_profile_for_principal(
session,
principal=principal,
profile_id=profile_id,
require_active=True,
)
try:
resolved = resolve_mail_transport(
session,
profile=profile,
protocol="jmap",
context=_transport_context_for_principal(
session,
principal=principal,
campaign_id=campaign_id,
),
server_id=server_id,
credential_id=credential_id,
)
except MailServerHierarchyError as exc:
raise MailProfileError(str(exc)) from exc
if not isinstance(resolved.config, JmapConfig):
raise MailProfileError("Mail-server profile has no JMAP configuration")
_assert_jmap_policy_allows_config(
session,
principal=principal,
profile=profile,
config=resolved.config,
campaign_id=campaign_id,
)
return resolved.config
def _assert_jmap_policy_allows_config(
session: Session,
*,
principal: ApiPrincipal,
profile,
config: JmapConfig | dict[str, Any],
campaign_id: str | None = None,
) -> None:
session_url = config.session_url if isinstance(config, JmapConfig) else config.get("session_url")
scope_type = profile.scope_type or "tenant"
scope_id = profile.scope_id
policy_context: dict[str, str | None] = {}
if campaign_id or scope_type == "campaign":
policy_context["campaign_id"] = campaign_id or scope_id
elif scope_type == "user":
policy_context["owner_user_id"] = scope_id
elif scope_type == "group":
policy_context["owner_group_id"] = scope_id
assert_mail_policy_allows_transport(
session,
tenant_id=principal.tenant_id,
smtp=None,
jmap={"session_url": session_url},
**policy_context,
)
def _require_mailbox_protocol(value: str) -> str:
clean = value.strip().casefold() if isinstance(value, str) else "imap"
if clean not in {"imap", "jmap"}:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
detail="Mailbox protocol must be imap or jmap",
)
return clean
def _parent_mail_profile_policy_payload(session: Session, *, tenant_id: str, scope_type: str, scope_id: str | None): def _parent_mail_profile_policy_payload(session: Session, *, tenant_id: str, scope_type: str, scope_id: str | None):
if scope_type == "system": if scope_type == "system":
return None return None
@@ -1625,6 +1821,13 @@ def create_profile_server(
principal=principal, principal=principal,
profile_id=profile_id, profile_id=profile_id,
) )
if payload.protocol == "jmap":
_assert_jmap_policy_allows_config(
session,
principal=principal,
profile=profile,
config=payload.config,
)
server = create_mail_server_endpoint( server = create_mail_server_endpoint(
session, session,
profile=profile, profile=profile,
@@ -1680,6 +1883,13 @@ def update_profile_server(
) )
if server.protocol == "pop3": if server.protocol == "pop3":
_require_scope(principal, "mail:pop3:manage") _require_scope(principal, "mail:pop3:manage")
if server.protocol == "jmap" and payload.config is not None:
_assert_jmap_policy_allows_config(
session,
principal=principal,
profile=profile,
config=payload.config,
)
update_mail_server_endpoint( update_mail_server_endpoint(
session, session,
server=server, server=server,
@@ -1706,7 +1916,7 @@ def update_profile_server(
profile=profile, profile=profile,
server=server, server=server,
) )
except MailServerHierarchyError as exc: except (MailProfileError, MailServerHierarchyError) as exc:
session.rollback() session.rollback()
raise HTTPException( raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
@@ -2696,6 +2906,73 @@ def test_profile_imap(
return MailConnectionTestResponse(ok=False, protocol="imap", message=_safe_error_message(exc), details={"error_type": exc.__class__.__name__}) return MailConnectionTestResponse(ok=False, protocol="imap", message=_safe_error_message(exc), details={"error_type": exc.__class__.__name__})
@router.post("/profiles/{profile_id}/test-jmap", response_model=MailConnectionTestResponse)
def test_profile_jmap(
profile_id: str,
server_id: str | None = Query(default=None),
credential_id: str | None = Query(default=None),
campaign_id: str | None = Query(default=None),
principal: ApiPrincipal = Depends(get_api_principal),
session: Session = Depends(get_session),
):
_require_scope(principal, "mail:profile:test")
_require_scope(principal, "mail:profile:use")
try:
jmap = _jmap_config_for_principal(
session,
principal=principal,
profile_id=profile_id,
server_id=server_id,
credential_id=credential_id,
campaign_id=campaign_id,
)
result = test_jmap_connection(jmap_config=jmap)
return MailConnectionTestResponse(
ok=True,
protocol="jmap",
host=result.host,
port=result.port,
security=result.security,
message="JMAP connection successful.",
details={
"authenticated": result.authenticated,
"account_id": result.account_id,
"session_state": result.session_state,
"capabilities": list(result.capabilities),
},
)
except MailProfileError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except (JmapConfigurationError, JmapCapabilityError) as exc:
return MailConnectionTestResponse(
ok=False,
protocol="jmap",
message=str(exc),
details={"error_type": exc.__class__.__name__},
)
except JmapAuthenticationError as exc:
return MailConnectionTestResponse(
ok=False,
protocol="jmap",
message=str(exc),
details={"error_type": "authentication"},
)
except JmapPermissionError as exc:
return MailConnectionTestResponse(
ok=False,
protocol="jmap",
message=str(exc),
details={"error_type": "permission"},
)
except JmapProviderError as exc:
return MailConnectionTestResponse(
ok=False,
protocol="jmap",
message=str(exc),
details={"error_type": "transient_provider"},
)
def _resolve_profile_pop3_transport( def _resolve_profile_pop3_transport(
session: Session, session: Session,
*, *,
@@ -3097,11 +3374,22 @@ def list_profile_mailbox_folders(
profile_id: str, profile_id: str,
include_status: bool = Query(default=False), include_status: bool = Query(default=False),
refresh: bool = False, refresh: bool = False,
protocol: str = Query(default="imap"),
principal: ApiPrincipal = Depends(get_api_principal), principal: ApiPrincipal = Depends(get_api_principal),
session: Session = Depends(get_session), session: Session = Depends(get_session),
): ):
_require_mailbox_read_scope(principal) _require_mailbox_read_scope(principal)
mailbox_protocol = _require_mailbox_protocol(protocol)
try: try:
if mailbox_protocol == "jmap":
jmap = _jmap_config_for_principal(
session,
principal=principal,
profile_id=profile_id,
)
return _mailbox_folder_response(
list_jmap_folders(jmap_config=jmap)
)
imap = _imap_config_for_principal(session, principal=principal, profile_id=profile_id) imap = _imap_config_for_principal(session, principal=principal, profile_id=profile_id)
if not include_status and not refresh: if not include_status and not refresh:
cached = cached_mailbox_folders(session, tenant_id=principal.tenant_id, profile_id=profile_id) cached = cached_mailbox_folders(session, tenant_id=principal.tenant_id, profile_id=profile_id)
@@ -3144,6 +3432,12 @@ def list_profile_mailbox_folders(
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(exc)) from exc raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(exc)) from exc
except ImapAppendError as exc: except ImapAppendError as exc:
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc
except (JmapConfigurationError, JmapCapabilityError) as exc:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(exc)) from exc
except (JmapAuthenticationError, JmapPermissionError) as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
except JmapProviderError as exc:
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc
@router.get("/profiles/{profile_id}/mailbox/bootstrap", response_model=MailMailboxBootstrapResponse) @router.get("/profiles/{profile_id}/mailbox/bootstrap", response_model=MailMailboxBootstrapResponse)
@@ -3154,11 +3448,56 @@ def bootstrap_profile_mailbox(
offset: int = Query(default=0, ge=0, le=100000), offset: int = Query(default=0, ge=0, le=100000),
refresh: bool = False, refresh: bool = False,
include_status: bool = Query(default=False), include_status: bool = Query(default=False),
protocol: str = Query(default="imap"),
principal: ApiPrincipal = Depends(get_api_principal), principal: ApiPrincipal = Depends(get_api_principal),
session: Session = Depends(get_session), session: Session = Depends(get_session),
) -> MailMailboxBootstrapResponse: ) -> MailMailboxBootstrapResponse:
_require_mailbox_read_scope(principal) _require_mailbox_read_scope(principal)
mailbox_protocol = _require_mailbox_protocol(protocol)
try: try:
if mailbox_protocol == "jmap":
jmap = _jmap_config_for_principal(
session,
principal=principal,
profile_id=profile_id,
)
result = load_jmap_mailbox_bootstrap(
jmap_config=jmap,
folder=folder,
limit=limit,
offset=offset,
)
next_cursor, cursor_stable = _next_jmap_mailbox_cursor(
tenant_id=principal.tenant_id,
profile_id=profile_id,
folder=result.messages.folder,
limit=result.messages.limit,
offset=result.messages.offset,
query_state=result.messages.uidvalidity,
messages=result.messages.messages,
total_count=result.messages.total_count,
query="",
)
return MailMailboxBootstrapResponse(
profile_id=profile_id,
folder=result.messages.folder,
folders=_mailbox_folder_response(result.folders),
messages=_mailbox_messages_response(
profile_id=profile_id,
folder=result.messages.folder,
host=result.messages.host,
port=result.messages.port,
security=result.messages.security,
total_count=result.messages.total_count,
offset=result.messages.offset,
limit=result.messages.limit,
cursor=None,
next_cursor=next_cursor,
cursor_stable=cursor_stable,
full=False,
messages=result.messages.messages,
),
)
imap = _imap_config_for_principal(session, principal=principal, profile_id=profile_id) imap = _imap_config_for_principal(session, principal=principal, profile_id=profile_id)
if not refresh: if not refresh:
cached_folders = cached_mailbox_folders(session, tenant_id=principal.tenant_id, profile_id=profile_id) cached_folders = cached_mailbox_folders(session, tenant_id=principal.tenant_id, profile_id=profile_id)
@@ -3285,6 +3624,12 @@ def bootstrap_profile_mailbox(
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(exc)) from exc raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(exc)) from exc
except ImapAppendError as exc: except ImapAppendError as exc:
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc
except (JmapConfigurationError, JmapCapabilityError) as exc:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(exc)) from exc
except (JmapAuthenticationError, JmapPermissionError) as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
except JmapProviderError as exc:
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc
@router.get("/profiles/{profile_id}/mailbox/messages", response_model=MailMailboxMessageListResponse) @router.get("/profiles/{profile_id}/mailbox/messages", response_model=MailMailboxMessageListResponse)
@@ -3295,11 +3640,68 @@ def list_profile_mailbox_messages(
offset: int = Query(default=0, ge=0, le=100000), offset: int = Query(default=0, ge=0, le=100000),
cursor: str | None = None, cursor: str | None = None,
refresh: bool = False, refresh: bool = False,
protocol: str = Query(default="imap"),
q: str | None = Query(default=None, max_length=500),
principal: ApiPrincipal = Depends(get_api_principal), principal: ApiPrincipal = Depends(get_api_principal),
session: Session = Depends(get_session), session: Session = Depends(get_session),
): ):
_require_mailbox_read_scope(principal) _require_mailbox_read_scope(principal)
mailbox_protocol = _require_mailbox_protocol(protocol)
try: try:
if mailbox_protocol == "jmap":
clean_query = q.strip() if isinstance(q, str) else ""
effective_limit = _jmap_mailbox_cursor_limit(cursor, limit)
fingerprint = _jmap_mailbox_cursor_fingerprint(
tenant_id=principal.tenant_id,
profile_id=profile_id,
folder=folder,
limit=effective_limit,
query=clean_query,
)
effective_offset, expected_query_state = _jmap_mailbox_cursor_position(
cursor,
fingerprint=fingerprint,
offset=offset,
)
jmap = _jmap_config_for_principal(
session,
principal=principal,
profile_id=profile_id,
)
result = list_jmap_messages(
jmap_config=jmap,
folder=folder,
limit=effective_limit,
offset=effective_offset,
expected_query_state=expected_query_state,
query=clean_query,
)
next_cursor, cursor_stable = _next_jmap_mailbox_cursor(
tenant_id=principal.tenant_id,
profile_id=profile_id,
folder=result.folder,
limit=result.limit,
offset=result.offset,
total_count=result.total_count,
query_state=result.uidvalidity,
messages=result.messages,
query=clean_query,
)
return _mailbox_messages_response(
profile_id=profile_id,
folder=result.folder,
host=result.host,
port=result.port,
security=result.security,
total_count=result.total_count,
offset=result.offset,
limit=result.limit,
cursor=cursor,
next_cursor=next_cursor,
cursor_stable=cursor_stable,
full=result.cursor_reset,
messages=result.messages,
)
imap = _imap_config_for_principal(session, principal=principal, profile_id=profile_id) imap = _imap_config_for_principal(session, principal=principal, profile_id=profile_id)
effective_limit = _mailbox_cursor_limit(cursor, limit) effective_limit = _mailbox_cursor_limit(cursor, limit)
fingerprint = _mailbox_cursor_fingerprint(tenant_id=principal.tenant_id, profile_id=profile_id, folder=folder, limit=effective_limit) fingerprint = _mailbox_cursor_fingerprint(tenant_id=principal.tenant_id, profile_id=profile_id, folder=folder, limit=effective_limit)
@@ -3407,6 +3809,55 @@ def list_profile_mailbox_messages(
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(exc)) from exc raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(exc)) from exc
except ImapAppendError as exc: except ImapAppendError as exc:
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc
except (JmapConfigurationError, JmapCapabilityError) as exc:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(exc)) from exc
except (JmapAuthenticationError, JmapPermissionError) as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
except JmapProviderError as exc:
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc
@router.get(
"/profiles/{profile_id}/mailbox/changes",
response_model=MailMailboxChangesResponse,
)
def get_profile_mailbox_changes(
profile_id: str,
since_state: str = Query(min_length=1, max_length=1_000),
max_changes: int = Query(default=500, ge=1, le=1_000),
principal: ApiPrincipal = Depends(get_api_principal),
session: Session = Depends(get_session),
):
_require_mailbox_read_scope(principal)
try:
jmap = _jmap_config_for_principal(
session,
principal=principal,
profile_id=profile_id,
)
result = get_jmap_email_changes(
jmap_config=jmap,
since_state=since_state,
max_changes=max_changes,
)
return MailMailboxChangesResponse(
profile_id=profile_id,
account_id=result.account_id,
old_state=result.old_state,
new_state=result.new_state,
has_more_changes=result.has_more_changes,
created=list(result.created),
updated=list(result.updated),
destroyed=list(result.destroyed),
)
except MailProfileError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
except (JmapConfigurationError, JmapCapabilityError) as exc:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
except (JmapAuthenticationError, JmapPermissionError) as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
except JmapProviderError as exc:
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc)) from exc
@router.get("/profiles/{profile_id}/mailbox/messages/{message_uid}", response_model=MailMailboxMessageResponse) @router.get("/profiles/{profile_id}/mailbox/messages/{message_uid}", response_model=MailMailboxMessageResponse)
@@ -3414,11 +3865,32 @@ def get_profile_mailbox_message(
profile_id: str, profile_id: str,
message_uid: str, message_uid: str,
folder: str = Query(default="INBOX", min_length=1, max_length=255), folder: str = Query(default="INBOX", min_length=1, max_length=255),
protocol: str = Query(default="imap"),
principal: ApiPrincipal = Depends(get_api_principal), principal: ApiPrincipal = Depends(get_api_principal),
session: Session = Depends(get_session), session: Session = Depends(get_session),
): ):
_require_mailbox_read_scope(principal) _require_mailbox_read_scope(principal)
mailbox_protocol = _require_mailbox_protocol(protocol)
try: try:
if mailbox_protocol == "jmap":
jmap = _jmap_config_for_principal(
session,
principal=principal,
profile_id=profile_id,
)
result = get_jmap_message(
jmap_config=jmap,
folder=folder,
email_id=message_uid,
)
return MailMailboxMessageResponse(
profile_id=profile_id,
folder=result.folder,
host=result.host,
port=result.port,
security=result.security,
message=_mailbox_detail_response(result.message),
)
imap = _imap_config_for_principal(session, principal=principal, profile_id=profile_id) imap = _imap_config_for_principal(session, principal=principal, profile_id=profile_id)
result = get_imap_message(imap_config=imap, folder=folder, uid=message_uid) result = get_imap_message(imap_config=imap, folder=folder, uid=message_uid)
return MailMailboxMessageResponse( return MailMailboxMessageResponse(
@@ -3436,6 +3908,13 @@ def get_profile_mailbox_message(
except ImapAppendError as exc: except ImapAppendError as exc:
status_code = status.HTTP_404_NOT_FOUND if "not found" in str(exc).casefold() else status.HTTP_502_BAD_GATEWAY status_code = status.HTTP_404_NOT_FOUND if "not found" in str(exc).casefold() else status.HTTP_502_BAD_GATEWAY
raise HTTPException(status_code=status_code, detail=str(exc)) from exc raise HTTPException(status_code=status_code, detail=str(exc)) from exc
except (JmapConfigurationError, JmapCapabilityError) as exc:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(exc)) from exc
except (JmapAuthenticationError, JmapPermissionError) as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
except JmapProviderError as exc:
status_code = status.HTTP_404_NOT_FOUND if "not found" in str(exc).casefold() else status.HTTP_502_BAD_GATEWAY
raise HTTPException(status_code=status_code, detail=str(exc)) from exc
def _safe_error_message(exc: Exception) -> str: def _safe_error_message(exc: Exception) -> str:
+16 -4
View File
@@ -197,7 +197,7 @@ class MailServerEndpointResponse(BaseModel):
id: str id: str
profile_id: str profile_id: str
tenant_id: str | None = None tenant_id: str | None = None
protocol: Literal["smtp", "imap", "pop3"] protocol: Literal["smtp", "imap", "jmap", "pop3"]
name: str name: str
config: dict[str, Any] = Field(default_factory=dict) config: dict[str, Any] = Field(default_factory=dict)
scope_type: MailProfileScope scope_type: MailProfileScope
@@ -214,7 +214,7 @@ class MailServerEndpointResponse(BaseModel):
class MailServerEndpointCreateRequest(BaseModel): class MailServerEndpointCreateRequest(BaseModel):
model_config = ConfigDict(extra="forbid") model_config = ConfigDict(extra="forbid")
protocol: Literal["smtp", "imap", "pop3"] protocol: Literal["smtp", "imap", "jmap", "pop3"]
name: str = Field(min_length=1, max_length=255) name: str = Field(min_length=1, max_length=255)
config: dict[str, Any] = Field(default_factory=dict) config: dict[str, Any] = Field(default_factory=dict)
inherit_to_lower_scopes: bool | None = None inherit_to_lower_scopes: bool | None = None
@@ -383,7 +383,7 @@ class MailContactCreateResponse(BaseModel):
class MailConnectionTestResponse(BaseModel): class MailConnectionTestResponse(BaseModel):
ok: bool ok: bool
protocol: Literal["smtp", "imap", "pop3"] protocol: Literal["smtp", "imap", "jmap", "pop3"]
host: str | None = None host: str | None = None
port: int | None = None port: int | None = None
security: str | None = None security: str | None = None
@@ -476,7 +476,7 @@ class MailImapFolderResponse(BaseModel):
class MailImapFolderListResponse(BaseModel): class MailImapFolderListResponse(BaseModel):
ok: bool ok: bool
protocol: Literal["imap"] = "imap" protocol: Literal["imap", "jmap"] = "imap"
host: str | None = None host: str | None = None
port: int | None = None port: int | None = None
security: str | None = None security: str | None = None
@@ -536,6 +536,18 @@ class MailMailboxMessageListResponse(BaseModel):
messages: list[MailMailboxMessageSummaryResponse] = Field(default_factory=list) messages: list[MailMailboxMessageSummaryResponse] = Field(default_factory=list)
class MailMailboxChangesResponse(BaseModel):
profile_id: str
protocol: Literal["jmap"] = "jmap"
account_id: str
old_state: str
new_state: str
has_more_changes: bool = False
created: list[str] = Field(default_factory=list)
updated: list[str] = Field(default_factory=list)
destroyed: list[str] = Field(default_factory=list)
class MailMailboxBootstrapResponse(BaseModel): class MailMailboxBootstrapResponse(BaseModel):
profile_id: str profile_id: str
folder: str folder: str
+847
View File
@@ -0,0 +1,847 @@
from __future__ import annotations
import base64
import json
import urllib.error
import urllib.parse
from dataclasses import dataclass
from typing import Any, Iterable, Mapping
from govoplan_core.security.http_fetch import fetch_http
from govoplan_mail.backend.config import JmapConfig
from govoplan_mail.backend.sending.imap import (
ImapMailboxAttachmentInfo,
ImapMailboxInfo,
ImapMailboxMessageDetail,
ImapMailboxMessageSummary,
)
JMAP_CORE_CAPABILITY = "urn:ietf:params:jmap:core"
JMAP_MAIL_CAPABILITY = "urn:ietf:params:jmap:mail"
_SUMMARY_PROPERTIES = [
"id",
"threadId",
"mailboxIds",
"keywords",
"size",
"receivedAt",
"sentAt",
"messageId",
"from",
"to",
"cc",
"subject",
"hasAttachment",
"preview",
]
_DETAIL_PROPERTIES = _SUMMARY_PROPERTIES + [
"replyTo",
"bcc",
"textBody",
"htmlBody",
"bodyValues",
"attachments",
]
class JmapConfigurationError(ValueError):
pass
class JmapAuthenticationError(RuntimeError):
pass
class JmapPermissionError(RuntimeError):
pass
class JmapCapabilityError(RuntimeError):
pass
class JmapProviderError(RuntimeError):
pass
@dataclass(frozen=True, slots=True)
class JmapSession:
api_url: str
account_id: str
session_state: str
capabilities: tuple[str, ...]
account_capabilities: tuple[str, ...]
username: str | None
@dataclass(frozen=True, slots=True)
class JmapConnectionTestResult:
host: str
port: int
security: str
authenticated: bool
account_id: str
session_state: str
capabilities: tuple[str, ...]
@dataclass(frozen=True, slots=True)
class JmapFolderListResult:
host: str
port: int
security: str
folders: list[ImapMailboxInfo]
detected_sent_folder: str | None
detected_folder_mappings: dict[str, str]
protocol: str = "jmap"
@dataclass(frozen=True, slots=True)
class JmapMailboxMessageListResult:
host: str
port: int
security: str
folder: str
messages: list[ImapMailboxMessageSummary]
total_count: int
offset: int
limit: int
uidvalidity: str
cursor_reset: bool = False
@dataclass(frozen=True, slots=True)
class JmapMailboxBootstrapResult:
folders: JmapFolderListResult
messages: JmapMailboxMessageListResult
@dataclass(frozen=True, slots=True)
class JmapMailboxMessageResult:
host: str
port: int
security: str
folder: str
message: ImapMailboxMessageDetail
@dataclass(frozen=True, slots=True)
class JmapEmailChangesResult:
account_id: str
old_state: str
new_state: str
has_more_changes: bool
created: tuple[str, ...]
updated: tuple[str, ...]
destroyed: tuple[str, ...]
def discover_jmap(config: JmapConfig) -> JmapSession:
payload = _fetch_json(config.session_url, config=config, method="GET")
capabilities = _string_keys(payload.get("capabilities"), "JMAP capabilities")
if JMAP_CORE_CAPABILITY not in capabilities:
raise JmapCapabilityError("The server does not advertise the JMAP Core capability")
if JMAP_MAIL_CAPABILITY not in capabilities:
raise JmapCapabilityError("The server does not advertise the JMAP Mail capability")
accounts = _object(payload.get("accounts"), "JMAP accounts")
account_id = _select_account_id(payload, accounts, config.account_id)
account = _object(accounts.get(account_id), "JMAP account")
account_capabilities = _string_keys(
account.get("accountCapabilities"),
"JMAP account capabilities",
)
if JMAP_MAIL_CAPABILITY not in account_capabilities:
raise JmapCapabilityError("The selected account does not support JMAP Mail")
api_url = _resolve_session_url(
config,
_required_text(payload.get("apiUrl"), "JMAP Session is missing apiUrl"),
label="JMAP apiUrl",
)
return JmapSession(
api_url=api_url,
account_id=account_id,
session_state=_required_text(
payload.get("state"),
"JMAP Session is missing state",
),
capabilities=tuple(sorted(capabilities)),
account_capabilities=tuple(sorted(account_capabilities)),
username=_optional_text(payload.get("username")),
)
def test_jmap_connection(*, jmap_config: JmapConfig) -> JmapConnectionTestResult:
session = discover_jmap(jmap_config)
_jmap_call(
jmap_config,
session,
[("Mailbox/get", {"accountId": session.account_id, "ids": []}, "mailboxes")],
)
host, port, security = _transport_coordinates(jmap_config.session_url)
return JmapConnectionTestResult(
host=host,
port=port,
security=security,
authenticated=True,
account_id=session.account_id,
session_state=session.session_state,
capabilities=session.capabilities,
)
def list_jmap_folders(*, jmap_config: JmapConfig) -> JmapFolderListResult:
session = discover_jmap(jmap_config)
mailboxes = _get_mailboxes(jmap_config, session)
paths = _mailbox_paths(mailboxes)
folders: list[ImapMailboxInfo] = []
mappings: dict[str, str] = {}
for mailbox in sorted(mailboxes, key=lambda item: paths[str(item["id"])].casefold()):
mailbox_id = str(mailbox["id"])
path = paths[mailbox_id]
role = _optional_text(mailbox.get("role"))
flags = [_jmap_role_flag(role)] if role else []
folders.append(
ImapMailboxInfo(
name=path,
flags=[flag for flag in flags if flag],
message_count=_optional_nonnegative_int(mailbox.get("totalEmails")),
unseen_count=_optional_nonnegative_int(mailbox.get("unreadEmails")),
)
)
if role in {"inbox", "sent", "drafts", "trash", "archive", "junk"}:
mappings[role] = path
host, port, security = _transport_coordinates(jmap_config.session_url)
return JmapFolderListResult(
host=host,
port=port,
security=security,
folders=folders,
detected_sent_folder=mappings.get("sent"),
detected_folder_mappings=mappings,
)
def list_jmap_messages(
*,
jmap_config: JmapConfig,
folder: str,
limit: int = 50,
offset: int = 0,
expected_query_state: str | None = None,
query: str | None = None,
) -> JmapMailboxMessageListResult:
clean_limit = max(1, min(int(limit), 100))
clean_offset = max(0, min(int(offset), 100_000))
clean_query = str(query or "").strip()
if len(clean_query) > 500:
raise JmapConfigurationError("JMAP mailbox search is limited to 500 characters")
session = discover_jmap(jmap_config)
mailboxes = _get_mailboxes(jmap_config, session)
mailbox, paths = _resolve_mailbox(mailboxes, folder)
query_payload: dict[str, Any] = {
"accountId": session.account_id,
"filter": {"inMailbox": mailbox["id"]},
"sort": [{"property": "receivedAt", "isAscending": False}],
"position": clean_offset,
"limit": clean_limit,
"calculateTotal": True,
}
if clean_query:
query_payload["filter"] = {
"operator": "AND",
"conditions": [
{"inMailbox": mailbox["id"]},
{"text": clean_query},
],
}
query_result = _method_result(
_jmap_call(
jmap_config,
session,
[("Email/query", query_payload, "query")],
),
name="Email/query",
call_id="query",
)
query_state = _required_text(
query_result.get("queryState"),
"JMAP Email/query response is missing queryState",
)
cursor_reset = bool(expected_query_state and expected_query_state != query_state)
if cursor_reset and clean_offset:
clean_offset = 0
query_payload["position"] = 0
query_result = _method_result(
_jmap_call(
jmap_config,
session,
[("Email/query", query_payload, "query-reset")],
),
name="Email/query",
call_id="query-reset",
)
query_state = _required_text(
query_result.get("queryState"),
"JMAP Email/query response is missing queryState",
)
ids = _string_list(query_result.get("ids"), "JMAP Email/query ids", maximum=100)
emails: list[dict[str, Any]] = []
if ids:
get_result = _method_result(
_jmap_call(
jmap_config,
session,
[(
"Email/get",
{
"accountId": session.account_id,
"ids": ids,
"properties": _SUMMARY_PROPERTIES,
},
"emails",
)],
),
name="Email/get",
call_id="emails",
)
emails = _object_list(get_result.get("list"), "JMAP Email/get list", maximum=100)
by_id = {str(item.get("id")): item for item in emails if item.get("id") is not None}
folder_path = paths[str(mailbox["id"])]
messages = [
_email_summary(by_id[email_id], folder=folder_path)
for email_id in ids
if email_id in by_id
]
host, port, security = _transport_coordinates(jmap_config.session_url)
total = query_result.get("total")
total_count = int(total) if isinstance(total, int) and total >= 0 else clean_offset + len(messages)
return JmapMailboxMessageListResult(
host=host,
port=port,
security=security,
folder=folder_path,
messages=messages,
total_count=total_count,
offset=clean_offset,
limit=clean_limit,
uidvalidity=query_state,
cursor_reset=cursor_reset,
)
def load_jmap_mailbox_bootstrap(
*,
jmap_config: JmapConfig,
folder: str = "INBOX",
limit: int = 50,
offset: int = 0,
) -> JmapMailboxBootstrapResult:
folders = list_jmap_folders(jmap_config=jmap_config)
selected = folder
names = {item.name for item in folders.folders}
if selected not in names:
selected = (
folders.detected_folder_mappings.get("inbox")
or (folders.folders[0].name if folders.folders else folder)
)
messages = list_jmap_messages(
jmap_config=jmap_config,
folder=selected,
limit=limit,
offset=offset,
)
return JmapMailboxBootstrapResult(folders=folders, messages=messages)
def get_jmap_message(
*,
jmap_config: JmapConfig,
folder: str,
email_id: str,
) -> JmapMailboxMessageResult:
clean_id = _required_text(email_id, "JMAP Email id is required")
if len(clean_id) > 255:
raise JmapConfigurationError("JMAP Email id is too long")
session = discover_jmap(jmap_config)
mailbox, paths = _resolve_mailbox(_get_mailboxes(jmap_config, session), folder)
mailbox_id = str(mailbox["id"])
canonical_folder = paths[mailbox_id]
result = _method_result(
_jmap_call(
jmap_config,
session,
[(
"Email/get",
{
"accountId": session.account_id,
"ids": [clean_id],
"properties": _DETAIL_PROPERTIES,
"bodyProperties": [
"partId",
"blobId",
"size",
"name",
"type",
"charset",
"disposition",
"cid",
],
"fetchTextBodyValues": True,
"fetchHTMLBodyValues": True,
"maxBodyValueBytes": jmap_config.max_body_value_bytes,
},
"email",
)],
),
name="Email/get",
call_id="email",
)
values = _object_list(result.get("list"), "JMAP Email/get list", maximum=1)
if not values:
raise JmapProviderError("JMAP message not found")
email = values[0]
mailbox_ids = email.get("mailboxIds")
if not isinstance(mailbox_ids, dict) or mailbox_ids.get(mailbox_id) is not True:
raise JmapProviderError("JMAP message is not available in the requested mailbox")
summary = _email_summary(email, folder=canonical_folder)
body_values = _object(email.get("bodyValues") or {}, "JMAP Email bodyValues")
body_text = _body_value(email.get("textBody"), body_values)
body_html = _body_value(email.get("htmlBody"), body_values)
attachments = [
ImapMailboxAttachmentInfo(
filename=_optional_text(item.get("name")),
content_type=_optional_text(item.get("type")) or "application/octet-stream",
size_bytes=_optional_nonnegative_int(item.get("size")) or 0,
)
for item in _object_list(
email.get("attachments") or [],
"JMAP Email attachments",
maximum=1_000,
)
]
headers = {
key: value
for key, value in {
"From": summary.from_header,
"To": summary.to_header,
"Cc": summary.cc_header,
"Bcc": _format_addresses(email.get("bcc")),
"Reply-To": _format_addresses(email.get("replyTo")),
"Message-ID": summary.message_id,
"Date": summary.date,
"Subject": summary.subject,
}.items()
if value
}
detail = ImapMailboxMessageDetail(
uid=summary.uid,
folder=summary.folder,
subject=summary.subject,
from_header=summary.from_header,
to_header=summary.to_header,
cc_header=summary.cc_header,
date=summary.date,
message_id=summary.message_id,
flags=summary.flags,
size_bytes=summary.size_bytes,
body_preview=summary.body_preview,
body_text=body_text,
body_html=body_html,
headers=headers,
attachments=attachments,
)
host, port, security = _transport_coordinates(jmap_config.session_url)
return JmapMailboxMessageResult(
host=host,
port=port,
security=security,
folder=canonical_folder,
message=detail,
)
def get_jmap_email_changes(
*,
jmap_config: JmapConfig,
since_state: str,
max_changes: int = 500,
) -> JmapEmailChangesResult:
clean_state = _required_text(since_state, "JMAP Email change state is required")
if len(clean_state) > 1_000:
raise JmapConfigurationError("JMAP Email change state is too long")
clean_max = max(1, min(int(max_changes), 1_000))
session = discover_jmap(jmap_config)
result = _method_result(
_jmap_call(
jmap_config,
session,
[(
"Email/changes",
{
"accountId": session.account_id,
"sinceState": clean_state,
"maxChanges": clean_max,
},
"changes",
)],
),
name="Email/changes",
call_id="changes",
)
return JmapEmailChangesResult(
account_id=session.account_id,
old_state=_required_text(result.get("oldState"), "JMAP changes is missing oldState"),
new_state=_required_text(result.get("newState"), "JMAP changes is missing newState"),
has_more_changes=bool(result.get("hasMoreChanges")),
created=tuple(_string_list(result.get("created"), "JMAP created ids", maximum=clean_max)),
updated=tuple(_string_list(result.get("updated"), "JMAP updated ids", maximum=clean_max)),
destroyed=tuple(_string_list(result.get("destroyed"), "JMAP destroyed ids", maximum=clean_max)),
)
def _get_mailboxes(config: JmapConfig, session: JmapSession) -> list[dict[str, Any]]:
result = _method_result(
_jmap_call(
config,
session,
[(
"Mailbox/get",
{
"accountId": session.account_id,
"properties": [
"id",
"name",
"parentId",
"role",
"sortOrder",
"isSubscribed",
"totalEmails",
"unreadEmails",
],
},
"mailboxes",
)],
),
name="Mailbox/get",
call_id="mailboxes",
)
rows = _object_list(result.get("list"), "JMAP Mailbox/get list", maximum=10_000)
for row in rows:
_required_text(row.get("id"), "JMAP Mailbox is missing id")
_required_text(row.get("name"), "JMAP Mailbox is missing name")
return rows
def _jmap_call(
config: JmapConfig,
session: JmapSession,
calls: Iterable[tuple[str, Mapping[str, Any], str]],
) -> dict[str, Any]:
method_calls = [[name, dict(arguments), call_id] for name, arguments, call_id in calls]
if not method_calls or len(method_calls) > 32:
raise JmapConfigurationError("A JMAP request must contain between 1 and 32 method calls")
body = json.dumps(
{
"using": [JMAP_CORE_CAPABILITY, JMAP_MAIL_CAPABILITY],
"methodCalls": method_calls,
},
separators=(",", ":"),
).encode("utf-8")
return _fetch_json(session.api_url, config=config, method="POST", body=body)
def _fetch_json(
url: str,
*,
config: JmapConfig,
method: str,
body: bytes | None = None,
) -> dict[str, Any]:
try:
response = fetch_http(
url,
timeout=config.timeout_seconds,
label="JMAP endpoint",
method=method,
headers={
"Accept": "application/json",
"Authorization": _authorization_header(config),
**({"Content-Type": "application/json"} if body is not None else {}),
},
body=body,
max_bytes=config.max_response_bytes,
)
except urllib.error.HTTPError as exc:
if exc.code == 401:
raise JmapAuthenticationError("JMAP authentication failed") from exc
if exc.code == 403:
raise JmapPermissionError("JMAP access is forbidden for this credential") from exc
raise JmapProviderError(f"JMAP provider returned HTTP {exc.code}") from exc
except (JmapAuthenticationError, JmapPermissionError, JmapProviderError):
raise
except Exception as exc:
raise JmapProviderError("JMAP provider is unavailable") from exc
try:
payload = json.loads(response.body.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
raise JmapProviderError("JMAP provider returned invalid JSON") from exc
return _object(payload, "JMAP response")
def _method_result(payload: Mapping[str, Any], *, name: str, call_id: str) -> dict[str, Any]:
responses = payload.get("methodResponses")
if not isinstance(responses, list):
raise JmapProviderError("JMAP response is missing methodResponses")
for item in responses:
if not isinstance(item, list) or len(item) != 3:
continue
response_name, arguments, response_id = item
if response_id != call_id:
continue
if response_name == "error":
error = _object(arguments, "JMAP method error")
error_type = _optional_text(error.get("type")) or "unknown"
if error_type in {"accountNotFound", "forbidden"}:
raise JmapPermissionError(f"JMAP {name} was denied ({error_type})")
if error_type in {"unknownMethod", "unknownCapability"}:
raise JmapCapabilityError(f"JMAP {name} is unsupported ({error_type})")
if error_type == "cannotCalculateChanges":
raise JmapCapabilityError("JMAP incremental state expired; perform a full refresh")
raise JmapProviderError(f"JMAP {name} failed ({error_type})")
if response_name != name:
raise JmapProviderError(f"JMAP returned {response_name!r} for {name}")
return _object(arguments, f"JMAP {name} response")
raise JmapProviderError(f"JMAP response did not include call {call_id!r}")
def _select_account_id(
session_payload: Mapping[str, Any],
accounts: Mapping[str, Any],
configured: str | None,
) -> str:
if configured:
if configured not in accounts:
raise JmapPermissionError("The configured JMAP account is not available")
return configured
primary = session_payload.get("primaryAccounts")
if isinstance(primary, dict) and primary.get(JMAP_MAIL_CAPABILITY):
account_id = str(primary[JMAP_MAIL_CAPABILITY])
if account_id in accounts:
return account_id
capable = [
str(account_id)
for account_id, value in accounts.items()
if isinstance(value, dict)
and JMAP_MAIL_CAPABILITY
in _string_keys(value.get("accountCapabilities"), "JMAP account capabilities")
]
if len(capable) == 1:
return capable[0]
if not capable:
raise JmapCapabilityError("No accessible account supports JMAP Mail")
raise JmapConfigurationError("Configure a JMAP account id because multiple mail accounts are available")
def _resolve_session_url(config: JmapConfig, value: str, *, label: str) -> str:
candidate = urllib.parse.urljoin(config.session_url, value)
candidate_origin = _origin(candidate)
allowed = {_origin(config.session_url), *config.allowed_api_origins}
if candidate_origin not in allowed:
raise JmapConfigurationError(
f"{label} uses unapproved origin {candidate_origin}; add it to allowed_api_origins"
)
return candidate
def _authorization_header(config: JmapConfig) -> str:
if config.auth_scheme == "bearer":
return f"Bearer {config.password}"
raw = f"{config.username}:{config.password}".encode("utf-8")
return f"Basic {base64.b64encode(raw).decode('ascii')}"
def _transport_coordinates(url: str) -> tuple[str, int, str]:
parsed = urllib.parse.urlsplit(url)
return (
parsed.hostname or "",
parsed.port or (443 if parsed.scheme == "https" else 80),
parsed.scheme,
)
def _origin(value: str) -> str:
parsed = urllib.parse.urlsplit(value)
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
raise JmapConfigurationError("JMAP Session advertised an invalid HTTP(S) URL")
if parsed.username or parsed.password or parsed.fragment:
raise JmapConfigurationError("JMAP Session advertised an unsafe URL")
port = parsed.port or (443 if parsed.scheme == "https" else 80)
default = 443 if parsed.scheme == "https" else 80
suffix = "" if port == default else f":{port}"
return f"{parsed.scheme.lower()}://{parsed.hostname.lower()}{suffix}"
def _mailbox_paths(mailboxes: list[dict[str, Any]]) -> dict[str, str]:
by_id = {str(item["id"]): item for item in mailboxes}
paths: dict[str, str] = {}
def path_for(mailbox_id: str, stack: tuple[str, ...] = ()) -> str:
if mailbox_id in paths:
return paths[mailbox_id]
if mailbox_id in stack:
raise JmapProviderError("JMAP mailbox hierarchy contains a cycle")
mailbox = by_id[mailbox_id]
name = _required_text(mailbox.get("name"), "JMAP Mailbox is missing name")
parent_id = _optional_text(mailbox.get("parentId"))
if parent_id and parent_id in by_id:
value = f"{path_for(parent_id, (*stack, mailbox_id))}/{name}"
else:
value = name
paths[mailbox_id] = value
return value
for mailbox_id in by_id:
path_for(mailbox_id)
return paths
def _resolve_mailbox(
mailboxes: list[dict[str, Any]],
folder: str,
) -> tuple[dict[str, Any], dict[str, str]]:
paths = _mailbox_paths(mailboxes)
clean = str(folder or "INBOX").strip()
for item in mailboxes:
mailbox_id = str(item["id"])
role = _optional_text(item.get("role"))
if mailbox_id == clean or paths[mailbox_id] == clean:
return item, paths
if clean.casefold() == "inbox" and role == "inbox":
return item, paths
raise JmapConfigurationError(f"JMAP mailbox {clean!r} is not available")
def _jmap_role_flag(role: str | None) -> str:
return {
"inbox": "\\Inbox",
"sent": "\\Sent",
"drafts": "\\Drafts",
"trash": "\\Trash",
"archive": "\\Archive",
"junk": "\\Junk",
}.get(role or "", "")
def _email_summary(email: Mapping[str, Any], *, folder: str) -> ImapMailboxMessageSummary:
email_id = _required_text(email.get("id"), "JMAP Email is missing id")
message_ids = email.get("messageId")
message_id = None
if isinstance(message_ids, list) and message_ids:
message_id = _optional_text(message_ids[0])
elif isinstance(message_ids, str):
message_id = _optional_text(message_ids)
keywords = email.get("keywords") if isinstance(email.get("keywords"), dict) else {}
flags = [
flag
for keyword, flag in (
("$seen", "\\Seen"),
("$flagged", "\\Flagged"),
("$answered", "\\Answered"),
("$draft", "\\Draft"),
)
if keywords.get(keyword) is True
]
return ImapMailboxMessageSummary(
uid=email_id,
folder=folder,
subject=_optional_text(email.get("subject")),
from_header=_format_addresses(email.get("from")),
to_header=_format_addresses(email.get("to")),
cc_header=_format_addresses(email.get("cc")),
date=_optional_text(email.get("receivedAt")) or _optional_text(email.get("sentAt")),
message_id=message_id,
flags=flags,
size_bytes=_optional_nonnegative_int(email.get("size")),
body_preview=_optional_text(email.get("preview")),
attachment_count=(1 if email.get("hasAttachment") is True else 0),
)
def _format_addresses(value: object) -> str | None:
if not isinstance(value, list):
return None
parts: list[str] = []
for item in value[:1_000]:
if not isinstance(item, dict):
continue
name = _optional_text(item.get("name"))
email = _optional_text(item.get("email"))
if name and email:
parts.append(f"{name} <{email}>")
elif email or name:
parts.append(email or name or "")
return ", ".join(parts) or None
def _body_value(parts: object, values: Mapping[str, Any]) -> str | None:
if not isinstance(parts, list):
return None
result: list[str] = []
for part in parts[:1_000]:
if not isinstance(part, dict):
continue
part_id = _optional_text(part.get("partId"))
body = values.get(part_id) if part_id else None
if isinstance(body, dict) and isinstance(body.get("value"), str):
result.append(body["value"])
return "\n".join(result) or None
def _object(value: object, label: str) -> dict[str, Any]:
if not isinstance(value, dict):
raise JmapProviderError(f"{label} must be an object")
return dict(value)
def _object_list(value: object, label: str, *, maximum: int) -> list[dict[str, Any]]:
if not isinstance(value, list) or len(value) > maximum:
raise JmapProviderError(f"{label} must be an array with at most {maximum} items")
if not all(isinstance(item, dict) for item in value):
raise JmapProviderError(f"{label} contains an invalid item")
return [dict(item) for item in value]
def _string_keys(value: object, label: str) -> set[str]:
if not isinstance(value, dict):
raise JmapProviderError(f"{label} must be an object")
return {str(key) for key in value}
def _string_list(value: object, label: str, *, maximum: int) -> list[str]:
if not isinstance(value, list) or len(value) > maximum:
raise JmapProviderError(f"{label} must be an array with at most {maximum} items")
if not all(isinstance(item, str) and item for item in value):
raise JmapProviderError(f"{label} contains an invalid id")
return list(value)
def _required_text(value: object, message: str) -> str:
text = str(value).strip() if isinstance(value, str) else ""
if not text:
raise JmapProviderError(message)
return text
def _optional_text(value: object) -> str | None:
if not isinstance(value, str):
return None
return value.strip() or None
def _optional_nonnegative_int(value: object) -> int | None:
return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None
+17 -7
View File
@@ -23,6 +23,8 @@ from govoplan_core.security.secrets import decrypt_secret
from govoplan_mail.backend.config import ( from govoplan_mail.backend.config import (
ImapConfig, ImapConfig,
ImapServerConfig, ImapServerConfig,
JmapConfig,
JmapServerConfig,
Pop3Config, Pop3Config,
Pop3ServerConfig, Pop3ServerConfig,
SmtpConfig, SmtpConfig,
@@ -36,7 +38,7 @@ from govoplan_mail.backend.db.models import (
) )
MAIL_SERVER_PROTOCOLS = frozenset({"smtp", "imap", "pop3"}) MAIL_SERVER_PROTOCOLS = frozenset({"smtp", "imap", "jmap", "pop3"})
class MailServerHierarchyError(RuntimeError): class MailServerHierarchyError(RuntimeError):
@@ -70,7 +72,7 @@ class ResolvedMailTransport:
profile: MailServerProfile profile: MailServerProfile
server: MailServerEndpoint | None server: MailServerEndpoint | None
credential: CredentialEnvelope | None credential: CredentialEnvelope | None
config: SmtpConfig | ImapConfig | Pop3Config config: SmtpConfig | ImapConfig | JmapConfig | Pop3Config
transport_revision: str transport_revision: str
@@ -953,9 +955,9 @@ def resolve_mail_transport(
) )
) )
if server is None: if server is None:
if clean_protocol == "pop3": if clean_protocol in {"jmap", "pop3"}:
raise MailServerHierarchyError( raise MailServerHierarchyError(
"The selected Mail profile has no active POP3 legacy-import server" f"The selected Mail profile has no active {clean_protocol.upper()} server"
) )
return _legacy_resolved_transport(profile, clean_protocol) return _legacy_resolved_transport(profile, clean_protocol)
binding, credential = _selected_server_credential( binding, credential = _selected_server_credential(
@@ -987,12 +989,14 @@ def resolve_mail_transport(
elif clean_protocol == "imap": elif clean_protocol == "imap":
payload["username"] = profile.imap_username payload["username"] = profile.imap_username
payload["password"] = decrypt_secret(profile.imap_password_encrypted) payload["password"] = decrypt_secret(profile.imap_password_encrypted)
config: SmtpConfig | ImapConfig | Pop3Config config: SmtpConfig | ImapConfig | JmapConfig | Pop3Config
try: try:
if clean_protocol == "smtp": if clean_protocol == "smtp":
config = SmtpConfig.model_validate(payload) config = SmtpConfig.model_validate(payload)
elif clean_protocol == "imap": elif clean_protocol == "imap":
config = ImapConfig.model_validate(payload) config = ImapConfig.model_validate(payload)
elif clean_protocol == "jmap":
config = JmapConfig.model_validate(payload)
else: else:
config = Pop3Config.model_validate(payload) config = Pop3Config.model_validate(payload)
except Exception as exc: except Exception as exc:
@@ -1037,7 +1041,7 @@ def select_mail_transport(
) )
) )
if server is None: if server is None:
if clean_protocol == "pop3": if clean_protocol in {"jmap", "pop3"}:
return SelectedMailTransport( return SelectedMailTransport(
profile=profile, profile=profile,
server=None, server=None,
@@ -1224,6 +1228,8 @@ def _server_matches_legacy_transport(
) -> bool: ) -> bool:
if not server.is_default: if not server.is_default:
return False return False
if server.protocol not in {"smtp", "imap"}:
return False
if server.protocol == "smtp": if server.protocol == "smtp":
legacy_config = profile.smtp_config or {} legacy_config = profile.smtp_config or {}
legacy_revision = profile.smtp_transport_revision legacy_revision = profile.smtp_transport_revision
@@ -1321,6 +1327,8 @@ def _validated_server_config(
model = SmtpServerConfig.model_validate(payload) model = SmtpServerConfig.model_validate(payload)
elif protocol == "imap": elif protocol == "imap":
model = ImapServerConfig.model_validate(payload) model = ImapServerConfig.model_validate(payload)
elif protocol == "jmap":
model = JmapServerConfig.model_validate(payload)
else: else:
model = Pop3ServerConfig.model_validate(payload) model = Pop3ServerConfig.model_validate(payload)
except Exception as exc: except Exception as exc:
@@ -1363,7 +1371,9 @@ def _server_scope(
def _normalize_protocol(value: str) -> str: def _normalize_protocol(value: str) -> str:
clean = str(value or "").strip().casefold() clean = str(value or "").strip().casefold()
if clean not in MAIL_SERVER_PROTOCOLS: if clean not in MAIL_SERVER_PROTOCOLS:
raise MailServerHierarchyError("Mail server protocol must be smtp, imap or pop3") raise MailServerHierarchyError(
"Mail server protocol must be smtp, imap, jmap or pop3"
)
return clean return clean
+344
View File
@@ -0,0 +1,344 @@
from __future__ import annotations
import base64
import json
import unittest
import urllib.error
from types import SimpleNamespace
from unittest.mock import patch
from govoplan_mail.backend.config import JmapConfig, JmapServerConfig
from govoplan_mail.backend.sending.jmap import (
JMAP_CORE_CAPABILITY,
JMAP_MAIL_CAPABILITY,
JmapAuthenticationError,
JmapCapabilityError,
JmapConfigurationError,
discover_jmap,
get_jmap_email_changes,
get_jmap_message,
list_jmap_folders,
list_jmap_messages,
test_jmap_connection,
)
def _response(payload: dict) -> SimpleNamespace:
return SimpleNamespace(
status=200,
headers={"Content-Type": "application/json"},
body=json.dumps(payload).encode("utf-8"),
)
def _session(*, api_url: str = "https://jmap.example.test/api") -> dict:
return {
"capabilities": {
JMAP_CORE_CAPABILITY: {"maxCallsInRequest": 32},
JMAP_MAIL_CAPABILITY: {},
},
"accounts": {
"account-1": {
"name": "Example",
"isPersonal": True,
"isReadOnly": False,
"accountCapabilities": {JMAP_MAIL_CAPABILITY: {}},
}
},
"primaryAccounts": {JMAP_MAIL_CAPABILITY: "account-1"},
"username": "reader@example.test",
"apiUrl": api_url,
"downloadUrl": "https://jmap.example.test/download/{accountId}/{blobId}/{name}",
"uploadUrl": "https://jmap.example.test/upload/{accountId}",
"eventSourceUrl": "https://jmap.example.test/events",
"state": "session-state-1",
}
def _mailboxes() -> list[dict]:
return [
{
"id": "mb-inbox",
"name": "Inbox",
"parentId": None,
"role": "inbox",
"sortOrder": 10,
"isSubscribed": True,
"totalEmails": 2,
"unreadEmails": 1,
},
{
"id": "mb-projects",
"name": "Projects",
"parentId": None,
"role": None,
"sortOrder": 20,
"isSubscribed": True,
"totalEmails": 1,
"unreadEmails": 0,
},
{
"id": "mb-project-2026",
"name": "2026",
"parentId": "mb-projects",
"role": None,
"sortOrder": 1,
"isSubscribed": True,
"totalEmails": 1,
"unreadEmails": 0,
},
{
"id": "mb-sent",
"name": "Sent",
"parentId": None,
"role": "sent",
"sortOrder": 30,
"isSubscribed": True,
"totalEmails": 4,
"unreadEmails": 0,
},
]
def _email(email_id: str = "email-1", *, detail: bool = False) -> dict:
value = {
"id": email_id,
"threadId": "thread-1",
"mailboxIds": {"mb-inbox": True},
"keywords": {"$seen": False, "$flagged": True},
"size": 1234,
"receivedAt": "2026-08-22T10:30:00Z",
"sentAt": "2026-08-22T10:29:00Z",
"messageId": ["message-1@example.test"],
"from": [{"name": "Sender", "email": "sender@example.test"}],
"to": [{"name": "Reader", "email": "reader@example.test"}],
"cc": [],
"subject": "A governed message",
"hasAttachment": True,
"preview": "A bounded preview",
}
if detail:
value.update(
{
"replyTo": [{"email": "reply@example.test"}],
"bcc": [],
"textBody": [{"partId": "text", "type": "text/plain"}],
"htmlBody": [{"partId": "html", "type": "text/html"}],
"bodyValues": {
"text": {"value": "Plain body", "isTruncated": False},
"html": {"value": "<p>HTML body</p>", "isTruncated": False},
},
"attachments": [
{
"partId": "attachment",
"blobId": "blob-1",
"name": "evidence.pdf",
"type": "application/pdf",
"size": 44,
}
],
}
)
return value
class _JmapProvider:
def __init__(self, *, query_states: list[str] | None = None) -> None:
self.requests: list[tuple[str, str, dict[str, str], dict | None]] = []
self.query_states = list(query_states or ["query-state-1"])
def __call__(self, url: str, **kwargs):
body = json.loads(kwargs["body"].decode("utf-8")) if kwargs.get("body") else None
self.requests.append((url, kwargs.get("method", "GET"), kwargs.get("headers", {}), body))
if kwargs.get("method") == "GET":
return _response(_session())
method, arguments, call_id = body["methodCalls"][0]
if method == "Mailbox/get":
payload = {"accountId": "account-1", "state": "mailbox-state-1", "list": _mailboxes(), "notFound": []}
elif method == "Email/query":
state = self.query_states.pop(0) if self.query_states else "query-state-1"
payload = {
"accountId": "account-1",
"queryState": state,
"canCalculateChanges": True,
"position": arguments["position"],
"ids": ["email-1", "email-2"][arguments["position"] : arguments["position"] + arguments["limit"]],
"total": 2,
"limit": arguments["limit"],
}
elif method == "Email/get":
detail = bool(arguments.get("fetchTextBodyValues"))
payload = {
"accountId": "account-1",
"state": "email-state-1",
"list": [_email(email_id, detail=detail) for email_id in arguments["ids"]],
"notFound": [],
}
elif method == "Email/changes":
payload = {
"accountId": "account-1",
"oldState": arguments["sinceState"],
"newState": "email-state-2",
"hasMoreChanges": False,
"created": ["email-new"],
"updated": ["email-1"],
"destroyed": ["email-old"],
}
else: # pragma: no cover - fixture guard
raise AssertionError(method)
return _response({"methodResponses": [[method, payload, call_id]], "sessionState": "session-state-1"})
class JmapTransportTests(unittest.TestCase):
def config(self, **overrides) -> JmapConfig:
return JmapConfig(
session_url="https://jmap.example.test/.well-known/jmap",
password="access-token",
**overrides,
)
def test_server_configuration_rejects_embedded_credentials_and_normalizes_origins(self) -> None:
with self.assertRaisesRegex(ValueError, "embedded credentials"):
JmapServerConfig(session_url="https://user:secret@example.test/jmap")
config = JmapServerConfig(
session_url="https://jmap.example.test/.well-known/jmap",
allowed_api_origins=["https://api.example.test/path", "https://api.example.test"],
)
self.assertEqual(config.allowed_api_origins, ["https://api.example.test"])
def test_discovery_selects_primary_mail_account_and_bearer_auth(self) -> None:
provider = _JmapProvider()
with patch("govoplan_mail.backend.sending.jmap.fetch_http", side_effect=provider):
result = discover_jmap(self.config())
self.assertEqual(result.account_id, "account-1")
self.assertIn(JMAP_MAIL_CAPABILITY, result.account_capabilities)
self.assertEqual(provider.requests[0][2]["Authorization"], "Bearer access-token")
self.assertNotIn("access-token", repr(result))
def test_basic_authentication_is_supported_without_exposing_credentials(self) -> None:
provider = _JmapProvider()
config = self.config(auth_scheme="basic", username="reader")
with patch("govoplan_mail.backend.sending.jmap.fetch_http", side_effect=provider):
test_jmap_connection(jmap_config=config)
expected = base64.b64encode(b"reader:access-token").decode("ascii")
self.assertEqual(provider.requests[0][2]["Authorization"], f"Basic {expected}")
def test_cross_origin_api_url_is_fail_closed_unless_allowlisted(self) -> None:
provider = _JmapProvider()
provider.requests = []
with patch(
"govoplan_mail.backend.sending.jmap.fetch_http",
return_value=_response(_session(api_url="https://api.example.test/jmap")),
):
with self.assertRaisesRegex(JmapConfigurationError, "unapproved origin"):
discover_jmap(self.config())
def test_lists_hierarchical_mailboxes_with_roles_and_counts(self) -> None:
provider = _JmapProvider()
with patch("govoplan_mail.backend.sending.jmap.fetch_http", side_effect=provider):
result = list_jmap_folders(jmap_config=self.config())
self.assertEqual(result.protocol, "jmap")
self.assertEqual(result.detected_folder_mappings["inbox"], "Inbox")
self.assertEqual(result.detected_sent_folder, "Sent")
self.assertIn("Projects/2026", [item.name for item in result.folders])
inbox = next(item for item in result.folders if item.name == "Inbox")
self.assertEqual((inbox.message_count, inbox.unseen_count), (2, 1))
def test_query_search_and_get_share_protocol_neutral_message_shape(self) -> None:
provider = _JmapProvider()
with patch("govoplan_mail.backend.sending.jmap.fetch_http", side_effect=provider):
result = list_jmap_messages(
jmap_config=self.config(),
folder="INBOX",
limit=1,
query="governed",
)
self.assertEqual(result.folder, "Inbox")
self.assertEqual(result.total_count, 2)
self.assertEqual(result.uidvalidity, "query-state-1")
self.assertEqual(result.messages[0].uid, "email-1")
self.assertEqual(result.messages[0].from_header, "Sender <sender@example.test>")
query_call = next(request[3]["methodCalls"][0] for request in provider.requests if request[3] and request[3]["methodCalls"][0][0] == "Email/query")
self.assertEqual(query_call[1]["filter"]["conditions"][1], {"text": "governed"})
def test_changed_query_state_restarts_the_page_without_skipping(self) -> None:
provider = _JmapProvider(query_states=["new-state", "newer-state"])
with patch("govoplan_mail.backend.sending.jmap.fetch_http", side_effect=provider):
result = list_jmap_messages(
jmap_config=self.config(),
folder="Inbox",
limit=1,
offset=1,
expected_query_state="old-state",
)
self.assertTrue(result.cursor_reset)
self.assertEqual(result.offset, 0)
query_positions = [
request[3]["methodCalls"][0][1]["position"]
for request in provider.requests
if request[3] and request[3]["methodCalls"][0][0] == "Email/query"
]
self.assertEqual(query_positions, [1, 0])
def test_detail_returns_bounded_body_values_and_attachment_metadata(self) -> None:
provider = _JmapProvider()
with patch("govoplan_mail.backend.sending.jmap.fetch_http", side_effect=provider):
result = get_jmap_message(
jmap_config=self.config(),
folder="Inbox",
email_id="email-1",
)
self.assertEqual(result.message.body_text, "Plain body")
self.assertEqual(result.message.body_html, "<p>HTML body</p>")
self.assertEqual(result.message.attachments[0].filename, "evidence.pdf")
detail_call = provider.requests[-1][3]["methodCalls"][0][1]
self.assertEqual(detail_call["maxBodyValueBytes"], 1024 * 1024)
def test_incremental_changes_are_bounded_and_preserve_server_state(self) -> None:
provider = _JmapProvider()
with patch("govoplan_mail.backend.sending.jmap.fetch_http", side_effect=provider):
result = get_jmap_email_changes(
jmap_config=self.config(),
since_state="email-state-1",
max_changes=25,
)
self.assertEqual(result.new_state, "email-state-2")
self.assertEqual(result.created, ("email-new",))
change_call = provider.requests[-1][3]["methodCalls"][0][1]
self.assertEqual(change_call["maxChanges"], 25)
def test_authentication_and_expired_change_state_have_distinct_diagnostics(self) -> None:
http_error = urllib.error.HTTPError(
"https://jmap.example.test/.well-known/jmap",
401,
"Unauthorized",
{},
None,
)
with patch("govoplan_mail.backend.sending.jmap.fetch_http", side_effect=http_error):
with self.assertRaisesRegex(JmapAuthenticationError, "authentication failed"):
discover_jmap(self.config())
def expired(url: str, **kwargs):
if kwargs.get("method") == "GET":
return _response(_session())
body = json.loads(kwargs["body"])
call_id = body["methodCalls"][0][2]
return _response(
{
"methodResponses": [
["error", {"type": "cannotCalculateChanges"}, call_id]
]
}
)
with patch("govoplan_mail.backend.sending.jmap.fetch_http", side_effect=expired):
with self.assertRaisesRegex(JmapCapabilityError, "full refresh"):
get_jmap_email_changes(
jmap_config=self.config(),
since_state="expired-state",
)
if __name__ == "__main__":
unittest.main()
+17
View File
@@ -592,6 +592,23 @@ class MailProfilePolicyHelperTests(unittest.TestCase):
self.assertEqual(policy.blacklist_patterns["smtp_hosts"], ["*.blocked.example"]) self.assertEqual(policy.blacklist_patterns["smtp_hosts"], ["*.blocked.example"])
self.assertFalse(policy.allow_lower_level_limits["blacklist.smtp_hosts"]) self.assertFalse(policy.allow_lower_level_limits["blacklist.smtp_hosts"])
def test_jmap_hostname_policy_has_independent_deny_and_lower_scope_lock(self):
policy = EffectiveMailProfilePolicy()
_merge_policy(
policy,
{
"blacklist": {"jmap_hosts": ["*.blocked.example"]},
"allow_lower_level_limits": {"blacklist.jmap_hosts": False},
},
source="system",
)
allowed, reason = policy.value_allowed("jmap_hosts", "mail.blocked.example")
self.assertFalse(allowed)
self.assertIn("jmap_hosts", reason or "")
self.assertFalse(policy.allow_lower_level_limits["blacklist.jmap_hosts"])
def test_parent_lock_violations_are_reported_per_field(self): def test_parent_lock_violations_are_reported_per_field(self):
violations = _policy_parent_lock_violations( violations = _policy_parent_lock_violations(
{ {
+28
View File
@@ -94,6 +94,34 @@ class MailManifestTests(unittest.TestCase):
pop3_topic = topics["mail.workflow.legacy-pop3-import"] pop3_topic = topics["mail.workflow.legacy-pop3-import"]
self.assertEqual(("user", "admin"), pop3_topic.documentation_types) self.assertEqual(("user", "admin"), pop3_topic.documentation_types)
self.assertIn("mail:pop3:import", pop3_topic.conditions[0].any_scopes) self.assertIn("mail:pop3:import", pop3_topic.conditions[0].any_scopes)
self.assertTrue(
{
"mail.pop3",
"mail.pop3.source-editor",
"mail.pop3.action.reload",
"mail.pop3.action.save-source",
"mail.pop3.action.import",
"mail.pop3.field.transport-security",
"mail.pop3.field.max-message-size",
"mail.pop3.field.password",
"mail.pop3.field.delete-after-import",
"mail.pop3.confirm-delete-source",
}.issubset(pop3_topic.metadata["help_contexts"])
)
self.assertGreaterEqual(len(pop3_topic.metadata["fields"]), 4)
self.assertGreaterEqual(
len(pop3_topic.metadata["operational_consequences"]),
3,
)
for topic in manifest.documentation:
with self.subTest(topic_id=topic.id):
german = topic.translations.get("de", {})
for attribute in ("title", "summary", "body"):
self.assertTrue(
str(german.get(attribute, "")).strip(),
f"{topic.id} is missing its German {attribute}",
)
pop3_provider = next( pop3_provider = next(
item item
+79
View File
@@ -821,6 +821,85 @@ class ProfileActorAuthorizationTests(unittest.TestCase):
self.assertFalse(response.refreshing) self.assertFalse(response.refreshing)
self.assertEqual(session.commits, 1) self.assertEqual(session.commits, 1)
def test_jmap_mailbox_list_uses_protocol_neutral_response_and_provider_search(self) -> None:
principal = _Principal({"mail:mailbox:read", "mail:profile:use"})
jmap = SimpleNamespace(session_url="https://jmap.example.test/.well-known/jmap")
provider_result = SimpleNamespace(
host="jmap.example.test",
port=443,
security="https",
folder="INBOX",
messages=[],
total_count=0,
offset=0,
limit=25,
uidvalidity="query-state-1",
cursor_reset=False,
)
with (
patch("govoplan_mail.backend.router._jmap_config_for_principal", return_value=jmap),
patch("govoplan_mail.backend.router.list_jmap_messages", return_value=provider_result) as provider,
patch("govoplan_mail.backend.router._next_jmap_mailbox_cursor", return_value=(None, True)),
):
response = router.list_profile_mailbox_messages(
"profile-1",
folder="INBOX",
limit=25,
offset=0,
cursor=None,
refresh=False,
protocol="jmap",
q="budget",
principal=principal, # type: ignore[arg-type]
session=_Session(), # type: ignore[arg-type]
)
provider.assert_called_once_with(
jmap_config=jmap,
folder="INBOX",
limit=25,
offset=0,
expected_query_state=None,
query="budget",
)
self.assertEqual("profile-1", response.profile_id)
self.assertEqual("INBOX", response.folder)
self.assertEqual([], response.messages)
self.assertTrue(response.cursor_stable)
def test_jmap_changes_maps_bounded_incremental_state(self) -> None:
principal = _Principal({"mail:mailbox:read", "mail:profile:use"})
jmap = SimpleNamespace(session_url="https://jmap.example.test/.well-known/jmap")
changes = SimpleNamespace(
account_id="account-1",
old_state="state-1",
new_state="state-2",
has_more_changes=False,
created=("email-1",),
updated=("email-2",),
destroyed=("email-3",),
)
with (
patch("govoplan_mail.backend.router._jmap_config_for_principal", return_value=jmap),
patch("govoplan_mail.backend.router.get_jmap_email_changes", return_value=changes) as provider,
):
response = router.get_profile_mailbox_changes(
"profile-1",
since_state="state-1",
max_changes=50,
principal=principal, # type: ignore[arg-type]
session=_Session(), # type: ignore[arg-type]
)
provider.assert_called_once_with(
jmap_config=jmap,
since_state="state-1",
max_changes=50,
)
self.assertEqual("jmap", response.protocol)
self.assertEqual(["email-1"], response.created)
self.assertEqual("state-2", response.new_state)
def test_unauthorized_profile_test_fails_before_credentials_or_provider_effect(self) -> None: def test_unauthorized_profile_test_fails_before_credentials_or_provider_effect(self) -> None:
principal = _Principal({"mail:profile:test", "mail:profile:use"}) principal = _Principal({"mail:profile:test", "mail:profile:use"})
with ( with (
+30 -2
View File
@@ -21,9 +21,11 @@ from govoplan_mail.backend.db.models import (
from govoplan_mail.backend.manifest import manifest from govoplan_mail.backend.manifest import manifest
from govoplan_mail.backend.provider_state import ( from govoplan_mail.backend.provider_state import (
IMAP_PROVIDER_ID, IMAP_PROVIDER_ID,
JMAP_PROVIDER_ID,
POP3_PROVIDER_ID, POP3_PROVIDER_ID,
SMTP_PROVIDER_ID, SMTP_PROVIDER_ID,
imap_provider_states, imap_provider_states,
jmap_provider_states,
pop3_provider_states, pop3_provider_states,
smtp_provider_states, smtp_provider_states,
) )
@@ -124,17 +126,43 @@ class MailProviderStateTests(unittest.TestCase):
), ),
) )
self.assertEqual( self.assertEqual(
{SMTP_PROVIDER_ID, IMAP_PROVIDER_ID, POP3_PROVIDER_ID}, {SMTP_PROVIDER_ID, IMAP_PROVIDER_ID, JMAP_PROVIDER_ID, POP3_PROVIDER_ID},
{item.id for item in manifest.external_providers}, {item.id for item in manifest.external_providers},
) )
self.assertEqual( self.assertEqual(
{SMTP_PROVIDER_ID, IMAP_PROVIDER_ID, POP3_PROVIDER_ID}, {SMTP_PROVIDER_ID, IMAP_PROVIDER_ID, JMAP_PROVIDER_ID, POP3_PROVIDER_ID},
{ {
item.provider_id item.provider_id
for item in manifest.external_provider_state_providers for item in manifest.external_provider_state_providers
}, },
) )
def test_jmap_state_reuses_protocol_neutral_index_without_endpoint_details(self) -> None:
self.session.add(
MailServerEndpoint(
id="jmap-server-1",
profile_id=self.profile.id,
tenant_id="tenant-1",
protocol="jmap",
name="JMAP",
config={"session_url": "https://jmap.example.test/.well-known/jmap"},
scope_type="tenant",
scope_id="tenant-1",
is_active=True,
)
)
self.session.flush()
state = jmap_provider_states(
ExternalProviderStateContext(session=self.session, tenant_id="tenant-1")
)[0]
self.assertEqual(JMAP_PROVIDER_ID, state.provider_id)
self.assertEqual("healthy", state.health)
self.assertEqual("current", state.freshness)
self.assertEqual("mail:profile:profile-1:jmap", state.binding_ref)
self.assertNotIn("jmap.example.test", str(state.to_dict()))
def test_pop3_state_is_disabled_by_default_and_projects_deletion_evidence(self) -> None: def test_pop3_state_is_disabled_by_default_and_projects_deletion_evidence(self) -> None:
endpoint = MailServerEndpoint( endpoint = MailServerEndpoint(
id="pop3-server-1", id="pop3-server-1",
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "@govoplan/mail-webui", "name": "@govoplan/mail-webui",
"version": "0.1.20", "version": "0.1.23",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@govoplan/mail-webui", "name": "@govoplan/mail-webui",
"version": "0.1.20", "version": "0.1.23",
"devDependencies": { "devDependencies": {
"typescript": "^5.7.2" "typescript": "^5.7.2"
}, },
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@govoplan/mail-webui", "name": "@govoplan/mail-webui",
"version": "0.1.20", "version": "0.1.23",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "src/index.ts", "main": "src/index.ts",
@@ -47,6 +47,25 @@ for (const sharedComponent of ["PageLayout", "PageActionBar", "SelectionList", "
assert.match(legacyImport, /archetype="collection"/); assert.match(legacyImport, /archetype="collection"/);
assert.match(legacyImport, /variant="collection"[\s\S]*refreshable[\s\S]*reloadAction=/); assert.match(legacyImport, /variant="collection"[\s\S]*refreshable[\s\S]*reloadAction=/);
assert.match(legacyImport, /topicId: "mail\.workflow\.legacy-pop3-import"/); assert.match(legacyImport, /topicId: "mail\.workflow\.legacy-pop3-import"/);
assert.match(legacyImport, /helpContextId="mail\.pop3"[\s\S]*helpTopicId="mail\.workflow\.legacy-pop3-import"/);
for (const helpContextId of [
"mail.pop3.source-editor",
"mail.pop3.action.reload",
"mail.pop3.action.save-source",
"mail.pop3.action.import",
"mail.pop3.field.transport-security",
"mail.pop3.field.max-message-size",
"mail.pop3.field.max-batch-size",
"mail.pop3.field.password",
"mail.pop3.field.delete-after-import",
"mail.pop3.confirm-delete-source",
]) {
assert.match(
legacyImport,
new RegExp(`helpContextId(?:=|:\\s*)"${helpContextId.replaceAll(".", "\\.")}"`)
);
}
assert.match(legacyImport, /data-help-context-id="mail\.pop3\.field\.message-selection"/);
assert.match(legacyImport, /<ConfirmDialog[\s\S]*tone="danger"[\s\S]*onConfirm=\{\(\) => void runImport\(\)\}/); assert.match(legacyImport, /<ConfirmDialog[\s\S]*tone="danger"[\s\S]*onConfirm=\{\(\) => void runImport\(\)\}/);
assert.match(legacyImport, /legacy_import_enabled: false[\s\S]*is_active: false[\s\S]*createMailServerCredential[\s\S]*updateMailServerEndpoint/); assert.match(legacyImport, /legacy_import_enabled: false[\s\S]*is_active: false[\s\S]*createMailServerCredential[\s\S]*updateMailServerEndpoint/);
assert.match(legacyImport, /expected_transport_revision: preview\.transport_revision/); assert.match(legacyImport, /expected_transport_revision: preview\.transport_revision/);
+60 -9
View File
@@ -164,6 +164,20 @@ export type MailMailboxMessageResponse = {
message: MailMailboxMessageDetail; message: MailMailboxMessageDetail;
}; };
export type MailMailboxProtocol = "imap" | "jmap";
export type MailMailboxChangesResponse = {
profile_id: string;
protocol: "jmap";
account_id: string;
old_state: string;
new_state: string;
has_more_changes: boolean;
created: string[];
updated: string[];
destroyed: string[];
};
export type MailSettingsDeltaResponse = { export type MailSettingsDeltaResponse = {
profiles: MailServerProfile[]; profiles: MailServerProfile[];
policy?: MailProfilePolicyResponse | null; policy?: MailProfilePolicyResponse | null;
@@ -296,7 +310,7 @@ export async function createMailServerProfile(settings: ApiSettings, payload: Ma
export type MailServerProfileUpdatePayload = Partial<MailServerProfilePayload> & { clear_imap?: boolean }; export type MailServerProfileUpdatePayload = Partial<MailServerProfilePayload> & { clear_imap?: boolean };
export type MailServerEndpointPayload = { export type MailServerEndpointPayload = {
protocol: "smtp" | "imap" | "pop3"; protocol: "smtp" | "imap" | "jmap" | "pop3";
name: string; name: string;
config: Record<string, unknown>; config: Record<string, unknown>;
inherit_to_lower_scopes?: boolean | null; inherit_to_lower_scopes?: boolean | null;
@@ -574,6 +588,23 @@ export async function testMailProfileImap(
); );
} }
export async function testMailProfileJmap(
settings: ApiSettings,
profileId: string,
serverId?: string | null,
credentialId?: string | null,
campaignId?: string | null
): Promise<MailConnectionTestResponse> {
return apiPost<MailConnectionTestResponse>(
settings,
apiPath(`/api/v1/mail/profiles/${encodeURIComponent(profileId)}/test-jmap`, {
server_id: serverId,
credential_id: credentialId,
campaign_id: campaignId
})
);
}
export async function testMailProfilePop3( export async function testMailProfilePop3(
settings: ApiSettings, settings: ApiSettings,
profileId: string, profileId: string,
@@ -648,10 +679,11 @@ export async function listMailProfileImapFolders(
); );
} }
export async function listMailboxFolders(settings: ApiSettings, profileId: string, includeStatus = false, refresh = false): Promise<MailImapFolderListResponse> { export async function listMailboxFolders(settings: ApiSettings, profileId: string, includeStatus = false, refresh = false, protocol: MailMailboxProtocol = "imap"): Promise<MailImapFolderListResponse> {
return apiFetch<MailImapFolderListResponse>(settings, apiPath(`/api/v1/mail/profiles/${encodeURIComponent(profileId)}/mailbox/folders`, { return apiFetch<MailImapFolderListResponse>(settings, apiPath(`/api/v1/mail/profiles/${encodeURIComponent(profileId)}/mailbox/folders`, {
include_status: includeStatus ? true : undefined, include_status: includeStatus ? true : undefined,
refresh: refresh ? true : undefined refresh: refresh ? true : undefined,
protocol
})); }));
} }
@@ -661,13 +693,15 @@ export async function bootstrapMailbox(
folder = "INBOX", folder = "INBOX",
limit = 50, limit = 50,
offset = 0, offset = 0,
refresh = false refresh = false,
protocol: MailMailboxProtocol = "imap"
): Promise<MailMailboxBootstrapResponse> { ): Promise<MailMailboxBootstrapResponse> {
return apiFetch<MailMailboxBootstrapResponse>(settings, apiPath(`/api/v1/mail/profiles/${encodeURIComponent(profileId)}/mailbox/bootstrap`, { return apiFetch<MailMailboxBootstrapResponse>(settings, apiPath(`/api/v1/mail/profiles/${encodeURIComponent(profileId)}/mailbox/bootstrap`, {
folder, folder,
limit, limit,
offset, offset,
refresh: refresh ? true : undefined refresh: refresh ? true : undefined,
protocol
})); }));
} }
@@ -678,14 +712,18 @@ export async function listMailboxMessages(
limit = 50, limit = 50,
offset = 0, offset = 0,
cursor?: string | null, cursor?: string | null,
refresh = false refresh = false,
protocol: MailMailboxProtocol = "imap",
query?: string | null
): Promise<MailMailboxMessageListResponse> { ): Promise<MailMailboxMessageListResponse> {
return apiFetch<MailMailboxMessageListResponse>(settings, apiPath(`/api/v1/mail/profiles/${encodeURIComponent(profileId)}/mailbox/messages`, { return apiFetch<MailMailboxMessageListResponse>(settings, apiPath(`/api/v1/mail/profiles/${encodeURIComponent(profileId)}/mailbox/messages`, {
folder, folder,
limit, limit,
offset, offset,
cursor, cursor,
refresh: refresh ? true : undefined refresh: refresh ? true : undefined,
protocol,
q: query || undefined
})); }));
} }
@@ -693,9 +731,22 @@ export async function getMailboxMessage(
settings: ApiSettings, settings: ApiSettings,
profileId: string, profileId: string,
folder: string, folder: string,
uid: string uid: string,
protocol: MailMailboxProtocol = "imap"
): Promise<MailMailboxMessageResponse> { ): Promise<MailMailboxMessageResponse> {
return apiFetch<MailMailboxMessageResponse>(settings, apiPath(`/api/v1/mail/profiles/${encodeURIComponent(profileId)}/mailbox/messages/${encodeURIComponent(uid)}`, { folder })); return apiFetch<MailMailboxMessageResponse>(settings, apiPath(`/api/v1/mail/profiles/${encodeURIComponent(profileId)}/mailbox/messages/${encodeURIComponent(uid)}`, { folder, protocol }));
}
export async function getMailboxChanges(
settings: ApiSettings,
profileId: string,
sinceState: string,
maxChanges = 500
): Promise<MailMailboxChangesResponse> {
return apiFetch<MailMailboxChangesResponse>(settings, apiPath(`/api/v1/mail/profiles/${encodeURIComponent(profileId)}/mailbox/changes`, {
since_state: sinceState,
max_changes: maxChanges
}));
} }
export async function testSmtpSettings( export async function testSmtpSettings(
@@ -338,6 +338,8 @@ export default function MailLegacyImportPage({
render: (item) => <input render: (item) => <input
type="checkbox" type="checkbox"
aria-label={`Select ${item.subject || item.uidl}`} aria-label={`Select ${item.subject || item.uidl}`}
data-help-context-id="mail.pop3.field.message-selection"
data-help-module-id="mail"
checked={selectedUidls.includes(item.uidl)} checked={selectedUidls.includes(item.uidl)}
disabled={Boolean(busy) || item.already_imported} disabled={Boolean(busy) || item.already_imported}
onChange={() => setSelectedUidls((current) => onChange={() => setSelectedUidls((current) =>
@@ -378,13 +380,16 @@ export default function MailLegacyImportPage({
archetype="collection" archetype="collection"
title="Legacy POP3 import" title="Legacy POP3 import"
description="Migrate bounded messages into encrypted local review records. POP3 is disabled by default and is not recommended for ongoing mailbox access." description="Migrate bounded messages into encrypted local review records. POP3 is disabled by default and is not recommended for ongoing mailbox access."
helpContextId="mail.pop3"
helpModuleId="mail"
helpTopicId="mail.workflow.legacy-pop3-import"
actions={<PageActionBar actions={<PageActionBar
variant="collection" variant="collection"
refreshable refreshable
reloadAction={{ onReload: () => void load(), disabled: Boolean(busy), disabledReason: busy ? "Wait for the current POP3 action to finish." : undefined }} reloadAction={{ onReload: () => void load(), helpContextId: "mail.pop3.action.reload", helpModuleId: "mail", helpTopicId: "mail.workflow.legacy-pop3-import", disabled: Boolean(busy), disabledReason: busy ? "Wait for the current POP3 action to finish." : undefined }}
contextActions={<Button onClick={() => navigate("/mail")}><ArrowLeft size={16} aria-hidden="true" /> Mailbox</Button>} contextActions={<Button onClick={() => navigate("/mail")}><ArrowLeft size={16} aria-hidden="true" /> Mailbox</Button>}
helpAction={<DocumentationHelpLink reference={DOCUMENTATION} />} helpAction={<DocumentationHelpLink reference={DOCUMENTATION} />}
createAction={canManage ? <Button variant="primary" onClick={() => openSourceDialog(null)} disabled={Boolean(busy) || configurableProfiles.length === 0} disabledReason={configurableProfiles.length === 0 ? "Create or gain write access to a Mail profile first." : undefined}><Plus size={16} aria-hidden="true" /> Add legacy source</Button> : undefined} createAction={canManage ? <Button helpContextId="mail.pop3.action.create-source" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import" variant="primary" onClick={() => openSourceDialog(null)} disabled={Boolean(busy) || configurableProfiles.length === 0} disabledReason={configurableProfiles.length === 0 ? "Create or gain write access to a Mail profile first." : undefined}><Plus size={16} aria-hidden="true" /> Add legacy source</Button> : undefined}
/>} />}
loading={loading} loading={loading}
loadingLabel="Loading legacy POP3 sources" loadingLabel="Loading legacy POP3 sources"
@@ -419,6 +424,9 @@ export default function MailLegacyImportPage({
icon: <Pencil aria-hidden="true" />, icon: <Pencil aria-hidden="true" />,
disabled: Boolean(busy), disabled: Boolean(busy),
disabledReason: busy ? "Wait for the current POP3 action to finish." : "", disabledReason: busy ? "Wait for the current POP3 action to finish." : "",
helpContextId: "mail.pop3.action.configure-source",
helpModuleId: "mail",
helpTopicId: "mail.workflow.legacy-pop3-import",
onClick: () => openSourceDialog(selectedSource) onClick: () => openSourceDialog(selectedSource)
}]} /> : undefined} }]} /> : undefined}
> >
@@ -427,8 +435,8 @@ export default function MailLegacyImportPage({
<FormField label="Policy"><StatusBadge status={selectedSource.server.config.legacy_import_enabled ? "success" : "inactive"} label={selectedSource.server.config.legacy_import_enabled ? "explicitly enabled" : "disabled"} /></FormField> <FormField label="Policy"><StatusBadge status={selectedSource.server.config.legacy_import_enabled ? "success" : "inactive"} label={selectedSource.server.config.legacy_import_enabled ? "explicitly enabled" : "disabled"} /></FormField>
<FormField label="Transport"><span>{selectedSource.server.config.security || "tls"} · {String(selectedSource.server.config.port || 995)}</span></FormField> <FormField label="Transport"><span>{selectedSource.server.config.security || "tls"} · {String(selectedSource.server.config.port || 995)}</span></FormField>
<FormField label="Credential"><span>{selectedCredential ? String(selectedCredential.public_data?.username || selectedCredential.name) : "No credential"}</span></FormField> <FormField label="Credential"><span>{selectedCredential ? String(selectedCredential.public_data?.username || selectedCredential.name) : "No credential"}</span></FormField>
<Button onClick={() => void runConnectionTest()} disabled={Boolean(busy) || !selectedCredential || !selectedSource.server.config.legacy_import_enabled} disabledReason={!selectedCredential ? "Store an encrypted POP3 credential first." : !selectedSource.server.config.legacy_import_enabled ? "Explicitly enable legacy import first." : busy ? "Wait for the current POP3 action to finish." : undefined}>Test connection</Button> <Button helpContextId="mail.pop3.action.test" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import" onClick={() => void runConnectionTest()} disabled={Boolean(busy) || !selectedCredential || !selectedSource.server.config.legacy_import_enabled} disabledReason={!selectedCredential ? "Store an encrypted POP3 credential first." : !selectedSource.server.config.legacy_import_enabled ? "Explicitly enable legacy import first." : busy ? "Wait for the current POP3 action to finish." : undefined}>Test connection</Button>
{canImport ? <Button variant="primary" onClick={() => void refreshPreview()} disabled={Boolean(busy) || !selectedCredential || !selectedSource.server.config.legacy_import_enabled} disabledReason={!selectedCredential ? "Store an encrypted POP3 credential first." : !selectedSource.server.config.legacy_import_enabled ? "Explicitly enable legacy import first." : busy ? "Wait for the current POP3 action to finish." : undefined}>Refresh live preview</Button> : null} {canImport ? <Button helpContextId="mail.pop3.action.preview" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import" variant="primary" onClick={() => void refreshPreview()} disabled={Boolean(busy) || !selectedCredential || !selectedSource.server.config.legacy_import_enabled} disabledReason={!selectedCredential ? "Store an encrypted POP3 credential first." : !selectedSource.server.config.legacy_import_enabled ? "Explicitly enable legacy import first." : busy ? "Wait for the current POP3 action to finish." : undefined}>Refresh live preview</Button> : null}
</FormGrid> : <p className="muted">Select or configure a legacy source.</p>} </FormGrid> : <p className="muted">Select or configure a legacy source.</p>}
</Card> </Card>
</ContentGrid> </ContentGrid>
@@ -438,8 +446,8 @@ export default function MailLegacyImportPage({
<p className="muted">Provider reports {preview.message_count} message(s), {formatBytes(preview.mailbox_size_bytes)} total. Preview and ordinary import do not delete source messages.</p> <p className="muted">Provider reports {preview.message_count} message(s), {formatBytes(preview.mailbox_size_bytes)} total. Preview and ordinary import do not delete source messages.</p>
<DataGrid id="mail-pop3-preview" rows={preview.messages} columns={previewColumns} getRowKey={(item) => item.uidl} emptyText="The legacy mailbox contains no messages." /> <DataGrid id="mail-pop3-preview" rows={preview.messages} columns={previewColumns} getRowKey={(item) => item.uidl} emptyText="The legacy mailbox contains no messages." />
<FormGrid columns={2} collapseAt="standard" spacing="block"> <FormGrid columns={2} collapseAt="standard" spacing="block">
<ToggleSwitch checked={deleteAfterImport} disabled={!canDelete || !preview.delete_after_import_allowed || Boolean(busy)} onChange={setDeleteAfterImport} label="Delete newly imported messages at the source" help="Destructive and separately governed. The local encrypted import is committed first." /> <ToggleSwitch helpContextId="mail.pop3.field.delete-after-import" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import" checked={deleteAfterImport} disabled={!canDelete || !preview.delete_after_import_allowed || Boolean(busy)} onChange={setDeleteAfterImport} label="Delete newly imported messages at the source" help="Destructive and separately governed. The local encrypted import is committed first." />
<Button variant={deleteAfterImport ? "danger" : "primary"} onClick={() => deleteAfterImport ? setDeleteConfirmationOpen(true) : void runImport()} disabled={Boolean(busy) || Boolean(importBlocker)} disabledReason={importBlocker || (busy ? "Wait for the current POP3 action to finish." : undefined)}>Import {selectedUidls.length || "selected"} message(s)</Button> <Button helpContextId="mail.pop3.action.import" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import" variant={deleteAfterImport ? "danger" : "primary"} onClick={() => deleteAfterImport ? setDeleteConfirmationOpen(true) : void runImport()} disabled={Boolean(busy) || Boolean(importBlocker)} disabledReason={importBlocker || (busy ? "Wait for the current POP3 action to finish." : undefined)}>Import {selectedUidls.length || "selected"} message(s)</Button>
</FormGrid> </FormGrid>
</> : <p className="muted">Refresh a source to obtain a bounded, non-destructive preview.</p>} </> : <p className="muted">Refresh a source to obtain a bounded, non-destructive preview.</p>}
</Card> </Card>
@@ -452,34 +460,37 @@ export default function MailLegacyImportPage({
<Dialog <Dialog
open={sourceDialogOpen} open={sourceDialogOpen}
title={editingSourceId ? "Configure legacy POP3 source" : "Add legacy POP3 source"} title={editingSourceId ? "Configure legacy POP3 source" : "Add legacy POP3 source"}
helpContextId="mail.pop3.source-editor"
helpModuleId="mail"
helpTopicId="mail.workflow.legacy-pop3-import"
onClose={() => !busy && setSourceDialogOpen(false)} onClose={() => !busy && setSourceDialogOpen(false)}
footer={<><Button onClick={() => setSourceDialogOpen(false)} disabled={Boolean(busy)}>Cancel</Button><Button variant="primary" onClick={() => void saveSource()} disabled={Boolean(busy) || Boolean(sourceBlocker)} disabledReason={sourceBlocker || (busy ? "Wait for the source to be saved." : undefined)}>Save source</Button></>} footer={<><Button onClick={() => setSourceDialogOpen(false)} disabled={Boolean(busy)}>Cancel</Button><Button helpContextId="mail.pop3.action.save-source" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import" variant="primary" onClick={() => void saveSource()} disabled={Boolean(busy) || Boolean(sourceBlocker)} disabledReason={sourceBlocker || (busy ? "Wait for the source to be saved." : undefined)}>Save source</Button></>}
> >
<FormGrid columns={2} collapseAt="standard"> <FormGrid columns={2} collapseAt="standard">
<FormField label="Mail profile" help="The profile supplies scope and lifecycle ownership for this dedicated source."> <FormField label="Mail profile" help="The profile supplies scope and lifecycle ownership for this dedicated source." helpContextId="mail.pop3.field.profile" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import">
<select value={sourceDraft.profileId} disabled={Boolean(editingSourceId) || Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, profileId: event.target.value }))}> <select value={sourceDraft.profileId} disabled={Boolean(editingSourceId) || Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, profileId: event.target.value }))}>
<option value="">Select a profile</option> <option value="">Select a profile</option>
{configurableProfiles.map((profile) => <option key={profile.id} value={profile.id}>{profile.name} ({profile.scope_type})</option>)} {configurableProfiles.map((profile) => <option key={profile.id} value={profile.id}>{profile.name} ({profile.scope_type})</option>)}
</select> </select>
</FormField> </FormField>
<FormField label="Source name"><input value={sourceDraft.name} disabled={Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, name: event.target.value }))} /></FormField> <FormField label="Source name" helpContextId="mail.pop3.field.name" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import"><input value={sourceDraft.name} disabled={Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, name: event.target.value }))} /></FormField>
<FormField label="POP3 host"><input value={sourceDraft.host} disabled={Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, host: event.target.value }))} placeholder="pop3.example.org" /></FormField> <FormField label="POP3 host" helpContextId="mail.pop3.field.host" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import"><input value={sourceDraft.host} disabled={Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, host: event.target.value }))} placeholder="pop3.example.org" /></FormField>
<FormField label="Port"><input type="number" min={1} max={65535} value={sourceDraft.port} disabled={Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, port: event.target.value }))} /></FormField> <FormField label="Port" helpContextId="mail.pop3.field.port" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import"><input type="number" min={1} max={65535} value={sourceDraft.port} disabled={Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, port: event.target.value }))} /></FormField>
<FormField label="Transport security"> <FormField label="Transport security" helpContextId="mail.pop3.field.transport-security" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import">
<select value={sourceDraft.security} disabled={Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, security: event.target.value as SourceDraft["security"], port: event.target.value === "tls" ? "995" : "110" }))}> <select value={sourceDraft.security} disabled={Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, security: event.target.value as SourceDraft["security"], port: event.target.value === "tls" ? "995" : "110" }))}>
<option value="tls">TLS</option> <option value="tls">TLS</option>
<option value="starttls">STARTTLS</option> <option value="starttls">STARTTLS</option>
<option value="plain">Plain (deployment policy may deny)</option> <option value="plain">Plain (deployment policy may deny)</option>
</select> </select>
</FormField> </FormField>
<FormField label="Timeout (seconds)"><input type="number" min={1} max={300} value={sourceDraft.timeoutSeconds} disabled={Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, timeoutSeconds: event.target.value }))} /></FormField> <FormField label="Timeout (seconds)" helpContextId="mail.pop3.field.timeout" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import"><input type="number" min={1} max={300} value={sourceDraft.timeoutSeconds} disabled={Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, timeoutSeconds: event.target.value }))} /></FormField>
<FormField label="Maximum message size (MiB)"><input type="number" min={1} max={50} value={sourceDraft.maxMessageMiB} disabled={Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, maxMessageMiB: event.target.value }))} /></FormField> <FormField label="Maximum message size (MiB)" helpContextId="mail.pop3.field.max-message-size" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import"><input type="number" min={1} max={50} value={sourceDraft.maxMessageMiB} disabled={Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, maxMessageMiB: event.target.value }))} /></FormField>
<FormField label="Maximum batch size (MiB)"><input type="number" min={1} max={500} value={sourceDraft.maxBatchMiB} disabled={Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, maxBatchMiB: event.target.value }))} /></FormField> <FormField label="Maximum batch size (MiB)" helpContextId="mail.pop3.field.max-batch-size" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import"><input type="number" min={1} max={500} value={sourceDraft.maxBatchMiB} disabled={Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, maxBatchMiB: event.target.value }))} /></FormField>
<FormField label="Preview body lines"><input type="number" min={0} max={100} value={sourceDraft.previewBodyLines} disabled={Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, previewBodyLines: event.target.value }))} /></FormField> <FormField label="Preview body lines" helpContextId="mail.pop3.field.preview-body-lines" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import"><input type="number" min={0} max={100} value={sourceDraft.previewBodyLines} disabled={Boolean(busy)} onChange={(event) => setSourceDraft((draft) => ({ ...draft, previewBodyLines: event.target.value }))} /></FormField>
<FormField label="Username"><input value={sourceDraft.username} disabled={Boolean(busy) || !canManageSecrets} onChange={(event) => setSourceDraft((draft) => ({ ...draft, username: event.target.value }))} autoComplete="username" /></FormField> <FormField label="Username" helpContextId="mail.pop3.field.username" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import"><input value={sourceDraft.username} disabled={Boolean(busy) || !canManageSecrets} onChange={(event) => setSourceDraft((draft) => ({ ...draft, username: event.target.value }))} autoComplete="username" /></FormField>
<FormField label={editingSourceId ? "New password (optional)" : "Password"}><input type="password" value={sourceDraft.password} disabled={Boolean(busy) || !canManageSecrets} onChange={(event) => setSourceDraft((draft) => ({ ...draft, password: event.target.value }))} autoComplete="new-password" /></FormField> <FormField label={editingSourceId ? "New password (optional)" : "Password"} helpContextId="mail.pop3.field.password" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import"><input type="password" value={sourceDraft.password} disabled={Boolean(busy) || !canManageSecrets} onChange={(event) => setSourceDraft((draft) => ({ ...draft, password: event.target.value }))} autoComplete="new-password" /></FormField>
<ToggleSwitch checked={sourceDraft.enabled} disabled={Boolean(busy)} onChange={(enabled) => setSourceDraft((draft) => ({ ...draft, enabled, allowDeleteAfterImport: enabled ? draft.allowDeleteAfterImport : false }))} label="Explicitly enable legacy import" help="Off is the product default." /> <ToggleSwitch helpContextId="mail.pop3.field.enabled" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import" checked={sourceDraft.enabled} disabled={Boolean(busy)} onChange={(enabled) => setSourceDraft((draft) => ({ ...draft, enabled, allowDeleteAfterImport: enabled ? draft.allowDeleteAfterImport : false }))} label="Explicitly enable legacy import" help="Off is the product default." />
<ToggleSwitch checked={sourceDraft.allowDeleteAfterImport} disabled={Boolean(busy) || !sourceDraft.enabled} onChange={(allowDeleteAfterImport) => setSourceDraft((draft) => ({ ...draft, allowDeleteAfterImport }))} label="Permit delete-after-import requests" help="Operators still need a separate destructive permission and must choose deletion per batch." /> <ToggleSwitch helpContextId="mail.pop3.field.allow-delete-after-import" helpModuleId="mail" helpTopicId="mail.workflow.legacy-pop3-import" checked={sourceDraft.allowDeleteAfterImport} disabled={Boolean(busy) || !sourceDraft.enabled} onChange={(allowDeleteAfterImport) => setSourceDraft((draft) => ({ ...draft, allowDeleteAfterImport }))} label="Permit delete-after-import requests" help="Operators still need a separate destructive permission and must choose deletion per batch." />
</FormGrid> </FormGrid>
</Dialog> </Dialog>
@@ -488,6 +499,9 @@ export default function MailLegacyImportPage({
title="Import and delete source messages" title="Import and delete source messages"
message={`Mail will first commit and audit ${selectedUidls.length} encrypted local import(s), then ask the POP3 server to delete only those newly imported messages. Provider deletion cannot be undone and may require reconciliation if its outcome is unknown.`} message={`Mail will first commit and audit ${selectedUidls.length} encrypted local import(s), then ask the POP3 server to delete only those newly imported messages. Provider deletion cannot be undone and may require reconciliation if its outcome is unknown.`}
confirmLabel="Import, then delete source" confirmLabel="Import, then delete source"
helpContextId="mail.pop3.confirm-delete-source"
helpModuleId="mail"
helpTopicId="mail.workflow.legacy-pop3-import"
tone="danger" tone="danger"
busy={Boolean(busy)} busy={Boolean(busy)}
onCancel={() => setDeleteConfirmationOpen(false)} onCancel={() => setDeleteConfirmationOpen(false)}
+173 -15
View File
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useState, type ReactNode } from "react"; import { useEffect, useMemo, useState, type ReactNode } from "react";
import { ActionToolbar, FormGrid, ActionBlockerHint, AdminSelectionList, ConnectionTree, DocumentationHelpLink, FieldLabel, LoadingFrame, MailServerSettingsPanel, PolicyLockedHint, PolicyPathHelp, PolicyRow, PolicySourcePath, PolicyTable, StageRail, StatusBadge, TableActionGroup, ToggleSwitch, hasMailImapSettings, mailImapSettingsPayload, mailServerSecurityOptions, mailSmtpSettingsPayload, mailTextOrNull, mailTransportCredentialsPayload, mergeDeltaRows, normalizeMailImapFolderMappings, normalizeMailServerSecurity, normalizePolicySourcePathItems, useDeltaWatermarks, type ConnectionTreeColumn, type MailImapFolderMappings, type MailImapFolderListResponse, type MailServerConnectionTestResult, type MailServerCredentialSettings, type MailServerImapSettings, type MailServerSmtpSettings, type NormalizedPolicySourcePathItem, type PolicySourcePathItem } from "@govoplan/core-webui"; import { ActionToolbar, FormGrid, ActionBlockerHint, AdminSelectionList, ConnectionTree, DocumentationHelpLink, FieldLabel, LoadingFrame, MailServerSettingsPanel, PolicyLockedHint, PolicyPathHelp, PolicyRow, PolicySourcePath, PolicyTable, StageRail, StatusBadge, TableActionGroup, ToggleSwitch, hasMailImapSettings, mailImapSettingsPayload, mailServerSecurityOptions, mailSmtpSettingsPayload, mailTextOrNull, mailTransportCredentialsPayload, mergeDeltaRows, normalizeMailImapFolderMappings, normalizeMailServerSecurity, normalizePolicySourcePathItems, useDeltaWatermarks, type ConnectionTreeColumn, type MailImapFolderMappings, type MailImapFolderListResponse, type MailJmapTransportSettings, type MailServerConnectionTestResult, type MailServerCredentialSettings, type MailServerImapSettings, type MailServerSmtpSettings, type NormalizedPolicySourcePathItem, type PolicySourcePathItem } from "@govoplan/core-webui";
import { ArrowLeft, ArrowRight, Inbox, KeyRound, Link2, Pencil, Plus, Send, Settings2, Trash2, Unlink } from "lucide-react"; import { ArrowLeft, ArrowRight, Inbox, KeyRound, Link2, Pencil, Plus, Send, Settings2, Trash2, Unlink } from "lucide-react";
import type { ApiSettings } from "../../types"; import type { ApiSettings } from "../../types";
import { import {
@@ -19,6 +19,7 @@ import {
updateMailProfilePolicy, updateMailProfilePolicy,
testImapSettings, testImapSettings,
testMailProfileImap, testMailProfileImap,
testMailProfileJmap,
testMailProfileSmtp, testMailProfileSmtp,
testSmtpSettings, testSmtpSettings,
unlinkMailServerCredential, unlinkMailServerCredential,
@@ -106,6 +107,15 @@ type ProfileDraft = {
imapSentFolder: string; imapSentFolder: string;
imapFolderMappings: MailImapFolderMappings; imapFolderMappings: MailImapFolderMappings;
imapTimeout: string; imapTimeout: string;
jmapSessionUrl: string;
jmapAccountId: string;
jmapAuthScheme: "bearer" | "basic";
jmapAllowedApiOrigins: string;
jmapTimeout: string;
jmapMaxResponseBytes: string;
jmapMaxBodyValueBytes: string;
jmapUsername: string;
jmapToken: string;
}; };
type MailProfileScopeManagerProps = { type MailProfileScopeManagerProps = {
@@ -163,6 +173,7 @@ const MAIL_PROFILE_WORKFLOW_DOCUMENTATION = {
const patternLabels: Record<MailProfilePatternKey, string> = { const patternLabels: Record<MailProfilePatternKey, string> = {
smtp_hosts: "i18n:govoplan-mail.smtp_hostnames.36eb51d8", smtp_hosts: "i18n:govoplan-mail.smtp_hostnames.36eb51d8",
imap_hosts: "i18n:govoplan-mail.imap_hostnames.ac9c1d78", imap_hosts: "i18n:govoplan-mail.imap_hostnames.ac9c1d78",
jmap_hosts: "JMAP hostnames",
envelope_senders: "i18n:govoplan-mail.envelope_senders.269065cd", envelope_senders: "i18n:govoplan-mail.envelope_senders.269065cd",
from_headers: "i18n:govoplan-mail.from_headers.b3ea473b", from_headers: "i18n:govoplan-mail.from_headers.b3ea473b",
recipient_domains: "i18n:govoplan-mail.recipient_domains.cb9b7b44" recipient_domains: "i18n:govoplan-mail.recipient_domains.cb9b7b44"
@@ -402,7 +413,11 @@ export function MailProfileScopeManager({
} else if (editingTarget.kind === "server") { } else if (editingTarget.kind === "server") {
const serverPayload = { const serverPayload = {
name: draft.serverName.trim(), name: draft.serverName.trim(),
config: editingTarget.protocol === "smtp" ? smtpServerPayload(draft) : imapServerPayload(draft), config: editingTarget.protocol === "smtp"
? smtpServerPayload(draft)
: editingTarget.protocol === "imap"
? imapServerPayload(draft)
: jmapServerPayload(draft),
inherit_to_lower_scopes: draft.serverInheritToLowerScopes, inherit_to_lower_scopes: draft.serverInheritToLowerScopes,
is_default: draft.serverIsDefault, is_default: draft.serverIsDefault,
is_active: draft.serverIsActive is_active: draft.serverIsActive
@@ -526,7 +541,7 @@ export function MailProfileScopeManager({
header: "i18n:govoplan-mail.transport.c10d76c9", header: "i18n:govoplan-mail.transport.c10d76c9",
width: "minmax(220px, 1fr)", width: "minmax(220px, 1fr)",
render: (row) => row.kind === "profile" ? render: (row) => row.kind === "profile" ?
<span>{transportLabel(row.profile.smtp)}{row.profile.imap ? i18nMessage("i18n:govoplan-mail.value.48afe802", { value0: transportLabel(row.profile.imap) }) : ""}</span> : <span>{profileTransportLabels(row.profile).join(" · ")}</span> :
row.kind === "server" ? row.kind === "server" ?
<TransportCell server={row.server} /> : <TransportCell server={row.server} /> :
<span>{String(row.credential.public_data?.username || "No username")}</span> <span>{String(row.credential.public_data?.username || "No username")}</span>
@@ -660,6 +675,7 @@ export function MailProfileScopeManager({
{ id: "edit", label: i18nMessage("i18n:govoplan-mail.edit_value.fad75899", { value0: row.profile.name }), icon: <Pencil size={16} />, disabled: Boolean(profileMutationBlocker), disabledReason: profileMutationBlocker, onClick: () => openEdit(row.profile) }, { id: "edit", label: i18nMessage("i18n:govoplan-mail.edit_value.fad75899", { value0: row.profile.name }), icon: <Pencil size={16} />, disabled: Boolean(profileMutationBlocker), disabledReason: profileMutationBlocker, onClick: () => openEdit(row.profile) },
{ id: "add-smtp", label: "Add SMTP server", icon: <Plus size={16} />, disabled: Boolean(profileMutationBlocker), disabledReason: profileMutationBlocker, onClick: () => openCreateServer(row.profile, "smtp") }, { id: "add-smtp", label: "Add SMTP server", icon: <Plus size={16} />, disabled: Boolean(profileMutationBlocker), disabledReason: profileMutationBlocker, onClick: () => openCreateServer(row.profile, "smtp") },
{ id: "add-imap", label: "Add IMAP server", icon: <Plus size={16} />, disabled: Boolean(profileMutationBlocker), disabledReason: profileMutationBlocker, onClick: () => openCreateServer(row.profile, "imap") }, { id: "add-imap", label: "Add IMAP server", icon: <Plus size={16} />, disabled: Boolean(profileMutationBlocker), disabledReason: profileMutationBlocker, onClick: () => openCreateServer(row.profile, "imap") },
{ id: "add-jmap", label: "Add JMAP server", icon: <Plus size={16} />, disabled: Boolean(profileMutationBlocker), disabledReason: profileMutationBlocker, onClick: () => openCreateServer(row.profile, "jmap") },
{ id: "deactivate", label: i18nMessage("i18n:govoplan-mail.deactivate_value.a276a667", { value0: row.profile.name }), icon: <Trash2 size={16} />, variant: "danger", disabled: Boolean(deactivationBlocker), disabledReason: deactivationBlocker, onClick: () => setDeactivating(row.profile) } { id: "deactivate", label: i18nMessage("i18n:govoplan-mail.deactivate_value.a276a667", { value0: row.profile.name }), icon: <Trash2 size={16} />, variant: "danger", disabled: Boolean(deactivationBlocker), disabledReason: deactivationBlocker, onClick: () => setDeactivating(row.profile) }
]} />; ]} />;
@@ -1166,8 +1182,9 @@ function ProfileForm({
const { translateText } = usePlatformLanguage(); const { translateText } = usePlatformLanguage();
const [smtpTestResult, setSmtpTestResult] = useState<MailServerConnectionTestResult | null>(null); const [smtpTestResult, setSmtpTestResult] = useState<MailServerConnectionTestResult | null>(null);
const [imapTestResult, setImapTestResult] = useState<MailServerConnectionTestResult | null>(null); const [imapTestResult, setImapTestResult] = useState<MailServerConnectionTestResult | null>(null);
const [jmapTestResult, setJmapTestResult] = useState<MailServerConnectionTestResult | null>(null);
const [imapFolderResult, setImapFolderResult] = useState<MailImapFolderListResponse | null>(null); const [imapFolderResult, setImapFolderResult] = useState<MailImapFolderListResponse | null>(null);
const [mailActionState, setMailActionState] = useState<"smtp" | "imap" | "folders" | null>(null); const [mailActionState, setMailActionState] = useState<"smtp" | "imap" | "jmap" | "folders" | null>(null);
const disabled = busy || !canWrite; const disabled = busy || !canWrite;
const credentialDisabled = disabled || !canManageCredentials; const credentialDisabled = disabled || !canManageCredentials;
@@ -1205,6 +1222,13 @@ function ProfileForm({
&& selectedServerId && selectedServerId
&& !draft.imapPassword && !draft.imapPassword
); );
const useSavedJmapTest = Boolean(
existingProfile
&& (editTarget.kind === "server" || editTarget.kind === "credentials")
&& editTarget.protocol === "jmap"
&& selectedServerId
&& !draft.jmapToken
);
const creatingCredential = editTarget.kind === "credentials" && !editTarget.credentialId; const creatingCredential = editTarget.kind === "credentials" && !editTarget.credentialId;
const creatingNewCredential = creatingCredential && !reuseCredentialId; const creatingNewCredential = creatingCredential && !reuseCredentialId;
const moduleReferenceOptions = useMemo<ReferenceOption[]>( const moduleReferenceOptions = useMemo<ReferenceOption[]>(
@@ -1249,8 +1273,9 @@ function ProfileForm({
); );
const policyMessages = useMemo(() => validateMailPolicy(effectivePolicy, { const policyMessages = useMemo(() => validateMailPolicy(effectivePolicy, {
smtpHost: draft.smtpHost, smtpHost: draft.smtpHost,
imapHost: draft.imapHost imapHost: draft.imapHost,
}), [draft.imapHost, draft.smtpHost, effectivePolicy]); jmapHost: jmapHostname(draft.jmapSessionUrl)
}), [draft.imapHost, draft.jmapSessionUrl, draft.smtpHost, effectivePolicy]);
const profileFormMutationBlocker = mailProfileMutationDisabledReason(canWrite, busy); const profileFormMutationBlocker = mailProfileMutationDisabledReason(canWrite, busy);
const smtpTestBlocker = profileFormMutationBlocker const smtpTestBlocker = profileFormMutationBlocker
|| (!draft.smtpHost.trim() ? "Enter an SMTP server hostname before testing the connection." : ""); || (!draft.smtpHost.trim() ? "Enter an SMTP server hostname before testing the connection." : "");
@@ -1260,6 +1285,7 @@ function ProfileForm({
useEffect(() => { useEffect(() => {
setSmtpTestResult(null); setSmtpTestResult(null);
setImapTestResult(null); setImapTestResult(null);
setJmapTestResult(null);
setImapFolderResult(null); setImapFolderResult(null);
setMailActionState(null); setMailActionState(null);
}, [editing, editTarget]); }, [editing, editTarget]);
@@ -1346,6 +1372,24 @@ function ProfileForm({
} }
} }
async function runJmapTest() {
if (!existingProfile || !selectedServerId) return;
setMailActionState("jmap");
setJmapTestResult(null);
try {
setJmapTestResult(await testMailProfileJmap(
settings,
existingProfile.id,
selectedServerId,
selectedCredentialId
));
} catch (err) {
setJmapTestResult({ ok: false, protocol: "jmap", message: errorMessage(err), details: {} });
} finally {
setMailActionState(null);
}
}
return ( return (
<div className="mail-profile-form"> <div className="mail-profile-form">
{!canManageCredentials && ( {!canManageCredentials && (
@@ -1359,7 +1403,7 @@ function ProfileForm({
details: "Profile metadata and server configuration are separate from encrypted credential authority.", details: "Profile metadata and server configuration are separate from encrypted credential authority.",
requiredAction: "Ask a Mail credential administrator to create, replace, or link the required credential.", requiredAction: "Ask a Mail credential administrator to create, replace, or link the required credential.",
actor: "Mail credential administrator", actor: "Mail credential administrator",
target: "The credential row beneath the relevant SMTP or IMAP server" target: "The credential row beneath the relevant SMTP, IMAP, or JMAP server"
}} }}
documentation={MAIL_PROFILE_DOCUMENTATION} /> documentation={MAIL_PROFILE_DOCUMENTATION} />
} }
@@ -1411,6 +1455,43 @@ function ProfileForm({
</FormGrid> </FormGrid>
} }
{editTarget.kind === "server" && editTarget.protocol === "jmap" &&
<FormGrid columns={2} gap="small" collapseAt="workspace" className="">
<FormField label="JMAP Session URL" help="Use the authenticated RFC 8620 Session resource URL; credentials must not be embedded in the URL." documentation={MAIL_PROFILE_DOCUMENTATION}>
<input value={draft.jmapSessionUrl} disabled={disabled} onChange={(event) => setDraft({ ...draft, jmapSessionUrl: event.target.value })} placeholder="https://mail.example.org/.well-known/jmap" />
</FormField>
<FormField label="Account id" help="Leave blank to use the primary JMAP Mail account. Configure it when the credential exposes multiple mail accounts.">
<input value={draft.jmapAccountId} disabled={disabled} onChange={(event) => setDraft({ ...draft, jmapAccountId: event.target.value })} />
</FormField>
<FormField label="Authentication scheme">
<select value={draft.jmapAuthScheme} disabled={disabled} onChange={(event) => setDraft({ ...draft, jmapAuthScheme: event.target.value as "bearer" | "basic" })}>
<option value="bearer">Bearer access token</option>
<option value="basic">Basic username and password</option>
</select>
</FormField>
<FormField label="Allowed API origins" help="Optional comma-separated origins for an apiUrl hosted on a different origin than the Session resource. Cross-origin endpoints fail closed unless listed.">
<textarea rows={2} value={draft.jmapAllowedApiOrigins} disabled={disabled} onChange={(event) => setDraft({ ...draft, jmapAllowedApiOrigins: event.target.value })} placeholder="https://api.example.org" />
</FormField>
<FormField label="Timeout (seconds)">
<input type="number" min="1" max="120" value={draft.jmapTimeout} disabled={disabled} onChange={(event) => setDraft({ ...draft, jmapTimeout: event.target.value })} />
</FormField>
<FormField label="Maximum response bytes">
<input type="number" min="65536" max="26214400" value={draft.jmapMaxResponseBytes} disabled={disabled} onChange={(event) => setDraft({ ...draft, jmapMaxResponseBytes: event.target.value })} />
</FormField>
<FormField label="Maximum body value bytes">
<input type="number" min="1024" max="5242880" value={draft.jmapMaxBodyValueBytes} disabled={disabled} onChange={(event) => setDraft({ ...draft, jmapMaxBodyValueBytes: event.target.value })} />
</FormField>
{editTarget.serverId &&
<div className="mail-server-field-span">
<Button onClick={() => void runJmapTest()} disabled={disabled || mailActionState !== null || (!useSavedJmapTest && !selectedCredentialId)} disabledReason={!useSavedJmapTest && !selectedCredentialId ? "Save or select a JMAP credential before testing." : undefined}>
{mailActionState === "jmap" ? "Testing JMAP…" : "Test saved JMAP"}
</Button>
<MailServerActionResult result={jmapTestResult} />
</div>
}
</FormGrid>
}
{editTarget.kind === "credentials" && {editTarget.kind === "credentials" &&
<FormGrid columns={2} gap="small" collapseAt="workspace" className=""> <FormGrid columns={2} gap="small" collapseAt="workspace" className="">
{creatingCredential && {creatingCredential &&
@@ -1469,6 +1550,18 @@ function ProfileForm({
onChange={(checked) => setDraft({ ...draft, credentialInheritToLowerScopes: checked })} onChange={(checked) => setDraft({ ...draft, credentialInheritToLowerScopes: checked })}
label="Visible to lower scopes" /> label="Visible to lower scopes" />
</div> </div>
{editTarget.protocol === "jmap" &&
<>
{draft.jmapAuthScheme === "basic" &&
<FormField label="JMAP username">
<input value={draft.jmapUsername} disabled={credentialDisabled} onChange={(event) => setDraft({ ...draft, jmapUsername: event.target.value })} autoComplete="username" />
</FormField>
}
<FormField label={draft.jmapAuthScheme === "bearer" ? "JMAP access token" : "JMAP password"} help={selectedCredential?.secret_configured ? "A secret is saved. Leave blank to retain it." : "The secret is encrypted in the governed credential envelope."}>
<input type="password" value={draft.jmapToken} disabled={credentialDisabled} onChange={(event) => setDraft({ ...draft, jmapToken: event.target.value })} autoComplete="new-password" />
</FormField>
</>
}
</> </>
} }
{reuseCredentialId && {reuseCredentialId &&
@@ -1574,6 +1667,7 @@ function MailCredentialTreeCell({ credential }: {credential: MailCredentialEnvel
} }
function ProfileTransportSummary({ profile }: {profile: MailServerProfile;}) { function ProfileTransportSummary({ profile }: {profile: MailServerProfile;}) {
const jmapServer = preferredProfileServer(profile, "jmap");
return ( return (
<div className="mail-profile-transport-summary"> <div className="mail-profile-transport-summary">
<div> <div>
@@ -1586,6 +1680,11 @@ function ProfileTransportSummary({ profile }: {profile: MailServerProfile;}) {
<strong>{transportLabel(profile.imap)}</strong> <strong>{transportLabel(profile.imap)}</strong>
<small>{profile.imap ? mailCredentialConfigured(profile, "imap") ? "i18n:govoplan-mail.password_saved.f6fab237" : "i18n:govoplan-mail.no_saved_password.32ce2b16" : "i18n:govoplan-mail.not_configured.811931bb"}</small> <small>{profile.imap ? mailCredentialConfigured(profile, "imap") ? "i18n:govoplan-mail.password_saved.f6fab237" : "i18n:govoplan-mail.no_saved_password.32ce2b16" : "i18n:govoplan-mail.not_configured.811931bb"}</small>
</div> </div>
<div>
<span>JMAP server</span>
<strong>{transportLabel(jmapServer?.config)}</strong>
<small>{jmapServer ? jmapServer.credentials.some((credential) => credential.secret_configured) ? "Credential saved" : "No saved credential" : "i18n:govoplan-mail.not_configured.811931bb"}</small>
</div>
</div>); </div>);
} }
@@ -1607,6 +1706,19 @@ function mailCredentialConfigured(profile: MailServerProfile, protocol: "smtp" |
return protocol === "smtp" ? profile.smtp_password_configured : profile.imap_password_configured; return protocol === "smtp" ? profile.smtp_password_configured : profile.imap_password_configured;
} }
function preferredProfileServer(profile: MailServerProfile, protocol: MailProfileProtocol): MailServerEndpoint | null {
const servers = (profile.servers ?? []).filter((server) => server.protocol === protocol && server.is_active);
return servers.find((server) => server.is_default) ?? servers[0] ?? null;
}
function profileTransportLabels(profile: MailServerProfile): string[] {
const labels = [`SMTP · ${transportLabel(profile.smtp)}`];
if (profile.imap) labels.push(`IMAP · ${transportLabel(profile.imap)}`);
const jmap = preferredProfileServer(profile, "jmap");
if (jmap) labels.push(`JMAP · ${transportLabel(jmap.config)}`);
return labels;
}
function credentialAvailabilityLabel(credential: MailCredentialEnvelope): string { function credentialAvailabilityLabel(credential: MailCredentialEnvelope): string {
const modules = credential.allowed_modules.length > 0 ? credential.allowed_modules.join(", ") : "all modules"; const modules = credential.allowed_modules.length > 0 ? credential.allowed_modules.join(", ") : "all modules";
const servers = credential.allowed_server_refs.length > 0 const servers = credential.allowed_server_refs.length > 0
@@ -1669,7 +1781,16 @@ function emptyProfileDraft(): ProfileDraft {
imapPassword: "", imapPassword: "",
imapSentFolder: "auto", imapSentFolder: "auto",
imapFolderMappings: {}, imapFolderMappings: {},
imapTimeout: "30" imapTimeout: "30",
jmapSessionUrl: "",
jmapAccountId: "",
jmapAuthScheme: "bearer",
jmapAllowedApiOrigins: "",
jmapTimeout: "20",
jmapMaxResponseBytes: String(5 * 1024 * 1024),
jmapMaxBodyValueBytes: String(1024 * 1024),
jmapUsername: "",
jmapToken: ""
}; };
} }
@@ -1688,6 +1809,7 @@ function profileToDraft(profile: MailServerProfile, target: MailProfileEditTarge
: undefined; : undefined;
const smtpConfig = targetServer?.protocol === "smtp" ? targetServer.config : profile.smtp; const smtpConfig = targetServer?.protocol === "smtp" ? targetServer.config : profile.smtp;
const imapConfig = targetServer?.protocol === "imap" ? targetServer.config : profile.imap; const imapConfig = targetServer?.protocol === "imap" ? targetServer.config : profile.imap;
const jmapConfig = targetServer?.protocol === "jmap" ? targetServer.config as MailJmapTransportSettings : undefined;
const targetUsername = stringValue(targetCredential?.public_data?.username); const targetUsername = stringValue(targetCredential?.public_data?.username);
return { return {
name: profile.name, name: profile.name,
@@ -1725,7 +1847,16 @@ function profileToDraft(profile: MailServerProfile, target: MailProfileEditTarge
...(imapConfig?.folder_mappings ?? {}), ...(imapConfig?.folder_mappings ?? {}),
...(!imapConfig?.folder_mappings?.sent && imapConfig?.sent_folder && imapConfig.sent_folder !== "auto" ? { sent: imapConfig.sent_folder } : {}) ...(!imapConfig?.folder_mappings?.sent && imapConfig?.sent_folder && imapConfig.sent_folder !== "auto" ? { sent: imapConfig.sent_folder } : {})
}), }),
imapTimeout: stringValue(imapConfig?.timeout_seconds ?? 30) imapTimeout: stringValue(imapConfig?.timeout_seconds ?? 30),
jmapSessionUrl: stringValue(jmapConfig?.session_url),
jmapAccountId: stringValue(jmapConfig?.account_id),
jmapAuthScheme: jmapConfig?.auth_scheme === "basic" ? "basic" : "bearer",
jmapAllowedApiOrigins: (jmapConfig?.allowed_api_origins ?? []).join(", "),
jmapTimeout: stringValue(jmapConfig?.timeout_seconds ?? 20),
jmapMaxResponseBytes: stringValue(jmapConfig?.max_response_bytes ?? 5 * 1024 * 1024),
jmapMaxBodyValueBytes: stringValue(jmapConfig?.max_body_value_bytes ?? 1024 * 1024),
jmapUsername: targetServer?.protocol === "jmap" && targetCredential ? targetUsername : "",
jmapToken: ""
}; };
} }
@@ -1758,8 +1889,8 @@ function updateProfilePayload(
} }
function credentialPayload(draft: ProfileDraft, protocol: MailProfileProtocol, preserveBlankPassword: boolean) { function credentialPayload(draft: ProfileDraft, protocol: MailProfileProtocol, preserveBlankPassword: boolean) {
const username = protocol === "smtp" ? draft.smtpUsername : draft.imapUsername; const username = protocol === "smtp" ? draft.smtpUsername : protocol === "imap" ? draft.imapUsername : draft.jmapUsername;
const password = protocol === "smtp" ? draft.smtpPassword : draft.imapPassword; const password = protocol === "smtp" ? draft.smtpPassword : protocol === "imap" ? draft.imapPassword : draft.jmapToken;
const allowedModules = commaValues(draft.credentialAllowedModules); const allowedModules = commaValues(draft.credentialAllowedModules);
const allowedServerRefs = commaValues(draft.credentialAllowedServerRefs); const allowedServerRefs = commaValues(draft.credentialAllowedServerRefs);
const payload: { const payload: {
@@ -1775,7 +1906,7 @@ function credentialPayload(draft: ProfileDraft, protocol: MailProfileProtocol, p
} = { } = {
name: draft.credentialName.trim(), name: draft.credentialName.trim(),
description: mailTextOrNull(draft.credentialDescription), description: mailTextOrNull(draft.credentialDescription),
credential_kind: "username_password", credential_kind: protocol === "jmap" && draft.jmapAuthScheme === "bearer" ? "bearer_token" : "username_password",
username: mailTextOrNull(username), username: mailTextOrNull(username),
inherit_to_lower_scopes: draft.credentialInheritToLowerScopes, inherit_to_lower_scopes: draft.credentialInheritToLowerScopes,
allowed_modules: allowedModules.length > 0 ? allowedModules : ["mail"], allowed_modules: allowedModules.length > 0 ? allowedModules : ["mail"],
@@ -1796,13 +1927,13 @@ function profileEditorCanSave(
if (editing === "new") return Boolean(draft.name.trim() && draft.smtpHost.trim()); if (editing === "new") return Boolean(draft.name.trim() && draft.smtpHost.trim());
if (target.kind === "profile") return Boolean(draft.name.trim()); if (target.kind === "profile") return Boolean(draft.name.trim());
if (target.kind === "server") { if (target.kind === "server") {
const host = target.protocol === "smtp" ? draft.smtpHost : draft.imapHost; const host = target.protocol === "smtp" ? draft.smtpHost : target.protocol === "imap" ? draft.imapHost : draft.jmapSessionUrl;
return Boolean(draft.serverName.trim() && host.trim()); return Boolean(draft.serverName.trim() && host.trim());
} }
if (target.kind === "credentials") { if (target.kind === "credentials") {
if (!target.serverId) return false; if (!target.serverId) return false;
if (!target.credentialId && reuseCredentialId) return true; if (!target.credentialId && reuseCredentialId) return true;
const password = target.protocol === "smtp" ? draft.smtpPassword : draft.imapPassword; const password = target.protocol === "smtp" ? draft.smtpPassword : target.protocol === "imap" ? draft.imapPassword : draft.jmapToken;
return Boolean(draft.credentialName.trim() && (target.credentialId || password)); return Boolean(draft.credentialName.trim() && (target.credentialId || password));
} }
return false; return false;
@@ -1906,6 +2037,18 @@ function imapServerPayload(draft: ProfileDraft): MailImapTestPayload {
); );
} }
function jmapServerPayload(draft: ProfileDraft): MailJmapTransportSettings {
return {
session_url: draft.jmapSessionUrl.trim(),
account_id: mailTextOrNull(draft.jmapAccountId),
auth_scheme: draft.jmapAuthScheme,
timeout_seconds: boundedInteger(draft.jmapTimeout, 20, 1, 120),
max_response_bytes: boundedInteger(draft.jmapMaxResponseBytes, 5 * 1024 * 1024, 64 * 1024, 25 * 1024 * 1024),
max_body_value_bytes: boundedInteger(draft.jmapMaxBodyValueBytes, 1024 * 1024, 1024, 5 * 1024 * 1024),
allowed_api_origins: commaValues(draft.jmapAllowedApiOrigins)
};
}
function profileCredentialsPayload(draft: ProfileDraft, preserveBlankPassword: boolean) { function profileCredentialsPayload(draft: ProfileDraft, preserveBlankPassword: boolean) {
return { return {
smtp: mailTransportCredentialsPayload(draft.smtpUsername, draft.smtpPassword, preserveBlankPassword), smtp: mailTransportCredentialsPayload(draft.smtpUsername, draft.smtpPassword, preserveBlankPassword),
@@ -2171,8 +2314,9 @@ function mailPolicySourcePath(scopeType: MailProfileScope): string[] {
return ["i18n:govoplan-mail.system.bc0792d8", "i18n:govoplan-mail.tenant.3ca93c78", "i18n:govoplan-mail.owner_policy.1e8df143", "i18n:govoplan-mail.campaign.69390e16"]; return ["i18n:govoplan-mail.system.bc0792d8", "i18n:govoplan-mail.tenant.3ca93c78", "i18n:govoplan-mail.owner_policy.1e8df143", "i18n:govoplan-mail.campaign.69390e16"];
} }
function transportLabel(transport: MailSmtpTestPayload | MailImapTestPayload | null | undefined): string { function transportLabel(transport: MailSmtpTestPayload | MailImapTestPayload | MailJmapTransportSettings | null | undefined): string {
if (!transport) return "i18n:govoplan-mail.not_configured.811931bb"; if (!transport) return "i18n:govoplan-mail.not_configured.811931bb";
if ("session_url" in transport) return transport.session_url || "No Session URL";
const host = transport.host || "i18n:govoplan-mail.no_host.4c710d7d"; const host = transport.host || "i18n:govoplan-mail.no_host.4c710d7d";
const port = transport.port ? `:${transport.port}` : ""; const port = transport.port ? `:${transport.port}` : "";
return `${host}${port}`; return `${host}${port}`;
@@ -2204,6 +2348,20 @@ function commaValues(value: string): string[] {
)]; )];
} }
function boundedInteger(value: string, fallback: number, minimum: number, maximum: number): number {
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed)) return fallback;
return Math.min(maximum, Math.max(minimum, parsed));
}
function jmapHostname(value: string): string {
try {
return new URL(value).hostname;
} catch {
return "";
}
}
function errorMessage(err: unknown): string { function errorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err); return err instanceof Error ? err.message : String(err);
} }
+10 -2
View File
@@ -16,6 +16,7 @@ import {
bootstrapMailbox, bootstrapMailbox,
listMailServerProfiles, listMailServerProfiles,
lookupMailAddresses, lookupMailAddresses,
type MailMailboxProtocol,
type MailMailboxMessageSummary type MailMailboxMessageSummary
} from "../../api/mail"; } from "../../api/mail";
import { mailLookupSuggestions, mailtoHref } from "./mailAddressIntegration"; import { mailLookupSuggestions, mailtoHref } from "./mailAddressIntegration";
@@ -53,9 +54,10 @@ export default function MailQuickAccess({
const lookupRequestRef = useRef(0); const lookupRequestRef = useRef(0);
const load = useCallback(async (): Promise<MailQuickAccessData> => { const load = useCallback(async (): Promise<MailQuickAccessData> => {
const profiles = await listMailServerProfiles(settings); const profiles = await listMailServerProfiles(settings);
const profile = profiles.find((item) => item.is_active && item.imap); const profile = profiles.find((item) => item.is_active && quickAccessMailboxProtocol(item));
if (!profile) return { messages: [], available: false }; if (!profile) return { messages: [], available: false };
const response = await bootstrapMailbox(settings, profile.id, "INBOX", 7, 0, false); const protocol = quickAccessMailboxProtocol(profile) ?? "imap";
const response = await bootstrapMailbox(settings, profile.id, "INBOX", 7, 0, false, protocol);
return { return {
profileName: profile.name, profileName: profile.name,
profileId: profile.id, profileId: profile.id,
@@ -188,6 +190,12 @@ export default function MailQuickAccess({
); );
} }
function quickAccessMailboxProtocol(profile: { imap?: unknown; servers?: Array<{ protocol: string; is_active: boolean; is_default?: boolean }> }): MailMailboxProtocol | null {
if (profile.servers?.some((server) => server.protocol === "jmap" && server.is_active)) return "jmap";
if (profile.imap || profile.servers?.some((server) => server.protocol === "imap" && server.is_active)) return "imap";
return null;
}
function formatMessageDate(value?: string | null): string | undefined { function formatMessageDate(value?: string | null): string | undefined {
if (!value) return undefined; if (!value) return undefined;
+66 -24
View File
@@ -30,6 +30,7 @@ import {
type MailImapFolderResponse, type MailImapFolderResponse,
type MailMailboxMessageDetail, type MailMailboxMessageDetail,
type MailMailboxMessageSummary, type MailMailboxMessageSummary,
type MailMailboxProtocol,
type MailServerProfile } from type MailServerProfile } from
"../../api/mail"; "../../api/mail";
import { buildMailboxFolderTree, findFolderNodeId, folderAncestorIds, type MailFolderNode } from "./mailboxFolders"; import { buildMailboxFolderTree, findFolderNodeId, folderAncestorIds, type MailFolderNode } from "./mailboxFolders";
@@ -77,29 +78,30 @@ export default function MailboxPage({ settings, auth }: { settings: ApiSettings;
const launchRequestRef = useRef<MailboxLaunch | null>(parseMailboxLaunch(location.search)); const launchRequestRef = useRef<MailboxLaunch | null>(parseMailboxLaunch(location.search));
const selectedProfile = profiles.find((profile) => profile.id === selectedProfileId) ?? null; const selectedProfile = profiles.find((profile) => profile.id === selectedProfileId) ?? null;
const imapProfiles = useMemo(() => profiles.filter((profile) => profile.is_active && profile.imap), [profiles]); const mailboxProfiles = useMemo(() => profiles.filter((profile) => profile.is_active && mailboxProtocolForProfile(profile)), [profiles]);
const selectedMailboxProtocol = mailboxProtocolForProfile(selectedProfile) ?? "imap";
const folderTree = useMemo(() => buildMailboxFolderTree(folders), [folders]); const folderTree = useMemo(() => buildMailboxFolderTree(folders), [folders]);
const selectedFolderNodeId = useMemo(() => findFolderNodeId(folderTree, selectedFolder) ?? "", [folderTree, selectedFolder]); const selectedFolderNodeId = useMemo(() => findFolderNodeId(folderTree, selectedFolder) ?? "", [folderTree, selectedFolder]);
const filteredMessages = useMemo(() => filterMessages(messages, messageQuery), [messageQuery, messages]); const filteredMessages = useMemo(() => filterMessages(messages, messageQuery), [messageQuery, messages]);
const messagePageCount = Math.max(1, Math.ceil((messageTotalCount ?? 0) / messagePageSize)); const messagePageCount = Math.max(1, Math.ceil((messageTotalCount ?? 0) / messagePageSize));
const shellBusy = loadingProfiles || loadingFolders || loadingMessages; const shellBusy = loadingProfiles || loadingFolders || loadingMessages;
const noImapProfiles = !loadingProfiles && imapProfiles.length === 0; const noMailboxProfiles = !loadingProfiles && mailboxProfiles.length === 0;
const foldersReady = Boolean(selectedProfileId) && foldersLoadedForProfile === selectedProfileId; const foldersReady = Boolean(selectedProfileId) && foldersLoadedForProfile === selectedProfileId;
const selectedMessageKey = pendingMessageKey || selectedMessageKeyState || (selectedMessage ? mailboxMessageKey(selectedMessage.folder || selectedFolder, selectedMessage.uid) : ""); const selectedMessageKey = pendingMessageKey || selectedMessageKeyState || (selectedMessage ? mailboxMessageKey(selectedMessage.folder || selectedFolder, selectedMessage.uid) : "");
const messageCountLabel = messageListCountLabel(messages.length, messageTotalCount, loadingMessages, foldersReady); const messageCountLabel = messageListCountLabel(messages.length, messageTotalCount, loadingMessages, foldersReady);
const syncState = mailboxSyncState(messageProvenance); const syncState = mailboxSyncState(messageProvenance);
const folderEmptyText = folderError || (noImapProfiles ? "i18n:govoplan-mail.no_imap_enabled_mail_profiles.61ae44d8" : loadingFolders ? "i18n:govoplan-mail.loading_folders.17f9f0e2" : "i18n:govoplan-mail.no_folders_available.14133b26"); const folderEmptyText = folderError || (noMailboxProfiles ? "No IMAP- or JMAP-enabled Mail profiles are available." : loadingFolders ? "i18n:govoplan-mail.loading_folders.17f9f0e2" : "i18n:govoplan-mail.no_folders_available.14133b26");
const messageEmptyText = messageError || (!selectedProfileId ? "i18n:govoplan-mail.select_an_imap_profile.5445648c" : !foldersReady || loadingMessages ? "i18n:govoplan-mail.loading_messages.77b62232" : messages.length > 0 && filteredMessages.length === 0 ? "i18n:govoplan-mail.no_messages_match_the_current_filter_on_this_pag.9dda6916" : "i18n:govoplan-mail.no_messages_in_this_folder.5c7fa25d"); const messageEmptyText = messageError || (!selectedProfileId ? "i18n:govoplan-mail.select_an_imap_profile.5445648c" : !foldersReady || loadingMessages ? "i18n:govoplan-mail.loading_messages.77b62232" : messages.length > 0 && filteredMessages.length === 0 ? "i18n:govoplan-mail.no_messages_match_the_current_filter_on_this_pag.9dda6916" : "i18n:govoplan-mail.no_messages_in_this_folder.5c7fa25d");
const previewEmptyText = detailError || (loadingMessage ? "i18n:govoplan-mail.loading_message.815c2094" : "i18n:govoplan-mail.select_a_message_to_inspect_its_content.5f3d1342"); const previewEmptyText = detailError || (loadingMessage ? "i18n:govoplan-mail.loading_message.815c2094" : "i18n:govoplan-mail.select_a_message_to_inspect_its_content.5f3d1342");
const loadingLabel = loadingProfiles ? "i18n:govoplan-mail.loading_mail_profiles.87de3560" : loadingFolders ? "i18n:govoplan-mail.loading_folders.17f9f0e2" : loadingMessages ? "i18n:govoplan-mail.loading_messages.77b62232" : "i18n:govoplan-mail.loading_message.815c2094"; const loadingLabel = loadingProfiles ? "i18n:govoplan-mail.loading_mail_profiles.87de3560" : loadingFolders ? "i18n:govoplan-mail.loading_folders.17f9f0e2" : loadingMessages ? "i18n:govoplan-mail.loading_messages.77b62232" : "i18n:govoplan-mail.loading_message.815c2094";
const profileReloadBlocker = loadingProfiles ? "Mail profiles are already loading." : ""; const profileReloadBlocker = loadingProfiles ? "Mail profiles are already loading." : "";
const folderReloadBlocker = !selectedProfileId const folderReloadBlocker = !selectedProfileId
? "Select an IMAP-enabled Mail profile before refreshing folders." ? "Select an IMAP- or JMAP-enabled Mail profile before refreshing folders."
: loadingFolders || loadingMessages : loadingFolders || loadingMessages
? "Wait for the current mailbox refresh to finish." ? "Wait for the current mailbox refresh to finish."
: ""; : "";
const messageReloadBlocker = !selectedProfileId const messageReloadBlocker = !selectedProfileId
? "Select an IMAP-enabled Mail profile before refreshing messages." ? "Select an IMAP- or JMAP-enabled Mail profile before refreshing messages."
: !selectedFolder || !foldersReady : !selectedFolder || !foldersReady
? "Select a loaded mailbox folder before refreshing messages." ? "Select a loaded mailbox folder before refreshing messages."
: loadingMessages : loadingMessages
@@ -111,7 +113,7 @@ export default function MailboxPage({ settings, auth }: { settings: ApiSettings;
const request = parseMailboxLaunch(location.search); const request = parseMailboxLaunch(location.search);
launchRequestRef.current = request; launchRequestRef.current = request;
if (!profiles.length || (!request.profileId && !request.folder && !request.folderRole && !request.messageUid)) return; if (!profiles.length || (!request.profileId && !request.folder && !request.folderRole && !request.messageUid)) return;
const usable = profiles.filter((profile) => profile.is_active && profile.imap); const usable = profiles.filter((profile) => profile.is_active && mailboxProtocolForProfile(profile));
const targetProfileId = request.profileId && usable.some((profile) => profile.id === request.profileId) const targetProfileId = request.profileId && usable.some((profile) => profile.id === request.profileId)
? request.profileId ? request.profileId
: selectedProfileId || usable[0]?.id || ""; : selectedProfileId || usable[0]?.id || "";
@@ -133,6 +135,15 @@ export default function MailboxPage({ settings, auth }: { settings: ApiSettings;
} }
void loadMessages(selectedProfileId, selectedFolder, messagePage, messagePageSize); void loadMessages(selectedProfileId, selectedFolder, messagePage, messagePageSize);
}, [foldersReady, messagePage, messagePageSize, selectedProfileId, selectedFolder]); }, [foldersReady, messagePage, messagePageSize, selectedProfileId, selectedFolder]);
useEffect(() => {
if (selectedMailboxProtocol !== "jmap" || !selectedProfileId || !selectedFolder || !foldersReady) return;
const handle = window.setTimeout(() => {
setMessagePage(1);
mailboxPageCursorsRef.current = {};
void loadMessages(selectedProfileId, selectedFolder, 1, messagePageSize);
}, 250);
return () => window.clearTimeout(handle);
}, [messageQuery]);
useEffect(() => { useEffect(() => {
const request = launchRequestRef.current; const request = launchRequestRef.current;
@@ -193,7 +204,7 @@ export default function MailboxPage({ settings, auth }: { settings: ApiSettings;
setError(""); setError("");
try { try {
const loaded = await listMailServerProfiles(settings); const loaded = await listMailServerProfiles(settings);
const usable = loaded.filter((profile) => profile.is_active && profile.imap); const usable = loaded.filter((profile) => profile.is_active && mailboxProtocolForProfile(profile));
const requestedProfileId = parseMailboxLaunch(location.search).profileId; const requestedProfileId = parseMailboxLaunch(location.search).profileId;
setProfiles(loaded); setProfiles(loaded);
setSelectedProfileId((current) => setSelectedProfileId((current) =>
@@ -224,7 +235,9 @@ export default function MailboxPage({ settings, auth }: { settings: ApiSettings;
async function loadMailboxBootstrap(profileId = selectedProfileId, refresh = false) { async function loadMailboxBootstrap(profileId = selectedProfileId, refresh = false) {
if (!profileId) return; if (!profileId) return;
const profileInbox = profiles.find((profile) => profile.id === profileId)?.imap?.folder_mappings?.inbox || ""; const targetProfile = profiles.find((profile) => profile.id === profileId) ?? null;
const mailboxProtocol = mailboxProtocolForProfile(targetProfile) ?? "imap";
const profileInbox = mailboxProtocol === "imap" ? targetProfile?.imap?.folder_mappings?.inbox || "" : "";
const requestedLaunch = launchRequestRef.current; const requestedLaunch = launchRequestRef.current;
const requestedLaunchFolder = requestedLaunch && (!requestedLaunch.profileId || requestedLaunch.profileId === profileId) const requestedLaunchFolder = requestedLaunch && (!requestedLaunch.profileId || requestedLaunch.profileId === profileId)
? mailboxLaunchFolder(requestedLaunch, profiles.find((profile) => profile.id === profileId) ?? null) ? mailboxLaunchFolder(requestedLaunch, profiles.find((profile) => profile.id === profileId) ?? null)
@@ -250,7 +263,7 @@ export default function MailboxPage({ settings, auth }: { settings: ApiSettings;
setDetailError(""); setDetailError("");
setError(""); setError("");
try { try {
const response = await bootstrapMailbox(settings, profileId, requestedFolder, messagePageSize, 0, refresh); const response = await bootstrapMailbox(settings, profileId, requestedFolder, messagePageSize, 0, refresh, mailboxProtocol);
if (folderRequestId !== folderRequestRef.current || messageRequestId !== messageListRequestRef.current) return; if (folderRequestId !== folderRequestRef.current || messageRequestId !== messageListRequestRef.current) return;
if (!response.folders.ok) throw new Error(response.folders.message || "i18n:govoplan-mail.mailbox_folders_could_not_be_loaded.c3e3880e"); if (!response.folders.ok) throw new Error(response.folders.message || "i18n:govoplan-mail.mailbox_folders_could_not_be_loaded.c3e3880e");
const loadedFolders = response.folders.folders?.length ? response.folders.folders : [{ name: "INBOX", flags: [] }]; const loadedFolders = response.folders.folders?.length ? response.folders.folders : [{ name: "INBOX", flags: [] }];
@@ -264,7 +277,7 @@ export default function MailboxPage({ settings, auth }: { settings: ApiSettings;
: loadedFolders.some((folder) => folder.name === "INBOX") ? "INBOX" : response.folders.detected_sent_folder || loadedFolders[0]?.name || "INBOX"; : loadedFolders.some((folder) => folder.name === "INBOX") ? "INBOX" : response.folders.detected_sent_folder || loadedFolders[0]?.name || "INBOX";
} }
const foldersWithCounts = loadedFolders.map((folder) => folder.name === nextFolder ? { ...folder, message_count: total } : folder); const foldersWithCounts = loadedFolders.map((folder) => folder.name === nextFolder ? { ...folder, message_count: total } : folder);
const cursorKey = mailboxCursorKey(profileId, nextFolder, messagePageSize); const cursorKey = mailboxCursorKey(profileId, nextFolder, messagePageSize, "");
mailboxPageCursorsRef.current = { mailboxPageCursorsRef.current = {
[`${cursorKey}:1`]: null, [`${cursorKey}:1`]: null,
[`${cursorKey}:2`]: response.messages.next_cursor ?? null [`${cursorKey}:2`]: response.messages.next_cursor ?? null
@@ -301,9 +314,10 @@ export default function MailboxPage({ settings, auth }: { settings: ApiSettings;
async function loadMessages(profileId = selectedProfileId, folder = selectedFolder, page = messagePage, pageSize = messagePageSize, refresh = false) { async function loadMessages(profileId = selectedProfileId, folder = selectedFolder, page = messagePage, pageSize = messagePageSize, refresh = false) {
if (!profileId || !folder) return; if (!profileId || !folder) return;
const mailboxProtocol = mailboxProtocolForProfile(profiles.find((profile) => profile.id === profileId) ?? null) ?? "imap";
const requestId = ++messageListRequestRef.current; const requestId = ++messageListRequestRef.current;
const offset = (Math.max(1, page) - 1) * pageSize; const offset = (Math.max(1, page) - 1) * pageSize;
const cursorKey = mailboxCursorKey(profileId, folder, pageSize); const cursorKey = mailboxCursorKey(profileId, folder, pageSize, mailboxProtocol === "jmap" ? messageQuery : "");
const cursor = page <= 1 ? null : mailboxPageCursorsRef.current[`${cursorKey}:${page}`] || null; const cursor = page <= 1 ? null : mailboxPageCursorsRef.current[`${cursorKey}:${page}`] || null;
setLoadingMessages(true); setLoadingMessages(true);
setMessageProvenance(null); setMessageProvenance(null);
@@ -311,7 +325,17 @@ export default function MailboxPage({ settings, auth }: { settings: ApiSettings;
setDetailError(""); setDetailError("");
setError(""); setError("");
try { try {
const response = await listMailboxMessages(settings, profileId, folder, pageSize, offset, cursor, refresh); const response = await listMailboxMessages(
settings,
profileId,
folder,
pageSize,
offset,
cursor,
refresh,
mailboxProtocol,
mailboxProtocol === "jmap" ? messageQuery : null
);
if (requestId !== messageListRequestRef.current) return; if (requestId !== messageListRequestRef.current) return;
const loaded = response.messages ?? []; const loaded = response.messages ?? [];
const total = response.total_count ?? loaded.length; const total = response.total_count ?? loaded.length;
@@ -356,7 +380,7 @@ export default function MailboxPage({ settings, auth }: { settings: ApiSettings;
setLoadingMessage(true); setLoadingMessage(true);
setError(""); setError("");
try { try {
const response = await getMailboxMessage(settings, selectedProfileId, folderName, message.uid); const response = await getMailboxMessage(settings, selectedProfileId, folderName, message.uid, selectedMailboxProtocol);
if (requestId !== messageDetailRequestRef.current) return; if (requestId !== messageDetailRequestRef.current) return;
setSelectedMessage(response.message); setSelectedMessage(response.message);
setSelectedMessageKeyState(mailboxMessageKey(response.message.folder || folderName, response.message.uid)); setSelectedMessageKeyState(mailboxMessageKey(response.message.folder || folderName, response.message.uid));
@@ -475,13 +499,13 @@ export default function MailboxPage({ settings, auth }: { settings: ApiSettings;
<div className="file-list-sticky"> <div className="file-list-sticky">
<ActionToolbar justify="between" className="file-manager-toolbar mailbox-toolbar" aria-label="i18n:govoplan-mail.mail_actions.c08b5f08"> <ActionToolbar justify="between" className="file-manager-toolbar mailbox-toolbar" aria-label="i18n:govoplan-mail.mail_actions.c08b5f08">
<label className="mailbox-profile-field"> <label className="mailbox-profile-field">
<span>i18n:govoplan-mail.imap_profile.5165df81</span> <span>Mailbox profile</span>
<select value={selectedProfileId} disabled={loadingProfiles || loadingFolders || imapProfiles.length === 0} onChange={(event) => selectProfile(event.target.value)}> <select value={selectedProfileId} disabled={loadingProfiles || loadingFolders || mailboxProfiles.length === 0} onChange={(event) => selectProfile(event.target.value)}>
{imapProfiles.length === 0 && <option value="">i18n:govoplan-mail.no_imap_profiles_available.d64589f8</option>} {mailboxProfiles.length === 0 && <option value="">No mailbox profiles available</option>}
{imapProfiles.map((profile) => <option key={profile.id} value={profile.id}>{profile.name}</option>)} {mailboxProfiles.map((profile) => <option key={profile.id} value={profile.id}>{profile.name}</option>)}
</select> </select>
</label> </label>
<ToolbarGroup grow className="mailbox-toolbar-meta">{selectedProfile?.imap ? transportLabel(selectedProfile) : "i18n:govoplan-mail.no_imap_profile_selected.e7d1516f"}</ToolbarGroup> <ToolbarGroup grow className="mailbox-toolbar-meta">{selectedProfile ? transportLabel(selectedProfile) : "No mailbox profile selected"}</ToolbarGroup>
<ToolbarGroup align="end" className="mailbox-toolbar-actions"> <ToolbarGroup align="end" className="mailbox-toolbar-actions">
<DocumentationHelpLink reference={MAILBOX_DOCUMENTATION} /> <DocumentationHelpLink reference={MAILBOX_DOCUMENTATION} />
{hasAnyScope(auth, ["mail:bounce:read", "mail:bounce:manage"]) && {hasAnyScope(auth, ["mail:bounce:read", "mail:bounce:manage"]) &&
@@ -504,13 +528,13 @@ export default function MailboxPage({ settings, auth }: { settings: ApiSettings;
</ToolbarGroup> </ToolbarGroup>
</ActionToolbar> </ActionToolbar>
{noImapProfiles && {noMailboxProfiles &&
<ActionBlockerHint <ActionBlockerHint
className="mailbox-profile-blocker" className="mailbox-profile-blocker"
reason={{ reason={{
summary: "No IMAP-enabled Mail profile is available.", summary: "No mailbox-enabled Mail profile is available.",
details: "The mailbox workspace is read-only and needs an active profile with an authorized IMAP server and credential.", details: "The mailbox workspace is read-only and needs an active profile with an authorized IMAP or JMAP server and credential.",
requiredAction: "Ask a Mail administrator to configure and authorize an IMAP-enabled profile.", requiredAction: "Ask a Mail administrator to configure and authorize an IMAP- or JMAP-enabled profile.",
actor: "Mail profile administrator", actor: "Mail profile administrator",
target: "Settings or Administration > Mail profiles" target: "Settings or Administration > Mail profiles"
}} }}
@@ -792,8 +816,8 @@ function mailboxMessageKey(folder: string, uid: string): string {
return `${folder || "INBOX"}::${uid}`; return `${folder || "INBOX"}::${uid}`;
} }
function mailboxCursorKey(profileId: string, folder: string, pageSize: number): string { function mailboxCursorKey(profileId: string, folder: string, pageSize: number, query: string): string {
return `${profileId}::${folder || "INBOX"}::${pageSize}`; return `${profileId}::${folder || "INBOX"}::${pageSize}::${query.trim()}`;
} }
function mailboxProvenance(response: { from_cache?: boolean; refreshing?: boolean; indexed_at?: string | null }): MailboxSyncProvenance { function mailboxProvenance(response: { from_cache?: boolean; refreshing?: boolean; indexed_at?: string | null }): MailboxSyncProvenance {
@@ -855,11 +879,29 @@ function displayFolderFlag(flag: string): string | null {
} }
function transportLabel(profile: MailServerProfile): string { function transportLabel(profile: MailServerProfile): string {
const jmap = preferredJmapServer(profile);
if (jmap) {
const sessionUrl = "session_url" in jmap.config ? jmap.config.session_url : null;
return `JMAP · ${String(sessionUrl || "configured endpoint")}`;
}
const imap = profile.imap; const imap = profile.imap;
if (!imap?.host) return "i18n:govoplan-mail.imap_not_configured.b2892af3"; if (!imap?.host) return "i18n:govoplan-mail.imap_not_configured.b2892af3";
return `${imap.host}:${imap.port ?? "?"} ${imap.security ?? ""}`.trim(); return `${imap.host}:${imap.port ?? "?"} ${imap.security ?? ""}`.trim();
} }
function preferredJmapServer(profile: MailServerProfile | null): MailServerProfile["servers"][number] | null {
if (!profile) return null;
const servers = (profile.servers ?? []).filter((server) => server.protocol === "jmap" && server.is_active);
return servers.find((server) => server.is_default) ?? servers[0] ?? null;
}
function mailboxProtocolForProfile(profile: MailServerProfile | null): MailMailboxProtocol | null {
if (!profile) return null;
if (preferredJmapServer(profile)) return "jmap";
if (profile.imap || (profile.servers ?? []).some((server) => server.protocol === "imap" && server.is_active)) return "imap";
return null;
}
function formatBytes(value?: number | null): string { function formatBytes(value?: number | null): string {
if (!value) return "-"; if (!value) return "-";
if (value < 1024) return i18nMessage("i18n:govoplan-mail.bytes_b", { value0: value }); if (value < 1024) return i18nMessage("i18n:govoplan-mail.bytes_b", { value0: value });
@@ -1,4 +1,4 @@
export type MailProfilePatternKey = "smtp_hosts" | "imap_hosts" | "envelope_senders" | "from_headers" | "recipient_domains"; export type MailProfilePatternKey = "smtp_hosts" | "imap_hosts" | "jmap_hosts" | "envelope_senders" | "from_headers" | "recipient_domains";
export type MailProfilePolicy = { export type MailProfilePolicy = {
whitelist?: Partial<Record<MailProfilePatternKey, string[]>> | null; whitelist?: Partial<Record<MailProfilePatternKey, string[]>> | null;
@@ -8,6 +8,7 @@ export type MailProfilePolicy = {
export type MailPolicyValidationInput = { export type MailPolicyValidationInput = {
smtpHost?: string | null; smtpHost?: string | null;
imapHost?: string | null; imapHost?: string | null;
jmapHost?: string | null;
envelopeSender?: string | null; envelopeSender?: string | null;
fromHeader?: string | null; fromHeader?: string | null;
recipientDomains?: Array<string | null | undefined> | null; recipientDomains?: Array<string | null | undefined> | null;
@@ -24,6 +25,7 @@ export type MailPolicyValidationMessage = {
const patternLabels: Record<MailProfilePatternKey, string> = { const patternLabels: Record<MailProfilePatternKey, string> = {
smtp_hosts: "i18n:govoplan-mail.smtp_host.2d4a434b", smtp_hosts: "i18n:govoplan-mail.smtp_host.2d4a434b",
imap_hosts: "i18n:govoplan-mail.imap_host.b53c3751", imap_hosts: "i18n:govoplan-mail.imap_host.b53c3751",
jmap_hosts: "JMAP host",
envelope_senders: "i18n:govoplan-mail.envelope_sender.5ec276a0", envelope_senders: "i18n:govoplan-mail.envelope_sender.5ec276a0",
from_headers: "i18n:govoplan-mail.from_header.bb78e85d", from_headers: "i18n:govoplan-mail.from_header.bb78e85d",
recipient_domains: "i18n:govoplan-mail.recipient_domain.778f2dcf" recipient_domains: "i18n:govoplan-mail.recipient_domain.778f2dcf"
@@ -43,6 +45,7 @@ input: MailPolicyValidationInput)
const checks: ValueCheck[] = [ const checks: ValueCheck[] = [
{ key: "smtp_hosts", value: input.smtpHost ?? "" }, { key: "smtp_hosts", value: input.smtpHost ?? "" },
{ key: "imap_hosts", value: input.imapHost ?? "" }, { key: "imap_hosts", value: input.imapHost ?? "" },
{ key: "jmap_hosts", value: input.jmapHost ?? "" },
{ key: "envelope_senders", value: input.envelopeSender ?? "" }, { key: "envelope_senders", value: input.envelopeSender ?? "" },
{ key: "from_headers", value: input.fromHeader ?? "" }, { key: "from_headers", value: input.fromHeader ?? "" },
...Array.from(new Set((input.recipientDomains ?? []).map(normalizeDomain).filter(Boolean))). ...Array.from(new Set((input.recipientDomains ?? []).map(normalizeDomain).filter(Boolean))).
@@ -1,5 +1,5 @@
export type MailProfileProtocol = "smtp" | "imap"; export type MailProfileProtocol = "smtp" | "imap" | "jmap";
export type MailProfileEditSection = MailProfileProtocol; export type MailProfileEditSection = "smtp" | "imap";
export type MailProfilePanelMode = "all" | "server" | "credentials"; export type MailProfilePanelMode = "all" | "server" | "credentials";
export type MailProfileCreateStage = export type MailProfileCreateStage =
| "profile" | "profile"
@@ -54,9 +54,11 @@ export type MailProfileTargetedUpdateParts = {
profile: Record<string, unknown>; profile: Record<string, unknown>;
smtp: Record<string, unknown>; smtp: Record<string, unknown>;
imap: Record<string, unknown> | null; imap: Record<string, unknown> | null;
jmap?: Record<string, unknown> | null;
credentials: { credentials: {
smtp: MailProfileTransportCredentialsLike; smtp: MailProfileTransportCredentialsLike;
imap: MailProfileTransportCredentialsLike; imap: MailProfileTransportCredentialsLike;
jmap?: MailProfileTransportCredentialsLike;
}; };
clearImap: boolean; clearImap: boolean;
}; };
@@ -72,7 +74,7 @@ export function mailProfileChildDescriptors(profile: MailProfileTreeProfileLike)
} }
export function mailProfileEditTargetInitialSection(target: MailProfileEditTarget): MailProfileEditSection { export function mailProfileEditTargetInitialSection(target: MailProfileEditTarget): MailProfileEditSection {
if (target.kind === "server" || target.kind === "credentials") return target.protocol; if (target.kind === "server" || target.kind === "credentials") return target.protocol === "jmap" ? "imap" : target.protocol;
return "smtp"; return "smtp";
} }
@@ -84,7 +86,7 @@ export function mailProfileEditTargetPanelMode(target: MailProfileEditTarget): M
} }
export function mailProfileEditTargetVisibleSections(target: MailProfileEditTarget): MailProfileEditSection[] { export function mailProfileEditTargetVisibleSections(target: MailProfileEditTarget): MailProfileEditSection[] {
if (target.kind === "server" || target.kind === "credentials") return [target.protocol]; if (target.kind === "server" || target.kind === "credentials") return target.protocol === "jmap" ? [] : [target.protocol];
if (target.kind === "create") return ["smtp", "imap"]; if (target.kind === "create") return ["smtp", "imap"];
return []; return [];
} }
@@ -94,7 +96,7 @@ export function mailProfileEditTargetShowsProfileFields(target: MailProfileEditT
} }
export function mailProfileEditTargetShowsSettingsPanel(target: MailProfileEditTarget): boolean { export function mailProfileEditTargetShowsSettingsPanel(target: MailProfileEditTarget): boolean {
return target.kind !== "profile"; return target.kind !== "profile" && !((target.kind === "server" || target.kind === "credentials") && target.protocol === "jmap");
} }
export function mailProfileCreateStagePanel( export function mailProfileCreateStagePanel(
@@ -152,12 +154,16 @@ export function mailProfileTargetedUpdatePayload(
if (target.kind === "profile") return parts.profile; if (target.kind === "profile") return parts.profile;
if (target.kind === "server") { if (target.kind === "server") {
if (target.protocol === "smtp") return { smtp: parts.smtp }; if (target.protocol === "smtp") return { smtp: parts.smtp };
if (target.protocol === "jmap") return { jmap: parts.jmap ?? null };
return parts.imap === null return parts.imap === null
? { imap: null, clear_imap: parts.clearImap } ? { imap: null, clear_imap: parts.clearImap }
: { imap: parts.imap }; : { imap: parts.imap };
} }
if (target.kind === "credentials") { if (target.kind === "credentials") {
return { credentials: { [target.protocol]: parts.credentials[target.protocol] } }; const credentials = target.protocol === "jmap"
? parts.credentials.jmap ?? {}
: parts.credentials[target.protocol];
return { credentials: { [target.protocol]: credentials } };
} }
throw new Error("Create is not an update target"); throw new Error("Create is not an update target");
} }
@@ -21,11 +21,13 @@ assertEqual(wildcardPatternMatches("smtp?.example.org", "smtp12.example.org"), f
const policy = { const policy = {
whitelist: { whitelist: {
smtp_hosts: ["smtp.allowed.test"], smtp_hosts: ["smtp.allowed.test"],
jmap_hosts: ["jmap.allowed.test"],
from_headers: ["*@allowed.test"], from_headers: ["*@allowed.test"],
recipient_domains: ["allowed.test"] recipient_domains: ["allowed.test"]
}, },
blacklist: { blacklist: {
smtp_hosts: ["smtp.blocked.test"], smtp_hosts: ["smtp.blocked.test"],
jmap_hosts: ["jmap.blocked.test"],
envelope_senders: ["blocked@*"] envelope_senders: ["blocked@*"]
} }
}; };
@@ -33,14 +35,17 @@ const policy = {
assertDeepEqual(mailPolicyValueAllowed(policy, "smtp_hosts", "smtp.allowed.test"), { allowed: true, value: "smtp.allowed.test" }); assertDeepEqual(mailPolicyValueAllowed(policy, "smtp_hosts", "smtp.allowed.test"), { allowed: true, value: "smtp.allowed.test" });
assertEqual(mailPolicyValueAllowed(policy, "smtp_hosts", "smtp.blocked.test").allowed, false, "blacklist wins for SMTP host"); assertEqual(mailPolicyValueAllowed(policy, "smtp_hosts", "smtp.blocked.test").allowed, false, "blacklist wins for SMTP host");
assertEqual(mailPolicyValueAllowed(policy, "smtp_hosts", "smtp.other.test").allowed, false, "whitelist blocks unknown SMTP host"); assertEqual(mailPolicyValueAllowed(policy, "smtp_hosts", "smtp.other.test").allowed, false, "whitelist blocks unknown SMTP host");
assertEqual(mailPolicyValueAllowed(policy, "jmap_hosts", "jmap.blocked.test").allowed, false, "JMAP hostname deny policy is independent");
const messages = validateMailPolicy(policy, { const messages = validateMailPolicy(policy, {
smtpHost: "smtp.other.test", smtpHost: "smtp.other.test",
jmapHost: "jmap.blocked.test",
envelopeSender: "blocked@allowed.test", envelopeSender: "blocked@allowed.test",
fromHeader: "sender@other.test", fromHeader: "sender@other.test",
recipientDomains: ["allowed.test", "denied.test", "user@denied.test"] recipientDomains: ["allowed.test", "denied.test", "user@denied.test"]
}); });
assert(messages.some((item) => item.key === "smtp_hosts" && item.value === "smtp.other.test")); assert(messages.some((item) => item.key === "smtp_hosts" && item.value === "smtp.other.test"));
assert(messages.some((item) => item.key === "jmap_hosts" && item.value === "jmap.blocked.test"));
assert(messages.some((item) => item.key === "envelope_senders" && item.value === "blocked@allowed.test")); assert(messages.some((item) => item.key === "envelope_senders" && item.value === "blocked@allowed.test"));
assert(messages.some((item) => item.key === "from_headers" && item.value === "sender@other.test")); assert(messages.some((item) => item.key === "from_headers" && item.value === "sender@other.test"));
assertEqual(messages.filter((item) => item.key === "recipient_domains" && item.value === "denied.test").length, 1, "recipient domains are normalized and de-duplicated"); assertEqual(messages.filter((item) => item.key === "recipient_domains" && item.value === "denied.test").length, 1, "recipient domains are normalized and de-duplicated");
+16 -1
View File
@@ -47,6 +47,9 @@ assertEqual(mailProfileEditTargetPanelMode({ kind: "credentials", protocol: "ima
assertEqual(mailProfileEditTargetPanelMode({ kind: "profile" }), null); assertEqual(mailProfileEditTargetPanelMode({ kind: "profile" }), null);
assertDeepEqual(mailProfileEditTargetVisibleSections({ kind: "create" }), ["smtp", "imap"]); assertDeepEqual(mailProfileEditTargetVisibleSections({ kind: "create" }), ["smtp", "imap"]);
assertDeepEqual(mailProfileEditTargetVisibleSections({ kind: "credentials", protocol: "imap" }), ["imap"]); assertDeepEqual(mailProfileEditTargetVisibleSections({ kind: "credentials", protocol: "imap" }), ["imap"]);
assertEqual(mailProfileEditTargetInitialSection({ kind: "server", protocol: "jmap" }), "imap");
assertDeepEqual(mailProfileEditTargetVisibleSections({ kind: "server", protocol: "jmap" }), []);
assertEqual(mailProfileEditTargetShowsSettingsPanel({ kind: "credentials", protocol: "jmap" }), false);
assertEqual(mailProfileEditTargetShowsProfileFields({ kind: "profile" }), true); assertEqual(mailProfileEditTargetShowsProfileFields({ kind: "profile" }), true);
assertEqual(mailProfileEditTargetShowsProfileFields({ kind: "server", protocol: "smtp" }), false); assertEqual(mailProfileEditTargetShowsProfileFields({ kind: "server", protocol: "smtp" }), false);
assertEqual(mailProfileEditTargetShowsSettingsPanel({ kind: "profile" }), false); assertEqual(mailProfileEditTargetShowsSettingsPanel({ kind: "profile" }), false);
@@ -118,9 +121,11 @@ const updateParts = {
profile: { name: "Renamed" }, profile: { name: "Renamed" },
smtp: { host: "smtp.example.org" }, smtp: { host: "smtp.example.org" },
imap: { host: "imap.example.org" }, imap: { host: "imap.example.org" },
jmap: { session_url: "https://jmap.example.org/.well-known/jmap" },
credentials: { credentials: {
smtp: { username: "smtp-user", password: "smtp-secret" }, smtp: { username: "smtp-user", password: "smtp-secret" },
imap: { username: "imap-user", password: "imap-secret" } imap: { username: "imap-user", password: "imap-secret" },
jmap: { password: "jmap-token" }
}, },
clearImap: false clearImap: false
}; };
@@ -139,6 +144,16 @@ assertDeepEqual(
{ credentials: { imap: { username: "imap-user", password: "imap-secret" } } }, { credentials: { imap: { username: "imap-user", password: "imap-secret" } } },
"credential edits send only the selected protocol" "credential edits send only the selected protocol"
); );
assertDeepEqual(
mailProfileTargetedUpdatePayload({ kind: "server", protocol: "jmap" }, updateParts),
{ jmap: { session_url: "https://jmap.example.org/.well-known/jmap" } },
"JMAP server edits remain isolated from legacy profile transports"
);
assertDeepEqual(
mailProfileTargetedUpdatePayload({ kind: "credentials", protocol: "jmap" }, updateParts),
{ credentials: { jmap: { password: "jmap-token" } } },
"JMAP credential edits retain only the selected credential"
);
assertEqual( assertEqual(
mailProfileCreateCredentialsPayload({ username: null }, { password: "" }), mailProfileCreateCredentialsPayload({ username: null }, { password: "" }),
undefined, undefined,