This document describes the current authenticated workspace contracts. Routes return the standard typed JSON envelope and reject unauthenticated or cross-owner requests without exposing mailbox existence.
GET /api/workspace/session returns the authenticated workspace snapshot. The response
contains activeFolder, mailboxPages, metrics, and mailIdentityOptions.
activeFolderisinbox,sent,drafts, orarchive.- Only the active folder's first page is loaded during the initial snapshot.
metricsis fetched once for the snapshot and is not repeated per folder.metricscontains mailbox counts and outbound aggregates for the full Owner when no identity filter is selected, or for the selected domain/address when one is active:queuedCount,delayedCount,failedCount,bouncedCount,complainedCount, andstaleDeliveryCount. These values cover the owned selected scope, not only the currently loaded page. A submission is stale after 15 minutes insubmittingstate.mailIdentityOptionscontains the Owner's configured domains and address choices. Address options expose lifecycle, address/domain send switches, Resend status and sending status, the last check time/failure flag, send readiness, and the selected default; they never expose provider credentials or remote API details.- Changing folder loads that folder lazily. The browser reuses a session-local
cache (16 views, 30-second freshness); stale cached lists remain visible during
refresh, and writes/cross-tab notifications invalidate freshness.
archiveis a mailbox section backed by inbox rows witharchived_at, not a persistedfoldervalue. - Logging out clears the client snapshot, metrics, selected message, detail cache, and mailbox pages before another user can log in.
The browser client adds X-Requested-With: XMLHttpRequest to requests whose
target is the current origin and /api or /api/..., including JSON requests
and attachment uploads. It removes the header from requests to every other
origin. This is Cloudflare Access's documented AJAX signal for returning
401 when an Access session expires instead of sending an XHR/fetch caller
through a login redirect.
On same-origin API requests, the client classifies a Worker JSON 401 with
ACCESS_REQUIRED or AUTHENTICATION_REQUIRED, an edge non-JSON 401, or a
redirect that ends at a recognized Cloudflare Access login URL as a session
expiry. Other HTML is not treated as a login page. 403 remains forbidden;
502/503, arbitrary invalid responses, offline status, and network/CORS
failures keep separate error states.
After expiry, normal API work, polling, and compose autosave stop. The open
composer and its edits remain in that tab's memory; credentials, tokens, and
draft bodies are not copied to local storage or broadcast. The user can open a
same-origin sign-in path or retry the session check. Once another tab has
authenticated, the expired tab receives only an authentication-state signal,
then refreshes GET /api/workspace/session and other safe workspace GETs.
Failed writes, sends, deletions, and bulk actions are never automatically
replayed. The user must choose the action again after recovery; a send retry
continues to use the existing stable idempotency key.
GET /api/workspace/mailbox?folder=inbox|sent|drafts|archive&limit=...&cursor=...
returns a page with an opaque cursor. q, filter, and identity are optional
server-side query parameters; identity accepts domain:<owned-id> or
address:<owned-id>. A cursor is only valid for the same folder, section,
query, filter, delivery status, and identity. The selected scope applies before
pagination to inbound mail, sent mail, drafts, search results, and metrics.
Unknown or foreign identity IDs are rejected; identity filters do not rely on
the current browser page.
Mailbox list rows contain metadata and a short snippet but do not select or
return stored inbound, sent, or draft bodies. Inbound text is loaded through
the owned message detail route. Workspace sent text is loaded through
GET /api/workspace/messages/:id/body; the response never contains raw HTML.
Ownership is checked on every list and detail path.
GET /api/workspace/messages/:id returns reader metadata, including the
current Owner's applied labels in message.userLabels.
Inbound email_messages."to" is the Cloudflare Email Routing envelope
recipient. MIME To and Cc remain separate parsed headers, and raw
Delivered-To remains a separate header snapshot. The detail view displays
the actual envelope destination independently from the message's To header.
GET /api/workspace/mailbox/metrics?identity=address:<id>|domain:<id> returns
{ metrics, metricsScope: { identityFilter } }. Omit identity for the Owner
scope. Invalid identity syntax returns 400; unknown/foreign identities return
404. Authentication is required. Category, search and pagination do not narrow
these metrics. inboxCount counts non-deleted, non-archived received messages;
unreadCount counts their unread subset. Inbox navigation badges use the latter.
Navigation badges represent attention rather than folder totals: Inbox uses
unreadCount; Drafts uses draftsCount; Sent adds queuedCount, delayedCount,
failedCount, bouncedCount, and complainedCount. queuedCount includes
queued/submitting and failedCount includes failed/suppressed. The submitting
subset staleDeliveryCount is not added again. Delivery metrics count only
existing, non-deleted sent messages owned by the current Owner within the chosen
identity; deleted messages and orphaned delivery rows are excluded. Sent/delivered
mail does not contribute. Starred, Archive, and Trash have no navigation badges.
inboxCount, sentCount, starredCount, archiveCount, and trashCount retain
their total-count meanings for lists and API consumers.
PATCH /api/workspace/messages/:id/flags accepts one or both boolean fields
read and starred. The optional identity query parameter selects response
metrics scope, not target ownership; the server validates it before writing.
Only supplied fields are updated, preserving concurrent changes to the other
field and archive/deletion state. Drafts have no read state; a read-only draft
patch is a no-op and does not rewrite its star. The response includes a body-free message,
metrics, and metricsScope. Deleted or foreign messages return 404; invalid
patches return 400. Existing calls without identity retain Owner-wide metrics.
GETs never mark messages read. The browser PATCHes a received message when its
reader becomes visible, including split view and both kinds of deep link. A
manual unread stays unread until that reader is closed and reopened. Writes are
serialized per message, and stale responses cannot replace a newer selection.
Lists, flags, and metrics remain private, no-store at the HTTP layer; the
browser view cache is in memory and is cleared on logout/authentication expiry.
Authenticated requests on these paths expose available phase durations and
total through Server-Timing; timing logs omit mail identifiers and content.
See the navigation and read-state spec for cache keys, failure behavior, regression cases and verification boundaries.
Owner-authenticated workspace APIs use the standard JSON envelope and CSRF protections:
GET /api/workspace/blocked-sendersreturnssenderswithemailandcreatedAt.POSTwith{ "email": "sender@example.com" }adds an exact case-insensitive address idempotently;DELETEwith the same JSON removes it idempotently.GET /api/workspace/quarantine?cursor=...&direction=next|previousreturnsitems(id, sender, subject, timestamp, quarantinedAt),previousCursor, andnextCursor; pages contain up to 20 messages and cursors are Owner-scoped.directiondefaults tonext;previousrequires a cursor.POST /api/workspace/quarantine/:idreleases one Owner-owned quarantined message. An unavailable or cross-owner message returns 404.- Matching uses MIME From, falling back to the envelope sender only when From is absent. Header addresses can be forged. Quarantined mail stays in D1/R2, is excluded from regular mailbox lists/search/counts and the compatibility
GET /api/messageslist, and does not trigger inbound notifications or auto-replies. Removing a rule does not release mail; releasing a message does not remove its rule. Rules apply to future mail only. Owned inbound message details exposequarantinedAtso direct readers can require release before reply or forward. - The feature requires migration
0029_blocked_senders.sql. See the spec for failure and deployment boundaries.
GET /api/workspace/mail-identities returns only the authenticated Owner's
configured domains and addresses. domainOnboarding reports whether browser
enrollment is available and whether route management credentials are configured.
routingReadOnly indicates whether the current deployment allows identity writes.
The deployment fixes MAIL_IDENTITY_WORKER_NAME and MAIL_IDENTITY_ACCOUNT_ID;
the browser supplies a domain and Zone ID, which the server verifies against
Cloudflare before recording the mapping. The browser cannot choose a Worker,
account, API origin, or Cloudflare endpoint. The operator command
bun run mail:domain:configure remains available. Provider-configuration flags
never return a token or key; cloudflareManagement separately reports whether
the management credential is available for the current environment.
providerConfiguration.productionVerifiesCatchAll identifies shared-inbound
PRE. Its catch-all status uses the production Cron observation to verify the
rule. The production delivery switch is checked separately at SMTP ingress.
With shared PRE and PROD inbound routing configured, creating an address or
enabling catch-all collection reserves a route for that environment. A
conflicting claim returns HTTP 409 with MAIL_ROUTING_OWNERSHIP_CONFLICT.
If a stored domain points to a different Worker, exact route provisioning and
catch-all enrollment return HTTP 409 with MAIL_DOMAIN_WORKER_MAPPING_CONFLICT.
Exceeding the PRE catch-all reservation limit returns HTTP 409 with
MAIL_PREVIEW_CATCH_ALL_CAPACITY_REACHED. Disabled domains retain ownership
and count toward the limit.
Sync imports only routes assigned to the current environment. Disabling or
deleting a mailbox preserves its receiving ownership. See the
shared inbound routing SPEC.
Enable catch-all collection in workspace domain settings when shared inbound
routing is configured. The domain configuration CLI only accepts reject in
that configuration.
For a collecting PRE domain without an ownership entry, check the domain and
save the collection setting again. After claiming the domain, production Cron
must verify the route before PRE accepts unknown recipients.
In standalone fixed-address PRE, the workspace can read saved identities.
Identity and domain writes and discovery return HTTP 403 with
MAIL_ROUTING_FIXED_PRE_READ_ONLY. Cloudflare identity checks are disabled
for this local mode.
Native shared-routing PRE acceptance returns HTTP 403 with
MAIL_ROUTING_PREVIEW_READ_ONLY for identity writes and discovery.
Authenticated readiness checks the bound ownership table and reports the
current routing environment and read-only state.
Domain warnings on both management pages use the current cloudflare_error_code
and resend_error_code independently, with provider-specific credential guidance
for access failures. These warnings first honor the current deployment's
providerConfiguration flags: absent credentials show a configuration message,
even if a shared database retains a provider error from another deployment.
The persisted error is preserved, and becomes visible when credentials are
configured. A missing credential is not reported as an access denial.
The legacy domain last_error_code mirrors the latest
Cloudflare check, including scheduled recovery; it does not represent Resend
health. Address last_error_code still reports that address's routing operation
failure. Discovery sync does not replace a provider health check or clear an
unresolved routing or sending error.
-
POST /api/workspace/mail-identities/syncdiscovers accessible zones in the deployment account and imports existing literal recipient rules targeting the configured Worker. It requires the authenticated workspace Owner and Zone Read / Email Routing Rules Read permissions. The management UI invokes it only after the Owner explicitly chooses the sync/import action. Address-list Refresh and the saved-list-only menu action useGET /api/workspace/mail-identities. Domains also performs automatic health observations through the separate/domains/:domainId/refreshendpoint; Refresh all uses the full domain check. Neither refresh discovers or imports new identity records. Provider requests are read-only, paginated and bounded. Other Worker/forward/drop rules, malformed recipients and competing exact rules are skipped. Worker catch-all imports a domain without inventing addresses; a new domain collects unknown recipients only when its catch-all is verified to target this Worker. Existing settings, tombstones and operations are preserved. Imported addresses are never granted send permission or remote rule ownership. Returnssync.domainsCreated,addressesCreated,skippedRulesand per-domainwarningswith safe error categories. Provider failures retain local configuration. This writes shared D1 identity metadata, without rewriting historical mail or remote routing. -
POST /api/workspace/mail-identities/domainsaccepts onlydomainNameandzoneId. It requires Zone Read permission, checks the zone ID, domain suffix boundary and deployment account, and enrolls with unknown recipients rejected. A repeated identical enrollment returns the existing domain; existing mappings and ownership are never overwritten. Enrollment does not modify DNS or create Email Routing rules, and does not claim receiving or sending readiness. -
PATCH /api/workspace/mail-identities/domains/:domainIdacceptsenabledand/orunknownRecipientPolicy(rejectorcollect). It preserves the zone, Worker mapping, addresses and historical mail. Switching to collect requires a fresh successful observation of catch-all targeting the configured Worker. Disabling a domain stops application receiving/sending without deleting external rules. Concurrent settings or health updates cause a refresh/retry. -
PATCH /api/workspace/mail-identities/:addressIdacceptsdisplayNameandsignature. It edits only the authenticated Owner's non-deleted address and preserves the email, routing, and receiving/sending preferences. -
GET /api/workspace/mail-identities/:addressId/delete-previewis an authenticated, read-only snapshot of the exact-address rule, catch-all target and freshness, local lifecycle, and history-retention effect. Its 60-second UI expiry is advisory; DELETE independently re-reads the configured zone and exact rule before any remote mutation. Unknown or stale provider state is shown as such and never enables removal of an unverified managed rule. -
POST /api/workspace/mail-identitiescreates an address in an already configured domain. The Worker creates an exact Email Routing rule and stores the returned rule ID. Repeated or concurrent requests reconcile the same address operation; an uncertain remote result remains visible as pending or error for a later check/retry. -
POST /api/workspace/mail-identities/domains/:domainId/refreshperforms an authenticated Owner-scoped health observation without reconciling address lifecycle or preferences. It reuses Cron's independent Cloudflare/Resend leases and enforces a five-minute cooldown against both success and error timestamps. The response containsrefresh.cloudflareandrefresh.resendsummaries; recent/busy providers perform no remote work. Provider operations are read-only, while health metadata is saved in D1. No request body options bypass cooldown. -
POST /api/workspace/mail-identities/domains/:domainId/checkreads that configured zone's exact rules and catch-all, and checks the domain-level Resend sending status. The two provider reads have separate expiring leases; a concurrent click or scheduled read returns an in-progress result instead of starting a duplicate request. The check has bounded provider timeouts. A matching Worker rule may be explicitly imported; a duplicate or same-name rule to another target is a conflict and is never overwritten automatically. Address results may bebusywhile another address operation owns its lease; that check result is discarded for that address. Route observations never change an address'sreceive_enabledpreference.deleted_absentis a completed tombstone result, whileimported_preservedis an expected preserved-rule result. -
POST /api/workspace/mail-identities/:addressIdsupportsdisable,enable,import,restore,retry,enable_send,disable_send, andmake_default. Receive lifecycle and sending permission are separate. -
DELETE /api/workspace/mail-identities/:addressIdrequires{ "confirm": "delete" }. Optionalpolicyisremove_owned_route,retain_reject_route, or (for explicitly imported routes only)preserve_imported_route; older clients may omit it and use the persisted/default behavior. The request closes local send/receive access and records a tombstone before remote rule cleanup. It does not delete historical mail, drafts, or R2 content. Before removing a FlareMail-owned rule it verifies the saved ID, API source, exact management marker, enabled literal recipient matcher, single Worker action, and full configured Worker target, then reads the rule set again immediately before DELETE. The preview recommends retaining a verified FlareMail route: the address becomes a deleted tombstone and inbound handling rejects it before catch-all collection, while the precise route remains in place. Removing the rule may still leave delivery through a separate external catch-all. Imported rules are never changed, and unverified imported state is reported as unverified rather than as confirmed preservation. A rule changed externally returns a conflict and is left alone. Restore is allowed only after deletion is reconciled and no address operation lease is active; it verifies or recreates the route before enabling receiving. An active operation or unresolved deletion returnsMAIL_ADDRESS_OPERATION_CONFLICT.
The Cloudflare Email Routing Rules API documents deletion by rule ID without an ETag/version precondition. The final read narrows the external-change window but cannot make the Cloudflare request and D1 update atomic. Timeouts are reconciled with a read before a retry can issue another DELETE.
The default unknown-recipient policy is reject. Optional collect is allowed
only for a configured domain whose read-only check confirms its catch-all
targets this Worker; collected messages retain the actual envelope address and
do not create a sendable identity. A healthy catch-all observation is normally
fresh for 24 hours. If the last check then fails with a transient Cloudflare
network, timeout, rate-limit, or upstream error, an already-confirmed explicit
collect domain may keep collecting for one additional bounded 24-hour grace.
This does not update the success timestamp. Permission/configuration errors,
missing credentials, an observed target mismatch, disabled domains, and
disabled/deleted explicit addresses do not receive that grace. Unknown domains
are never globally accepted. A previously disabled/deleted explicit address
is rejected before catch-all collection. Deleting this application's exact
rule cannot block an external Worker or forwarding catch-all that also matches
the domain. reject_route_preserved is an expected terminal observation for a
deleted address whose exact FlareMail route was deliberately retained; checks
do not enqueue cleanup or reactivate the address.
Inbound plus addressing follows Cloudflare's
subaddressing contract.
An explicitly registered name+tag identity takes precedence, including its
disabled/deleted state. Otherwise the Worker resolves name+tag to the
configured name identity and applies the same ownership, lifecycle, receive,
and routing guards. The original envelope recipient is retained in the stored
message and dedupe key; aliases do not create another address or grant a new
sender identity. Without a configured base, the existing unknown-recipient
policy applies. Cloudflare's subaddressing setting controls whether a base
routing rule delivers an alias to this Worker.
A processing ingest lease is not proof of persistence. When another invocation
holds the lease, the Worker rechecks the committed message before treating the
delivery as a duplicate. If no message exists, it throws INBOUND_CLAIM_BUSY
without writing R2, changing the other claim, or calling setReject. A completed
claim remains evidence of a previously committed delivery, including after an
operator has deleted that message. See the
inbound reliability spec.
The current Email Routing Worker handler contract
documents message.setReject() for an explicit refusal but does not promise
automatic redelivery when a handler throws. FlareMail therefore does not rely
on throw-to-retry as a delivery guarantee. Inbound storage or D1 failures still
throw rather than being converted to a permanent reject; their redelivery
behavior must be verified against the deployed Cloudflare account separately.
There is no automatic inbound replay queue: a lease expiring or being removed
does not itself redeliver or reconstruct mail.
For new mail and forwards, a ready exact address selected in the mailbox filter is the initial sender. Other views, including a domain filter, use the ready global default; if the exact address is not ready, the client falls back to that ready global default or leaves From unset. Replies and Reply All keep the identity of the specific received message or sent message, regardless of a later filter change. An opened draft keeps its saved sender ID, including an explicitly empty sender, rather than adopting a newer default.
The compose view explains whether sending is blocked by address or domain disablement, an unverified/disabled Resend sending state, a stale successful check, or a failed provider check. A refreshed identity list changes the available status and explanation without replacing the current From choice or discarding compose edits. Draft content can still be saved while its sender is not ready; the server independently enforces sender readiness before delivery.
The existing one-minute Worker Cron remains active for Telegram's durable outbox. Mail health checks run in an independently caught scheduled task. Each provider selects only due rows through indexed next-check fields and an independent expiring D1 lease; one invocation checks at most one due domain per provider. Cloudflare reads are capped at ten rules pages and a 12-second provider deadline; Resend reads have a 10-second total deadline. No scheduler path calls the Cloudflare create/delete API or changes address lifecycle, send, or receive preferences.
Healthy provider checks schedule the next attempt 16–20 hours later with stable
per-domain jitter. Checks that observe a non-ready domain or route schedule a
six-hour review. Retryable API errors use jittered exponential backoff capped
at 20 hours; permission/configuration errors retry after six hours. Provider
success timestamps never advance on a timeout, 403, 429, invalid response, or
unknown result. A real Resend state such as pending, failed, missing, or
sending-disabled is stored as an observation with its actual check time and a
degraded state. Cloudflare and Resend timestamps/errors do not block one another.
Mail health refresh uses CLOUDFLARE_EMAIL_ROUTING_READ_TOKEN when configured
and falls back to CLOUDFLARE_EMAIL_ROUTING_TOKEN for existing deployments.
The former needs read-only zone/routing access; address create/delete
operations still require the latter's edit permission.
GET /api/readiness is authenticated and includes per-domain provider state
(fresh, stale, refreshing, degraded, or not_configured), last success,
next scheduled check, last failure, safe error code, and catch-all observation
time. Public GET /api/health remains only { "ok": true }.
Authenticated JSON routes use one correlation ID in the response body and the
X-Request-ID header:
{
"ok": false,
"error": {
"code": "D1_UNAVAILABLE",
"message": "工作区数据服务暂时不可用。",
"retryable": true
},
"requestId": "correlation-id"
}Runtime failures are classified as CONFIG_INVALID,
AUTHENTICATION_UNAVAILABLE, SCHEMA_NOT_READY, D1_UNAVAILABLE,
R2_UNAVAILABLE, NETWORK_FAILURE, or INTERNAL_ERROR. Server logs contain
the correlation ID and safe classification metadata, never request bodies,
mail content, bindings, credentials, or raw exception messages. HTML page loads
return a typed unavailable view with retry and the read-only health link; they
do not turn a storage or schema failure into the login page.
GET /api/health is a minimal public liveness endpoint and returns only
{ "ok": true }; it does not read bindings or disclose deployment state.
GET /api/readiness is private and requires a valid workspace session. It
checks runtime configuration, the exact required schema version/tables, and
reports safe cleanup-queue counts and mail-domain health metadata. It never
returns provider credentials, zone IDs, message or address records. Failures
return a typed safe error and correlation ID without configuration values or
schema internals.
Telegram routes are authenticated workspace operations and use the standard
{ ok, data, requestId } envelope with cache-control: private, no-store.
They never return the Bot token or Telegram chat ID and cannot select another
user's binding or delivery rows.
GET /api/workspace/notifications/telegram/settingsreturns global enabled state, configuration/schema readiness, the current user's candidate/active binding state, privacy/summary/AI-summary switches, and a small recent-delivery list.POST /api/workspace/notifications/telegram/bindcreates a 10-minute, one-time deep link. The token is returned only in that authenticated response and is stored only as a hash. An active binding must be explicitly unbound before it can be replaced.POST /api/workspace/notifications/telegram/confirmpromotes the current candidate to an active but disabled binding.PATCH /api/workspace/notifications/telegram/settingsaccepts booleanenabled,privacyMode,summaryEnabled, and/oraiSummaryEnabled. The AI switch defaults off and has queue-time/current consent intersection; it also requires summaries and non-private delivery. Enabling notifications requires an active binding;forwardingEnabledandINBOUND_NOTIFICATION_ENABLEDare separate legacy controls.POST /api/workspace/notifications/telegram/testsends only a fixed safe test line to the current active/enabled chat.POST /api/workspace/notifications/telegram/unbindrevokes the binding, increments its authorization version, and cancels pending/not-started rows.GET /api/workspace/notifications/telegram/deliveries?limit=...&cursor=...returns owner-scoped status metadata without body or attachment content. The response containsdeliveries,hasMore, andnextCursor(null at the end). Limit defaults to 20 and accepts 1–50; omit cursor for the first page. Cursors bind the Owner and creation-time/ID order. Invalid or foreign cursors return400 INVALID_CURSOR; invalid limits return400 INVALID_LIMIT.POST /api/workspace/notifications/telegram/deliveries/:id/retryis a manual owner-scoped retry for failed/retryable/unknown rows. The response carries a manual-duplicate warning forunknown_delivery.
POST /api/webhooks/telegram is not a browser API. It validates
X-Telegram-Bot-Api-Secret-Token before parsing or D1 access, accepts only
private non-bot chats, and deduplicates by Telegram update_id. See
docs/TELEGRAM.md for setup, Cron and production evidence
limits.
POST /api/send is a compatibility adapter for the first-generation compose
client. It is still an authenticated workspace operation; it is not a public
Resend proxy. The adapter keeps RESEND_API_KEY server-side and applies the
same recipient/subject/body limits, sender authorization, and rate limits as
the workspace send route. senderAddressId is the requested managed identity;
the server resolves its From name/email/signature from D1. A new message may
omit the ID only when an explicit ready default sender exists. Arbitrary from
and client-controlled replyTo values do not set the outgoing identity.
Legacy OUTBOUND_FROM_EMAIL / MAIL_FROM values are used only for system
auto-replies and inbound notifications, never to override a workspace sender.
The minimum legacy request is:
POST /api/send
Content-Type: application/json
Idempotency-Key: flaremail-legacy-client-20260823-001
{
"senderAddressId": "managed-address-uuid",
"to": "recipient@example.test",
"subject": "Hello",
"html": "<p>Hello from FlareMail</p>"
}to may be a single address (the legacy shape); implementations may also
accept the current address-list form. text, cc, bcc, and RFC threading
fields are optional extensions. New clients should send senderAddressId; the
server still validates it against the authenticated Owner and current address
and domain send readiness. The server must reject an empty/invalid
recipient, an overlong subject/body, and malformed JSON. Idempotency-Key is
recommended for retryable clients; when it is absent, the server uses the
request correlation ID, so a later retry must reuse that ID to deduplicate the
logical send. A successful compatibility response retains the old fields (the
standard envelope also adds ok, data, and requestId):
{
"ok": true,
"data": {
"message": {
"id": "sent-local-message-id",
"deliveryProviderMessageId": "provider-message-id"
},
"metrics": {}
},
"success": true,
"id": "provider-message-id",
"sentAt": "2026-08-23T12:00:00.000Z",
"messageId": "sent-local-message-id",
"requestId": "correlation-id"
}The id is a provider message ID, not proof of delivery. The standard data
payload remains the typed workspace message/metrics result used by the web UI;
the top-level fields preserve the small compatibility contract. Clients should
inspect the persisted submitted/delivered state. Errors use the normal private
requestId/field-error envelope where possible; they never include the API key,
raw message body, R2 key, or provider credential details. The application-level
limit is 10 send or retry attempts per authenticated user per 60-second fixed
window; HTTP 429 includes Retry-After. 400, 401, 409, 429, and 503
retain their normal meaning and are safe for clients to retry only when the
response contract allows it.
On the first accepted logical send, the server persists the chosen address ID,
From name/email, signature-rendered body, recipient sets, threading data, and
Message-ID domain. Same-key retries replay that persisted payload and never
switch to a new default or signature. If that original address can no longer
send, retry stops with an explicit error and leaves its persisted delivery
state intact. Reply-To is omitted unless generated from trusted server state;
it is never copied from the client. Replies to inbound mail default to the
address that received that exact delivery, while replies to sent mail preserve
the sent item's historical sender identity.
The html field is email content, not trusted application markup. The adapter
must validate its UTF-8 size and treat it as an opaque payload for the provider;
it must never expose RESEND_API_KEY to the browser or interpolate the request
into a page with Svelte {@html}. Any preview, sent-message detail, or inbound
message display goes through the server sanitizer and the sandboxed HTML route:
- scripts, event-handler attributes, forms, frames, SVG,
javascript:/unsafedata:URLs, and unsafe CSS are removed; - inbound HTML reading preserves allowlisted inline CSS, scoped class/id rules, width media queries, and table presentation attributes using CSSTree. CSS URLs, imports, web fonts, active functions, and positioning are removed even when HTTPS images are enabled. The isolated mail canvas stays light and does not add borders or padding to layout-table cells. Solid fallback colors are retained when a background image URL is removed; safe local gradients remain supported. Reader links keep their layout and show the URL on hover; mode explanations appear in the reader toolbar's information control rather than in the message. Already allowlisted reader HTML is normalized with parse5 in a div context so malformed tables cannot escape the content wrapper. The normalized HTML, CSS share the output byte limit. Repaired DOM depth and node count are checked iteratively before recursive serialization; element creation is also capped during parsing. Logical html/body roots are synthesized when omitted and retain type-selector specificity without matching div/span rules. Legacy presentation hints retain their lower cascade priority, and bgcolor/text/font colors follow HTML legacy-color parsing rather than CSS syntax alone (including hex colors without a leading #). Compose sanitization is unchanged;
- links receive safe target/rel handling.
GET /api/workspace/messages/:id/htmldefaults to Safe HTML and always blocks remote images, including when the legacyremote=1parameter is supplied. Only explicitmode=unsafeselects Unsafe HTML and permits HTTPS image sources. Both modes retain the shared structural/CSS sanitizer, ownership checks, no-referrer policy and sandbox/CSP; scripts, forms, frames, CSS resource requests and HTTP images stay blocked. Unsafe HTML names its remote tracking/privacy risk rather than enabling script execution. The selection is scoped to the message reader and resets when the reader changes messages; - inline CID images are resolved only through an ownership-checked attachment route; attachment bytes and raw MIME are never embedded in JSON;
- the text view remains the safe fallback, and raw
.emldownload is an attachment response rather than executable HTML.
This boundary protects FlareMail's UI even when an outbound or inbound message contains hostile HTML. It does not claim that a recipient's mail client will render provider-delivered HTML identically; production testing must use a dedicated mailbox and must not send secrets or personal data in fixtures.
GET /api/workspace/drafts/:id returns the current owned draft with its full
text body, server-owned senderAddressId and From snapshot, an opaque
bodyRevision, visible attachment lifecycle summaries, and an integer
attachmentRevision. Draft writes include senderAddressId when changing the
selected identity and expectedUpdatedAt,
the version observed by the editor, and echo bodyRevision after a canonical
body write. A client must present that revision before changing a tiered body;
an edit based only on a list projection returns DRAFT_BODY_RELOAD_REQUIRED.
The server updates only when that version still matches. A stale write returns
HTTP 409 with a typed DRAFT_CONFLICT error containing only draftId and
updatedAt. The server validates the sender against the same Owner and stores
its current identity snapshot; client From/Reply-To headers do not override
that snapshot. The client keeps the local edit visible and explicitly fetches the
owned current draft if the user chooses the server version; error envelopes do
not reflect a mail body.
Attachment bytes never enter the compose JSON or D1. The browser computes a
SHA-256 digest, then sends the raw request body to
PUT /api/workspace/drafts/:draftId/attachments/:attachmentId with filename,
size, and attachmentRevision query parameters plus Content-Type and
X-FlareMail-SHA256 headers. The Worker streams that body to a server-generated
outbound/v1/... R2 key that contains no user filename. The response returns
the next attachment revision and the complete visible lifecycle summary list.
failed and interrupted uploading rows remain visible after refresh so the
client can retry or remove them; delete_pending rows are hidden and do not
block sending while maintenance completes cleanup.
PATCH on the same route accepts { filename, attachmentRevision }; DELETE
accepts attachmentRevision in the query. Every operation checks draft owner,
uses optimistic concurrency, sanitizes the display filename, and keeps failed
or interrupted objects in a bounded cleanup lifecycle. Limits are 10 files,
8 MiB per file, and 12 MiB total raw bytes. The total leaves headroom below
Resend's 40 MB post-Base64 message limit and the Worker serialization budget.
The server validates a present Content-Length and always wraps the request
stream in a byte-counting transform, so chunked or misleading uploads abort as
soon as they exceed the declared per-file limit.
A draft send must present the current attachmentRevision. Before persistence,
the server reloads every ready R2 object and verifies its size and SHA-256. The
sent message insert, attachment relation transfer, and draft deletion then run
in one guarded D1 batch. Provider failure or an unknown result does not delete
the attachment: same-key delivery retries reload and verify the same persisted
objects. GET /api/workspace/messages/:id/body includes sent attachment
summaries, and the owned attachment route forces safe download headers after a
fresh integrity check.
Email Routing ingest computes SHA-256 from the already bounded parsed bytes and persists the same lowercase digest in R2 put metadata and the owned D1 attachment row. The download route first resolves session, message, relation, attachment ID, and owner scope. It then requires the object, exact size, and, for new rows, a matching SHA-256 before returning any bytes.
Missing, size-mismatched, and checksum-mismatched objects return controlled
typed errors without an R2 key, filename, object bytes, or storage exception.
Responses retain no-store, nosniff, safe Content-Disposition, and a
bounded content type. Historical checksum-null rows use actual-byte size
verification and the degraded integrity event until an operator runs the
bounded repair workflow; a download never performs bulk repair.
POST /api/workspace/mailbox/mutate
{
"action": "archive|unarchive|read|unread|star|unstar|trash",
"ids": ["selected-message-id"],
"scope": {
"section": "inbox|sent|archive|starred|label",
"identityFilter": null,
"threadScope": "selected"
}
}scope is required; old clients that omit it receive MAILBOX_SCOPE_REQUIRED.
Every explicit ID is checked against the authenticated Owner and declared
section/address filter by the server before any write. identityFilter is
null, { "kind": "domain", "id": "..." }, or
{ "kind": "address", "id": "..." }. A foreign identity, section, Owner,
or selected message outside that scope is rejected without a partial mutation.
For section: "label", scope.labelId is required and each selected ID must
still belong to that Owner's label. For section: "starred", each selected ID
must still be starred. These two cross-folder views accept only
threadScope: "selected"; they never expand a thread or silently include
unselected mail. Drafts can be selected for bulk label management, but are
not targets of this mailbox mutation endpoint.
The client selects only currently loaded rows. “Select all” means all rows
loaded in the current page that match the active search, unread, or starred
filter; it does not mean every result in searchTotal. A normal selected-message
operation (threadScope: "selected") changes only the IDs in ids and must
not include threadKeys. A filtered-thread operation explicitly includes the
selected thread anchors and repeats the current query and filter; the server
checks each anchor belongs to an explicit ID and resolves only messages in
those threads that match that query, section, address
filter, and unread/starred filter. This can include matching messages outside
the loaded page, but never other search results. An Owner-wide thread operation
uses threadScope: "owner" and is an explicit expansion across the Owner's
addresses and inbox/archive/sent sections. Archive and unarchive still affect
only inbox rows; drafts are not bulk-thread targets.
All IDs are resolved and capped at 100 before the transaction. Oversized or
partially invalid requests fail before any write. The write is one D1
batch() transaction. Archive and unarchive only operate on inbox-owned rows
and change archived_at; they never rewrite folder to manufacture an archive
folder.
The response returns affected summaries, movement information, the resolved
scope, and metrics with an explicit metricsScope.identityFilter. A null
metrics identity is Owner-global; a domain/address value is scoped to that
identity and is not narrowed to the selected page or search. Clients discard
metrics from a different identity scope and refresh when a message delta does
not fit the current page.
Trash has no identity filter: entering it clears the current identity filter,
and its list/empty operation is Owner-global. A bulk trash action from
any mailbox view is still scoped to the declared identity and section or
cross-folder view membership.
GET /api/workspace/mailbox accepts q/query and executes the normalized
query through the owner-scoped D1 FTS5 projection. Free text and the following
operators are supported: from:, to:, cc:, subject:, is:unread,
is:starred, is:archived, is:trash, has:attachment, attachment:yes|no,
date:YYYY-MM-DD (the exact UTC day), after:YYYY-MM-DD,
before:YYYY-MM-DD, status: and label:. has:attachment is an alias for
attachment:yes; contradictory attachment filters are rejected. Quotes group spaces. Unknown
operators, malformed quotes, dates and statuses return
INVALID_SEARCH_QUERY; no user input is interpolated as SQL or as an FTS
column name.
Search pages keep the normal opaque timestamp/id cursor. The first page also
returns searchTotal and searchHitFields; each result can include a bounded
searchSnippet whose private-use delimiters are rendered as text highlights,
never as HTML. BCC, raw MIME, attachment bytes and secrets are not searchable.
Retry is available only when the persisted delivery state is retryable
(submitting, delayed, or failed), the durable idempotency key is present,
the attempt has started, and the attempt remains inside the 24-hour provider
idempotency window. queued, submitted, accepted, delivered, and other
terminal states are not ordinary retry targets.
The UI and server use the same domain eligibility rule. The server additionally rechecks ownership, message/delivery linkage, persisted key, attempt count, and window before sending. A business rejection returns a typed conflict/error response; an expired attempt requires delivery review rather than silently creating a new provider idempotency key.
DELETE /api/workspace/messages/:id is a soft delete. It keeps the owned
message, draft, or inbound state and records its deletion time; repeated
requests are idempotent. Normal mailbox lists and counts exclude these rows.
GET /api/workspace/trash?limit=100&cursor=... returns one ownership-scoped page across
workspace messages, drafts, and inbound messages. Each item includes its
deletedAt and originalFolder (inbox, archive, sent, or drafts).
The response retains items, hasMore, and metrics, and adds nextCursor
(null at the end). Omit cursor for the first page; limit defaults to 100 and
accepts 1–500, while the browser requests 40. The opaque cursor binds the Owner
and the merged deletion-time/public-ID/kind order across all three sources.
It remains usable after its boundary record is removed. Invalid or foreign
cursors return 400 INVALID_CURSOR; invalid limits return 400 INVALID_LIMIT.
Every request still checks the authenticated Owner independently of the cursor.
POST /api/workspace/trash/:id restores an item to the persisted folder and
archive state. DELETE /api/workspace/trash/:id permanently deletes only an
owned trash item. Permanent deletion removes delivery status, attempts,
events, receipts, attachment/body metadata, and their owned R2 objects. The
operation is ownership-preflighted and safe to retry. It commits the owned D1
deletion before deleting R2 objects, so a storage failure cannot leave live D1
pointers to missing data. The same D1 transaction records every object in
workspace_r2_cleanup_queue; successful deletes mark those records completed
and retain the lifecycle evidence. cleanupPending: true means retry/backoff or
manual review remains. Claim tokens, leases, bounded attempts, canonical key
scope, and source ownership make later API or reviewed maintenance replay
idempotent.
POST /api/workspace/trash with { "action": "empty" } permanently deletes
all owned trash items up to the bounded batch size. Expired trash is reported
by scripts/maintenance.ts --trash-retention-days 30 in dry-run mode; the
maintenance command does not perform remote destructive trash cleanup.
Unit, D1 integration, isolated Playwright, and axe checks use local/fake bindings and do not prove production delivery. Production deployment, remote migration, real Resend calls, Email Routing, and real-mail smoke tests remain explicit operator actions.
GET /api/workspace/messages/[id]/ai?language=zh-CN|en reads an owner-scoped cache, never the model. Request language remains a validated legacy interface-context field; the saved preference controls output, with auto resolving to the saved workspace background language for all callers. POST to the same path accepts only { "language": "en", "regenerate": false } (JSON, at most 1024 bytes); regenerate is optional. URL, model, key and body overrides are rejected. Authentication, CSRF and no-store policies apply.
The standard envelope contains {status, analysis, language?, truncated?, updatedAt?, refreshing?, appliedCategory?}; status is disabled, unconfigured, empty, processing or ready. Analysis contains summary, keyPoints, actionItems, verbatim dates, language, and nullable suggestion: {category, confidence, reason}. Categories are primary, transactions, security, updates, subscriptions and promotions. Retired social/forums filter and mutation IDs normalize to updates. AI-confirmed category PATCH requests set onlyIfAutomatic: true; the database updates only a null category override, so concurrent manual edits win and the response returns their current summaries. language exposes the effective output-language code when present. GET never mutates categories. When automatic classification is enabled, explicit POST analysis can save an automatic category and return appliedCategory. A successful null suggestion clears an existing automatic category and returns the local-rule fallback as appliedCategory; manual overrides, current consent and saved-analysis guards are preserved atomically. The category PATCH endpoint records manual choices. AI-confirmation requests use category all for the selected message while retaining its identity filter, so an automatic category change does not invalidate an open reader’s old category link. updatedAt is the last successful generation time; refreshing indicates an in-flight replacement while a previous valid result is retained. Failed regeneration preserves that success.
Only owned inbox messages are supported, including archived inbox sources. Trash, quarantine, blocked messages, sent mail and drafts cannot generate analyses. Claims expire after 60 seconds, with a 30-second cooldown and 30 attempts/hour per Owner. Body/model/endpoint/language/schema changes invalidate caches. Permanent deletion triggers cache cleanup. See privacy, environment configuration and error codes.
GET /api/workspace/ai/settings returns {settings, hasApiKey, canSave, revision, source}.
settings contains enabled, baseUrl, model, apiFormat (chat-completions or
responses), timeoutMs (100–30000), maxInputChars (256–32000),
automaticClassification (boolean, default false), summaryLanguage (auto or a canonical BCP 47 tag up to 64 characters), and
backgroundLanguage (zh-CN or en). Missing legacy fields default to auto
and zh-CN; clients omitting them on save preserve current preferences. All auto callers use the language saved with AI settings. Classification opt-in is independent of Telegram and only queues newly arriving eligible mail; server-only consent tokens are never accepted from or exposed to clients.
PATCH accepts those fields plus the latest revision, optional apiKey and
optional clearApiKey (JSON, at most 12 KiB). Blank/omitted keys are retained;
endpoint changes require key re-entry. Delete with clearApiKey: true while
disabled. Unknown fields and invalid public HTTPS endpoints are rejected.
Only the singleton Owner can read/write these settings; authentication, CSRF
and no-store apply. Neither API returns plaintext/ciphertext keys. Stale saves
return 409 AI_SETTINGS_CONFLICT; encryption setup errors return 503
AI_SETTINGS_KEY_UNAVAILABLE. Saving has no provider call and takes effect
on the next analysis request. Existing encrypted settings override environment
defaults. The language preferences reuse the existing settings JSON; Telegram
automatic generation additionally requires migration 0031. See the
summary and classification SPEC. Schema 32 is required; durable classification jobs, independent automatic/manual category fields and last-success times are added by migration 0032.
AI provider URLs accept either an HTTPS base or a full /responses or /chat/completions URL. The selected API format determines the final method path; it is appended once. Stored URL values are preserved to retain encrypted-key bindings.
For direct OpenAI Platform requests, the adapter uses the official api.openai.com
origin with strict structured output: Responses text.format and
max_output_tokens, or Chat Completions response_format.json_schema and
max_completion_tokens. Common provider failures use AI_PROVIDER_AUTH,
AI_PROVIDER_FORBIDDEN, AI_PROVIDER_MODEL_NOT_FOUND, AI_PROVIDER_NOT_FOUND,
AI_PROVIDER_BAD_REQUEST, AI_PROVIDER_QUOTA and AI_RATE_LIMITED. Upstream
401/403 do not expire the workspace session: they return an application 503 with
a provider error code and retryable: false. Provider quota failures return
429 without an automatic retry. Output-token exhaustion (AI_OUTPUT_LIMIT) and
refusal (AI_REFUSED) return 502 without partial analysis or upstream messages.
Provider failures may include a safe error.details.reason: provider_http_<status> or a fixed network category (provider_redirect, provider_tls_error, provider_dns_error, provider_header_error, provider_network_error). These diagnostics never include upstream messages, URLs, keys or email content.
AI_TIMEOUT with error.details.reason: before_provider_request means the local time budget expired before invoking the provider. Background classification defers this work without consuming its single generation attempt; a timeout after invoking the provider is not automatically retried.