@hadoku/worker-utils

中文文档
1.7.24发布于 2026/11/15ISCES Module近 30 天下载 5393

Shared utilities for Cloudflare Workers

原始使用文档
文档目录13 节
  1. Files
  2. auth.ts
  3. masking.ts
  4. validation.ts
  5. cors.ts
  6. logging.ts
  7. responses.ts
  8. types.ts
  9. Common Patterns
  10. Minimal Worker
  11. With Validation
  12. With Logging
  13. See Also

Worker Utilities - Quick Reference

Shared utilities for Cloudflare Workers. Generic, reusable patterns extracted from production workers.

Import: import { ... } from '@wolffm/worker-utils'


Files

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

Edge-verified authentication:

A worker does NOT resolve keys. edge-router resolves the caller against its KV key registry, then stamps X-Hadoku-Tier alongside an X-Edge-Auth provenance header; createEdgeAuth verifies the provenance against EDGE_AUTH_SECRET before trusting the tier, and degrades to public when it doesn't verify. Tier priority: admin > service > friend > public. service is for worker-to-worker / sibling-app traffic.

Removed in 1.3.0: createHadokuAuth, HadokuAuthEnv, parseKeysFromEnv, parseKeysWithNames, validateKeyAndGetType. They read the ADMIN_KEYS / SERVICE_KEYS / FRIEND_KEYS env arrays, which were retired 2026-07-26 — so they had already stopped authenticating anyone. createEdgeAuth is a drop-in (same context shape, same extend option).

// 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',
  }))
);

Functions:

  • createKeyAuth(keyMap, options?) - Simple key → userType mapping
  • createAuthMiddleware(config) - Custom auth logic
  • validateKeyAndGetType(key, adminKeys, friendKeys, serviceKeys?) - Validate key & return userType (4-arg form opts into the 'service' tier)
  • parseKeysFromEnv(jsonString) - Parse key config from env vars
  • getAuthContext(c) - Get auth from context
  • requireMinTier('friend') - Gate a route at a MINIMUM tier (public < member < friend < service < wife < admin); every higher tier is admitted by rank
  • tierAtLeast(auth, 'admin') - Same rank check for an already-resolved auth context, for in-handler branching. Never compare auth.userType to a string
  • TIER_RANK / Tier - The rank table and tier union, shared by the edge gate and the in-worker gate
  • requireUserType([...]) - Removed 2026-07-25. Translate to requireMinTier(<lowest tier in the list>)

Adds to context: c.get('authContext') → { userType, isAdmin, isFriend, isPublic }


masking.ts

Mask sensitive data for logging:

logRequest('POST', '/session/create', {
  sessionId: maskSessionId(sessionId), // "1a2b3c4d5e6f7g8h"
  key: maskKey(authKey), // "admin-secre" (50%)
});

Functions:

  • maskKey(key, percentage?) - Mask key (show first 50% by default, no suffix)
  • maskSessionId(id) - Mask session ID (show first 16 chars, no suffix)
  • maskEmail(email) - Mask email (show first char + domain)
  • redactFields(obj, fields) - Redact sensitive fields from objects

Constants:

  • MASKING.KEY_PERCENTAGE - Percentage of key to show (0.5 = 50%)
  • MASKING.KEY_MIN_LENGTH - Minimum characters to show (4)
  • MASKING.SESSION_ID_PREFIX_LENGTH - Default session ID prefix (16)
  • SENSITIVE_FIELDS - Common sensitive field names

Examples:

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]' }

Extract common fields:

const { userId, sessionId } = extractUserContext(c);
const boardId = extractField(c, ['query:boardId', 'body:boardId'], 'main');

Functions:

  • extractUserContext(c) - Get userId, sessionId
  • extractField(c, sources, default?, transform?) - Single field from multiple sources
  • extractContext(c, config) - Multiple fields at once
  • extractPagination(c) - Get page, limit, offset
  • extractSorting(c) - Get sortBy, sortOrder
  • getRequestMetadata(c) - Get IP, userAgent, country, etc.

Source format: 'header:X-User-Id', 'query:boardId', 'body:title'


validation.ts

Validate request data:

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);

Functions:

  • validateFields(data, rules) - Full validation with rules
  • requireFields(data, ['id', 'title']) - Quick required check
  • validateBody(rules) - Middleware for auto-validation
  • createValidator(rules) - Reusable validator function

CommonRules:

  • CommonRules.id() - UUID validation
  • CommonRules.title({ maxLength }) - String 1-200 chars
  • CommonRules.email(required) - Email pattern
  • CommonRules.url(required) - URL pattern
  • CommonRules.enum('status', ['active', 'inactive']) - Enum validation
  • CommonRules.array('tags', options) - Array validation
  • CommonRules.number('age', { min, max, integer }) - Number constraints

cors.ts

Standard Hadoku CORS:

app.use('*', createHadokuCors());

Functions:

  • createHadokuCors(additionalOrigins?) - Hadoku defaults + custom
  • createCorsMiddleware(config) - Full custom config
  • matchOrigin(origin, pattern) - Wildcard matching

Presets:

  • CORSPresets.hadoku - Production Hadoku origins
  • CORSPresets.development - Includes localhost
  • CORSPresets.production(origins) - Custom production
  • CORSPresets.publicApi - Public API (all origins)

logging.ts

Log requests and errors:

logRequest('GET', '/api/items', { userId, boardId });
logError('POST', '/api/items', 'Validation failed', { errors });

Functions:

  • logRequest(method, path, context?, level?) - Log HTTP requests
  • logError(method, path, error, context?) - Log errors
  • createLogger(config) - Custom logger instance
  • createRequestLogger(method, path, baseContext) - Request-scoped logger
  • startTimer() - Performance timing (timer.end(message, context))
  • redactFields(obj, fields) - Remove sensitive data

Constants:

  • SENSITIVE_FIELDS - Common sensitive field names (password, apiKey, token, etc.)

responses.ts

Standard HTTP responses:

return ok(c, { items });
return created(c, { item });
return badRequest(c, 'Missing field: id');
return notFound(c, 'Task');

Success:

  • ok(c, data, message?) - 200
  • created(c, data, message?) - 201
  • noContent(c) - 204

Errors:

  • 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 with validation details

Health & Error Handling:

  • healthCheck(c, service, checks?) - Health check response
  • createHealthCheckHandler(service, config) - Health check handler factory
  • handleError(c, error, message) - Generic error handler
  • withErrorHandling(handler) - Async error wrapper

types.ts

Import types:

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';

Common Patterns

Minimal Worker

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;

With Validation

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 });
});

With Logging

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');
  }
});

See Also

版本与发布记录

@hadoku/worker-utils 共发布 28 个版本,首次发布于 2026/10/31;过去 12 个月发布了 28 个版本。

版本发布日期距今
1.7.24latest2026/11/151 天前
1.7.232026/11/125 天前
1.7.222026/11/125 天前
1.7.212026/11/125 天前
1.7.202026/11/125 天前
1.7.192026/11/116 天前

关于 @hadoku/worker-utils 的常见问题

@hadoku/worker-utils 是什么?

Shared utilities for Cloudflare Workers

如何安装 @hadoku/worker-utils?

在项目目录运行 npm install @hadoku/worker-utils,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:hono(^4.11.4)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@hadoku/worker-utils 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/hadoku__worker-utils 是否存在。

@hadoku/worker-utils 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@hadoku/worker-utils 可以商用吗?

@hadoku/worker-utils 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@hadoku/worker-utils 的下载量有多少?

根据 npm 官方下载统计,@hadoku/worker-utils 在 2026/10/17 – 2026/11/15 这 30 天内被下载 5,393 次,日均约 180 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@hadoku/worker-utils 还在维护吗?

最新版本 1.7.24 发布于 2026/11/15(1 天前);至今共发布 28 个版本,其中过去 12 个月发布了 28 个;首次发布于 2026/10/31。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。