web: gated access, anchored viewers, mobile tabs and chat colour
- serve.mjs requires a signed session cookie for every page, artifact and the WebSocket, with a password file, 30-day sessions, login throttling and public brand assets for the sign-in page. - The diff viewer is a fixed-height top-anchored panel whose toolbar (modes, copy, previous, next, close as icons) is its first row; the artifact viewer is likewise a fixed frame so its navigation never moves. - The audit's selected tab uses the app's normal selected surface and bottom accent. Sessions that were not recorded say so plainly. - Chat code blocks are syntax-coloured; graph pinch-zoom works with two fingers while a single pointer still pans and clicks nodes. - Phones always keep the destination bar (pane collapse is wide-only), with the destinations spread evenly and Search on the right; the list default width is narrower; the theme colour matches the app. - Code-format and layout tests, plus the full browser suite, pass.
This commit is contained in:
+252
@@ -16,6 +16,9 @@
|
||||
//
|
||||
// The default host is 127.0.0.1. Use --host 0.0.0.0 only on a trusted LAN/VPN.
|
||||
import { createServer, request } from "node:http";
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { readFile, stat } from "node:fs/promises";
|
||||
import { extname, join, normalize, resolve, sep } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -23,6 +26,196 @@ import net from "node:net";
|
||||
|
||||
const ROOT = resolve(fileURLToPath(new URL(".", import.meta.url)));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Access control
|
||||
//
|
||||
// The proxy can be reached from a tailnet, so it refuses to serve anything
|
||||
// without a session cookie. The password and cookie secret live in a 0600 file
|
||||
// outside the repository; tests may disable the gate explicitly.
|
||||
// ---------------------------------------------------------------------------
|
||||
const AUTH_DISABLED = process.env.PIPELINES_WEB_AUTH === "disabled";
|
||||
const AUTH_FILE =
|
||||
process.env.PIPELINES_WEB_AUTH_FILE ?? join(homedir(), ".config", "pipelines", "web-auth.json");
|
||||
const SESSION_COOKIE = "pipelines_session";
|
||||
const SESSION_TTL_SECONDS = 30 * 24 * 60 * 60;
|
||||
|
||||
function loadAuth() {
|
||||
if (AUTH_DISABLED) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(AUTH_FILE, "utf8"));
|
||||
if (
|
||||
typeof parsed.password === "string" &&
|
||||
parsed.password.length >= 8 &&
|
||||
typeof parsed.secret === "string" &&
|
||||
parsed.secret.length >= 32
|
||||
) {
|
||||
return { password: parsed.password, secret: parsed.secret };
|
||||
}
|
||||
} catch {
|
||||
// Fall through to the refusal below.
|
||||
}
|
||||
console.error(
|
||||
`web auth: refusing to start without ${AUTH_FILE} (or PIPELINES_WEB_AUTH=disabled for tests)`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
const auth = loadAuth();
|
||||
|
||||
function cookieValue(req, name) {
|
||||
for (const part of String(req.headers.cookie ?? "").split(";")) {
|
||||
const i = part.indexOf("=");
|
||||
if (i < 0) continue;
|
||||
if (part.slice(0, i).trim() === name) {
|
||||
try {
|
||||
return decodeURIComponent(part.slice(i + 1).trim());
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function signSession(expires) {
|
||||
return `${expires}.${createHmac("sha256", auth.secret).update(String(expires)).digest("base64url")}`;
|
||||
}
|
||||
|
||||
function sessionToken() {
|
||||
return signSession(Math.floor(Date.now() / 1000) + SESSION_TTL_SECONDS);
|
||||
}
|
||||
|
||||
function validSession(value) {
|
||||
if (!auth || typeof value !== "string") return false;
|
||||
const [expires, signature] = value.split(".");
|
||||
if (!expires || !signature) return false;
|
||||
const expected = createHmac("sha256", auth.secret).update(expires).digest();
|
||||
let given;
|
||||
try {
|
||||
given = Buffer.from(signature, "base64url");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (given.length !== expected.length || !timingSafeEqual(given, expected)) return false;
|
||||
return Number(expires) > Math.floor(Date.now() / 1000);
|
||||
}
|
||||
|
||||
function isAuthed(req) {
|
||||
return !auth || validSession(cookieValue(req, SESSION_COOKIE));
|
||||
}
|
||||
|
||||
function passwordOk(candidate) {
|
||||
if (!auth) return true;
|
||||
const given = Buffer.from(String(candidate ?? ""));
|
||||
const expected = Buffer.from(auth.password);
|
||||
return given.length === expected.length && timingSafeEqual(given, expected);
|
||||
}
|
||||
|
||||
function sessionCookie(req) {
|
||||
const bits = [
|
||||
`${SESSION_COOKIE}=${sessionToken()}`,
|
||||
"Path=/",
|
||||
"HttpOnly",
|
||||
"SameSite=Strict",
|
||||
`Max-Age=${SESSION_TTL_SECONDS}`,
|
||||
];
|
||||
// Tailscale terminates TLS and usually forwards the scheme; when it does, the
|
||||
// cookie is Secure. A direct plain-http LAN visit still works without it.
|
||||
const forwarded = String(req.headers["x-forwarded-proto"] ?? "").split(",")[0].trim();
|
||||
if (forwarded === "https") bits.push("Secure");
|
||||
return bits.join("; ");
|
||||
}
|
||||
|
||||
/** Small per-address brake on password guessing. */
|
||||
const loginFailures = new Map();
|
||||
function loginBlocked(address) {
|
||||
const entry = loginFailures.get(address);
|
||||
return Boolean(entry && entry.until > Date.now());
|
||||
}
|
||||
function noteLoginFailure(address) {
|
||||
const now = Date.now();
|
||||
const entry = loginFailures.get(address) ?? { count: 0, until: 0 };
|
||||
entry.count += 1;
|
||||
if (entry.count >= 8) {
|
||||
entry.count = 0;
|
||||
entry.until = now + 30_000;
|
||||
}
|
||||
loginFailures.set(address, entry);
|
||||
}
|
||||
|
||||
function safeNext(value) {
|
||||
const next = String(value ?? "");
|
||||
return next.startsWith("/") && !next.startsWith("//") ? next : "/";
|
||||
}
|
||||
|
||||
function loginPage({ next = "/", error = "" } = {}) {
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="robots" content="noindex" />
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<meta name="theme-color" content="#0a0a0b" />
|
||||
<title>Pipelines · sign in</title>
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-height: 100vh; display: grid; place-items: center;
|
||||
background: #101013; color: #e8e8ea;
|
||||
font: 14px/1.5 ui-sans-serif, -apple-system, "Segoe UI", sans-serif; }
|
||||
main { width: min(360px, calc(100vw - 32px)); padding: 28px 24px 22px;
|
||||
background: #17171b; border: 1px solid #2a2a31; border-radius: 16px; }
|
||||
.mark { width: 40px; height: 40px; border-radius: 10px; display: block;
|
||||
border: 1px solid #2a2a31; background: #101013; }
|
||||
h1 { margin: 14px 0 4px; font-size: 20px; }
|
||||
p { margin: 0 0 18px; color: #9a9aa2; font-size: 13px; }
|
||||
label { display: block; font-size: 12px; color: #b8b8c0; margin-bottom: 6px; }
|
||||
input { width: 100%; padding: 11px 12px; border-radius: 9px; border: 1px solid #33333c;
|
||||
background: #101013; color: #e8e8ea; font: inherit; }
|
||||
input:focus { outline: 2px solid #8fa8c8; outline-offset: 1px; }
|
||||
button { width: 100%; margin-top: 14px; padding: 11px 12px; border: 0; border-radius: 9px;
|
||||
background: #8fa8c8; color: #101013; font: inherit; font-weight: 650; cursor: pointer; }
|
||||
.error { margin: 10px 0 0; color: #e08a8a; font-size: 13px; }
|
||||
.hint { margin: 16px 0 0; font-size: 11px; color: #77777f; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<img class="mark" src="/favicon.svg" alt="" width="40" height="40" />
|
||||
<h1>Pipelines</h1>
|
||||
<p>Sign in to reach this server.</p>
|
||||
<form method="post" action="/login">
|
||||
<input type="hidden" name="next" value="${next.replace(/"/g, """)}" />
|
||||
<label for="password">Password</label>
|
||||
<input id="password" name="password" type="password" autocomplete="current-password" autofocus required />
|
||||
${error ? `<p class="error">${error}</p>` : ""}
|
||||
<button type="submit">Sign in</button>
|
||||
</form>
|
||||
<p class="hint">The session lasts 30 days on this device.</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
function readRequestBody(req, limit = 4096) {
|
||||
return new Promise((resolveBody, rejectBody) => {
|
||||
let size = 0;
|
||||
const chunks = [];
|
||||
req.on("data", (chunk) => {
|
||||
size += chunk.length;
|
||||
if (size > limit) {
|
||||
rejectBody(new Error("request too large"));
|
||||
req.destroy();
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
req.on("end", () => resolveBody(Buffer.concat(chunks).toString("utf8")));
|
||||
req.on("error", rejectBody);
|
||||
});
|
||||
}
|
||||
|
||||
const MIME = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
@@ -123,6 +316,59 @@ function proxyArtifact(req, res) {
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
const pathname = (req.url ?? "/").split("?")[0];
|
||||
if (auth) {
|
||||
// Brand assets are public so the sign-in page itself can show the app icon.
|
||||
if (
|
||||
req.method === "GET" &&
|
||||
(pathname === "/favicon.svg" || pathname === "/apple-touch-icon.png")
|
||||
) {
|
||||
// fall through to the static handler below
|
||||
} else if (pathname === "/login" && req.method === "GET") {
|
||||
if (isAuthed(req)) {
|
||||
res.writeHead(302, { Location: "/" }).end();
|
||||
return;
|
||||
}
|
||||
const next = new URL(req.url ?? "/login", "http://localhost").searchParams.get("next") ?? "/";
|
||||
res
|
||||
.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" })
|
||||
.end(loginPage({ next: safeNext(next) }));
|
||||
return;
|
||||
} else if (pathname === "/login" && req.method === "POST") {
|
||||
const body = await readRequestBody(req).catch(() => "");
|
||||
const fields = new URLSearchParams(body);
|
||||
const address = req.socket.remoteAddress ?? "";
|
||||
if (loginBlocked(address)) {
|
||||
res
|
||||
.writeHead(429, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" })
|
||||
.end(loginPage({ error: "Too many attempts. Wait 30 seconds." }));
|
||||
return;
|
||||
}
|
||||
if (!passwordOk(fields.get("password"))) {
|
||||
noteLoginFailure(address);
|
||||
res
|
||||
.writeHead(401, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" })
|
||||
.end(loginPage({ next: safeNext(fields.get("next")), error: "Wrong password." }));
|
||||
return;
|
||||
}
|
||||
res.setHeader("Set-Cookie", sessionCookie(req));
|
||||
res.writeHead(303, { Location: safeNext(fields.get("next")) }).end();
|
||||
return;
|
||||
} else if (pathname === "/logout") {
|
||||
res.setHeader("Set-Cookie", `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0`);
|
||||
res.writeHead(303, { Location: "/login" }).end();
|
||||
return;
|
||||
} else if (!isAuthed(req)) {
|
||||
const wantsHtml = String(req.headers.accept ?? "").includes("text/html");
|
||||
if (req.method === "GET" && wantsHtml) {
|
||||
res.writeHead(302, { Location: `/login?next=${encodeURIComponent(req.url ?? "/")}` }).end();
|
||||
return;
|
||||
}
|
||||
res
|
||||
.writeHead(401, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" })
|
||||
.end("Sign in required\n");
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (pathname.startsWith("/artifacts/")) {
|
||||
proxyArtifact(req, res);
|
||||
return;
|
||||
@@ -208,6 +454,11 @@ function proxyUpgrade(req, clientSocket, clientHead) {
|
||||
|
||||
server.on("upgrade", (req, clientSocket, clientHead) => {
|
||||
const pathname = (req.url ?? "").split("?")[0];
|
||||
if (auth && !isAuthed(req)) {
|
||||
clientSocket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
|
||||
clientSocket.destroy();
|
||||
return;
|
||||
}
|
||||
if (pathname !== "/connect") {
|
||||
clientSocket.destroy();
|
||||
return;
|
||||
@@ -221,4 +472,5 @@ server.listen(port, host, () => {
|
||||
const shown = host === "0.0.0.0" ? "127.0.0.1" : host;
|
||||
console.log(`web spike: http://${shown}:${port}/ (bound ${host}:${port})`);
|
||||
console.log(`proxying /connect (ws) and /artifacts/ (http) -> ${targetHost}:${targetPort}`);
|
||||
console.log(auth ? "auth: sign-in required" : "auth: DISABLED (tests)");
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user