Hash the web password and revoke sessions server-side
Store a scrypt hash (migrating a plaintext password without changing it), sign sessions with a generation that ./password and --revoke-all rotate, make logout a same-origin POST that revokes the token, add sign out everywhere, and close proxied websockets whose session ends. Enforce a strength rule for new passwords, back off logins per client and server-wide, check Origin on login, tighten next, add security headers and a __Host- cookie over https.
This commit is contained in:
+187
-79
@@ -18,14 +18,27 @@
|
||||
//
|
||||
// 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, randomBytes } from "node:crypto";
|
||||
import { createReadStream, readFileSync } from "node:fs";
|
||||
import { createReadStream } 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";
|
||||
import net from "node:net";
|
||||
import { sameOriginUpgrade } from "./src/proxySecurity.js";
|
||||
import { AuthStore, verifyPassword } from "./src/authStore.js";
|
||||
import { LoginLimiter, clientKey } from "./src/loginLimiter.js";
|
||||
import { PASSWORD_RULE } from "./src/passwordPolicy.js";
|
||||
import { SessionSockets } from "./src/sessionSockets.js";
|
||||
import {
|
||||
HOST_SESSION_COOKIE,
|
||||
SESSION_COOKIE,
|
||||
applySecurityHeaders,
|
||||
isHttps,
|
||||
pageHeaders,
|
||||
safeNext,
|
||||
sameOriginRequest,
|
||||
sessionCookieName,
|
||||
} from "./src/webSecurity.js";
|
||||
import { PeerRelay, proxyDiscovery } from "./src/peerRelay.js";
|
||||
|
||||
// The proxy's own directory holds the sign-in page's icons.
|
||||
@@ -46,20 +59,12 @@ const UPDATES = flag(process.argv, "--updates", "") ? resolve(flag(process.argv,
|
||||
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 store = AUTH_DISABLED ? null : new AuthStore(AUTH_FILE);
|
||||
|
||||
function loadAuth(fatal = true) {
|
||||
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 };
|
||||
}
|
||||
return store.load();
|
||||
} catch {
|
||||
// Fall through to the refusal below.
|
||||
}
|
||||
@@ -69,7 +74,41 @@ function loadAuth(fatal = true) {
|
||||
}
|
||||
let auth = loadAuth();
|
||||
|
||||
function refreshAuth() { auth = loadAuth(false); }
|
||||
// Every upgraded browser socket remembers its session token, so a sign-out,
|
||||
// a password change or an expiry closes it (on the event, and on a timer).
|
||||
const sockets = new SessionSockets();
|
||||
function sweepSockets() {
|
||||
sockets.sweep((token) => {
|
||||
try {
|
||||
return store.check(token) !== null;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Reloads the credential; a new password or secret closes every socket. */
|
||||
function refreshAuth() {
|
||||
const previous = auth;
|
||||
try {
|
||||
auth = loadAuth(false);
|
||||
} catch (error) {
|
||||
// Fail closed: an unusable credential file ends every open connection.
|
||||
sockets.sweep(() => false);
|
||||
throw error;
|
||||
}
|
||||
if (previous && auth && (previous.secret !== auth.secret || previous.generation !== auth.generation)) sweepSockets();
|
||||
}
|
||||
|
||||
const SWEEP_MS = Math.max(200, Number(process.env.PIPELINES_WEB_SWEEP_MS) || 5000);
|
||||
if (!AUTH_DISABLED) {
|
||||
setInterval(() => {
|
||||
try {
|
||||
refreshAuth();
|
||||
sweepSockets();
|
||||
} catch {}
|
||||
}, SWEEP_MS).unref();
|
||||
}
|
||||
|
||||
function cookieValue(req, name) {
|
||||
for (const part of String(req.headers.cookie ?? "").split(";")) {
|
||||
@@ -86,47 +125,44 @@ function cookieValue(req, name) {
|
||||
return "";
|
||||
}
|
||||
|
||||
function signSession(expires) {
|
||||
const payload = `${expires}.${randomBytes(18).toString("base64url")}`;
|
||||
return `${payload}.${createHmac("sha256", auth.secret).update(payload).digest("base64url")}`;
|
||||
/** The request's session token (the https cookie name first). */
|
||||
function sessionValue(req) {
|
||||
return cookieValue(req, HOST_SESSION_COOKIE) || cookieValue(req, SESSION_COOKIE);
|
||||
}
|
||||
|
||||
const SESSION_LONG_SECONDS = 30 * 24 * 60 * 60;
|
||||
const SESSION_SHORT_SECONDS = 12 * 60 * 60;
|
||||
|
||||
function sessionToken(remember = false) {
|
||||
const ttl = remember ? SESSION_LONG_SECONDS : SESSION_SHORT_SECONDS;
|
||||
return signSession(Math.floor(Date.now() / 1000) + ttl);
|
||||
}
|
||||
|
||||
function validSession(value) {
|
||||
if (!auth || typeof value !== "string") return false;
|
||||
const parts = value.split(".");
|
||||
if (parts.length !== 2 && parts.length !== 3) return false;
|
||||
const expires = parts[0], signature = parts.at(-1);
|
||||
if (!/^\d+$/.test(expires) || !signature) return false;
|
||||
const expected = createHmac("sha256", auth.secret).update(parts.slice(0, -1).join(".")).digest();
|
||||
let given;
|
||||
/** The request's live session, or null. */
|
||||
function session(req) {
|
||||
if (!auth) return null;
|
||||
try {
|
||||
given = Buffer.from(signature, "base64url");
|
||||
return store.check(sessionValue(req));
|
||||
} catch {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
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));
|
||||
return !auth || session(req) !== null;
|
||||
}
|
||||
|
||||
const peerRelay = new PeerRelay((req) => AUTH_DISABLED ? "test-auth-disabled" : cookieValue(req, SESSION_COOKIE));
|
||||
const peerRelay = new PeerRelay((req) => AUTH_DISABLED ? "test-auth-disabled" : sessionValue(req));
|
||||
|
||||
function passwordOk(candidate) {
|
||||
// Password checks are scrypt (32 MiB each); a few run at once and the rest
|
||||
// are answered 429 rather than queued without bound.
|
||||
const VERIFY_LIMIT = 4;
|
||||
let verifying = 0;
|
||||
async 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);
|
||||
const value = String(candidate ?? "");
|
||||
if (value.length > 4096) return false;
|
||||
verifying++;
|
||||
try {
|
||||
return await verifyPassword(auth.hash, value);
|
||||
} finally {
|
||||
verifying--;
|
||||
}
|
||||
}
|
||||
|
||||
function sessionCookie(req, remember = false) {
|
||||
@@ -134,40 +170,65 @@ function sessionCookie(req, remember = false) {
|
||||
// a top-level navigation, and a Strict cookie is withheld on that first
|
||||
// request, which made a remembered session look forgotten. Lax still keeps
|
||||
// the cookie off cross-site subresource and POST requests.
|
||||
const bits = [`${SESSION_COOKIE}=${sessionToken(remember)}`, "Path=/", "HttpOnly", "SameSite=Lax"];
|
||||
const { token } = store.issue(remember ? SESSION_LONG_SECONDS : SESSION_SHORT_SECONDS);
|
||||
const bits = [`${sessionCookieName(req)}=${token}`, "Path=/", "HttpOnly", "SameSite=Lax"];
|
||||
// Remember me persists the cookie; otherwise it is a browser-session cookie
|
||||
// (and the signed token itself expires after 12 hours).
|
||||
if (remember) {
|
||||
const expires = new Date(Date.now() + SESSION_LONG_SECONDS * 1000).toUTCString();
|
||||
bits.push(`Max-Age=${SESSION_LONG_SECONDS}`, `Expires=${expires}`);
|
||||
}
|
||||
// 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");
|
||||
// Tailscale terminates TLS and forwards the scheme; then the cookie is
|
||||
// Secure and host-locked (__Host-). A plain-http LAN visit keeps the plain name.
|
||||
if (isHttps(req)) 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);
|
||||
/** Set-Cookie values that clear both session cookie names. */
|
||||
function clearedCookies(req) {
|
||||
const cleared = [`${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`];
|
||||
if (isHttps(req)) cleared.push(`${HOST_SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Secure; Max-Age=0`);
|
||||
return cleared;
|
||||
}
|
||||
|
||||
function safeNext(value) {
|
||||
const next = String(value ?? "");
|
||||
return next.startsWith("/") && !next.startsWith("//") ? next : "/";
|
||||
/** Ends one session: server-side revocation, its relayed peers and sockets. */
|
||||
function signOut(req) {
|
||||
const token = sessionValue(req);
|
||||
peerRelay.forget(req);
|
||||
try {
|
||||
store.revoke(token);
|
||||
} catch {}
|
||||
sweepSockets();
|
||||
}
|
||||
|
||||
const limiter = new LoginLimiter();
|
||||
|
||||
function logoutPage() {
|
||||
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" />
|
||||
<title>Pipelines · sign out</title>
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
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: 24px; background: #17171b;
|
||||
border: 1px solid #2a2a31; border-radius: 16px; }
|
||||
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; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Sign out</h1>
|
||||
<p>Sign this browser out of Pipelines.</p>
|
||||
<form method="post" action="/logout"><button type="submit">Sign out</button></form>
|
||||
</main>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
function loginPage({ next = "/", error = "" } = {}) {
|
||||
@@ -212,7 +273,7 @@ function loginPage({ next = "/", error = "" } = {}) {
|
||||
<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, """)}" />
|
||||
<input type="hidden" name="next" value="${next.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<")}" />
|
||||
<label for="password">Password</label>
|
||||
<input id="password" name="password" type="password" autocomplete="current-password" autofocus required />
|
||||
<label class="remember"><input type="checkbox" name="remember" checked /> Remember me on this device</label>
|
||||
@@ -394,6 +455,7 @@ function proxyArtifact(req, res) {
|
||||
}
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
applySecurityHeaders(req, res);
|
||||
try { refreshAuth(); } catch {
|
||||
res.writeHead(503, { "Content-Type": "text/plain", "Cache-Control": "no-store" }).end("Web authentication unavailable");
|
||||
return;
|
||||
@@ -412,6 +474,10 @@ const server = createServer(async (req, res) => {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!auth && (pathname === "/api/session" || pathname === "/api/sessions/revoke-all")) {
|
||||
res.writeHead(404, { "Content-Type": "application/json", "Cache-Control": "no-store" }).end('{"error":"sign-in is disabled"}');
|
||||
return;
|
||||
}
|
||||
if (auth) {
|
||||
if (pathname === "/login" && req.method === "GET") {
|
||||
if (isAuthed(req)) {
|
||||
@@ -419,36 +485,54 @@ const server = createServer(async (req, res) => {
|
||||
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) }));
|
||||
res.writeHead(200, pageHeaders()).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." }));
|
||||
// Login CSRF: a cross-site form must not sign the browser in to this server.
|
||||
if (!sameOriginRequest(req)) {
|
||||
req.resume();
|
||||
res.writeHead(403, pageHeaders()).end(loginPage({ error: "Sign-in refused: the form came from another site." }));
|
||||
return;
|
||||
}
|
||||
if (!passwordOk(fields.get("password"))) {
|
||||
noteLoginFailure(address);
|
||||
const body = await readRequestBody(req).catch(() => "");
|
||||
const fields = new URLSearchParams(body);
|
||||
const key = clientKey(req);
|
||||
const wait = limiter.blocked(key);
|
||||
if (wait > 0 || verifying >= VERIFY_LIMIT) {
|
||||
const seconds = Math.max(1, Math.ceil(wait / 1000));
|
||||
res
|
||||
.writeHead(401, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" })
|
||||
.writeHead(429, pageHeaders({ "Retry-After": String(seconds) }))
|
||||
.end(loginPage({ next: safeNext(fields.get("next")), error: `Too many attempts. Wait ${seconds} seconds.` }));
|
||||
return;
|
||||
}
|
||||
if (!(await passwordOk(fields.get("password")))) {
|
||||
limiter.fail(key);
|
||||
res
|
||||
.writeHead(401, pageHeaders())
|
||||
.end(loginPage({ next: safeNext(fields.get("next")), error: "Wrong password." }));
|
||||
return;
|
||||
}
|
||||
limiter.succeed(key);
|
||||
const remember = fields.get("remember") === "on";
|
||||
res.setHeader("Set-Cookie", sessionCookie(req, remember));
|
||||
res.writeHead(303, { Location: safeNext(fields.get("next")) }).end();
|
||||
return;
|
||||
} else if (pathname === "/logout") {
|
||||
peerRelay.forget(req);
|
||||
res.setHeader("Set-Cookie", `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0`);
|
||||
} else if (pathname === "/logout" && req.method === "POST") {
|
||||
// Signing out is state-changing: POST from this origin only.
|
||||
if (!sameOriginRequest(req)) {
|
||||
req.resume();
|
||||
res.writeHead(403, pageHeaders()).end(logoutPage());
|
||||
return;
|
||||
}
|
||||
req.resume();
|
||||
signOut(req);
|
||||
res.setHeader("Set-Cookie", clearedCookies(req));
|
||||
res.writeHead(303, { Location: "/login" }).end();
|
||||
return;
|
||||
} else if (pathname === "/logout") {
|
||||
// A link (or a cross-site page) only reaches a confirmation button.
|
||||
res.writeHead(200, pageHeaders()).end(logoutPage());
|
||||
return;
|
||||
} else if (!isAuthed(req)) {
|
||||
const wantsHtml = String(req.headers.accept ?? "").includes("text/html");
|
||||
if (req.method === "GET" && wantsHtml && !pathname.startsWith("/api/") && !pathname.startsWith("/peers/")) {
|
||||
@@ -459,6 +543,28 @@ const server = createServer(async (req, res) => {
|
||||
.writeHead(401, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" })
|
||||
.end("Sign in required\n");
|
||||
return;
|
||||
} else if (pathname === "/api/session" && req.method === "GET") {
|
||||
const current = session(req);
|
||||
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" }).end(
|
||||
JSON.stringify({
|
||||
weak_password: auth.weak === true,
|
||||
password_rule: PASSWORD_RULE,
|
||||
expires_at: new Date(current.expires * 1000).toISOString(),
|
||||
}),
|
||||
);
|
||||
return;
|
||||
} else if (pathname === "/api/sessions/revoke-all" && req.method === "POST") {
|
||||
req.resume();
|
||||
if (!sameOriginRequest(req)) {
|
||||
res.writeHead(403, { "Content-Type": "application/json", "Cache-Control": "no-store" }).end('{"error":"cross-site request refused"}');
|
||||
return;
|
||||
}
|
||||
peerRelay.forget(req);
|
||||
store.revokeAll();
|
||||
sweepSockets();
|
||||
res.setHeader("Set-Cookie", clearedCookies(req));
|
||||
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" }).end('{"revoked":true}');
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (pathname === "/api/discovery" && req.method === "GET") {
|
||||
@@ -576,6 +682,8 @@ server.on("upgrade", (req, clientSocket, clientHead) => {
|
||||
clientSocket.destroy();
|
||||
return;
|
||||
}
|
||||
// Closed again when this session is signed out, revoked or expires.
|
||||
if (auth) sockets.track(clientSocket, sessionValue(req));
|
||||
if (peerRelay.upgrade(req, clientSocket, clientHead)) return;
|
||||
if (pathname !== "/connect") {
|
||||
clientSocket.destroy();
|
||||
|
||||
Reference in New Issue
Block a user