AI Translation Notice
This page is synchronized with the Chinese HTTP contracts specification. Refer to the Chinese edition and src/ source files as the authoritative reference.
HTTP Contracts, Security & FAQ
This document specifies the HTTP endpoints, framing checks, authentication semantics, UTF-8 byte quotas, response envelopes, and security boundaries enforced by Cloudflare Email Relay.
Endpoints & Request Framing
| Path | Method | Purpose & Intended Callers |
|---|---|---|
/v1/send | POST | Standard send endpoint: Recommended for all new services, backends, and CI workflows |
/v1/panel | POST | Legacy panel compatibility: For panels fixed on {token, from, fromName, to, title, msg, type} without custom auth headers |
/healthz | GET / HEAD | Readiness probe: Returns boolean health checks without exposing configuration values |
Every send request to /v1/send or /v1/panel must pass these HTTP framing rules before body processing:
- No URL query parameters: Any
?key=valuereturns400 invalid_request. - Content type & encoding:
Content-Typemust have media typeapplication/json(415 unsupported_media_typeotherwise); compressedContent-Encodingis rejected—only omitted oridentityis accepted (415 unsupported_content_encoding). - Bounded streaming UTF-8 JSON: Body bytes are streamed and capped at 128 KiB (
413 payload_too_large), decoded strictly as UTF-8, and parsed into a non-null plain JSON object (400 invalid_requestfor empty body, arrays, strings, or invalid JSON).
Authentication, Source Guard & Multi-Token Rotation
Requests execute in strict order: Config load -> CF-Connecting-IP & allowlist -> optional RATE_LIMITER -> bounded JSON read -> token match -> field validation. Keeping field validation strictly after authentication prevents unauthenticated callers from probing allowed sender domains or field rules via 400 invalid_field.
- Header token:
Authorization: Bearer <token>(case-insensitiveBearerscheme;Basicor empty bearer value is treated as missing). - Panel fallback: Only
/v1/panelmay fall back to JSONbody.tokenwhen noAuthorizationheader token is present; providing tokens in both places returns400 credentials_ambiguous. - Token syntax: Must match
^[A-Za-z0-9._~+/=-]{32,512}$; non-matching candidates fail before hashing. - Zero-downtime rotation: Comma-separated tokens in
AUTH_TOKENSare normalized into SHA-256 digests and XOR-compared across every configured digest without early exit. Rotate by appending the new token toAUTH_TOKENS, updating callers, and then deleting the old token.
Payload Schemas & UTF-8 Byte Limits
Both endpoints reject unknown fields with 400 invalid_field. All length caps measure UTF-8 encoded byte length rather than UTF-16 code units.
Standard Payload (POST /v1/send)
Allowed fields (STANDARD_FIELDS): from, to, cc, bcc, subject, text, html, replyTo.
| Field | Type | Required | Constraints & Limits |
|---|---|---|---|
from | "a@b.c" or { email, name? } | Yes | Domain must match ALLOWED_SENDER_DOMAINS |
to | Address or non-empty array | Yes | Combined to + cc + bcc count <= MAX_RECIPIENTS (default 10, max 50) |
cc / bcc | Same as to | No | Shares recipient limit; case-insensitive duplicates rejected across fields |
subject | string | Yes | Non-empty after trim, <= 256 UTF-8 bytes, rejects control/CR/LF, bidi, and zero-width chars |
text | string | Conditional* | Non-empty, <= 96 KiB, allows newlines \n, forbids \0 |
html | string | Conditional* | Non-empty, <= 96 KiB, same char rules; at least one of text or html is required |
replyTo | Same as from | No | Domain must also match ALLOWED_SENDER_DOMAINS |
Address & display name details:
- Email address total length
<= 254bytes, local part<= 64bytes (no leading/trailing dots,.., or whitespace), domain lowercased and must contain.. - Optional
name/fromNamemust be non-empty,<= 128UTF-8 bytes, and cannot contain<,>,",\, or control/bidi/zero-width characters.
Legacy Panel Payload (POST /v1/panel)
Allowed fields (PANEL_FIELDS): token, from, fromName, to, title, msg, type:
titlemaps tosubject(<= 256UTF-8 bytes).msgmaps to plain-texttext; whentypeis provided (<= 128UTF-8 bytes) and is not"text", the Worker prepends通知类型:<type>\n\nbefore<msg>, and the combined text must still fit within96 KiB.fromNamemaps tofrom.nameunder the same128-byte and delimiter rules.
Response Envelope, Error Codes & Logs
Every JSON response sets Content-Type: application/json; charset=utf-8, X-Request-Id, Cache-Control: no-store, X-Content-Type-Options: nosniff, Content-Security-Policy: default-src 'none', and Referrer-Policy: no-referrer.
// 200 OK
{
"ok": true,
"requestId": "8fcea792-6e49-411e-a386-ffabd65c386b",
"data": {
"messageId": "mid-1",
"accepted": { "to": ["ops@example.org"], "cc": [], "bcc": [] }
}
}| HTTP | error.code | Cause | Extra Fields / Headers |
|---|---|---|---|
200 | — | Delivered to EMAIL.send | data.messageId, data.accepted |
400 | invalid_request | Query string present, invalid UTF-8, malformed JSON, non-object, empty body | X-Request-Id |
400 | invalid_field | Field type, length, domain, duplicate recipient, or unknown field violation | error.field (e.g., to[1], from.name) |
400 | credentials_ambiguous | Both Bearer header and JSON token supplied on /v1/panel | — |
401 | unauthorized | Missing or non-matching token | WWW-Authenticate: Bearer realm="email-relay" |
403 | forbidden | Client IP rejected by allowlist, or missing CF-Connecting-IP | — |
404 | not_found | Unknown route | — |
405 | method_not_allowed | Unsupported HTTP method | Allow: POST or Allow: GET, HEAD |
413 | payload_too_large | Streamed body exceeds 128 KiB | — |
415 | unsupported_media_type / unsupported_content_encoding | Non-JSON Content-Type or compressed Content-Encoding | — |
429 | rate_limited | Triggered by RATE_LIMITER.limit | Retry-After: 60 |
502 | upstream_failed | EMAIL.send rejected or threw | Truncated error.details.providerCode (<= 64 chars) |
503 | not_configured | Missing/invalid env config or broken binding | error.details.checks on /healthz |
500 | internal_error | Unhandled internal exception | — |
Structured JSON logs ({ level, event, requestId, ... }) record email_sent, email_send_failed, ip_allowlist_disabled, configuration_error, and unhandled_error, and never emit raw tokens, secret values, or message bodies.
Extension & API FAQ
Q: Why are error.message strings in English while repository comments and docs are Chinese-primary?error.message strings form part of the stable HTTP API contract tested by downstream callers (such as Request body must be valid UTF-8). Translating those runtime strings would break automated assertions.
Q: What must be considered before adding attachment or custom-header support?STANDARD_FIELDS rejects both by design. Any future extension in src/validate.ts would need strict CRLF/header-injection checks plus per-attachment and aggregate byte caps compatible with the 128 KiB MAX_REQUEST_BYTES ceiling, backed by adversarial unit tests.
Q: Why does sending token inside a /v1/send body return 401 without a Bearer header instead of 400 invalid_field?/v1/send only reads Authorization: Bearer. Because field validation runs strictly after authentication, unauthenticated calls always receive 401 rather than leaking schema rules. Sending a valid Bearer header together with an unexpected token field returns 400 invalid_field (field: "token").
Next: trace the runtime execution path and topology in Request Flow & Topology.