Files
smart-home-tablet/middleware.ts
Cosmo c7fc4d6e8e
All checks were successful
Deploy / deploy (push) Successful in 2m34s
fix: use Web Crypto API in middleware (Edge Runtime compat)
2026-04-22 19:12:19 +00:00

45 lines
1.4 KiB
TypeScript

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
async function hmacSha256(secret: string, message: string): Promise<string> {
const enc = new TextEncoder()
const key = await crypto.subtle.importKey(
'raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']
)
const sig = await crypto.subtle.sign('HMAC', key, enc.encode(message))
return Array.from(new Uint8Array(sig)).map(b => b.toString(16).padStart(2, '0')).join('')
}
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
if (
pathname.startsWith('/api/auth') ||
pathname.startsWith('/_next') ||
pathname.startsWith('/favicon') ||
pathname === '/manifest.json'
) {
return NextResponse.next()
}
const token = request.cookies.get('auth_token')?.value
const pin = process.env.APP_PIN || '1234'
const secret = process.env.APP_SECRET || 'smart-home-default-secret-change-me'
const expectedToken = await hmacSha256(secret, pin)
if (token !== expectedToken) {
if (pathname.startsWith('/api/')) {
return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
}
const url = request.nextUrl.clone()
url.searchParams.set('locked', '1')
return NextResponse.rewrite(url)
}
return NextResponse.next()
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico|manifest.json).*)'],
}