Files
smart-home-tablet/middleware.ts
Cosmo 7fb05181e6
All checks were successful
Deploy / deploy (push) Successful in 3m10s
fix(voice/tools): use x-voice-internal header for loopback fetches
Tool endpoints (events, notes, transport, weather) call other /api/*
routes via loopback (http://localhost:3000). Those routes are
middleware-protected — cookie-less loopbacks were getting 401, which
surfaced to the voice agent as get_today_events → tool_http_502.

Add internal header bypass: middleware lets the request through when
x-voice-internal matches VOICE_API_KEY. Only our own tool endpoints
use this header, from inside the same container, so the blast radius
is limited to loopback traffic.

- middleware.ts: check x-voice-internal before cookie
- lib/voice-tools.ts: internalHeaders() helper
- app/api/voice/tools/{weather,transport,events,notes}: use it
2026-04-23 13:41:57 +00:00

39 lines
1.4 KiB
TypeScript

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
// Only protect API routes. /api/voice/event, /api/voice/tools/*, /api/voice/timer
// have their own bearer-token auth (VOICE_API_KEY) and bypass the cookie check.
const isVoiceBearer =
pathname === '/api/voice/event' ||
pathname.startsWith('/api/voice/tools/') ||
pathname === '/api/voice/timer'
if (!pathname.startsWith('/api/') || pathname.startsWith('/api/auth') || isVoiceBearer) {
return NextResponse.next()
}
// Internal loopback bypass: tool endpoints shell out to other API routes.
// They pass x-voice-internal with the same VOICE_API_KEY — safe because
// only processes on the same host (the tablet container itself) know the key.
const internal = request.headers.get('x-voice-internal')
if (internal && internal === process.env.VOICE_API_KEY) {
return NextResponse.next()
}
// Check auth by forwarding to auth check
const token = request.cookies.get('auth_token')?.value
if (!token) {
return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
}
// Let the request through — individual API routes can do further validation if needed
// The auth cookie existence is sufficient since it is httpOnly and set by server
return NextResponse.next()
}
export const config = {
matcher: ['/api/:path*'],
}