From a8e623546b4308c3a211269f1979f9ed26a63f1d Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 2 Nov 2026 00:35:09 +0800 Subject: [PATCH 01/10] refactor: extract shared prefix validation into src/utils/prefix.ts validatePrefix was duplicated in both handlers and sanitizePrefix lived privately in storage.ts. Consolidate them into one util module; also drop the BOM and an unused import from http.ts. No behavior change: the regex and the 100-char key cap are identical to the local copies. --- src/handlers/email.ts | 4 +--- src/handlers/http.ts | 8 +++----- src/services/storage.ts | 4 +--- src/utils/prefix.ts | 17 +++++++++++++++++ 4 files changed, 22 insertions(+), 11 deletions(-) create mode 100644 src/utils/prefix.ts diff --git a/src/handlers/email.ts b/src/handlers/email.ts index d9966bc..fa6e4fa 100644 --- a/src/handlers/email.ts +++ b/src/handlers/email.ts @@ -3,14 +3,12 @@ import { parseEmail } from '../services/parser'; import { extractVerificationCode } from '../services/extractor'; import { saveEmail } from '../services/storage'; import { parseTTLConfig } from '../utils/ttl'; +import { validatePrefix } from '../utils/prefix'; function sanitizeForLog(input: string): string { return input.replace(/[\r\n\t]/g, '_').slice(0, 200); } -function validatePrefix(prefix: string): boolean { - return /^[a-z0-9][a-z0-9._-]*$/.test(prefix) && prefix !== '.' && prefix !== '..'; -} function checkSenderFilter(from: string, env: Env): { pass: boolean; reason?: string } { const filterMode = env.FILTER_MODE?.toLowerCase() || 'none'; diff --git a/src/handlers/http.ts b/src/handlers/http.ts index 7b142ac..0fe0cc4 100644 --- a/src/handlers/http.ts +++ b/src/handlers/http.ts @@ -1,10 +1,11 @@ -import { Hono } from 'hono'; +import { Hono } from 'hono'; import { cors } from 'hono/cors'; import { secureHeaders } from 'hono/secure-headers'; -import type { Env, ErrorResponse } from '../types'; +import type { Env } from '../types'; import { ErrorCode } from '../types'; import { authMiddleware } from '../middleware/auth'; import { getEmail, getCode } from '../services/storage'; +import { validatePrefix } from '../utils/prefix'; const app = new Hono<{ Bindings: Env }>(); @@ -19,9 +20,6 @@ app.use('/*', authMiddleware); app.get('/', (c) => c.json({ status: 'ok', ts: new Date().toISOString() })); -function validatePrefix(prefix: string): boolean { - return /^[a-z0-9][a-z0-9._-]*$/.test(prefix) && prefix.length >= 1 && prefix !== '.' && prefix !== '..'; -} app.get('/:prefix/email', async (c) => { const prefix = c.req.param('prefix').toLowerCase(); diff --git a/src/services/storage.ts b/src/services/storage.ts index eabf2a8..aa7cf95 100644 --- a/src/services/storage.ts +++ b/src/services/storage.ts @@ -1,11 +1,9 @@ import type { EmailData } from '../types'; +import { sanitizePrefix } from '../utils/prefix'; const EMAIL_KEY_PREFIX = 'email:'; const CODE_KEY_PREFIX = 'code:'; -function sanitizePrefix(prefix: string): string { - return prefix.replace(/[^a-z0-9._-]/g, '').slice(0, 100); -} export async function saveEmail( kv: KVNamespace, diff --git a/src/utils/prefix.ts b/src/utils/prefix.ts new file mode 100644 index 0000000..1fbafb0 --- /dev/null +++ b/src/utils/prefix.ts @@ -0,0 +1,17 @@ +/** + * Validates an email prefix (the part before @domain). + * Must start with alphanumeric, may contain dots/underscores/hyphens. + * Rejects '.', '..', and empty strings. + */ +export function validatePrefix(prefix: string): boolean { + if (!prefix || prefix === '.' || prefix === '..') return false; + return /^[a-z0-9][a-z0-9._-]*$/.test(prefix); +} + +/** + * Sanitizes a prefix for safe use as a KV key component. + * Strips invalid characters and limits length. + */ +export function sanitizePrefix(prefix: string): string { + return prefix.replace(/[^a-z0-9._-]/g, '').slice(0, 100); +} From 040c0e0135a8794fb2bd91e48e7e64e0d0cc4ba0 Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 2 Nov 2026 00:35:12 +0800 Subject: [PATCH 02/10] fix: treat empty stored code as missing so GET /code returns 404 When extraction finds no code, saveEmail stores an empty string under code:, and getCode handed that empty string back as a 200 with an empty body. Return null instead so the handler answers 404 no_code_found. --- src/services/storage.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/services/storage.ts b/src/services/storage.ts index aa7cf95..c8edfab 100644 --- a/src/services/storage.ts +++ b/src/services/storage.ts @@ -43,7 +43,9 @@ export async function getCode( ): Promise { const safePrefix = sanitizePrefix(prefix); const key = `${CODE_KEY_PREFIX}${safePrefix}`; - return await kv.get(key); + const value = await kv.get(key); + // Empty string means no code was extracted; treat as null + return value || null; } export async function deleteEmail( From e0db199d4cad31fba94cda7bce30272e762697f4 Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 2 Nov 2026 00:35:15 +0800 Subject: [PATCH 03/10] fix: harden Workers AI fallback extraction Race the AI call against a 10s timeout so a hung inference request cannot stall email handling, copy the match arrays before sorting so selectBestMatch/extractAlphanumericCode never mutate their inputs, and log the raw error object on AI failures. --- src/services/extractor.ts | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/services/extractor.ts b/src/services/extractor.ts index d7fb6c1..7c3f275 100644 --- a/src/services/extractor.ts +++ b/src/services/extractor.ts @@ -52,7 +52,7 @@ function selectBestMatch(matches: Match[]): string | null { if (contextualMatches.length === 1) return contextualMatches[0].code; if (contextualMatches.length > 1) { - return contextualMatches.sort((a, b) => a.index - b.index)[0].code; + return [...contextualMatches].sort((a, b) => a.index - b.index)[0].code; } const uniqueCodes = [...new Set(matches.map(m => m.code))]; @@ -88,7 +88,7 @@ function extractAlphanumericCode(text: string): { code: string; confidence: numb if (candidates.length === 0) return null; - return candidates.sort((a, b) => b.confidence - a.confidence)[0]; + return [...candidates].sort((a, b) => b.confidence - a.confidence)[0]; } function sanitizeForAI(text: string): string { @@ -114,20 +114,31 @@ async function extractWithAI(text: string, env: Env): Promise { ]; try { - const response = await env.AI.run(AI_MODEL, { + const AI_TIMEOUT_MS = 10000; + const aiPromise = env.AI.run(AI_MODEL, { messages, max_tokens: 16, temperature: 0, - }) as { response: string }; + }) as Promise<{ response: string }>; - const output = response?.response?.trim(); + const timeoutPromise = new Promise((resolve) => + setTimeout(() => resolve(null), AI_TIMEOUT_MS) + ); + + const response = await Promise.race([aiPromise, timeoutPromise]); + if (!response) { + console.warn('[extractor] AI extraction timed out'); + return null; + } + + const output = response.response?.trim(); if (!output || output === 'NONE') return null; const cleaned = output.replace(/\D/g, ''); if (cleaned.length >= 4 && cleaned.length <= 8) return cleaned; return null; } catch (e) { - console.error('[AI extraction failed]', e instanceof Error ? e.message : 'unknown error'); + console.error('[AI extraction failed]', e); return null; } } From 4a523487165246a137a5621fba5015220e6f9f68 Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 2 Nov 2026 00:35:17 +0800 Subject: [PATCH 04/10] fix: release raw stream reader lock in parser finally block On the 1MB truncation path the reader lock was never released after the read loop broke; release it in a finally block. --- src/services/parser.ts | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/services/parser.ts b/src/services/parser.ts index 2669e4e..661acee 100644 --- a/src/services/parser.ts +++ b/src/services/parser.ts @@ -31,15 +31,19 @@ export async function parseEmail(message: ForwardableEmailMessage): Promise MAX_EMAIL_SIZE) { - console.warn('[parser] email exceeds max size, truncating'); - break; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + totalSize += value.length; + if (totalSize > MAX_EMAIL_SIZE) { + console.warn('[parser] email exceeds max size, truncating'); + break; + } + chunks.push(value); } - chunks.push(value); + } finally { + reader.releaseLock(); } const limitedStream = new ReadableStream({ From 4d745437799969d7d154324ec2efc3fb1320dce3 Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 2 Nov 2026 00:35:20 +0800 Subject: [PATCH 05/10] docs: align setup skill and wrangler.toml with actual behavior Add an AUTH_TOKEN placeholder to [vars] with a comment pointing at REQUIRE_AUTH, document the AUTH_TOKEN row and the missing-token 500 failure mode in the setup skill, correct the skill's FILTER_LIST examples to bare sender domains (matching email.ts and the README fix in a11fec7), and bump the skill's Wrangler requirement to >=4 to match the wrangler devDependency. --- skills/cf-email-api-setup/SKILL.md | 10 ++++++---- wrangler.toml | 2 ++ 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/skills/cf-email-api-setup/SKILL.md b/skills/cf-email-api-setup/SKILL.md index 8157ac2..c6bd32d 100644 --- a/skills/cf-email-api-setup/SKILL.md +++ b/skills/cf-email-api-setup/SKILL.md @@ -4,7 +4,7 @@ description: "Use when setting up, deploying, or configuring the CF Email API pr compatibility: - OS: macOS, Linux, Windows - Node.js: ">=18" - - Wrangler: ">=3" + - Wrangler: ">=4" - Cloudflare Account with Email Routing enabled allowed-tools: - Bash @@ -120,21 +120,22 @@ npx wrangler deploy | `DEFAULT_TTL_UNIT` | `seconds` | TTL unit: `seconds`, `minutes`, `hours`, `days` | | `ENABLE_AI` | `true` | Enable AI fallback for code extraction | | `REQUIRE_AUTH` | `false` | Require API token for access | +| `AUTH_TOKEN` | `""` | API authentication token (required when `REQUIRE_AUTH` = `true`) | | `FILTER_MODE` | `none` | Filter mode: `none`, `whitelist`, `blacklist` | -| `FILTER_LIST` | `""` | Comma-separated domains (e.g., `@openai.com,@github.com`) | +| `FILTER_LIST` | `""` | Comma-separated domains (e.g., `openai.com,github.com`) | ### Filter Mode Examples **Whitelist (only accept from listed domains):** ```toml FILTER_MODE = "whitelist" -FILTER_LIST = "@openai.com,@github.com,@x.ai" +FILTER_LIST = "openai.com,github.com,x.ai" ``` **Blacklist (block listed domains):** ```toml FILTER_MODE = "blacklist" -FILTER_LIST = "@spam.com,@trash.net" +FILTER_LIST = "spam.com,trash.net" ``` ## Common Mistakes @@ -153,6 +154,7 @@ FILTER_LIST = "@spam.com,@trash.net" - **Email Delay**: Cloudflare Email Routing may take 5-15 seconds to deliver. - **AI Fallback**: Uses `@cf/meta/llama-3.3-70b-instruct-fp8-fast`. Free tier = 10,000 inferences/day. - **Domain Required**: You MUST own a domain added to Cloudflare. Cannot use `workers.dev` subdomain for email. +- **Auth Misconfiguration**: When `REQUIRE_AUTH=true`, also set `AUTH_TOKEN` in `wrangler.toml`. Missing `AUTH_TOKEN` will block all API requests with HTTP 500. - **Email Routing Setup**: Must complete domain onboarding (MX records) before Catch-all works. ## API Usage diff --git a/wrangler.toml b/wrangler.toml index 5b73cd4..cb3cba4 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -13,6 +13,8 @@ ENABLE_AI = "true" REQUIRE_AUTH = "false" FILTER_MODE = "none" FILTER_LIST = "" +# Set AUTH_TOKEN when REQUIRE_AUTH is "true" to enable API authentication +AUTH_TOKEN = "" [[kv_namespaces]] binding = "EMAIL_KV" From 6147e66532c7e847748969dae594658147079727 Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 2 Nov 2026 00:53:46 +0800 Subject: [PATCH 06/10] fix: cancel the Workers AI request when the timeout fires Promise.race left the underlying env.AI.run pending after the 10s timeout won. Pass an AbortSignal to the binding and abort it from the timer so the inference request is actually cancelled; the catch keeps the dedicated timeout log. AiOptions.signal exists in @cloudflare/workers-types 4.20260408.1 (index.d.ts AiOptions), so the binding types accept the option. CodeRabbit review finding (Minor, Performance) on PR #11. --- src/services/extractor.ts | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/src/services/extractor.ts b/src/services/extractor.ts index 7c3f275..f27e632 100644 --- a/src/services/extractor.ts +++ b/src/services/extractor.ts @@ -113,23 +113,20 @@ async function extractWithAI(text: string, env: Env): Promise { }, ]; + const AI_TIMEOUT_MS = 10000; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), AI_TIMEOUT_MS); + try { - const AI_TIMEOUT_MS = 10000; - const aiPromise = env.AI.run(AI_MODEL, { - messages, - max_tokens: 16, - temperature: 0, - }) as Promise<{ response: string }>; - - const timeoutPromise = new Promise((resolve) => - setTimeout(() => resolve(null), AI_TIMEOUT_MS) - ); - - const response = await Promise.race([aiPromise, timeoutPromise]); - if (!response) { - console.warn('[extractor] AI extraction timed out'); - return null; - } + const response = (await env.AI.run( + AI_MODEL, + { + messages, + max_tokens: 16, + temperature: 0, + }, + { signal: controller.signal } + )) as { response?: string }; const output = response.response?.trim(); if (!output || output === 'NONE') return null; @@ -138,8 +135,14 @@ async function extractWithAI(text: string, env: Env): Promise { if (cleaned.length >= 4 && cleaned.length <= 8) return cleaned; return null; } catch (e) { - console.error('[AI extraction failed]', e); + if (controller.signal.aborted) { + console.warn('[extractor] AI extraction timed out'); + } else { + console.error('[AI extraction failed]', e); + } return null; + } finally { + clearTimeout(timer); } } From af34376d6c698225ff8c8d3ac5879e3aac044bda Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 2 Nov 2026 00:53:46 +0800 Subject: [PATCH 07/10] fix: keep AUTH_TOKEN out of [vars] and document it as a Wrangler secret A [vars] entry named the same as a secret replaces the secret on deploy, leaving an empty AUTH_TOKEN and 500s on every request when REQUIRE_AUTH=true. Remove the placeholder var, keep a pointer to "wrangler secret put AUTH_TOKEN" in wrangler.toml, and fix the setup skill's AUTH_TOKEN row and misconfiguration note to match. This also aligns with REQUIRE.md, which already mandates the secret. CodeRabbit review finding (Major, CWE-312) on PR #11. --- skills/cf-email-api-setup/SKILL.md | 4 ++-- wrangler.toml | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/skills/cf-email-api-setup/SKILL.md b/skills/cf-email-api-setup/SKILL.md index c6bd32d..856db6d 100644 --- a/skills/cf-email-api-setup/SKILL.md +++ b/skills/cf-email-api-setup/SKILL.md @@ -120,7 +120,7 @@ npx wrangler deploy | `DEFAULT_TTL_UNIT` | `seconds` | TTL unit: `seconds`, `minutes`, `hours`, `days` | | `ENABLE_AI` | `true` | Enable AI fallback for code extraction | | `REQUIRE_AUTH` | `false` | Require API token for access | -| `AUTH_TOKEN` | `""` | API authentication token (required when `REQUIRE_AUTH` = `true`) | +| `AUTH_TOKEN` | secret | API authentication token; set with `wrangler secret put AUTH_TOKEN` (required when `REQUIRE_AUTH` = `true`) | | `FILTER_MODE` | `none` | Filter mode: `none`, `whitelist`, `blacklist` | | `FILTER_LIST` | `""` | Comma-separated domains (e.g., `openai.com,github.com`) | @@ -154,7 +154,7 @@ FILTER_LIST = "spam.com,trash.net" - **Email Delay**: Cloudflare Email Routing may take 5-15 seconds to deliver. - **AI Fallback**: Uses `@cf/meta/llama-3.3-70b-instruct-fp8-fast`. Free tier = 10,000 inferences/day. - **Domain Required**: You MUST own a domain added to Cloudflare. Cannot use `workers.dev` subdomain for email. -- **Auth Misconfiguration**: When `REQUIRE_AUTH=true`, also set `AUTH_TOKEN` in `wrangler.toml`. Missing `AUTH_TOKEN` will block all API requests with HTTP 500. +- **Auth Misconfiguration**: When `REQUIRE_AUTH=true`, set the token as a secret with `wrangler secret put AUTH_TOKEN`; do not put it in `[vars]` — a same-named var replaces the secret on deploy. A missing token blocks all API requests with HTTP 500. - **Email Routing Setup**: Must complete domain onboarding (MX records) before Catch-all works. ## API Usage diff --git a/wrangler.toml b/wrangler.toml index cb3cba4..27b958e 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -13,8 +13,9 @@ ENABLE_AI = "true" REQUIRE_AUTH = "false" FILTER_MODE = "none" FILTER_LIST = "" -# Set AUTH_TOKEN when REQUIRE_AUTH is "true" to enable API authentication -AUTH_TOKEN = "" +# AUTH_TOKEN is a secret, not a var: run "wrangler secret put AUTH_TOKEN" +# when REQUIRE_AUTH is "true" (a same-named [vars] entry would replace the +# secret on deploy) [[kv_namespaces]] binding = "EMAIL_KV" From fcf8662b42f0a2aa19205f83571da1dbb8aadcb0 Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 2 Nov 2026 01:04:54 +0800 Subject: [PATCH 08/10] docs: use npx for the wrangler secret command in setup docs Wrangler is a local devDependency, and every other command in the setup skill and README uses npx; a bare wrangler call can fail after the documented npm install. CodeRabbit review finding (Minor, Functional Correctness) on PR #11. --- skills/cf-email-api-setup/SKILL.md | 4 ++-- wrangler.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/skills/cf-email-api-setup/SKILL.md b/skills/cf-email-api-setup/SKILL.md index 856db6d..62b9988 100644 --- a/skills/cf-email-api-setup/SKILL.md +++ b/skills/cf-email-api-setup/SKILL.md @@ -120,7 +120,7 @@ npx wrangler deploy | `DEFAULT_TTL_UNIT` | `seconds` | TTL unit: `seconds`, `minutes`, `hours`, `days` | | `ENABLE_AI` | `true` | Enable AI fallback for code extraction | | `REQUIRE_AUTH` | `false` | Require API token for access | -| `AUTH_TOKEN` | secret | API authentication token; set with `wrangler secret put AUTH_TOKEN` (required when `REQUIRE_AUTH` = `true`) | +| `AUTH_TOKEN` | secret | API authentication token; set with `npx wrangler secret put AUTH_TOKEN` (required when `REQUIRE_AUTH` = `true`) | | `FILTER_MODE` | `none` | Filter mode: `none`, `whitelist`, `blacklist` | | `FILTER_LIST` | `""` | Comma-separated domains (e.g., `openai.com,github.com`) | @@ -154,7 +154,7 @@ FILTER_LIST = "spam.com,trash.net" - **Email Delay**: Cloudflare Email Routing may take 5-15 seconds to deliver. - **AI Fallback**: Uses `@cf/meta/llama-3.3-70b-instruct-fp8-fast`. Free tier = 10,000 inferences/day. - **Domain Required**: You MUST own a domain added to Cloudflare. Cannot use `workers.dev` subdomain for email. -- **Auth Misconfiguration**: When `REQUIRE_AUTH=true`, set the token as a secret with `wrangler secret put AUTH_TOKEN`; do not put it in `[vars]` — a same-named var replaces the secret on deploy. A missing token blocks all API requests with HTTP 500. +- **Auth Misconfiguration**: When `REQUIRE_AUTH=true`, set the token as a secret with `npx wrangler secret put AUTH_TOKEN`; do not put it in `[vars]` — a same-named var replaces the secret on deploy. A missing token blocks all API requests with HTTP 500. - **Email Routing Setup**: Must complete domain onboarding (MX records) before Catch-all works. ## API Usage diff --git a/wrangler.toml b/wrangler.toml index 27b958e..d4824de 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -13,7 +13,7 @@ ENABLE_AI = "true" REQUIRE_AUTH = "false" FILTER_MODE = "none" FILTER_LIST = "" -# AUTH_TOKEN is a secret, not a var: run "wrangler secret put AUTH_TOKEN" +# AUTH_TOKEN is a secret, not a var: run "npx wrangler secret put AUTH_TOKEN" # when REQUIRE_AUTH is "true" (a same-named [vars] entry would replace the # secret on deploy) From b3105278af447750687050d716fd38ccfc513e27 Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 2 Nov 2026 01:15:23 +0800 Subject: [PATCH 09/10] fix: sync REQUIRE auth guides with the fail-closed middleware The guides described fail-open behavior (requests pass through when AUTH_TOKEN is missing) and a URL query parameter token method, but auth.ts rejects unconfigured secrets with HTTP 500 and reads only the Authorization header. Correct both guides: fail-closed 500 on missing secret, header-only client integration, and npx-prefixed wrangler commands. CodeRabbit review finding (Minor, Functional Correctness) on PR #11. --- REQUIRE.md | 23 ++++++++++------------- REQUIRE_EN.md | 23 ++++++++++------------- 2 files changed, 20 insertions(+), 26 deletions(-) diff --git a/REQUIRE.md b/REQUIRE.md index 621fb8d..70819b1 100644 --- a/REQUIRE.md +++ b/REQUIRE.md @@ -10,7 +10,7 @@ REQUIRE_AUTH = "true" **2. 通过 Secret 设置 Token(加密存储)** ```bash -wrangler secret put AUTH_TOKEN +npx wrangler secret put AUTH_TOKEN # 输入你的 Token,例如:cf-114514-ff 或者 Cloudflare Dashboard → 计算 → Workers & Pages → cf-email-api → 设置 → 变量和机密 @@ -19,13 +19,6 @@ Cloudflare Dashboard → 计算 → Workers & Pages → cf-email-api → 设置 **3. 注册机调用方式** ```python -# 方式一:URL 参数 -code = requests.get( - "https://xxx.workers.dev/random123/code", - params={"token": "cf_mail_s3cr3t_2026"} -).text - -# 方式二:Header code = requests.get( "https://xxx.workers.dev/random123/code", headers={"Authorization": "Bearer cf_mail_s3cr3t_2026"} @@ -50,24 +43,28 @@ if (!requireAuth) return next(); // 直接放行 ```typescript const authToken = c.env.AUTH_TOKEN; -if (!authToken) return next(); // 兜底:Token 未配置也放行 +if (!authToken) { + // 兜底:Token 未配置直接拒绝(fail-closed) + return c.json( + { error: 'unauthorized', message: 'Authentication not configured' }, + 500 + ); +} ``` -即使 `REQUIRE_AUTH = "true"`,如果你**没有通过 `wrangler secret put AUTH_TOKEN` 设置 Token**,请求依然会被放行。这是一个安全兜底设计,防止锁死自己。 +即使 `REQUIRE_AUTH = "true"`,如果你**没有通过 `npx wrangler secret put AUTH_TOKEN` 设置 Token**,所有请求都会返回 **HTTP 500 "Authentication not configured"**。中间件是 **fail-closed**:密钥未配置时不会放行任何流量。 ### 第三步:校验请求携带的 Token ```typescript const providedToken = - c.req.query('token') || c.req.header('Authorization')?.replace('Bearer ', ''); ``` -支持两种传 Token 方式(**二选一即可**): +只支持一种传 Token 方式: | 方式 | 示例 | |------|------| -| **URL 查询参数** | `GET /random123/code?token=你的TOKEN` | | **HTTP Header** | `Authorization: Bearer 你的TOKEN` | Token 不匹配或缺失时,返回 **HTTP 401**: diff --git a/REQUIRE_EN.md b/REQUIRE_EN.md index 38f9807..cbed169 100644 --- a/REQUIRE_EN.md +++ b/REQUIRE_EN.md @@ -14,7 +14,7 @@ REQUIRE_AUTH = "true" **2. Set the Token via Wrangler Secret (Encrypted Storage)** ```bash -wrangler secret put AUTH_TOKEN +npx wrangler secret put AUTH_TOKEN # Enter your token when prompted, e.g.: cf-114514-ff ``` @@ -27,13 +27,6 @@ Alternatively, configure it via the Cloudflare Dashboard: **3. Client Integration Example** ```python -# Method 1: URL query parameter -code = requests.get( - "https://xxx.workers.dev/random123/code", - params={"token": "cf_mail_s3cr3t_2026"} -).text - -# Method 2: Authorization header code = requests.get( "https://xxx.workers.dev/random123/code", headers={"Authorization": "Bearer cf_mail_s3cr3t_2026"} @@ -59,24 +52,28 @@ Authentication is only enforced when `REQUIRE_AUTH` is explicitly set to `"true" ```typescript const authToken = c.env.AUTH_TOKEN; -if (!authToken) return next(); // Fail-open: allow requests if secret is not set +if (!authToken) { + // Fail-closed: every request fails until the secret is provisioned + return c.json( + { error: 'unauthorized', message: 'Authentication not configured' }, + 500 + ); +} ``` -Even when `REQUIRE_AUTH = "true"`, if `AUTH_TOKEN` has **not been provisioned via `wrangler secret put AUTH_TOKEN`**, requests will still pass through. This is an intentional **fail-open** safety mechanism to prevent accidental self-lockout. +Even when `REQUIRE_AUTH = "true"`, if `AUTH_TOKEN` has **not been provisioned via `npx wrangler secret put AUTH_TOKEN`**, every request fails with **HTTP 500 "Authentication not configured"**. The middleware is **fail-closed**: it never serves traffic while the secret is missing. ### Step 3: Validate the Token Provided by the Client ```typescript const providedToken = - c.req.query('token') || c.req.header('Authorization')?.replace('Bearer ', ''); ``` -Two token delivery methods are supported (**use either one**): +Only one token delivery method is supported: | Method | Example | |--------|---------| -| **URL Query Parameter** | `GET /random123/code?token=YOUR_TOKEN` | | **HTTP Authorization Header** | `Authorization: Bearer YOUR_TOKEN` | If the token is missing or does not match, the Worker returns **HTTP 401 Unauthorized**: From d40b679d32fe62333c726b292a4bcf5a8f2bef86 Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 2 Nov 2026 01:15:23 +0800 Subject: [PATCH 10/10] docs: mark AUTH_TOKEN as not set by default in setup skill The Default column said "secret", implying authentication is provisioned automatically; the value only exists after "npx wrangler secret put AUTH_TOKEN". CodeRabbit review finding (Minor, Functional Correctness) on PR #11. --- skills/cf-email-api-setup/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/cf-email-api-setup/SKILL.md b/skills/cf-email-api-setup/SKILL.md index 62b9988..b77b87f 100644 --- a/skills/cf-email-api-setup/SKILL.md +++ b/skills/cf-email-api-setup/SKILL.md @@ -120,7 +120,7 @@ npx wrangler deploy | `DEFAULT_TTL_UNIT` | `seconds` | TTL unit: `seconds`, `minutes`, `hours`, `days` | | `ENABLE_AI` | `true` | Enable AI fallback for code extraction | | `REQUIRE_AUTH` | `false` | Require API token for access | -| `AUTH_TOKEN` | secret | API authentication token; set with `npx wrangler secret put AUTH_TOKEN` (required when `REQUIRE_AUTH` = `true`) | +| `AUTH_TOKEN` | not set | API authentication token; set with `npx wrangler secret put AUTH_TOKEN` (required when `REQUIRE_AUTH` = `true`) | | `FILTER_MODE` | `none` | Filter mode: `none`, `whitelist`, `blacklist` | | `FILTER_LIST` | `""` | Comma-separated domains (e.g., `openai.com,github.com`) |