improve web ui

This commit is contained in:
2026-06-26 05:43:34 +00:00
parent 00cf51d610
commit 803573b4ec
73 changed files with 3373 additions and 2847 deletions
+33 -18
View File
@@ -2,26 +2,41 @@
// (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'
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
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' }
}
// 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
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)
})
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,
);
});
+23 -15
View File
@@ -1,20 +1,28 @@
// 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'
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 }
})
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 };
});
+6 -6
View File
@@ -1,9 +1,9 @@
// POST /_auth/logout — clear the session cookie.
import { defineEventHandler, useSession } from 'h3'
import { sessionConfig, type SessionData } from '../../util/auth'
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 }
})
const session = await useSession<SessionData>(event, sessionConfig());
await session.clear();
return { ok: true };
});
+29 -21
View File
@@ -3,26 +3,34 @@
// (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, setResponseStatus } from 'h3'
import { mgmtToken, mgmtUrl } from '../../util/auth'
import {
defineEventHandler,
getRequestURL,
proxyRequest,
setResponseStatus,
} 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()
// The mgmt API now requires a token always. Without one configured, forwarding an empty bearer
// would just bounce as 401 — fail fast and legibly instead (the packaged service sources the
// host's ~/.config/punktfunk/mgmt-token, so this only fires on a misconfigured/early-start deploy).
if (!token) {
setResponseStatus(event, 503)
return { error: 'management token not configured (PUNKTFUNK_MGMT_TOKEN / ~/.config/punktfunk/mgmt-token)' }
}
return proxyRequest(event, target, {
headers: {
// Overwrite, not append: the host-held token replaces anything the browser sent.
authorization: `Bearer ${token}`,
// Don't forward the session cookie to the management API.
cookie: '',
},
})
})
const { pathname, search } = getRequestURL(event);
const target = `${mgmtUrl()}${pathname}${search}`;
const token = mgmtToken();
// The mgmt API now requires a token always. Without one configured, forwarding an empty bearer
// would just bounce as 401 — fail fast and legibly instead (the packaged service sources the
// host's ~/.config/punktfunk/mgmt-token, so this only fires on a misconfigured/early-start deploy).
if (!token) {
setResponseStatus(event, 503);
return {
error:
"management token not configured (PUNKTFUNK_MGMT_TOKEN / ~/.config/punktfunk/mgmt-token)",
};
}
return proxyRequest(event, target, {
headers: {
// Overwrite, not append: the host-held token replaces anything the browser sent.
authorization: `Bearer ${token}`,
// Don't forward the session cookie to the management API.
cookie: "",
},
});
});
+45 -39
View File
@@ -4,26 +4,29 @@
//
// 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'
import {
createHash,
timingSafeEqual as nodeTimingSafeEqual,
} from "node:crypto";
import type { SessionConfig } from "h3";
export const SESSION_NAME = 'pf_session'
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 ?? ''
return process.env.PUNKTFUNK_UI_PASSWORD ?? "";
}
/** The management API the proxy forwards to (loopback by default — never LAN-exposed). It serves
* HTTPS with the host's self-signed identity cert, so the deployment also sets
* NODE_TLS_REJECT_UNAUTHORIZED=0 for the (loopback-only) proxy fetch — see .env.example. */
export function mgmtUrl(): string {
return process.env.PUNKTFUNK_MGMT_URL ?? 'https://127.0.0.1:47990'
return process.env.PUNKTFUNK_MGMT_URL ?? "https://127.0.0.1:47990";
}
/** Bearer token for the management API, injected server-side. */
export function mgmtToken(): string {
return process.env.PUNKTFUNK_MGMT_TOKEN ?? ''
return process.env.PUNKTFUNK_MGMT_TOKEN ?? "";
}
/**
@@ -32,34 +35,37 @@ export function mgmtToken(): string {
* (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,
// Bounds a stolen/replayed cookie's lifetime (sets the cookie Max-Age AND the iron
// seal TTL). 7 days for a single-user console.
maxAge: 60 * 60 * 24 * 7,
cookie: {
httpOnly: true,
sameSite: 'lax',
path: '/',
// h3 defaults Secure to true, which browsers DROP over plain http:// (so login
// silently fails on a LAN HTTP server). Only mark Secure when actually behind TLS
// (set PUNKTFUNK_UI_SECURE=1 / =true then).
secure: /^(1|true)$/i.test(process.env.PUNKTFUNK_UI_SECURE ?? ''),
},
}
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,
// Bounds a stolen/replayed cookie's lifetime (sets the cookie Max-Age AND the iron
// seal TTL). 7 days for a single-user console.
maxAge: 60 * 60 * 24 * 7,
cookie: {
httpOnly: true,
sameSite: "lax",
path: "/",
// h3 defaults Secure to true, which browsers DROP over plain http:// (so login
// silently fails on a LAN HTTP server). Only mark Secure when actually behind TLS
// (set PUNKTFUNK_UI_SECURE=1 / =true then).
secure: /^(1|true)$/i.test(process.env.PUNKTFUNK_UI_SECURE ?? ""),
},
};
}
/** 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)
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 the build's
@@ -70,21 +76,21 @@ export function timingSafeEqual(a: string, b: string): boolean {
* generic `*.json` allowlist would expose `/api/v1/openapi.json` (and any future
* `.json`/`.png` management route) through the proxy unauthenticated. */
export function isPublicPath(pathname: string): boolean {
if (pathname === '/api' || pathname.startsWith('/api/')) return false // always gated
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
return false
if (pathname === "/api" || pathname.startsWith("/api/")) return false; // always gated
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;
return false;
}
/** Validate a post-login redirect target: a same-origin path only. Rejects protocol-
* relative (`//evil.com`) and absolute URLs to prevent an open redirect. */
export function safeNextPath(next: string | undefined): string {
if (!next || !next.startsWith('/') || next.startsWith('//')) return '/'
return next
if (!next || !next.startsWith("/") || next.startsWith("//")) return "/";
return next;
}
export interface SessionData {
authenticated?: boolean
authenticated?: boolean;
}