Skip to content
Merged
23 changes: 10 additions & 13 deletions REQUIRE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 → 设置 → 变量和机密
Expand All @@ -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"}
Expand All @@ -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**:
Expand Down
23 changes: 10 additions & 13 deletions REQUIRE_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```

Expand All @@ -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"}
Expand All @@ -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**:
Expand Down
10 changes: 6 additions & 4 deletions skills/cf-email-api-setup/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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` | 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`) |
| `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
Expand All @@ -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`, 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.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
- **Email Routing Setup**: Must complete domain onboarding (MX records) before Catch-all works.

## API Usage
Expand Down
4 changes: 1 addition & 3 deletions src/handlers/email.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
8 changes: 3 additions & 5 deletions src/handlers/http.ts
Original file line number Diff line number Diff line change
@@ -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 }>();

Expand All @@ -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();
Expand Down
34 changes: 24 additions & 10 deletions src/services/extractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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))];
Expand Down Expand Up @@ -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 {
Expand All @@ -113,22 +113,36 @@ async function extractWithAI(text: string, env: Env): Promise<string | null> {
},
];

try {
const response = await env.AI.run(AI_MODEL, {
messages,
max_tokens: 16,
temperature: 0,
}) as { response: string };
const AI_TIMEOUT_MS = 10000;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), AI_TIMEOUT_MS);

const output = response?.response?.trim();
try {
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;

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');
if (controller.signal.aborted) {
console.warn('[extractor] AI extraction timed out');
} else {
console.error('[AI extraction failed]', e);
}
return null;
} finally {
clearTimeout(timer);
}
}

Expand Down
20 changes: 12 additions & 8 deletions src/services/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,19 @@ export async function parseEmail(message: ForwardableEmailMessage): Promise<Pars
const chunks: Uint8Array[] = [];
let totalSize = 0;

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;
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({
Expand Down
8 changes: 4 additions & 4 deletions src/services/storage.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -45,7 +43,9 @@ export async function getCode(
): Promise<string | null> {
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(
Expand Down
17 changes: 17 additions & 0 deletions src/utils/prefix.ts
Original file line number Diff line number Diff line change
@@ -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);
}
3 changes: 3 additions & 0 deletions wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ ENABLE_AI = "true"
REQUIRE_AUTH = "false"
FILTER_MODE = "none"
FILTER_LIST = ""
# 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)

[[kv_namespaces]]
binding = "EMAIL_KV"
Expand Down
Loading