|
| 1 | +import crypto from "node:crypto"; |
| 2 | +import type { Context, MiddlewareHandler } from "hono"; |
| 3 | +import { getCookie, getSignedCookie, setSignedCookie } from "hono/cookie"; |
| 4 | +import { cookieOptions } from "../main.js"; |
| 5 | + |
| 6 | +const COOKIE_NAME = "browserId"; |
| 7 | + |
| 8 | +/** |
| 9 | + * Express の署名付きクッキー(s:value.signature 形式)を検証して値を取り出す |
| 10 | + */ |
| 11 | +function unsignExpressCookie(signedValue: string, secret: string): string | null { |
| 12 | + if (!signedValue.startsWith("s:")) return null; |
| 13 | + |
| 14 | + const raw = signedValue.slice(2); // `s:` を削除 |
| 15 | + const lastDotIndex = raw.lastIndexOf("."); |
| 16 | + if (lastDotIndex === -1) return null; |
| 17 | + |
| 18 | + const value = raw.slice(0, lastDotIndex); // 署名前の値(uuid) |
| 19 | + const signature = raw.slice(lastDotIndex + 1); |
| 20 | + |
| 21 | + // Express と同じアルゴリズムで署名を検証 |
| 22 | + const expectedSignature = crypto.createHmac("sha256", secret).update(value).digest("base64").replace(/=+$/, ""); |
| 23 | + |
| 24 | + if (signature === expectedSignature) { |
| 25 | + return value; |
| 26 | + } |
| 27 | + |
| 28 | + return null; |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Express → Hono の移行で signed cookie 形式が変わったため両方に対応するミドルウェア |
| 33 | + */ |
| 34 | +export const browserIdMiddleware: MiddlewareHandler = async (c: Context, next) => { |
| 35 | + const cookieSecret = process.env.COOKIE_SECRET; |
| 36 | + if (!cookieSecret) { |
| 37 | + console.error("COOKIE_SECRET is not set"); |
| 38 | + return c.json({ message: "サーバー設定エラー" }, 500); |
| 39 | + } |
| 40 | + |
| 41 | + let browserId: string | undefined; |
| 42 | + let needsReissue = false; |
| 43 | + |
| 44 | + // 新形式 (Hono) を試す |
| 45 | + browserId = (await getSignedCookie(c, cookieSecret, COOKIE_NAME)) || undefined; |
| 46 | + |
| 47 | + if (!browserId) { |
| 48 | + const rawCookie = getCookie(c, COOKIE_NAME); |
| 49 | + |
| 50 | + if (rawCookie?.startsWith("s:")) { |
| 51 | + const legacy = unsignExpressCookie(rawCookie, cookieSecret); |
| 52 | + if (legacy) { |
| 53 | + browserId = legacy; |
| 54 | + needsReissue = true; |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + if (browserId && needsReissue) { |
| 60 | + await setSignedCookie(c, COOKIE_NAME, browserId, cookieSecret, cookieOptions); |
| 61 | + } |
| 62 | + |
| 63 | + if (!browserId) { |
| 64 | + browserId = crypto.randomUUID(); |
| 65 | + await setSignedCookie(c, COOKIE_NAME, browserId, cookieSecret, cookieOptions); |
| 66 | + } |
| 67 | + |
| 68 | + // コンテキストに保存(後続のハンドラで c.get('browserId') で取得可能) |
| 69 | + c.set("browserId", browserId); |
| 70 | + |
| 71 | + await next(); |
| 72 | +}; |
0 commit comments