Skip to content

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 ​

PathMethodPurpose & Intended Callers
/v1/sendPOSTStandard send endpoint: Recommended for all new services, backends, and CI workflows
/v1/panelPOSTLegacy panel compatibility: For panels fixed on {token, from, fromName, to, title, msg, type} without custom auth headers
/healthzGET / HEADReadiness 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:

  1. No URL query parameters: Any ?key=value returns 400 invalid_request.
  2. Content type & encoding: Content-Type must have media type application/json (415 unsupported_media_type otherwise); compressed Content-Encoding is rejected—only omitted or identity is accepted (415 unsupported_content_encoding).
  3. 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_request for 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-insensitive Bearer scheme; Basic or empty bearer value is treated as missing).
  • Panel fallback: Only /v1/panel may fall back to JSON body.token when no Authorization header token is present; providing tokens in both places returns 400 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_TOKENS are normalized into SHA-256 digests and XOR-compared across every configured digest without early exit. Rotate by appending the new token to AUTH_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.

FieldTypeRequiredConstraints & Limits
from"a@b.c" or { email, name? }YesDomain must match ALLOWED_SENDER_DOMAINS
toAddress or non-empty arrayYesCombined to + cc + bcc count <= MAX_RECIPIENTS (default 10, max 50)
cc / bccSame as toNoShares recipient limit; case-insensitive duplicates rejected across fields
subjectstringYesNon-empty after trim, <= 256 UTF-8 bytes, rejects control/CR/LF, bidi, and zero-width chars
textstringConditional*Non-empty, <= 96 KiB, allows newlines \n, forbids \0
htmlstringConditional*Non-empty, <= 96 KiB, same char rules; at least one of text or html is required
replyToSame as fromNoDomain must also match ALLOWED_SENDER_DOMAINS

Address & display name details:

  • Email address total length <= 254 bytes, local part <= 64 bytes (no leading/trailing dots, .., or whitespace), domain lowercased and must contain ..
  • Optional name / fromName must be non-empty, <= 128 UTF-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:

  • title maps to subject (<= 256 UTF-8 bytes).
  • msg maps to plain-text text; when type is provided (<= 128 UTF-8 bytes) and is not "text", the Worker prepends 通知类型:<type>\n\n before <msg>, and the combined text must still fit within 96 KiB.
  • fromName maps to from.name under the same 128-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.

json
// 200 OK
{
  "ok": true,
  "requestId": "8fcea792-6e49-411e-a386-ffabd65c386b",
  "data": {
    "messageId": "mid-1",
    "accepted": { "to": ["ops@example.org"], "cc": [], "bcc": [] }
  }
}
HTTPerror.codeCauseExtra Fields / Headers
200—Delivered to EMAIL.senddata.messageId, data.accepted
400invalid_requestQuery string present, invalid UTF-8, malformed JSON, non-object, empty bodyX-Request-Id
400invalid_fieldField type, length, domain, duplicate recipient, or unknown field violationerror.field (e.g., to[1], from.name)
400credentials_ambiguousBoth Bearer header and JSON token supplied on /v1/panel—
401unauthorizedMissing or non-matching tokenWWW-Authenticate: Bearer realm="email-relay"
403forbiddenClient IP rejected by allowlist, or missing CF-Connecting-IP—
404not_foundUnknown route—
405method_not_allowedUnsupported HTTP methodAllow: POST or Allow: GET, HEAD
413payload_too_largeStreamed body exceeds 128 KiB—
415unsupported_media_type / unsupported_content_encodingNon-JSON Content-Type or compressed Content-Encoding—
429rate_limitedTriggered by RATE_LIMITER.limitRetry-After: 60
502upstream_failedEMAIL.send rejected or threwTruncated error.details.providerCode (<= 64 chars)
503not_configuredMissing/invalid env config or broken bindingerror.details.checks on /healthz
500internal_errorUnhandled 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.