工人公用事业 - 快速参考
为Cloudflare工人共享公用事业。 从生产工人那里提取的通用的、可重复使用的模式.
导入 : import { ... } from '@wolffm/worker-utils'
文件
workers/shared/
├── types.ts # TypeScript type definitions
├── auth.ts # Authentication middleware
├── context.ts # Request context extraction
├── validation.ts # Input validation
├── cors.ts # CORS configuration
├── logging.ts # Structured logging
├── masking.ts # Data masking for safe logging
├── responses.ts # HTTP response helpers
└── index.ts # Barrel export
auth.ts (帮助)
边缘验证认证 :
工人不解决钥匙。 边缘路由器将调用者与其 KV 相对抗
密钥登记簿,然后是邮票 X-Hadoku-Tier 与一个 X-Edge-Auth 来源
页眉; createEdgeAuth 校对出处 EDGE_AUTH_SECRET
在信任等级之前 public 当它不验证.
分级优先级 : admin > service > friend > public。 。 。 . service 用于
工人与工人之间的交通.
在1.3.0中删除:
createHadokuAuth, (中文(简体) ),HadokuAuthEnv, (中文(简体) ),parseKeysFromEnv, (中文(简体) ),parseKeysWithNames, (中文(简体) ),validateKeyAndGetType他们读了ADMIN_KEYS编号 :SERVICE_KEYS编号 :FRIEND_KEYS已退役的env阵列 2026-07-26 - 所以他们已经停止认证任何人.createEdgeAuth是一个 滴入( 相同的上下文形状, 相同)extend选项).
// Standard hadoku ecosystem auth:
import { createEdgeAuth } from '@wolffm/worker-utils';
app.use('*', createEdgeAuth());
// ↑ verifies X-Edge-Auth, then trusts the edge-stamped X-Hadoku-Tier
// Generic helper (single-key-per-tier case only):
app.use(
'*',
createKeyAuth((env) => ({
[env.SOME_SINGLE_KEY]: 'admin',
}))
);
函数 :
createKeyAuth(keyMap, options?)- 简单的密钥 — 用户类型映射createAuthMiddleware(config)- 自定义认证逻辑validateKeyAndGetType(key, adminKeys, friendKeys, serviceKeys?)- 验证密钥返回用户Type( 4- arg 形式)'service'等级)parseKeysFromEnv(jsonString)- 解析自定义的密钥配置getAuthContext(c)- 从上下文获取认证requireMinTier('friend')- 在MINIMUM一级打开一条路线(public < member < friend < service < wife < admin);每个较高级别按级别录取tierAtLeast(auth, 'admin')- 对一个已经解开的认证上下文进行相同的级别检查,用于手动分支。 永远不要比较auth.userType到字符串TIER_RANK编号 :Tier- 由边门和工人门共用的军衔表和等级联盟- 说吧 删除 2026-07-25. (中文(简体) ). 翻译为requireUserType([...])requireMinTier(<lowest tier in the list>)
添加到上下文中 : c.get('authContext') → { userType, isAdmin, isFriend, isPublic }
口罩( t)
用于记录的遮罩敏感数据 :
logRequest('POST', '/session/create', {
sessionId: maskSessionId(sessionId), // "1a2b3c4d5e6f7g8h"
key: maskKey(authKey), // "admin-secre" (50%)
});
函数 :
maskKey(key, percentage?)- 遮盖键(默认显示前50%,无后缀)maskSessionId(id)- 遮罩会话ID(显示前16个字符,无后缀)maskEmail(email)- 遮罩电子邮件(显示第一个字符+域名)redactFields(obj, fields)- 从物体中调整敏感字段
常数 :
MASKING.KEY_PERCENTAGE- 要显示的密钥百分比(0.5=50%)MASKING.KEY_MIN_LENGTH- 显示最小字符(4)MASKING.SESSION_ID_PREFIX_LENGTH- 默认会话 ID 前缀( 16)SENSITIVE_FIELDS- 常见的敏感字段名称
实例:
maskKey('admin-secret-key-123'); // "admin-secre"
maskSessionId('1a2b3c4d5e6f7g8h9i0j'); // "1a2b3c4d5e6f7g8h"
maskEmail('[email protected]'); // "j***@example.com"
redactFields({ username: 'john', password: 'secret' }, ['password']);
// { username: 'john', password: '[REDACTED]' }
提取常见字段 :
const { userId, sessionId } = extractUserContext(c);
const boardId = extractField(c, ['query:boardId', 'body:boardId'], 'main');
函数 :
extractUserContext(c)- 获取用户编号, 会话编号extractField(c, sources, default?, transform?)- 多个来源的单一领域extractContext(c, config)- 一次多块地extractPagination(c)- 获取页面,限制,平移extractSorting(c)- 排序By,排序命令getRequestMetadata(c)- 获取IP,用户代理,国家等.
资料来源格式 : 'header:X-User-Id', (中文(简体) ), 'query:boardId', (中文(简体) ), 'body:title'
校验.ts
验证请求数据 :
const validation = validateFields(body, [
{ field: 'id', required: true, type: 'string' },
{ field: 'title', required: true, minLength: 1, maxLength: 200 },
]);
if (!validation.valid) return validationError(c, validation.errors);
函数 :
validateFields(data, rules)- 全面验证规则requireFields(data, ['id', 'title'])- 所需的快速检查validateBody(rules)- 自动验证的中间软件createValidator(rules)- 可重复使用的验证器功能
共同规则 :
CommonRules.id()- UUID 验证CommonRules.title({ maxLength })- 1 -200个字符CommonRules.email(required)- 电子邮件模式CommonRules.url(required)- URL图案CommonRules.enum('status', ['active', 'inactive'])- Enum验证CommonRules.array('tags', options)- 阵列验证CommonRules.number('age', { min, max, integer })- 数量限制
皮层
标准 Hadoku CORS :
app.use('*', createHadokuCors());
函数 :
createHadokuCors(additionalOrigins?)- Hadoku 默认 + 自定义createCorsMiddleware(config)- 完全定制配置matchOrigin(origin, pattern)- 通关卡匹配
预设 :
CORSPresets.hadoku- 生产出出自哈多库CORSPresets.development- 包括当地东道主CORSPresets.production(origins)- 定制生产CORSPresets.publicApi- 公共API(所有来源)
记录.ts
日志请求和错误 :
logRequest('GET', '/api/items', { userId, boardId });
logError('POST', '/api/items', 'Validation failed', { errors });
函数 :
logRequest(method, path, context?, level?)- 日志 HTTP 请求logError(method, path, error, context?)- 日志错误createLogger(config)- 自定义日志实例createRequestLogger(method, path, baseContext)- 请求扫描器startTimer()- 业绩时间(timer.end(message, context)(中文(简体) )redactFields(obj, fields)- 删除敏感数据
常数 :
SENSITIVE_FIELDS- 常见的敏感字段名称(密码、 apiKey、 符号等)
回应.ts
标准 HTTP 响应 :
return ok(c, { items });
return created(c, { item });
return badRequest(c, 'Missing field: id');
return notFound(c, 'Task');
成功 :
ok(c, data, message?)- 200块created(c, data, message?)- 201号noContent(c)- 204号
错误 :
badRequest(c, message, details?)- 400岁unauthorized(c, message?)- 401号forbidden(c, message?)- 403岁notFound(c, resource?)- 404岁conflict(c, message, details?)- 409号serverError(c, message, details?)- 500块validationError(c, errors)- 400个附有验证细节
卫生和错误处理 :
healthCheck(c, service, checks?)- 健康检查对策createHealthCheckHandler(service, config)- 健康检查员工厂handleError(c, error, message)- 通用错误处理器withErrorHandling(handler)- 同步错误包装
类型.ts
导入类型 :
import type {
UserType, // 'admin' | 'service' | 'friend' | 'public'
AuthContext, // { userType, userId?, isAdmin, isFriend, isPublic }
ValidationRule, // { field, required?, type?, minLength?, ... }
ValidationResult, // { valid, errors }
LoggerConfig, // { prefix?, minLevel?, includeTimestamp? }
CORSConfig, // { origins, methods, allowedHeaders, ... }
} from '@wolffm/worker-utils';
常见模式
最小工人
import { Hono } from 'hono';
import {
createKeyAuth,
createHadokuCors,
extractUserContext,
ok,
} from '@wolffm/worker-utils';
const app = new Hono();
app.use('*', createHadokuCors());
app.use('*', createEdgeAuth());
// ↑ verifies X-Edge-Auth, trusts the edge-stamped tier
app.get('/api/items', async (c) => {
const { userId } = extractUserContext(c);
const items = await getItems(userId);
return ok(c, { items });
});
export default app;
有验证
app.post('/api/items', async (c) => {
const body = await c.req.json();
const validation = validateFields(body, [
CommonRules.id(),
CommonRules.title({ maxLength: 200 }),
]);
if (!validation.valid) {
return validationError(c, validation.errors);
}
const item = await createItem(body);
return created(c, { item });
});
正在登录
app.post('/api/items', async (c) => {
const { userId } = extractUserContext(c);
logRequest('POST', '/api/items', { userId });
try {
const item = await createItem(body);
return created(c, { item });
} catch (error) {
logError('POST', '/api/items', error.message, { userId });
return serverError(c, 'Failed to create item');
}
});
另见
- 工人(md) - 工人指数和设置指南
- 文件/儿童应用程序/NEW CHILD APP CHECKLIST.md - 后端工人设置(见"可选:后端API"部分)
- 一般事务人员(其他职等) - 工人调试和常见模式