@@ -38,35 +38,36 @@ export const browserIdMiddleware: MiddlewareHandler = async (c: Context, next) =
3838 return c . json ( { message : "サーバー設定エラー" } , 500 ) ;
3939 }
4040
41- let browserId : string | undefined ;
42- let needsReissue = false ;
43-
4441 // 新形式 (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- }
42+ const browserIdHono = ( await getSignedCookie ( c , cookieSecret , COOKIE_NAME ) ) || undefined ;
43+ if ( browserIdHono ) {
44+ c . set ( "browserId" , browserIdHono ) ;
45+ return next ( ) ;
5746 }
5847
59- if ( browserId && needsReissue ) {
48+ // "browserId" という Cookie が存在しない場合は新規発行
49+ const rawCookie = getCookie ( c , COOKIE_NAME ) ;
50+ if ( ! rawCookie ) {
51+ const browserId = crypto . randomUUID ( ) ;
6052 await setSignedCookie ( c , COOKIE_NAME , browserId , cookieSecret , cookieOptions ) ;
53+ c . set ( "browserId" , browserId ) ;
54+ return next ( ) ;
6155 }
6256
63- if ( ! browserId ) {
64- browserId = crypto . randomUUID ( ) ;
65- await setSignedCookie ( c , COOKIE_NAME , browserId , cookieSecret , cookieOptions ) ;
57+ // 旧形式(Express)を試す
58+ const browserIdExpress = unsignExpressCookie ( rawCookie , cookieSecret ) ;
59+ if ( browserIdExpress ) {
60+ // 旧形式が有効な場合は新形式で再発行
61+ await setSignedCookie ( c , COOKIE_NAME , browserIdExpress , cookieSecret , cookieOptions ) ;
62+ c . set ( "browserId" , browserIdExpress ) ;
63+ return next ( ) ;
6664 }
6765
68- // コンテキストに保存(後続のハンドラで c.get('browserId') で取得可能)
69- c . set ( "browserId" , browserId ) ;
70-
71- await next ( ) ;
66+ // ここまで来たら Cookie が不正
67+ return c . json (
68+ {
69+ message : "ブラウザのCookie設定に問題があります。" ,
70+ } ,
71+ 400 ,
72+ ) ;
7273} ;
0 commit comments