Files
punktfunk/web/server/routes/api/[...].ts
T
enricobuehlerandClaude Opus 5 4575134c21 fix(web): one bad password from anywhere stops locking out the whole console
The console's login throttle was documented as per-IP and was not. Nitro's
`localFetch` hands the app a synthetic request whose socket has no
`remoteAddress`, so `getRequestIP()` returned undefined for every request and
every attempt was charged to one shared "unknown" bucket. Five wrong guesses
from any LAN peer locked out everyone — including the operator, and including
the update-apply route, which shares that budget. The Bun entry is the only
place the real peer is knowable, so it now stamps it into a header (deleting
any client-supplied copy first) and `peerAddress()` reads it back.

Verified on a real build bound to 0.0.0.0: seven wrong logins from 127.0.0.1
lock 127.0.0.1 out, a different peer still logs in on the first try, and a
request forging the header is charged to its real address.

Also on the way through:

- Installing an unreviewed package and adding a catalog source now re-ask for
  the console password, like applying an update already did. A 7-day session
  cookie should not be able to run new code on the host, and `store/install`
  with `accept_unverified` did exactly that through the generic passthrough.
  The gate sits at the trust boundary — adding a source, or a raw spec — not
  on every install from a source the operator already chose to trust.
- The ui-credential denylist is matched against the normalised path too, so
  `/api//v1/...` and friends can no longer walk around it.
- The console serves nosniff, a no-referrer policy, and a CSP that pins
  frame-ancestors, object-src and base-uri.
- A plugin UI's response no longer re-emits the content-encoding that `fetch`
  already decoded (which made compressed plugin pages fail to load), no longer
  sets cookies on the console's origin, and OPTIONS reaches the plugin instead
  of being refused 405 by us.
- An unreachable host reads as 502 on these routes, matching the passthrough,
  instead of a bare 500.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-01 00:20:10 +02:00

86 lines
3.9 KiB
TypeScript

// /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 {
createError,
defineEventHandler,
getRequestURL,
proxyRequest,
setResponseStatus,
} from "h3";
import {
isLoopbackUrl,
mgmtToken,
mgmtUrl,
normalizePath,
} from "../../util/auth";
export default defineEventHandler((event) => {
const { pathname, search } = getRequestURL(event);
// A plugin UI's proxy credential (its per-boot secret) is fetched server-side by the
// /plugin-ui proxy and must NEVER reach a browser — deny it on the generic passthrough so a
// session-authed page can't read it (plugin-ui-surface §5, D6). The secret-free list at
// /api/v1/plugins is fine; only the {id}/ui-credential leaf is blocked.
//
// Matched against the NORMALIZED path as well as the raw one: `/api//v1/...`, `/api/./v1/...`
// and percent-encoded variants all reach the same upstream route, and a denylist that only
// knows the canonical spelling is one router-quirk away from leaking the secret.
const denied = /^\/api\/v1\/plugins\/[^/]+\/ui-credential\/?$/i;
if (denied.test(pathname) || denied.test(normalizePath(pathname))) {
setResponseStatus(event, 403);
return {
error: "plugin UI credentials are not accessible from the browser",
};
}
const base = mgmtUrl();
const target = `${base}${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)",
};
}
// TLS scoping (replaces the old process-wide NODE_TLS_REJECT_UNAUTHORIZED=0): the host presents a
// SELF-SIGNED, no-SAN identity cert on loopback, which normal verification rejects. We relax
// verification ONLY for this one loopback hop, via Bun's per-request `tls` option — so any OTHER
// outbound TLS the process ever makes still verifies normally (the global env unverified
// everything). If the operator points PUNKTFUNK_MGMT_URL at a NON-loopback host, we do NOT relax:
// a remote mgmt API must present a valid chain, which is stricter than the old blanket accept.
const fetchOptions = isLoopbackUrl(base)
? // `tls` is a Bun.fetch extension (the console runs on bun — Bun.serve/`bun .output/...`), not
// in the standard RequestInit type, so cast through unknown.
({ tls: { rejectUnauthorized: false } } as unknown as RequestInit)
: undefined;
return proxyRequest(event, target, {
fetchOptions,
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: "",
},
onResponse: (_event, response) => {
// This handler only runs AFTER the gate (middleware/auth.ts) confirmed a valid session, so
// a 401 HERE is the management API rejecting OUR host token — a server/deploy misconfig, not
// an expired user session. Forwarding it would make the browser bounce a logged-in user to
// /login, where re-auth succeeds but the next call 401s again → a redirect loop. Surface it
// as a 502 (upstream failure) so the console shows an error instead of looping.
if (response.status === 401) {
throw createError({
statusCode: 502,
statusMessage:
"management API rejected the host token (check PUNKTFUNK_MGMT_TOKEN)",
});
}
},
});
});