### Usage example for setup status check Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/23-setup-seed.md Example of importing getSetupRequirementChecks and using it to check if setup is complete. It retrieves the checks and verifies all are configured. ```ts import { getSetupRequirementChecks } from "@/lib/setup/configuration"; // GET /api/setup/status const checks = getSetupRequirementChecks(env); const complete = checks.every((check) => check.configured); ``` -------------------------------- ### Quick start: clone, configure, and run with Docker Compose Source: https://github.com/hieunc229/mailflare/blob/main/docs/self-hosting.md Clones the Mailflare repository, copies the example environment file, and starts the container with Docker Compose. Edit the .env.docker file to configure how to receive and send mail before running. ```bash git clone https://github.com/hieunc229/mailflare && cd mailflare cp .env.docker.example .env.docker # edit: how to receive and send mail docker compose up -d --build ``` -------------------------------- ### Install, build, and run Mailflare without Docker Source: https://github.com/hieunc229/mailflare/blob/main/docs/self-hosting.md Run these commands to install dependencies, build for Node.js, and start the server. The runtime requires root or the cap_net_bind_service capability for port 25; otherwise set SMTP_INBOUND_PORT=2525 and forward the port. ```bash npm ci npm run build:node MAILFLARE_RUNTIME=node NODE_ENV=production DATA_DIR=./data node dist/server.mjs ``` -------------------------------- ### Docker Self-Hosting Commands Source: https://github.com/hieunc229/mailflare/blob/main/README.md Commands to self-host Mailflare with Docker. Copy the example environment file and start the container stack. Requires Docker and Docker Compose. The container uses SQLite and local files instead of D1 and R2. ```bash cp .env.docker.example .env.docker docker compose up -d --build ``` -------------------------------- ### GET /api/push/config Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/22-push.md Exposes the VAPID public key for client-side push subscription setup. ```APIDOC ## [GET] /api/push/config ### Description Exposes the VAPID public key for client-side push subscription setup. ### Method GET ### Endpoint /api/push/config ### Response #### Success Response (200) - (No explicit response fields documented) #### Response Example (No explicit response example documented) ``` -------------------------------- ### Install dependencies and deploy locally Source: https://github.com/hieunc229/mailflare/blob/main/docs/deployment.md Run these commands to install dependencies and deploy the Worker locally. The local deploy builds with vinext and uploads the complete Worker with Wrangler, generating dist/server/wrangler.json. ```bash npm install npm run deploy:local ``` -------------------------------- ### Usage Example Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/14-mcp.md Example of using authenticateMcpRequest and createMailflareMcpHandler in a Cloudflare Worker. ```APIDOC ## Usage Example ### Description Example of using `authenticateMcpRequest` and `createMailflareMcpHandler` in a Cloudflare Worker. ### Code ```ts import { authenticateMcpRequest } from "@/lib/mcp/auth"; import { createMailflareMcpHandler } from "@/lib/mcp/server"; const principal = await authenticateMcpRequest(env, request); if (!principal) return new Response("Unauthorized", { status: 401 }); const handler = createMailflareMcpHandler(env, principal, url.origin, request.headers.get("Authorization") ?? ""); return handler.fetch(request); ``` ``` -------------------------------- ### Server Usage Example Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/22-push.md Example of sending push notifications from the server using both Web Push and native APNs. Both are invoked automatically from notifyUsersOfNewMessage. ```typescript import { sendPushNotifications } from "@/lib/push/server"; import { sendNativePush } from "@/lib/push/native"; await sendPushNotifications(env, userIds, { type: "new_message", messageId, mailboxId, from, fromName, subject }); await sendNativePush(env, userIds, sameMessage); ``` -------------------------------- ### Usage example for API key authentication Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/06-api-key-auth.md Example of using authenticateApiKey and hasScope in a route handler to enforce authentication and scope-based authorization. ```TypeScript import { authenticateApiKey } from "@/lib/api/auth"; import { hasScope } from "@/lib/api/key-auth"; const auth = await authenticateApiKey(env, request.headers.get("Authorization")); if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (!hasScope(auth.scopes, "send")) return NextResponse.json({ error: "Forbidden" }, { status: 403 }); ``` -------------------------------- ### MCP server usage example Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/14-mcp.md Shows how to authenticate an incoming request and create the MCP handler, then fetch the response. ```TypeScript import { authenticateMcpRequest } from "@/lib/mcp/auth"; import { createMailflareMcpHandler } from "@/lib/mcp/server"; const principal = await authenticateMcpRequest(env, request); if (!principal) return new Response("Unauthorized", { status: 401 }); const handler = createMailflareMcpHandler(env, principal, url.origin, request.headers.get("Authorization") ?? ""); return handler.fetch(request); ``` -------------------------------- ### Setup requirement check types Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/23-setup-seed.md Type definitions for setup requirement checks and preparation results. The SetupRequirementCheck type includes a key, configured flag, and message. The SetupPreparationResult type includes an array of checks and a migrated flag. ```ts // src/lib/setup/types.d.ts export type SetupRequirementCheck = { key: string; configured: boolean; message: string }; export type SetupPreparationResult = { checks: SetupRequirementCheck[]; migrated: boolean }; ``` -------------------------------- ### Local Development Setup Commands Source: https://github.com/hieunc229/mailflare/blob/main/README.md Run these commands in order to set up the local development environment. Requires Cloudflare credentials in .dev.vars and optionally a seed command for sample data. ```bash cp .dev.vars.example .dev.vars npm install npm run db:migrate:local npm run dev ``` -------------------------------- ### GET /api/v1/storage Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Retrieves storage configuration details. ```APIDOC ## GET /api/v1/storage ### Description Retrieves storage configuration details. ### Method GET ### Endpoint /api/v1/storage ### Scope `storage` ### Response #### Success Response (200) - **storage** (object) - Storage configuration - **provider** (string) - Storage provider: `backblaze`, `s3`, `r2`, or `files` - **configured** (boolean) - Whether storage is configured - **bucket** (string) - Bucket name - **endpoint** (string) - Endpoint URL - **warning** (string) - Any warning message ``` -------------------------------- ### Usage example for zone and email routing Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/11-cloudflare-api.md Shows how to find a zone by hostname, ensure an email routing rule to a worker, and list sending subdomains. ```typescript import { findZoneByHostname, ensureEmailRoutingRuleToWorker, listSendingSubdomains } from "@/lib/cloudflare-api"; const zone = await findZoneByHostname(env, "example.com"); if (!zone) throw new Error("Zone not found"); await ensureEmailRoutingRuleToWorker(env, zone.id, "hello@example.com", changes); await listSendingSubdomains(env, zone.id); ``` -------------------------------- ### GET /api/realtime Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md WebSocket upgrade endpoint for realtime communication. ```APIDOC ## GET /api/realtime ### Description WebSocket upgrade endpoint for realtime communication. ### Method GET ### Endpoint `/api/realtime` ### Authentication Session cookie. ### Response WebSocket connection. ``` -------------------------------- ### Usage example with analyzeSpam and recordReputationObservation Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/21-spam.md Shows how to import and use the spam engine. Calls analyzeSpam with the parsed email, then stores the spam score/verdict/signals on the message row and records a reputation observation using the fingerprint. ```TypeScript import { analyzeSpam } from "@/lib/spam/engine"; import { getReputationKeys } from "@/lib/spam/analyzers/reputation"; import { recordReputationObservation } from "@/lib/spam/repository"; const analysis = await analyzeSpam(db, { mailboxId, userId, envelopeFrom, headers, message: parsed }); // store spamScore/spamVerdict/spamSignals on the message row await recordReputationObservation(env, mailboxId, getReputationKeys(parsed, analysis.fingerprint)); ``` -------------------------------- ### POST /api/auth/register Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Registers the first user and sets up the primary domain and admin account. Used during initial setup. ```APIDOC ## POST /api/auth/register ### Description Registers the first user and sets up the primary domain and admin account. Used during initial setup. ### Method POST ### Endpoint /api/auth/register ### Parameters #### Request Body - **turnstileToken** (string) - Optional - Turnstile verification token. ### Request Example { "turnstileToken": "token" } ### Response #### Success Response (200) - **ok** (boolean) - Always true on success. #### Response Example { "ok": true } ``` -------------------------------- ### Usage example: dispatching and manual retry Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/09-email-webhooks.md Shows how to import and use dispatchWebhooks and runDelivery in the inbound pipeline and admin UI. ```TypeScript import { dispatchWebhooks, runDelivery, sendTestDelivery } from "@/lib/email/webhooks"; // in the inbound pipeline await dispatchWebhooks(env, user.id, "message.inbound", { messageId, from, to, subject }); // manual retry from the admin UI const result = await runDelivery(env, deliveryId, { userId: admin.id }); if (!result) return NextResponse.json({ error: "Not found" }, { status: 404 }); return NextResponse.json({ status: result.status }); ``` -------------------------------- ### Service functions for domain provisioning Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/12-domains.md Exported async functions for listing, adding, retrieving DNS, removing, and getting a domain for a user. These are the main entry points for domain management. ```typescript export async function listUserDomains(env: CloudflareEnv, userId: string) export async function addDomainForUser(env: CloudflareEnv, userId: string, input: { ... }) export async function getDomainDns(env: CloudflareEnv, userId: string, domainId: string) export async function removeDomainForUser(env: CloudflareEnv, userId: string, domainId: string) export async function getDomainForUser(env: CloudflareEnv, userId: string, domainId: string) ``` -------------------------------- ### getSetupRequirementChecks function signature Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/23-setup-seed.md Function signature for retrieving setup requirement checks. It takes a CloudflareEnv object and returns an array of SetupRequirementCheck objects. ```ts export function getSetupRequirementChecks(env: CloudflareEnv): SetupRequirementCheck[] ``` -------------------------------- ### GET /api/domains/[id]/receiving/[provider] Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Returns the receiving checklist for a specific provider. ```APIDOC ## GET /api/domains/[id]/receiving/[provider] ### Description Returns the receiving checklist for a specific provider. ### Method GET ### Endpoint /api/domains/[id]/receiving/[provider] ### Authentication Requires session. ### Path Parameters - `id` (string) - Required - The domain ID. - `provider` (string) - Required - The provider (`resend` or `ses`). ``` -------------------------------- ### FileBucket / openFileBucket Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/01-server-runtime.md FileBucket implements the R2 bucket API over a directory. It provides methods for get, head, put, multipart uploads, and delete. The openFileBucket function returns an R2Bucket instance. ```APIDOC ## FileBucket / openFileBucket ### Description Implements the R2 bucket API over a directory. Objects are files under `root`; HTTP and custom metadata are stored in a `.meta.json` sidecar. `get` supports byte ranges (`offset`/`length`/`suffix`). Paths escaping the root throw `Error("Object key escapes the bucket root")`. `list()` is not implemented and throws. ### Class: FileBucket #### Constructor - `constructor(root: string)` - Creates a new FileBucket instance rooted at the given directory. #### Methods - `async get(key: string, options?: { range?: { offset?: number; length?: number; suffix?: number } }): Promise` - Retrieves an object. Supports byte ranges via `offset`, `length`, or `suffix`. - `async head(key: string): Promise` - Retrieves object metadata without the body. - `async put(key: string, value: ArrayBuffer | ArrayBufferView | string | ReadableStream | Blob | null, options?: { httpMetadata?: StoredMeta["httpMetadata"] | Headers; customMetadata?: Record }): Promise` - Stores an object. Metadata is stored only when options are provided; otherwise it is reconstructed from file stat. - `async createMultipartUpload(key: string, options?: { httpMetadata?: StoredMeta["httpMetadata"] }): Promise<...>` - Creates a multipart upload. - `resumeMultipartUpload(key: string, uploadId: string): { key; uploadId; uploadPart(...); abort(); complete(parts) }` - Resumes a multipart upload and returns an object with methods to upload parts, abort, and complete. - `async delete(keys: string | string[]): Promise` - Deletes one or more objects. - `async list(): Promise` - Not implemented; throws an error. ### Function: openFileBucket - `openFileBucket(root: string): R2Bucket` - Opens a file bucket and returns an R2Bucket-compatible instance. ``` -------------------------------- ### Client-side WebSocket usage example Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/16-realtime.md Connects to the /api/realtime WebSocket endpoint, sends a revision ping on open, and handles new_message and revision messages to refresh the inbox or mailbox. ```TypeScript const socket = new WebSocket(`${location.origin.replace(/^http/, "ws")}/api/realtime`); socket.onopen = () => socket.send(JSON.stringify({ type: "ping", revision: lastRevision })); socket.onmessage = (event) => { const message = JSON.parse(event.data); if (message.type === "new_message") refreshInbox(message.messageId); if (message.type === "revision" && message.changed) refreshMailbox(); }; ``` -------------------------------- ### Error handling example Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/11-cloudflare-api.md Shows how to catch Cloudflare API errors and check for a specific error code (2008) to return a custom response. ```typescript import { CloudflareApiError, isCloudflareApiErrorCode } from "@/lib/cloudflare-api-error"; try { await enableEmailRouting(env, zoneId); } catch (error) { if (isCloudflareApiErrorCode(error, 2008)) { return { code: "MX_RECORDS_CONFLICT", status: 409 }; } throw error; } ``` -------------------------------- ### GET /jmap/download/{accountId}/{blobId}/{name*} Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/13-jmap.md Downloads a blob. The `name` path parameter and the `?type=` query parameter override the content type. ```APIDOC ## [GET] /jmap/download/{accountId}/{blobId}/{name*} ### Description Downloads a blob. The `name` path parameter and the `?type=` query parameter override the content type. ### Method GET ### Endpoint /jmap/download/{accountId}/{blobId}/{name*} ### Parameters #### Path Parameters - **accountId** (string) - Required - The account ID. - **blobId** (string) - Required - The blob ID. - **name** (string) - Required - The file name; used to override content type. #### Query Parameters - **type** (string) - Optional - Overrides the content type. ### Response #### Success Response (200) - Body: blob content - Content-Type: determined by `name` or `type` parameter #### Response Example (Not provided in source) ``` -------------------------------- ### GET /api/v1/storage Source: https://github.com/hieunc229/mailflare/blob/main/docs/api.md Retrieves the active object storage configuration and its status. Returns provider details and a warning if configuration is incomplete. ```APIDOC ## GET /api/v1/storage ### Description Retrieves the active object storage configuration and its status. Returns provider details and a warning if configuration is incomplete. ### Method GET ### Endpoint /api/v1/storage ### Response #### Success Response (200) - **storage** (object) - Contains provider, configured, bucket, and endpoint fields. - **warning** (string) - Explains a half-set B2_* configuration. #### Response Example { "storage": { "provider": "backblaze | s3 | r2 | files", "configured": true, "bucket": "my-bucket", "endpoint": "https://s3.example.com" }, "warning": "B2_KEY_ID is set but B2_APPLICATION_KEY is missing." } ``` -------------------------------- ### POST /api/agent/chat Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Starts a streaming chat with the agent. Requires session authentication. ```APIDOC ## POST /api/agent/chat ### Description Starts a streaming chat with the agent. Requires session authentication. ### Method POST ### Endpoint /api/agent/chat ### Parameters #### Request Body - **message** (string) - Required - The user's message. ### Response #### Success Response (200) - **stream** (stream) - A streaming response. #### Response Example (streaming data) ``` -------------------------------- ### Webhook payload examples Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/09-email-webhooks.md Shows the JSON payloads sent to endpoints for each event type: message.inbound, message.outbound, and message.failed. ```JSON { "type": "message.inbound", "data": { "messageId": "...", "from": "...", "to": "...", "cc": "...", "subject": "...", "threadId": "...", "spamScore": 12, "spamVerdict": "inbox" } } { "type": "message.outbound", "data": { "messageId": "...", "providerMessageId": "...", "to": "...", "cc": "..." } } { "type": "message.failed", "data": { "messageId": "...", "error": "..." } } ``` -------------------------------- ### GET /jmap/eventsource Source: https://github.com/hieunc229/mailflare/blob/main/docs/api.md Pushes state changes by polling, allowing clients to stay in sync. ```APIDOC ## GET /jmap/eventsource ### Description Pushes state changes by polling, allowing clients to stay in sync. ### Method GET ### Endpoint /jmap/eventsource ### Authentication Bearer token or HTTP Basic password with `jmap` scope. ### Response #### Success Response (200) Server-sent events stream. ``` -------------------------------- ### GET /api/calendar/events Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Retrieves calendar events within a specified date range. Defaults to the next 31 days if no start and end parameters are provided. ```APIDOC ## GET /api/calendar/events ### Description Retrieves calendar events within a specified date range. Defaults to the next 31 days if no start and end parameters are provided. ### Method GET ### Endpoint /api/calendar/events ### Parameters #### Query Parameters - **start** (string) - Optional - Start date/time of the range. - **end** (string) - Optional - End date/time of the range. ### Response #### Success Response (200) - **events** (array) - List of calendar events in the range. #### Response Example { "events": [] } ``` -------------------------------- ### awsJson example: Get SES account Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/10-aws.md Uses awsJson to call the SES v2 JSON REST API to retrieve account details. The response is typed as { Account: { Id: string; Arn: string } }. ```typescript const acct = await awsJson<{ Account: { Id: string; Arn: string } }>({ config, service: "ses", region: config.region, method: "GET", path: "/v2/email/account", }); ``` -------------------------------- ### beginMfaEnrollment(env, { id, email }) Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/05-session-auth.md Begins MFA enrollment for a user, returning a QR code SVG for scanning. ```APIDOC ## beginMfaEnrollment(env, { id, email }) ### Description Begins MFA enrollment for a user, returning a QR code SVG for scanning. ### Method beginMfaEnrollment ### Parameters - **env** (object) - Required - The environment object containing bindings. - **user** (object) - Required - The user object with `id` and `email` properties. ### Returns - **enrollment** (object) - Contains `qrSvg` (string) - The QR code SVG to display to the user. ### Example ```ts const enrollment = await beginMfaEnrollment(env, { id: user.id, email: user.email }); // show enrollment.qrSvg; user scans and enters a code ``` ``` -------------------------------- ### npm run commands for development, build, database, and deployment Source: https://github.com/hieunc229/mailflare/blob/main/CLAUDE.md Lists the primary npm scripts for Mailflare. Use `npm run dev` for local development with Vite and vinext in workerd, `npm run lint` for ESLint, and `npm run build` for the vinext build including the complete Worker. Database commands include `db:generate`, `db:migrate:local`, `db:migrate:remote`, and `db:seed`. Deployment is done via `npm run deploy`, with `npm run preview` for local preview and `npm run cf-typegen` to regenerate cloudflare-env.d.ts. Note that `db:migrate:remote` requires a concrete database_id in wrangler.jsonc, and `db:seed` posts to localhost:3000. ```bash npm run dev # Vite + vinext in local workerd npm run lint # eslint (next/core-web-vitals + next/typescript) npm run build # vinext build, including the complete Worker npm run db:generate # drizzle-kit generate from src/db/schema/index.ts npm run db:migrate:local # wrangler d1 migrations apply DB --local npm run db:migrate:remote # --remote (needs a concrete database_id in wrangler.jsonc) npm run db:seed # POST /api/seed against localhost:3000 npm run deploy # vinext build + wrangler deploy npm run deploy # build and deploy; migrate later from Admin settings npm run preview # build and preview the vinext Worker locally npm run cf-typegen # regenerate cloudflare-env.d.ts from wrangler.jsonc ``` -------------------------------- ### GET /api/domains/[id] Source: https://github.com/hieunc229/mailflare/blob/main/docs/api.md Gets a connected domain by its ID. This endpoint is part of the domain management API and requires authentication. ```APIDOC ## GET /api/domains/[id] ### Description Get a connected domain. ### Method GET ### Endpoint /api/domains/[id] ### Parameters #### Path Parameters - **id** (string) - Required - The domain ID. ### Response #### Success Response (200) - **domain** (object) - The domain details. #### Response Example { "domain": {} } ``` -------------------------------- ### FileBucket, SqliteDatabase, and RateLimit constructors Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/configuration.md Lists the constructor signatures for FileBucket, SqliteDatabase, and openRateLimiter. FileBucket takes a root path, SqliteDatabase takes a filename, and openRateLimiter takes a limit and period in seconds returning a RateLimit. ```TypeScript // server/runtime/file-bucket.ts — new FileBucket(root: string) / openFileBucket(root) // server/runtime/sqlite-database.ts — new SqliteDatabase(filename: string) // server/runtime/misc.ts — openRateLimiter(limit: number, periodSeconds: number): RateLimit ``` -------------------------------- ### MFA Enrollment and Verification with beginMfaEnrollment, confirmMfaEnrollment, verifySecondFactor Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/05-session-auth.md Demonstrates the MFA enrollment flow: begin enrollment to get a QR SVG, confirm with a code, and later verify a second factor at login, returning 'totp', 'recovery', or null. ```typescript import { beginMfaEnrollment, confirmMfaEnrollment, verifySecondFactor } from "@/lib/auth/mfa"; const enrollment = await beginMfaEnrollment(env, { id: user.id, email: user.email }); // show enrollment.qrSvg; user scans and enters a code const result = await confirmMfaEnrollment(env, user, code, currentSessionToken); if (!result.ok) return /* error: result.error */; // later, at login: const factor = await verifySecondFactor(env, user, code); // "totp" | "recovery" | null ``` -------------------------------- ### AI Agent Deployment Prompt Source: https://github.com/hieunc229/mailflare/blob/main/README.md Paste this prompt into an AI coding agent with terminal access to deploy Mailflare. Requires a Cloudflare account ID and two separate scoped API tokens: a deployment token (CLOUDFLARE_API_TOKEN) and a runtime token (CF_TOKEN). The prompt instructs the agent to read README.md, docs/deployment.md, and wrangler.jsonc, keep the Worker name exactly 'mailflare', create or reuse D1 database 'mailflare', R2 bucket 'mailflare-raw', and Queues 'mailflare-inbound', 'mailflare-outbound', and 'mailflare-agent'. It also specifies to set the D1 database_id in the local Wrangler config, run 'npm run deploy', and set the runtime CF_TOKEN as a Worker secret. The /setup flow initializes the database; do not run remote D1 migrations manually. ```text Install Mailflare from https://github.com/hieunc229/mailflare in my Cloudflare account. Ask me for my Cloudflare account ID, a scoped deployment API token, and a separate runtime CF_TOKEN through a secret input. Never print, commit, or place either token in a command argument or a tracked file. Use the deployment token only for Wrangler authentication (CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID). Read README.md, docs/deployment.md, and wrangler.jsonc first. Keep the Worker name exactly mailflare. In the selected account, create or reuse the D1 database mailflare, R2 bucket mailflare-raw, and Queues mailflare-inbound, mailflare-outbound, and mailflare-agent. Set the D1 database_id in the local Wrangler config without committing that account-specific ID. Install dependencies, run npm run deploy, and set the runtime CF_TOKEN as a Worker secret. Do not run remote D1 migrations manually; the /setup flow initializes the database. Give me the deployed URL and any remaining Cloudflare account actions. I will open /setup, create the first admin account, and connect my domain there. ``` -------------------------------- ### JMAP GET Route Handler Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/13-jmap.md Imports handleJmapRequest from @/lib/jmap/handler and uses it in a GET function. Returns a 404 response if the handler returns null. ```TypeScript // src/app/.well-known/jmap/route.ts and src/app/jmap/[[...segments]]/route.ts import { handleJmapRequest } from "@/lib/jmap/handler"; export async function GET(request: Request) { const env = getEnv(); const response = await handleJmapRequest(request, env); return response ?? new Response("Not found", { status: 404 }); } ``` -------------------------------- ### Create account with alias - JSON body Source: https://github.com/hieunc229/mailflare/blob/main/docs/api.md JSON body for POST /api/v1/accounts or manage_accounts MCP action to create sam@example.com with sales@example.net as an additional alias. useAllDomains defaults to true when omitted; pass false for primary-only or selected-alias accounts. Alias domains must be active and owned by the admin. ```json { "username": "sam", "domainId": "dom_example_com", "password": "REPLACE_WITH_A_STRONG_PASSWORD", "useAllDomains": false, "aliases": [ { "domainId": "dom_example_net", "localPart": "sales" } ] } ``` -------------------------------- ### readFormDataBody usage example Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/04-http-helpers.md Example of reading a form data body with a 25,000,000 byte limit and retrieving a file field. Calls assertRequestSize first. ```typescript const form = await readFormDataBody(request, 25_000_000); const file = form.get("file") as File; ``` -------------------------------- ### GET /api/domains/[id]/receiving Source: https://github.com/hieunc229/mailflare/blob/main/docs/api.md Gets which receiving providers still have configuration for the domain. This endpoint is part of the domain management API and requires authentication. ```APIDOC ## GET /api/domains/[id]/receiving ### Description Which providers still have configuration for the domain. ### Method GET ### Endpoint /api/domains/[id]/receiving ### Parameters #### Path Parameters - **id** (string) - Required - The domain ID. ### Response #### Success Response (200) - **providers** (array) - List of providers with configuration. #### Response Example { "providers": [] } ``` -------------------------------- ### GET /api/domains/[id]/sending Source: https://github.com/hieunc229/mailflare/blob/main/docs/api.md Gets which sending providers still have configuration for the domain. This endpoint is part of the domain management API and requires authentication. ```APIDOC ## GET /api/domains/[id]/sending ### Description Which providers still have configuration for the domain. ### Method GET ### Endpoint /api/domains/[id]/sending ### Parameters #### Path Parameters - **id** (string) - Required - The domain ID. ### Response #### Success Response (200) - **providers** (array) - List of providers with configuration. #### Response Example { "providers": [] } ``` -------------------------------- ### GET /api/v1/domains/[id] Source: https://github.com/hieunc229/mailflare/blob/main/docs/api.md Gets a connected domain by ID. This endpoint is part of the public API v1 and requires an admin API key with the `domains` scope. ```APIDOC ## GET /api/v1/domains/[id] ### Description Get a connected domain. ### Method GET ### Endpoint /api/v1/domains/[id] ### Authentication - **Authorization** (header) - Required - Bearer token with `domains` scope. ### Parameters #### Path Parameters - **id** (string) - Required - The domain ID. ### Response #### Success Response (200) - **domain** (object) - The domain details. #### Response Example { "domain": {} } ``` -------------------------------- ### activateLicense(env, licenseKey, instanceUrl, plan) Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/18-licenses.md Activates a license with the given key, instance URL, and plan. Calls the Paymug API and persists the result. ```APIDOC ## activateLicense(env, licenseKey, instanceUrl, plan) ### Description Activates a license with the given key, instance URL, and plan. Calls the Paymug API and persists the result. ### Method Function ### Signature ```ts export function activateLicense(env: CloudflareEnv, licenseKey: string, instanceUrl: string, plan: Exclude) ``` ### Parameters - **env** (CloudflareEnv) - Required - The Cloudflare environment bindings. - **licenseKey** (string) - Required - The license key to activate. - **instanceUrl** (string) - Required - The URL of the instance. - **plan** (LicensePlan) - Required - The plan to activate ("pro" or "team"). ### Throws - **Error** - Throws if the license is invalid, expired, or the product does not match. ``` -------------------------------- ### readJsonBody usage example Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/04-http-helpers.md Example of reading a JSON body with a 1,000,000 byte limit. Returns parsed JSON or {} for empty body; throws RequestBodyTooLargeError if size exceeded. ```typescript import { readJsonBody } from "@/lib/http/request"; const body = await readJsonBody<{ subject: string }>(request, 1_000_000); ``` -------------------------------- ### Initialize Agent Model with Environment Settings Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/20-agent.md Imports the agent model, provider configuration, and email tool modules, then retrieves the agent model using environment settings and the mailbox model ID. Returns a 400 error if no AI model is configured. ```typescript import { getAgentModel, agentSystemPrompt } from "@/lib/agent/model"; import { getAgentProviderConfig } from "@/lib/agent/provider"; import { runEmailTool } from "@/lib/agent/tools"; const { model } = await getAgentModel(env, mailboxSettings.modelId); if (!model) return NextResponse.json({ error: "No AI model configured" }, { status: 400 }); ``` -------------------------------- ### Create and Retrieve Session with createSession and getUserFromSession Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/05-session-auth.md Shows how to create a session token and set the ep_session cookie, then retrieve the current user via cookie or Bearer token using getCurrentUser, and verify a token with getUserFromSession. ```typescript import { createSession, getUserFromSession } from "@/lib/auth/session"; import { getCurrentUser } from "@/lib/auth/cookies"; const token = await createSession(env, user.id); // set cookie ep_session= const user = await getCurrentUser(env, request); // cookie or Bearer const same = await getUserFromSession(env, token); ``` -------------------------------- ### GET /api/v1/mailboxes Source: https://github.com/hieunc229/mailflare/blob/main/docs/api.md Lists all managed mailboxes. ```APIDOC ## GET /api/v1/mailboxes ### Description Lists all managed mailboxes. ### Method GET ### Endpoint /api/v1/mailboxes ### Response #### Success Response (200) - **mailboxes** (array) - List of mailbox objects. ``` -------------------------------- ### Usage of createNodeRuntime in server/index.ts Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/01-server-runtime.md Shows the main flow: create the runtime, set the global environment, and apply migrations. ```TypeScript import { createNodeRuntime } from "./runtime/env"; import { applyMigrations } from "./runtime/migrate"; const runtime = createNodeRuntime(); const { env } = runtime; globalThis.__mailflareNodeEnv = env; await applyMigrations(runtime.database, resolve(process.env.MIGRATIONS_DIR ?? join(process.cwd(), "drizzle", "migrations"))); ``` -------------------------------- ### GET /api/v1/accounts Source: https://github.com/hieunc229/mailflare/blob/main/docs/api.md Lists all managed accounts. ```APIDOC ## GET /api/v1/accounts ### Description Lists all managed accounts. ### Method GET ### Endpoint /api/v1/accounts ### Response #### Success Response (200) - **accounts** (array) - List of account objects. ``` -------------------------------- ### Usage: Activate License with Error Handling Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/18-licenses.md Demonstrates activating a Pro license with try/catch to return a 400 response on failure, including the error message from the service. ```TypeScript try { await activateLicense(env, key, instanceUrl, "pro"); } catch (error) { return NextResponse.json( { error: error instanceof Error ? error.message : "License activation failed" }, { status: 400 }, ); } ``` -------------------------------- ### GET /api/admin/aws Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Returns shared AWS credentials. ```APIDOC ## GET /api/admin/aws ### Description Returns shared AWS credentials. ### Method GET ### Endpoint /api/admin/aws ### Authentication Requires admin. ``` -------------------------------- ### POST /api/domains/[id]/receiving/[provider] Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Sets up receiving for a provider. For `cloudflare` provider, returns 409 MX_CONFLICT until `replaceMx: true` is provided. ```APIDOC ## POST /api/domains/[id]/receiving/[provider] ### Description Sets up receiving for a provider. ### Method POST ### Endpoint /api/domains/[id]/receiving/[provider] ### Authentication Requires session. ### Path Parameters - `id` (string) - Required - The domain ID. - `provider` (string) - Required - The provider (`resend`, `ses`, or `cloudflare`). ### Response #### Error Response (409) - `MX_CONFLICT` - Returned until `replaceMx: true` is provided. ``` -------------------------------- ### GET /api/admin/resend-key Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Returns the shared Resend key. ```APIDOC ## GET /api/admin/resend-key ### Description Returns the shared Resend key. ### Method GET ### Endpoint /api/admin/resend-key ### Authentication Requires admin. ``` -------------------------------- ### GET /api/domains/[id] Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Retrieves details for a single domain. ```APIDOC ## GET /api/domains/[id] ### Description Retrieves details for a single domain. ### Method GET ### Endpoint /api/domains/[id] ### Authentication Requires session. ### Path Parameters - `id` (string) - Required - The domain ID. ``` -------------------------------- ### GET /api/agent/jobs Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Retrieves auto-draft jobs. Requires session authentication. ```APIDOC ## GET /api/agent/jobs ### Description Retrieves auto-draft jobs. Requires session authentication. ### Method GET ### Endpoint /api/agent/jobs ### Response #### Success Response (200) - **jobs** (array) - List of jobs. #### Response Example { "jobs": [] } ``` -------------------------------- ### GET /jmap/eventsource Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md JMAP event source endpoint for real-time updates. ```APIDOC ## GET /jmap/eventsource ### Description JMAP event source endpoint for real-time updates. ### Method GET ### Endpoint `/jmap/eventsource` ### Authentication Bearer or Basic with key as password; `jmap` scope. ### Response Server-sent events stream. ``` -------------------------------- ### POST /api/v1/domains/[id]/dns/setup Source: https://github.com/hieunc229/mailflare/blob/main/docs/api.md Creates a missing DNS record for a domain. This endpoint is part of the public API v1 and requires an admin API key with the `domains` scope. ```APIDOC ## POST /api/v1/domains/[id]/dns/setup ### Description Create a missing record. ### Method POST ### Endpoint /api/v1/domains/[id]/dns/setup ### Authentication - **Authorization** (header) - Required - Bearer token with `domains` scope. ### Parameters #### Path Parameters - **id** (string) - Required - The domain ID. #### Request Body - **record** (string) - Required - The record type: `mx`, `spf`, `dkim`, or `dmarc`. ### Request Example { "record": "mx" } ### Response #### Success Response (200) - **success** (boolean) - Indicates success. #### Error Response (400) - **error** (string) - Error message if DNS is managed manually. #### Response Example { "success": true } ``` -------------------------------- ### POST /api/domains/[id]/ses Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Sets up SES sending. ```APIDOC ## POST /api/domains/[id]/ses ### Description Sets up SES sending. ### Method POST ### Endpoint /api/domains/[id]/ses ### Authentication Requires session. ### Path Parameters - `id` (string) - Required - The domain ID. ``` -------------------------------- ### GET /api/v1/domains/[id] Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Retrieves details for a specific domain by its ID. ```APIDOC ## GET /api/v1/domains/[id] ### Description Retrieves details for a specific domain by its ID. ### Method GET ### Endpoint /api/v1/domains/[id] ### Scope `domains` ### Path Parameters - **id** (string) - Required - The domain ID ``` -------------------------------- ### startSmtpListener function signature Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/01-server-runtime.md Starts an SMTP server with the given configuration. Default port is 25, overridable by SMTP_INBOUND_PORT. STARTTLS is only offered with real certificates; AUTH is disabled. Reject reasons map to SMTP codes: 550 routing reject, 552 attachment limit, 451 temporary failure. ```TypeScript export function startSmtpListener( env: CloudflareEnv, mailer: Mailer, options: { port: number; host?: string; maxSize: number; hostname?: string; tls: { keyPath: string; certPath: string } | null }, ): void ``` -------------------------------- ### GET /api/domains/[id]/ses Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Returns SES sending status. ```APIDOC ## GET /api/domains/[id]/ses ### Description Returns SES sending status. ### Method GET ### Endpoint /api/domains/[id]/ses ### Authentication Requires session. ### Path Parameters - `id` (string) - Required - The domain ID. ``` -------------------------------- ### GET /api/domains/[id]/resend Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Returns Resend sending status. ```APIDOC ## GET /api/domains/[id]/resend ### Description Returns Resend sending status. ### Method GET ### Endpoint /api/domains/[id]/resend ### Authentication Requires session. ### Path Parameters - `id` (string) - Required - The domain ID. ``` -------------------------------- ### OPTIONS any Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/13-jmap.md Handles CORS preflight requests for all JMAP paths. Returns 204 with CORS headers allowing all origins. ```APIDOC ## [OPTIONS] any ### Description Handles CORS preflight requests for all JMAP paths. Returns 204 with CORS headers allowing all origins. ### Method OPTIONS ### Endpoint any ### Response #### Success Response (204) - CORS headers: `Access-Control-Allow-Origin: *` #### Response Example (No body) ``` -------------------------------- ### InProcessQueue and SMTP listener options Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/configuration.md Shows the option objects for new InProcessQueue(name, options?) and startSmtpListener(env, mailer, options). The queue options include name and maxRetries (default 3). The SMTP listener options include port, optional host, maxSize, optional hostname, and TLS key/cert paths or null. ```TypeScript // server/runtime/queue.ts — new InProcessQueue(name, options?) { name: string; maxRetries?: number } // maxRetries default 3 // server/runtime/smtp.ts — startSmtpListener(env, mailer, options) { port: number; host?: string; maxSize: number; hostname?: string; tls: { keyPath: string; certPath: string } | null } ``` -------------------------------- ### GET /api/auth/accounts/[userId]/avatar Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Returns the avatar of a remembered account. ```APIDOC ## GET /api/auth/accounts/[userId]/avatar ### Description Returns the avatar of a remembered account. ### Method GET ### Endpoint /api/auth/accounts/[userId]/avatar ### Parameters #### Path Parameters - **userId** (string) - Required - Identifier of the user whose avatar is requested. ### Response #### Success Response (200) - **avatar** (binary) - The avatar image. #### Response Example [Binary image data] ``` -------------------------------- ### GET /api/auth/accounts Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Returns the list of remembered accounts for the current session. ```APIDOC ## GET /api/auth/accounts ### Description Returns the list of remembered accounts for the current session. ### Method GET ### Endpoint /api/auth/accounts ### Parameters None ### Response #### Success Response (200) - **accounts** (array) - List of remembered accounts. #### Response Example { "accounts": [] } ``` -------------------------------- ### GET /api/auth/me Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/endpoints.md Returns the current authenticated user's information. ```APIDOC ## GET /api/auth/me ### Description Returns the current authenticated user's information. ### Method GET ### Endpoint /api/auth/me ### Parameters None ### Response #### Success Response (200) - **user** (object) - The current user object. #### Response Example { "user": {} } ``` -------------------------------- ### Run scheduled and manual database backups Source: https://github.com/hieunc229/mailflare/blob/main/_autodocs/api-reference/19-backups.md Imports backup runner and service functions, then shows a cron-triggered scheduled backup and a manual backup via POST /api/backups. The scheduled backup uses the controller's scheduledTime, while the manual backup creates a record with user ID before running the backup. ```typescript import { runScheduledDatabaseBackup, deleteExpiredBackups } from "@/lib/backups/runner"; import { getBackupSettings, updateBackupSettings, listBackups } from "@/lib/backups/service"; // cron `0 2 * * *` await runScheduledDatabaseBackup(env, new Date(controller.scheduledTime)); // manually (POST /api/backups) const id = await createBackupRecord(env, "manual", user.id); await runDatabaseBackup(env, id); ``` -------------------------------- ### GET /.well-known/jmap Source: https://github.com/hieunc229/mailflare/blob/main/docs/api.md Discovery endpoint that redirects to the JMAP session resource. ```APIDOC ## GET /.well-known/jmap ### Description Discovery endpoint that redirects to the JMAP session resource. ### Method GET ### Endpoint /.well-known/jmap ### Response #### Success Response (302) Redirects to /jmap/session. ``` -------------------------------- ### GET /api/settings/trash-retention Source: https://github.com/hieunc229/mailflare/blob/main/docs/api.md Retrieves the current trash retention settings for the user. ```APIDOC ## GET /api/settings/trash-retention ### Description Retrieves the current trash retention settings for the user. ### Method GET ### Endpoint /api/settings/trash-retention ### Response #### Success Response (200) - **days** (number or null) - Number of days to retain trash/spam, or null for never. #### Response Example { "days": 30 } ``` -------------------------------- ### GET /api/v1/mailboxes/[id] Source: https://github.com/hieunc229/mailflare/blob/main/docs/api.md Retrieves a specific managed mailbox by its ID. ```APIDOC ## GET /api/v1/mailboxes/[id] ### Description Retrieves a specific managed mailbox by its ID. ### Method GET ### Endpoint /api/v1/mailboxes/[id] ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the mailbox. ### Response #### Success Response (200) - **mailbox** (object) - The mailbox object. ``` -------------------------------- ### GET /api/v1/accounts/[id] Source: https://github.com/hieunc229/mailflare/blob/main/docs/api.md Retrieves a specific managed account by its ID. ```APIDOC ## GET /api/v1/accounts/[id] ### Description Retrieves a specific managed account by its ID. ### Method GET ### Endpoint /api/v1/accounts/[id] ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the account. ### Response #### Success Response (200) - **account** (object) - The account object. ```