feat(web): login-gated BFF auth — sealed session cookie + server-side token injection
ci / rust (push) Has been cancelled
ci / rust (push) Has been cancelled
Single-user, LAN-reachable-but-gated. The web server is a backend-for-frontend:
- Login: POST /_auth/login {password} checks PUNKTFUNK_UI_PASSWORD (constant-time) and
sets a SEALED session cookie (h3 useSession / AES-GCM). server/middleware/auth.ts gates
every request — pages 302 → /login, /api → 401 — and FAILS CLOSED (503) when
PUNKTFUNK_UI_PASSWORD is unset, so a misconfigured LAN-exposed server admits no one.
- The management API stays loopback-only + token (never LAN-exposed). The proxy
(server/routes/api/[...].ts) injects PUNKTFUNK_MGMT_TOKEN server-side and drops the
browser's cookie before forwarding — the token never reaches the browser, which only
holds the session cookie.
Nitro doesn't auto-scan a server/ dir, so the Nitro plugin gets an explicit scanDirs to
pick up middleware + routes. Client: removed the localStorage token (server injects it);
the fetcher bounces to /login on 401; new /login page (bare, no shell); Settings drops the
token field and gains a Sign-out button; en/de strings.
Validated live end to end: unauth /→302, /api→401; wrong pw→401; right pw→200+cookie;
authed /api/v1/status→200 (proxied, mgmt token injected — the host required it); logout→
session cleared→401. tsc + build green.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
// The single server-side gate. Runs for EVERY request to the deployed Bun/Nitro server
|
||||
// (pages, the /api proxy, everything) before routing. Unauthenticated requests are
|
||||
// redirected to /login (page navigations) or rejected 401 (/api). Fails CLOSED if
|
||||
// PUNKTFUNK_UI_PASSWORD is unset, so a misconfigured LAN-exposed server admits no one.
|
||||
import { defineEventHandler, getRequestURL, sendRedirect, setResponseStatus, useSession } from 'h3'
|
||||
import { isPublicPath, sessionConfig, uiPassword, type SessionData } from '../util/auth'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const { pathname } = getRequestURL(event)
|
||||
if (isPublicPath(pathname)) return
|
||||
|
||||
// Misconfigured: refuse everything rather than serve open on the LAN.
|
||||
if (!uiPassword()) {
|
||||
setResponseStatus(event, 503)
|
||||
return { error: 'auth not configured: set PUNKTFUNK_UI_PASSWORD' }
|
||||
}
|
||||
|
||||
const session = await useSession<SessionData>(event, sessionConfig())
|
||||
if (session.data.authenticated) return // authenticated — let it through
|
||||
|
||||
if (pathname.startsWith('/api')) {
|
||||
setResponseStatus(event, 401)
|
||||
return { error: 'unauthorized' }
|
||||
}
|
||||
// Page navigation → bounce to the login screen, remembering where they were headed.
|
||||
return sendRedirect(event, `/login?next=${encodeURIComponent(pathname)}`, 302)
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
// POST /_auth/login {password} — verify the shared password (constant-time), then seal an
|
||||
// authenticated session cookie. Public (allowlisted in the gate) so an unauthenticated user
|
||||
// can actually log in.
|
||||
import { defineEventHandler, readBody, createError, useSession } from 'h3'
|
||||
import { sessionConfig, timingSafeEqual, uiPassword, type SessionData } from '../../util/auth'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const expected = uiPassword()
|
||||
if (!expected) {
|
||||
throw createError({ statusCode: 503, statusMessage: 'auth not configured' })
|
||||
}
|
||||
const body = await readBody<{ password?: string }>(event)
|
||||
const password = String(body?.password ?? '')
|
||||
if (!timingSafeEqual(password, expected)) {
|
||||
throw createError({ statusCode: 401, statusMessage: 'invalid password' })
|
||||
}
|
||||
const session = await useSession<SessionData>(event, sessionConfig())
|
||||
await session.update({ authenticated: true })
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -0,0 +1,9 @@
|
||||
// POST /_auth/logout — clear the session cookie.
|
||||
import { defineEventHandler, useSession } from 'h3'
|
||||
import { sessionConfig, type SessionData } from '../../util/auth'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const session = await useSession<SessionData>(event, sessionConfig())
|
||||
await session.clear()
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -0,0 +1,21 @@
|
||||
// /api/** → the management API. By the time we get here the gate (middleware/auth.ts) has
|
||||
// confirmed an authenticated session. We inject the management bearer token server-side
|
||||
// (the browser never sees it) and drop the browser's own cookies/auth from the upstream
|
||||
// request, then proxy. The management API itself binds loopback only — this proxy is the
|
||||
// ONLY path to it from the LAN, and it's authenticated.
|
||||
import { defineEventHandler, getRequestURL, proxyRequest } from 'h3'
|
||||
import { mgmtToken, mgmtUrl } from '../../util/auth'
|
||||
|
||||
export default defineEventHandler((event) => {
|
||||
const { pathname, search } = getRequestURL(event)
|
||||
const target = `${mgmtUrl()}${pathname}${search}`
|
||||
const token = mgmtToken()
|
||||
return proxyRequest(event, target, {
|
||||
headers: {
|
||||
// Overwrite, not append: the host-held token replaces anything the browser sent.
|
||||
authorization: token ? `Bearer ${token}` : '',
|
||||
// Don't forward the session cookie to the management API.
|
||||
cookie: '',
|
||||
},
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
// Shared auth helpers for the Nitro server (the deployed Bun server). Single-user,
|
||||
// shared-password gate: the user logs in with PUNKTFUNK_UI_PASSWORD, which sets a SEALED
|
||||
// (h3 useSession — AES-GCM) cookie; every request is gated by server/middleware/auth.ts.
|
||||
//
|
||||
// The management token never reaches the browser: server/routes/api/[...].ts injects it
|
||||
// server-side when proxying to the loopback management API.
|
||||
import { createHash, timingSafeEqual as nodeTimingSafeEqual } from 'node:crypto'
|
||||
import type { SessionConfig } from 'h3'
|
||||
|
||||
export const SESSION_NAME = 'pf_session'
|
||||
|
||||
/** The login password. Empty string ⇒ auth is MISCONFIGURED (the gate fails closed). */
|
||||
export function uiPassword(): string {
|
||||
return process.env.PUNKTFUNK_UI_PASSWORD ?? ''
|
||||
}
|
||||
|
||||
/** The management API the proxy forwards to (loopback by default — never LAN-exposed). */
|
||||
export function mgmtUrl(): string {
|
||||
return process.env.PUNKTFUNK_MGMT_URL ?? 'http://127.0.0.1:47990'
|
||||
}
|
||||
|
||||
/** Bearer token for the management API, injected server-side. */
|
||||
export function mgmtToken(): string {
|
||||
return process.env.PUNKTFUNK_MGMT_TOKEN ?? ''
|
||||
}
|
||||
|
||||
/**
|
||||
* The cookie-sealing key for h3 `useSession` (must be ≥ 32 chars). Use PUNKTFUNK_UI_SECRET
|
||||
* if set; otherwise derive a stable 64-hex key from the password so single-var config works
|
||||
* (changing the password then invalidates existing sessions, which is fine).
|
||||
*/
|
||||
export function sessionConfig(): SessionConfig {
|
||||
const secret = process.env.PUNKTFUNK_UI_SECRET
|
||||
const password = secret && secret.length >= 32
|
||||
? secret
|
||||
: createHash('sha256').update(`punktfunk-session-v1:${uiPassword()}`).digest('hex')
|
||||
return { name: SESSION_NAME, password }
|
||||
}
|
||||
|
||||
/** Constant-time string comparison (avoids leaking the password via timing). */
|
||||
export function timingSafeEqual(a: string, b: string): boolean {
|
||||
const ab = Buffer.from(a)
|
||||
const bb = Buffer.from(b)
|
||||
if (ab.length !== bb.length) return false
|
||||
return nodeTimingSafeEqual(ab, bb)
|
||||
}
|
||||
|
||||
/** Paths reachable WITHOUT a session: the login page, the auth endpoints, and static
|
||||
* assets (the login page needs its own CSS/JS). Everything else is gated. */
|
||||
export function isPublicPath(pathname: string): boolean {
|
||||
if (pathname === '/login') return true
|
||||
if (pathname.startsWith('/_auth/')) return true
|
||||
if (pathname.startsWith('/assets/')) return true
|
||||
if (pathname === '/favicon.ico' || pathname === '/robots.txt') return true
|
||||
// Vite/TanStack client chunks and source maps requested by the login page.
|
||||
if (/\.(js|css|map|ico|svg|png|woff2?|json)$/.test(pathname)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
export interface SessionData {
|
||||
authenticated?: boolean
|
||||
}
|
||||
Reference in New Issue
Block a user