refactor: migrate webhook to Hono router with auth middleware

webhook.ts:
- Convert handleWebhook() to Hono router pattern
- Create telegramAuth middleware with security validations:
  - HTTP method validation (POST only)
  - Content-Type validation (application/json)
  - Timing-safe secret token comparison
  - Timestamp validation (5-min replay attack prevention)
  - Request body structure validation
- Always return 200 to Telegram (prevents retry storms)
- Structured logging with context

index.ts:
- Import webhookRouter instead of handleWebhook
- Use app.route('/webhook', webhookRouter)

Benefits:
- Consistent Hono pattern across all routes
- Reusable auth middleware
- Better separation of concerns

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
kappa
2026-01-29 10:02:35 +09:00
parent 3cfcb06f27
commit 40447952a9
2 changed files with 97 additions and 22 deletions

View File

@@ -1,6 +1,6 @@
import { Env, EmailMessage, ProvisionMessage, MessageBatch } from './types';
import { sendMessage, setWebhook, getWebhookInfo } from './telegram';
import { handleWebhook } from './routes/webhook';
import { webhookRouter } from './routes/webhook';
import { apiRouter } from './routes/api';
import { handleHealthCheck } from './routes/health';
import { parseBankSMS } from './services/bank-sms-parser';
@@ -72,8 +72,8 @@ app.get('/webhook-info', async (c) => {
// API routes - use Hono router
app.route('/api', apiRouter);
// Telegram Webhook
app.post('/webhook', (c) => handleWebhook(c.req.raw, c.env));
// Telegram Webhook - use Hono router with middleware
app.route('/webhook', webhookRouter);
// Root path
app.get('/', (c) => {