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();
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
// The web sign-in credential and its sessions.
|
||||
//
|
||||
// web-auth.json (0600, outside the repository) holds:
|
||||
// password_hash "scrypt$N$r$p$<salt>$<key>" (unpadded base64url); the same
|
||||
// hash scripts/password.py writes and the Go server verifies
|
||||
// for step-up re-authentication
|
||||
// password_weak true when the stored password predates the strength rule
|
||||
// secret the cookie HMAC key
|
||||
// generation bumped (with a new secret) by every password change and by
|
||||
// `./password --revoke-all`
|
||||
// A file still holding a plaintext "password" is migrated to a hash the first
|
||||
// time it is loaded; the password itself does not change.
|
||||
//
|
||||
// Sessions are signed tokens "v2.<generation>.<issued ms>.<expires s>.<id>.<mac>".
|
||||
// <auth file>.sessions.json (0600, written only by this proxy) records signed
|
||||
// out token ids until they expire and a "not_before" time for "sign out
|
||||
// everywhere" from Settings.
|
||||
import { createHmac, randomBytes, scrypt, scryptSync, timingSafeEqual } from "node:crypto";
|
||||
import { closeSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeSync } from "node:fs";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
import { passwordProblem } from "./passwordPolicy.js";
|
||||
|
||||
export const SCRYPT = { N: 1 << 15, r: 8, p: 1, keyLength: 32 };
|
||||
const MAXMEM = 64 * 1024 * 1024;
|
||||
/** Signed-out token ids kept until they expire; the soonest to expire go first. */
|
||||
export const REVOKED_LIMIT = 10000;
|
||||
|
||||
const b64 = (buffer) => Buffer.from(buffer).toString("base64url");
|
||||
|
||||
export function hashPassword(password, { N, r, p, keyLength } = SCRYPT) {
|
||||
const salt = randomBytes(16);
|
||||
const key = scryptSync(String(password), salt, keyLength, { N, r, p, maxmem: MAXMEM });
|
||||
return `scrypt$${N}$${r}$${p}$${b64(salt)}$${b64(key)}`;
|
||||
}
|
||||
|
||||
export function parseHash(value) {
|
||||
const parts = String(value ?? "").split("$");
|
||||
if (parts.length !== 6 || parts[0] !== "scrypt") return null;
|
||||
const [N, r, p] = parts.slice(1, 4).map((part) => (/^\d{1,7}$/.test(part) ? Number(part) : 0));
|
||||
const salt = Buffer.from(parts[4], "base64url");
|
||||
const key = Buffer.from(parts[5], "base64url");
|
||||
if (N < 2 || N > 1 << 20 || (N & (N - 1)) !== 0 || r < 1 || r > 32 || p < 1 || p > 16) return null;
|
||||
if (salt.length < 8 || key.length < 16 || key.length > 64) return null;
|
||||
return { N, r, p, salt, key };
|
||||
}
|
||||
|
||||
/** Constant-time check of candidate against a stored hash. */
|
||||
export function verifyPassword(stored, candidate) {
|
||||
const parsed = parseHash(stored);
|
||||
if (!parsed) return Promise.resolve(false);
|
||||
const { N, r, p, salt, key } = parsed;
|
||||
return new Promise((done) => {
|
||||
scrypt(String(candidate ?? ""), salt, key.length, { N, r, p, maxmem: MAXMEM }, (error, derived) => {
|
||||
done(!error && derived.length === key.length && timingSafeEqual(derived, key));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Writes data to path through a private temporary file and a rename. */
|
||||
function writePrivateAtomic(path, text, unchanged) {
|
||||
const temporary = join(dirname(path), `.${basename(path)}.${randomBytes(6).toString("hex")}`);
|
||||
const fd = openSync(temporary, "wx", 0o600);
|
||||
try {
|
||||
writeSync(fd, text);
|
||||
fsyncSync(fd);
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
try {
|
||||
if (unchanged && !unchanged()) throw new Error("file changed during the update");
|
||||
renameSync(temporary, path);
|
||||
} catch (error) {
|
||||
try {
|
||||
unlinkSync(temporary);
|
||||
} catch {}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const signature = (info) => `${info.dev}:${info.ino}:${info.mtimeMs}:${info.size}`;
|
||||
|
||||
export class AuthStore {
|
||||
constructor(file, { now = Date.now, log = (line) => console.error(line) } = {}) {
|
||||
this.file = file;
|
||||
this.sessionsFile = `${file}.sessions.json`;
|
||||
this.now = now;
|
||||
this.log = log;
|
||||
this.state = null;
|
||||
this.stamp = "";
|
||||
this.notBefore = 0;
|
||||
this.revoked = new Map(); // id -> expires (seconds)
|
||||
this.revokedGeneration = null;
|
||||
this.loadSessions();
|
||||
}
|
||||
|
||||
/** The current credential; throws when the file is missing or invalid. */
|
||||
load() {
|
||||
const info = lstatSync(this.file);
|
||||
if (!info.isFile()) throw new Error("web auth file is not a regular file");
|
||||
if (this.state && signature(info) === this.stamp) return this.state;
|
||||
const parsed = JSON.parse(readFileSync(this.file, "utf8"));
|
||||
if (!parsed || typeof parsed !== "object" || typeof parsed.secret !== "string" || parsed.secret.length < 32)
|
||||
throw new Error("web auth file has no valid secret");
|
||||
let hash = parsed.password_hash;
|
||||
let weak = parsed.password_weak === true;
|
||||
if (typeof hash !== "string" && typeof parsed.password === "string" && parsed.password.length >= 8) {
|
||||
({ hash, weak } = this.migrate(parsed, info));
|
||||
}
|
||||
if (!parseHash(hash)) throw new Error("web auth file has no valid password hash");
|
||||
const generation = Number.isSafeInteger(parsed.generation) && parsed.generation >= 0 ? parsed.generation : 0;
|
||||
this.state = { hash, weak, secret: parsed.secret, generation };
|
||||
// Re-stat: a successful migration replaced the file.
|
||||
try {
|
||||
this.stamp = signature(lstatSync(this.file));
|
||||
} catch {
|
||||
this.stamp = "";
|
||||
}
|
||||
if (this.revokedGeneration !== generation) {
|
||||
// A new generation already invalidates every older token.
|
||||
this.revoked.clear();
|
||||
this.notBefore = 0;
|
||||
this.revokedGeneration = generation;
|
||||
}
|
||||
return this.state;
|
||||
}
|
||||
|
||||
/** Replaces a plaintext password by its hash, keeping the password itself. */
|
||||
migrate(parsed, info) {
|
||||
const hash = hashPassword(parsed.password);
|
||||
const weak = passwordProblem(parsed.password) !== null;
|
||||
const next = { ...parsed, password_hash: hash, password_weak: weak };
|
||||
delete next.password;
|
||||
if (this.state) {
|
||||
// A plaintext password written over a running proxy's file is a password
|
||||
// change: like ./password, it signs every session out.
|
||||
const generation = Number.isSafeInteger(parsed.generation) && parsed.generation >= 0 ? parsed.generation : 0;
|
||||
next.generation = generation + 1;
|
||||
next.secret = randomBytes(48).toString("base64url");
|
||||
parsed.generation = next.generation;
|
||||
parsed.secret = next.secret;
|
||||
}
|
||||
try {
|
||||
writePrivateAtomic(this.file, `${JSON.stringify(next, null, 2)}\n`, () => {
|
||||
const current = lstatSync(this.file);
|
||||
return signature(current) === signature(info);
|
||||
});
|
||||
this.log(`web auth: stored the sign-in password as a scrypt hash${weak ? "; it is weak, choose a stronger one with ./password" : ""}`);
|
||||
} catch (error) {
|
||||
// Signing in keeps working from the in-memory hash until the file changes.
|
||||
this.log(`web auth: could not migrate the password file to a hash (${error.message})`);
|
||||
}
|
||||
return { hash, weak };
|
||||
}
|
||||
|
||||
loadSessions() {
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(this.sessionsFile, "utf8"));
|
||||
this.revokedGeneration = Number.isSafeInteger(parsed.generation) ? parsed.generation : null;
|
||||
this.notBefore = Number.isFinite(parsed.not_before) ? parsed.not_before : 0;
|
||||
for (const [id, expires] of Object.entries(parsed.revoked ?? {}))
|
||||
if (/^[A-Za-z0-9_-]{8,64}$/.test(id) && Number.isFinite(expires)) this.revoked.set(id, expires);
|
||||
} catch {
|
||||
// No list yet (or unreadable): nothing has been signed out.
|
||||
}
|
||||
}
|
||||
|
||||
saveSessions() {
|
||||
const nowSeconds = Math.floor(this.now() / 1000);
|
||||
for (const [id, expires] of this.revoked) if (expires <= nowSeconds) this.revoked.delete(id);
|
||||
if (this.revoked.size > REVOKED_LIMIT) {
|
||||
const sorted = [...this.revoked].sort((a, b) => a[1] - b[1]);
|
||||
this.revoked = new Map(sorted.slice(sorted.length - REVOKED_LIMIT));
|
||||
}
|
||||
const body = {
|
||||
generation: this.revokedGeneration,
|
||||
not_before: this.notBefore,
|
||||
revoked: Object.fromEntries(this.revoked),
|
||||
};
|
||||
try {
|
||||
writePrivateAtomic(this.sessionsFile, `${JSON.stringify(body)}\n`);
|
||||
} catch (error) {
|
||||
// The revocation still holds in memory until the proxy restarts.
|
||||
this.log(`web auth: could not record signed-out sessions (${error.message})`);
|
||||
}
|
||||
}
|
||||
|
||||
mac(payload) {
|
||||
return createHmac("sha256", this.load().secret).update(payload).digest();
|
||||
}
|
||||
|
||||
/** A new signed session token valid for ttlSeconds. */
|
||||
issue(ttlSeconds) {
|
||||
const { generation } = this.load();
|
||||
const now = this.now();
|
||||
const expires = Math.floor(now / 1000) + ttlSeconds;
|
||||
const payload = `v2.${generation}.${now}.${expires}.${randomBytes(18).toString("base64url")}`;
|
||||
return { token: `${payload}.${b64(this.mac(payload))}`, expires };
|
||||
}
|
||||
|
||||
/** The session a token names, or null when it is forged, old or revoked. */
|
||||
check(token) {
|
||||
if (typeof token !== "string" || token.length > 256) return null;
|
||||
const parts = token.split(".");
|
||||
if (parts.length !== 6 || parts[0] !== "v2") return null;
|
||||
const [, generation, issued, expires, id, mac] = parts;
|
||||
if (![generation, issued, expires].every((part) => /^\d{1,16}$/.test(part))) return null;
|
||||
const state = this.load();
|
||||
const expected = this.mac(parts.slice(0, 5).join("."));
|
||||
const given = Buffer.from(mac, "base64url");
|
||||
if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null;
|
||||
if (Number(generation) !== state.generation) return null;
|
||||
if (Number(expires) <= Math.floor(this.now() / 1000)) return null;
|
||||
if (Number(issued) <= this.notBefore || this.revoked.has(id)) return null;
|
||||
return { id, expires: Number(expires), issued: Number(issued) };
|
||||
}
|
||||
|
||||
/** Signs one token out (server-side logout). */
|
||||
revoke(token) {
|
||||
const session = this.check(token);
|
||||
if (!session) return false;
|
||||
this.revoked.set(session.id, session.expires);
|
||||
this.saveSessions();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Signs every token issued so far out ("Sign out everywhere"). */
|
||||
revokeAll() {
|
||||
this.load();
|
||||
this.notBefore = Math.max(this.now(), this.notBefore + 1);
|
||||
this.revoked.clear();
|
||||
this.saveSessions();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// A brake on password guessing: per client exponential backoff after a few
|
||||
// free failures, plus a server-wide sliding window so many clients (or one
|
||||
// client behind many addresses) cannot keep guessing. The per-client map is
|
||||
// bounded; the least recently failed client is evicted first.
|
||||
|
||||
export class LoginLimiter {
|
||||
constructor({
|
||||
now = Date.now,
|
||||
freeFailures = 5,
|
||||
baseMs = 1000,
|
||||
maxMs = 15 * 60 * 1000,
|
||||
idleMs = 60 * 60 * 1000,
|
||||
maxKeys = 1024,
|
||||
globalLimit = 50,
|
||||
globalWindowMs = 5 * 60 * 1000,
|
||||
} = {}) {
|
||||
Object.assign(this, { now, freeFailures, baseMs, maxMs, idleMs, maxKeys, globalLimit, globalWindowMs });
|
||||
this.clients = new Map(); // key -> { count, until, last }; insertion order = recency
|
||||
this.recent = []; // failure times, oldest first, at most globalLimit
|
||||
}
|
||||
|
||||
prune(now) {
|
||||
while (this.recent.length && this.recent[0] <= now - this.globalWindowMs) this.recent.shift();
|
||||
}
|
||||
|
||||
/** Milliseconds key must wait before its next attempt (0: go ahead). */
|
||||
blocked(key) {
|
||||
const now = this.now();
|
||||
this.prune(now);
|
||||
let wait = 0;
|
||||
if (this.recent.length >= this.globalLimit) wait = this.recent[0] + this.globalWindowMs - now;
|
||||
const entry = this.clients.get(key);
|
||||
if (entry && now - entry.last > this.idleMs) this.clients.delete(key);
|
||||
else if (entry && entry.until > now) wait = Math.max(wait, entry.until - now);
|
||||
return Math.max(0, wait);
|
||||
}
|
||||
|
||||
fail(key) {
|
||||
const now = this.now();
|
||||
this.prune(now);
|
||||
this.recent.push(now);
|
||||
if (this.recent.length > this.globalLimit) this.recent.shift();
|
||||
const entry = this.clients.get(key) ?? { count: 0, until: 0, last: now };
|
||||
this.clients.delete(key);
|
||||
entry.count += 1;
|
||||
entry.last = now;
|
||||
if (entry.count >= this.freeFailures) {
|
||||
const doublings = Math.min(entry.count - this.freeFailures, 20);
|
||||
entry.until = now + Math.min(this.baseMs * 2 ** doublings, this.maxMs);
|
||||
}
|
||||
this.clients.set(key, entry);
|
||||
while (this.clients.size > this.maxKeys) this.clients.delete(this.clients.keys().next().value);
|
||||
}
|
||||
|
||||
succeed(key) {
|
||||
this.clients.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
const LOOPBACK = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
|
||||
|
||||
/**
|
||||
* The client a login attempt is charged to. Behind `tailscale serve` every
|
||||
* request arrives from loopback, so there (and only there: a loopback peer
|
||||
* that carries Tailscale's identity headers) the tailnet user, else the
|
||||
* forwarded address, names the client. Any other request is its socket
|
||||
* address. A local process could forge these headers, but it already runs on
|
||||
* the machine; the global window still bounds it.
|
||||
*/
|
||||
export function clientKey(req) {
|
||||
const address = req.socket?.remoteAddress ?? "";
|
||||
if (LOOPBACK.has(address) && Object.keys(req.headers).some((name) => name.startsWith("tailscale-"))) {
|
||||
const login = String(req.headers["tailscale-user-login"] ?? "").trim().toLowerCase();
|
||||
if (login) return `tailscale:${login.slice(0, 256)}`;
|
||||
const forwarded = String(req.headers["x-forwarded-for"] ?? "").split(",")[0].trim();
|
||||
if (forwarded) return `forwarded:${forwarded.slice(0, 64)}`;
|
||||
}
|
||||
return `address:${address}`;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// The strength rule for a new web password, kept in step with
|
||||
// scripts/password.py (which enforces it). The proxy only uses it to mark a
|
||||
// migrated plaintext password as weak, so Settings can warn about it once.
|
||||
|
||||
export const PASSWORD_RULE =
|
||||
"Use at least 16 characters, or a passphrase of 4 or more random words " +
|
||||
"separated by spaces or dashes (15 characters or more in all). Common words, " +
|
||||
"keyboard runs and repeated characters do not count towards the length.";
|
||||
|
||||
const COMMON = [
|
||||
"password", "passwort", "pipelines", "pipeline", "qwerty", "azerty", "letmein",
|
||||
"welcome", "admin", "administrator", "iloveyou", "monkey", "dragon", "master",
|
||||
"secret", "login", "changeme", "default", "football", "baseball", "sunshine",
|
||||
"princess", "shadow", "trustno", "superman", "hello", "test", "guest", "root",
|
||||
].sort((a, b) => b.length - a.length);
|
||||
const ROWS = ["qwertyuiop", "asdfghjkl", "zxcvbnm", "1234567890"];
|
||||
const SEPARATORS = /[\s\-_.,;:+/]+/g;
|
||||
|
||||
/** Removes runs of 3+ repeated characters and 4+ consecutive characters. */
|
||||
function withoutRuns(text) {
|
||||
const chars = [...text];
|
||||
const out = [];
|
||||
let i = 0;
|
||||
while (i < chars.length) {
|
||||
let j = i + 1;
|
||||
while (j < chars.length && chars[j] === chars[i]) j++;
|
||||
if (j - i >= 3) {
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
let run = 0;
|
||||
for (const step of [1, -1]) {
|
||||
j = i + 1;
|
||||
while (j < chars.length && chars[j].codePointAt(0) - chars[j - 1].codePointAt(0) === step) j++;
|
||||
if (j - i >= 4) {
|
||||
run = j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (run) {
|
||||
i = run;
|
||||
continue;
|
||||
}
|
||||
out.push(chars[i]);
|
||||
i++;
|
||||
}
|
||||
return out.join("");
|
||||
}
|
||||
|
||||
function substance(password) {
|
||||
let text = password.toLowerCase();
|
||||
for (const word of COMMON) text = text.split(word).join("");
|
||||
for (const row of ROWS)
|
||||
for (let size = row.length; size > 3; size--)
|
||||
for (let start = 0; start + size <= row.length; start++)
|
||||
text = text.split(row.slice(start, start + size)).join("");
|
||||
return withoutRuns(text).replace(SEPARATORS, "");
|
||||
}
|
||||
|
||||
/** Why a new password is too weak, or null. Lengths count code points. */
|
||||
export function passwordProblem(password) {
|
||||
const value = String(password ?? "");
|
||||
const length = [...value].length;
|
||||
if (length > 1024) return "Choose a password of at most 1024 characters.";
|
||||
const words = value.split(SEPARATORS).filter(Boolean).map((word) => word.toLowerCase());
|
||||
const passphrase =
|
||||
words.length >= 4 &&
|
||||
new Set(words).size >= 4 &&
|
||||
words.every((word) => [...word].length >= 3) &&
|
||||
length >= 15 &&
|
||||
[...substance(value)].length >= 12;
|
||||
if (passphrase) return null;
|
||||
if (length < 16) return `Too short. ${PASSWORD_RULE}`;
|
||||
if (new Set(value).size < 8 || [...substance(value)].length < 12) return `Too predictable. ${PASSWORD_RULE}`;
|
||||
return null;
|
||||
}
|
||||
@@ -61,6 +61,8 @@ export class PeerRelay extends PeerRegistry {
|
||||
"x-upload-name",
|
||||
"x-chat-file-name",
|
||||
"x-pipelines-upload-name",
|
||||
// The remote machine's own step-up token (POST /files).
|
||||
"x-pipelines-elevation",
|
||||
])
|
||||
if (req.headers[name]) headers[name] = req.headers[name];
|
||||
const upstream = remoteRequest(target.url, {
|
||||
|
||||
@@ -75,7 +75,7 @@ export function boundedRequest(
|
||||
export function sessionCookie(response) {
|
||||
return (response.headers["set-cookie"] ?? [])
|
||||
.map((value) => value.split(";")[0])
|
||||
.filter((value) => value.startsWith("pipelines_session="))
|
||||
.filter((value) => value.startsWith("pipelines_session=") || value.startsWith("__Host-pipelines_session="))
|
||||
.join("; ");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// The upgraded browser sockets (the /connect websocket and relayed peer
|
||||
// sockets), each with the session token it was opened with. A sweep destroys
|
||||
// every socket whose session is no longer valid: signed out, signed out
|
||||
// everywhere, expired, or issued before a password change.
|
||||
export class SessionSockets {
|
||||
constructor() {
|
||||
this.sockets = new Map(); // socket -> token
|
||||
}
|
||||
|
||||
track(socket, token) {
|
||||
this.sockets.set(socket, token);
|
||||
socket.once("close", () => this.sockets.delete(socket));
|
||||
}
|
||||
|
||||
get size() {
|
||||
return this.sockets.size;
|
||||
}
|
||||
|
||||
/** Destroys the sockets whose token valid() rejects; returns how many. */
|
||||
sweep(valid) {
|
||||
let closed = 0;
|
||||
for (const [socket, token] of this.sockets) {
|
||||
if (valid(token)) continue;
|
||||
this.sockets.delete(socket);
|
||||
socket.destroy();
|
||||
closed++;
|
||||
}
|
||||
return closed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// Browser-facing hygiene for the proxy: request origin checks, the post-login
|
||||
// redirect target, the session cookie's name and the security headers.
|
||||
import { sameOriginUpgrade } from "./proxySecurity.js";
|
||||
|
||||
export const SESSION_COOKIE = "pipelines_session";
|
||||
/** Over https the cookie is host-locked (Secure, Path=/, no Domain). */
|
||||
export const HOST_SESSION_COOKIE = "__Host-pipelines_session";
|
||||
|
||||
/** Whether the browser reached the proxy over https (Tailscale serve). */
|
||||
export function isHttps(req) {
|
||||
const forwarded = String(req.headers["x-forwarded-proto"] ?? "").split(",")[0].trim().toLowerCase();
|
||||
return forwarded === "https" || Boolean(req.socket?.encrypted);
|
||||
}
|
||||
|
||||
export function sessionCookieName(req) {
|
||||
return isHttps(req) ? HOST_SESSION_COOKIE : SESSION_COOKIE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a state-changing request comes from this origin. Browsers send
|
||||
* Origin on every POST; a native client (the app, curl, a peer proxy) sends
|
||||
* none and has no ambient cookies to abuse. `Origin: null` and a cross-site
|
||||
* Sec-Fetch-Site are refused.
|
||||
*/
|
||||
export function sameOriginRequest(req) {
|
||||
const origin = req.headers.origin;
|
||||
const site = req.headers["sec-fetch-site"];
|
||||
if (site && !["same-origin", "none"].includes(String(site))) return false;
|
||||
if (origin === undefined) return true;
|
||||
return sameOriginUpgrade(origin, req.headers.host);
|
||||
}
|
||||
|
||||
/**
|
||||
* The local path to return to after signing in: one "/" followed by anything
|
||||
* but "/" or "\" (which browsers treat as another host), no backslashes or
|
||||
* control characters anywhere, else "/".
|
||||
*/
|
||||
export function safeNext(value) {
|
||||
const next = String(value ?? "");
|
||||
if (next.length > 2048 || !/^\/(?![/\\])/.test(next) || /[\\\u0000-\u001f\u007f]/.test(next)) return "/";
|
||||
return next;
|
||||
}
|
||||
|
||||
/** The proxy's own pages (sign-in, sign-out) are never framed and run no script. */
|
||||
export const PAGE_POLICY =
|
||||
"default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; form-action 'self'; " +
|
||||
"frame-ancestors 'none'; base-uri 'none'";
|
||||
|
||||
/**
|
||||
* Headers every response starts with. The app frames only its own documents
|
||||
* (sandboxed srcdoc HTML previews), so same-origin framing stays allowed; a
|
||||
* response that sets its own value (for example a sandboxing CSP) overrides
|
||||
* these at writeHead. HSTS only on https.
|
||||
*/
|
||||
export function applySecurityHeaders(req, res) {
|
||||
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||
res.setHeader("Referrer-Policy", "same-origin");
|
||||
res.setHeader("X-Frame-Options", "SAMEORIGIN");
|
||||
res.setHeader("Content-Security-Policy", "frame-ancestors 'self'");
|
||||
if (isHttps(req)) res.setHeader("Strict-Transport-Security", "max-age=31536000");
|
||||
}
|
||||
|
||||
/** Marks a response as one of the proxy's own pages. */
|
||||
export function pageHeaders(extra = {}) {
|
||||
return {
|
||||
"Content-Type": "text/html; charset=utf-8",
|
||||
"Cache-Control": "no-store",
|
||||
"Content-Security-Policy": PAGE_POLICY,
|
||||
"X-Frame-Options": "DENY",
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import net from "node:net";
|
||||
import { once } from "node:events";
|
||||
import { hashPassword } from "../src/authStore.js";
|
||||
|
||||
const here = fileURLToPath(new URL("..", import.meta.url));
|
||||
const PASSWORD = "tulip orbit canyon ember";
|
||||
|
||||
async function freePort() {
|
||||
const server = net.createServer().listen(0, "127.0.0.1");
|
||||
await once(server, "listening");
|
||||
const { port } = server.address();
|
||||
await new Promise((done) => server.close(done));
|
||||
return port;
|
||||
}
|
||||
|
||||
/** A stand-in Pipelines server that accepts every websocket upgrade and holds it. */
|
||||
async function fakeUpstream(t) {
|
||||
const held = new Set();
|
||||
const server = net.createServer((socket) => {
|
||||
held.add(socket);
|
||||
socket.once("data", () => socket.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n"));
|
||||
socket.on("error", () => {});
|
||||
socket.on("close", () => held.delete(socket));
|
||||
}).listen(0, "127.0.0.1");
|
||||
await once(server, "listening");
|
||||
t.after(() => { for (const socket of held) socket.destroy(); return new Promise((done) => server.close(done)); });
|
||||
return server.address().port;
|
||||
}
|
||||
|
||||
async function startProxy(t, authData) {
|
||||
const dir = await mkdtemp(join(tmpdir(), "pipelines-auth-proxy-"));
|
||||
t.after(() => rm(dir, { recursive: true, force: true }));
|
||||
const auth = join(dir, "web-auth.json");
|
||||
await writeFile(auth, JSON.stringify(authData), { mode: 0o600 });
|
||||
const upstream = await fakeUpstream(t);
|
||||
const port = await freePort();
|
||||
const child = spawn(process.execPath, ["serve.mjs", "--port", String(port), "--root", join(dir, "absent"),
|
||||
"--pipelines", `127.0.0.1:${upstream}`], {
|
||||
cwd: here,
|
||||
env: { ...process.env, PIPELINES_WEB_AUTH: "", PIPELINES_WEB_AUTH_FILE: auth, PIPELINES_WEB_SWEEP_MS: "200" },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
t.after(async () => { const exited = once(child, "exit"); child.kill(); await exited; });
|
||||
await once(child.stdout, "data");
|
||||
const base = `http://127.0.0.1:${port}`;
|
||||
return { auth, port, base, host: `127.0.0.1:${port}` };
|
||||
}
|
||||
|
||||
const login = (proxy, headers = {}, password = PASSWORD) =>
|
||||
fetch(proxy.base + "/login", { method: "POST", body: new URLSearchParams({ password, next: "/runs/1" }), redirect: "manual", headers });
|
||||
const cookieOf = (response) => response.headers.get("set-cookie").split(";")[0];
|
||||
const signedIn = async (proxy, cookie) =>
|
||||
(await fetch(proxy.base + "/login", { headers: { Cookie: cookie }, redirect: "manual" })).status === 302;
|
||||
|
||||
/** Opens /connect through the proxy and resolves when the 101 arrives. */
|
||||
async function openSocket(proxy, cookie) {
|
||||
const socket = net.connect(proxy.port, "127.0.0.1");
|
||||
await once(socket, "connect");
|
||||
socket.write(`GET /connect HTTP/1.1\r\nHost: ${proxy.host}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
|
||||
`Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\nCookie: ${cookie}\r\n\r\n`);
|
||||
const [chunk] = await once(socket, "data");
|
||||
assert.match(chunk.toString(), /^HTTP\/1.1 101/);
|
||||
const closed = once(socket, "close");
|
||||
socket.on("error", () => {});
|
||||
return { socket, closed };
|
||||
}
|
||||
|
||||
const within = (promise, ms, what) =>
|
||||
Promise.race([promise, new Promise((_, fail) => setTimeout(() => fail(new Error(`${what} not within ${ms} ms`)), ms))]);
|
||||
|
||||
test("login: Origin check, safe next, headers and the cookie prefix", async (t) => {
|
||||
const proxy = await startProxy(t, { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40), generation: 0 });
|
||||
const cross = await login(proxy, { Origin: "https://evil.example" });
|
||||
assert.equal(cross.status, 403);
|
||||
assert.equal(cross.headers.get("set-cookie"), null);
|
||||
const page = await fetch(proxy.base + "/login?next=/%5Cevil.com");
|
||||
const html = await page.text();
|
||||
assert.match(html, /name="next" value="\/"/);
|
||||
assert.match(page.headers.get("content-security-policy"), /frame-ancestors 'none'/);
|
||||
assert.match(page.headers.get("content-security-policy"), /default-src 'none'/);
|
||||
assert.equal(page.headers.get("x-frame-options"), "DENY");
|
||||
assert.equal(page.headers.get("x-content-type-options"), "nosniff");
|
||||
assert.equal(page.headers.get("referrer-policy"), "same-origin");
|
||||
assert.equal(page.headers.get("strict-transport-security"), null);
|
||||
const ok = await login(proxy, { Origin: proxy.base });
|
||||
assert.equal(ok.status, 303);
|
||||
assert.equal(ok.headers.get("location"), "/runs/1");
|
||||
assert.match(ok.headers.get("set-cookie"), /^pipelines_session=v2\./);
|
||||
assert.doesNotMatch(ok.headers.get("set-cookie"), /Secure/);
|
||||
// An app response may be framed by the app itself only.
|
||||
const app = await fetch(proxy.base + "/runs/1", { headers: { Cookie: cookieOf(ok) } });
|
||||
assert.equal(app.headers.get("x-frame-options"), "SAMEORIGIN");
|
||||
assert.match(app.headers.get("content-security-policy"), /frame-ancestors 'self'/);
|
||||
// Over https (Tailscale serve): __Host- prefix, Secure, HSTS.
|
||||
const https = await login(proxy, { "X-Forwarded-Proto": "https" });
|
||||
const secure = https.headers.get("set-cookie");
|
||||
assert.match(secure, /^__Host-pipelines_session=v2\./);
|
||||
assert.match(secure, /; Path=\/;/);
|
||||
assert.match(secure, /; Secure/);
|
||||
assert.doesNotMatch(secure, /Domain=/i);
|
||||
assert.match(https.headers.get("strict-transport-security"), /max-age=\d+/);
|
||||
assert.equal(await signedIn(proxy, cookieOf(https)), true);
|
||||
// A native client (no Origin) still signs in.
|
||||
assert.equal((await login(proxy)).status, 303);
|
||||
});
|
||||
|
||||
test("logout is a same-origin POST that revokes the token and closes its sockets", async (t) => {
|
||||
const proxy = await startProxy(t, { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40) });
|
||||
const a = cookieOf(await login(proxy));
|
||||
const b = cookieOf(await login(proxy));
|
||||
const ws = await openSocket(proxy, a);
|
||||
const other = await openSocket(proxy, b);
|
||||
// GET only shows a button; a cross-site POST is refused.
|
||||
const page = await fetch(proxy.base + "/logout", { headers: { Cookie: a }, redirect: "manual" });
|
||||
assert.equal(page.status, 200);
|
||||
assert.match(await page.text(), /method="post" action="\/logout"/);
|
||||
assert.equal((await fetch(proxy.base + "/logout", { method: "POST", headers: { Cookie: a, Origin: "https://evil.example" }, redirect: "manual" })).status, 403);
|
||||
assert.equal(await signedIn(proxy, a), true);
|
||||
const out = await fetch(proxy.base + "/logout", { method: "POST", headers: { Cookie: a, Origin: proxy.base }, redirect: "manual" });
|
||||
assert.equal(out.status, 303);
|
||||
assert.match(out.headers.get("set-cookie"), /pipelines_session=; .*Max-Age=0/);
|
||||
// The copied cookie no longer works anywhere, and its socket is gone.
|
||||
assert.equal(await signedIn(proxy, a), false);
|
||||
await within(ws.closed, 2000, "the signed-out socket closing");
|
||||
assert.equal(await signedIn(proxy, b), true);
|
||||
assert.equal(other.socket.destroyed, false);
|
||||
other.socket.destroy();
|
||||
});
|
||||
|
||||
test("a password change revokes every session and closes open websockets", async (t) => {
|
||||
const data = { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40), generation: 4 };
|
||||
const proxy = await startProxy(t, data);
|
||||
const cookie = cookieOf(await login(proxy));
|
||||
const ws = await openSocket(proxy, cookie);
|
||||
// What ./password writes: a new hash, secret and generation, atomically.
|
||||
const next = { ...data, password_hash: hashPassword("ember canyon orbit tulip"), secret: "n".repeat(40), generation: 5 };
|
||||
await writeFile(proxy.auth + ".next", JSON.stringify(next), { mode: 0o600 });
|
||||
await rename(proxy.auth + ".next", proxy.auth);
|
||||
await within(ws.closed, 3000, "the websocket closing after the password change");
|
||||
assert.equal(await signedIn(proxy, cookie), false);
|
||||
assert.equal((await login(proxy)).status, 401);
|
||||
assert.equal((await login(proxy, {}, "ember canyon orbit tulip")).status, 303);
|
||||
});
|
||||
|
||||
test("sign out everywhere from Settings, the session report and the weak-password warning", async (t) => {
|
||||
const proxy = await startProxy(t, { password: "old-password", secret: "s".repeat(40) });
|
||||
// The migration kept the old password working and stored only a hash.
|
||||
const first = await login(proxy, {}, "old-password");
|
||||
assert.equal(first.status, 303);
|
||||
const stored = JSON.parse(await readFile(proxy.auth, "utf8"));
|
||||
assert.equal(stored.password, undefined);
|
||||
assert.match(stored.password_hash, /^scrypt\$/);
|
||||
const a = cookieOf(first);
|
||||
const b = cookieOf(await login(proxy, {}, "old-password"));
|
||||
assert.equal((await fetch(proxy.base + "/api/session")).status, 401);
|
||||
const report = await (await fetch(proxy.base + "/api/session", { headers: { Cookie: a } })).json();
|
||||
assert.equal(report.weak_password, true);
|
||||
assert.match(report.password_rule, /16 characters/);
|
||||
const ws = await openSocket(proxy, b);
|
||||
assert.equal((await fetch(proxy.base + "/api/sessions/revoke-all", { method: "POST", headers: { Cookie: a, Origin: "https://evil.example" } })).status, 403);
|
||||
const revoke = await fetch(proxy.base + "/api/sessions/revoke-all", { method: "POST", headers: { Cookie: a, Origin: proxy.base } });
|
||||
assert.equal(revoke.status, 200);
|
||||
assert.deepEqual(await revoke.json(), { revoked: true });
|
||||
await within(ws.closed, 2000, "every socket closing");
|
||||
assert.equal(await signedIn(proxy, a), false);
|
||||
assert.equal(await signedIn(proxy, b), false);
|
||||
assert.equal(await signedIn(proxy, cookieOf(await login(proxy, {}, "old-password"))), true);
|
||||
});
|
||||
|
||||
test("repeated wrong passwords are slowed down", async (t) => {
|
||||
const proxy = await startProxy(t, { password_hash: hashPassword(PASSWORD), secret: "s".repeat(40) });
|
||||
for (let i = 0; i < 5; i++) assert.equal((await login(proxy, {}, "wrong")).status, 401);
|
||||
const blocked = await login(proxy, {}, PASSWORD);
|
||||
assert.equal(blocked.status, 429);
|
||||
assert.ok(Number(blocked.headers.get("retry-after")) >= 1);
|
||||
});
|
||||
@@ -27,11 +27,14 @@ test("atomic password updates take effect without restart and fail closed on inv
|
||||
const cookie = first.headers.get("set-cookie").split(";")[0];
|
||||
await writeFile(auth + ".next", JSON.stringify({ ...data, password:"new-password" })); await rename(auth + ".next",auth);
|
||||
assert.equal((await login("old-password")).status,401);
|
||||
assert.equal((await login("new-password")).status,303);
|
||||
assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie},redirect:"manual"})).status,302);
|
||||
const second = await login("new-password"); assert.equal(second.status,303);
|
||||
// A changed password signs the earlier session out; the new one is signed in.
|
||||
assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie},redirect:"manual"})).status,200);
|
||||
const cookie2 = second.headers.get("set-cookie").split(";")[0];
|
||||
assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie2},redirect:"manual"})).status,302);
|
||||
await writeFile(auth + ".next", "malformed"); await rename(auth + ".next",auth);
|
||||
assert.equal((await login("new-password")).status,503);
|
||||
assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie},redirect:"manual"})).status,503);
|
||||
assert.equal((await fetch(base + "/login", {headers:{Cookie:cookie2},redirect:"manual"})).status,503);
|
||||
await writeFile(auth,JSON.stringify(data));
|
||||
assert.equal((await login("old-password")).status,303);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, readFile, rm, stat, writeFile, rename } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { AuthStore, REVOKED_LIMIT, hashPassword, parseHash, verifyPassword } from "../src/authStore.js";
|
||||
import { passwordProblem } from "../src/passwordPolicy.js";
|
||||
import { LoginLimiter, clientKey } from "../src/loginLimiter.js";
|
||||
import { safeNext, sameOriginRequest, isHttps, sessionCookieName } from "../src/webSecurity.js";
|
||||
import { SessionSockets } from "../src/sessionSockets.js";
|
||||
|
||||
const CHEAP = { N: 1024, r: 8, p: 1, keyLength: 32 };
|
||||
|
||||
async function fixture(t, data) {
|
||||
const dir = await mkdtemp(join(tmpdir(), "pipelines-auth-store-"));
|
||||
t.after(() => rm(dir, { recursive: true, force: true }));
|
||||
const file = join(dir, "web-auth.json");
|
||||
await writeFile(file, JSON.stringify(data), { mode: 0o600 });
|
||||
return file;
|
||||
}
|
||||
|
||||
const replace = async (file, data) => {
|
||||
await writeFile(`${file}.next`, JSON.stringify(data), { mode: 0o600 });
|
||||
await rename(`${file}.next`, file);
|
||||
};
|
||||
|
||||
test("hashes are scrypt with recorded parameters and verify in constant time", async () => {
|
||||
const stored = hashPassword("tulip orbit canyon ember", CHEAP);
|
||||
assert.match(stored, /^scrypt\$1024\$8\$1\$[A-Za-z0-9_-]+\$[A-Za-z0-9_-]+$/);
|
||||
assert.ok(parseHash(stored));
|
||||
assert.equal(await verifyPassword(stored, "tulip orbit canyon ember"), true);
|
||||
assert.equal(await verifyPassword(stored, "tulip orbit canyon embers"), false);
|
||||
assert.equal(await verifyPassword("scrypt$1000$8$1$AAAAAAAAAAA$BBBBBBBBBBBBBBBBBBBBBB", "x"), false);
|
||||
assert.equal(parseHash("plain"), null);
|
||||
});
|
||||
|
||||
test("a plaintext password migrates to a hash without changing it", async (t) => {
|
||||
const file = await fixture(t, { password: "old-password", secret: "s".repeat(40), other: "kept" });
|
||||
const logs = [];
|
||||
const store = new AuthStore(file, { log: (line) => logs.push(line) });
|
||||
const state = store.load();
|
||||
const written = JSON.parse(await readFile(file, "utf8"));
|
||||
assert.equal(written.password, undefined);
|
||||
assert.equal(written.other, "kept");
|
||||
assert.equal(written.password_weak, true);
|
||||
assert.equal(written.secret, "s".repeat(40)); // first start: sessions stay valid
|
||||
assert.equal(state.weak, true);
|
||||
assert.equal(await verifyPassword(written.password_hash, "old-password"), true);
|
||||
assert.equal((await stat(file)).mode & 0o777, 0o600);
|
||||
assert.ok(!logs.join("\n").includes("old-password"));
|
||||
// A strong plaintext is not flagged.
|
||||
const strong = await fixture(t, { password: "tulip orbit canyon ember", secret: "s".repeat(40) });
|
||||
assert.equal(new AuthStore(strong, { log() {} }).load().weak, false);
|
||||
});
|
||||
|
||||
test("a plaintext password written over a running proxy signs every session out", async (t) => {
|
||||
const file = await fixture(t, { password_hash: hashPassword("first passphrase here ok", CHEAP), secret: "s".repeat(40), generation: 3 });
|
||||
const store = new AuthStore(file, { log() {} });
|
||||
const { token } = store.issue(60);
|
||||
await replace(file, { password: "new-password", secret: "s".repeat(40), generation: 3 });
|
||||
assert.equal(store.check(token), null);
|
||||
const written = JSON.parse(await readFile(file, "utf8"));
|
||||
assert.equal(written.generation, 4);
|
||||
assert.notEqual(written.secret, "s".repeat(40));
|
||||
});
|
||||
|
||||
test("tokens: signature, expiry, generation, logout and sign out everywhere", async (t) => {
|
||||
let now = 1_800_000_000_000;
|
||||
const data = { password_hash: hashPassword("tulip orbit canyon ember", CHEAP), secret: "s".repeat(40), generation: 1 };
|
||||
const file = await fixture(t, data);
|
||||
const store = new AuthStore(file, { now: () => now, log() {} });
|
||||
const a = store.issue(60).token;
|
||||
const b = store.issue(3600).token;
|
||||
assert.ok(store.check(a));
|
||||
assert.equal(store.check(a.slice(0, -2) + (a.endsWith("A") ? "BB" : "AA")), null);
|
||||
assert.equal(store.check(a.replace(/^v2\.1\./, "v2.2.")), null);
|
||||
assert.equal(store.check("1800000000.abc.def"), null); // the old unversioned format
|
||||
// Server-side logout of one token leaves the other.
|
||||
assert.equal(store.revoke(a), true);
|
||||
assert.equal(store.check(a), null);
|
||||
assert.ok(store.check(b));
|
||||
// The list survives a proxy restart.
|
||||
assert.equal(new AuthStore(file, { now: () => now, log() {} }).check(a), null);
|
||||
assert.equal(((await stat(`${file}.sessions.json`)).mode & 0o777), 0o600);
|
||||
// Expiry.
|
||||
now += 61_000;
|
||||
const c = store.issue(60).token;
|
||||
now += 1000;
|
||||
assert.ok(store.check(c));
|
||||
now += 60_000;
|
||||
assert.equal(store.check(c), null);
|
||||
// Sign out everywhere: every earlier token, but not a later sign-in.
|
||||
const d = store.issue(3600).token;
|
||||
now += 1;
|
||||
store.revokeAll();
|
||||
assert.equal(store.check(b), null);
|
||||
assert.equal(store.check(d), null);
|
||||
now += 1;
|
||||
const e = store.issue(3600).token;
|
||||
assert.ok(store.check(e));
|
||||
assert.ok(new AuthStore(file, { now: () => now, log() {} }).check(e));
|
||||
assert.equal(new AuthStore(file, { now: () => now, log() {} }).check(d), null);
|
||||
// ./password (new secret and generation) ends every session.
|
||||
await replace(file, { ...data, secret: "t".repeat(40), generation: 2 });
|
||||
assert.equal(store.check(e), null);
|
||||
const f = store.issue(3600).token;
|
||||
assert.ok(store.check(f));
|
||||
});
|
||||
|
||||
test("the signed-out list is bounded, dropping the soonest to expire", async (t) => {
|
||||
const file = await fixture(t, { password_hash: hashPassword("tulip orbit canyon ember", CHEAP), secret: "s".repeat(40) });
|
||||
const store = new AuthStore(file, { now: () => 1_000_000, log() {} });
|
||||
store.load();
|
||||
for (let i = 0; i < REVOKED_LIMIT + 5; i++) store.revoked.set(`token-id-${String(i).padStart(6, "0")}`, 10_000 + i);
|
||||
store.saveSessions();
|
||||
assert.equal(store.revoked.size, REVOKED_LIMIT);
|
||||
assert.ok(!store.revoked.has("token-id-000000"));
|
||||
assert.ok(store.revoked.has(`token-id-${String(REVOKED_LIMIT + 4).padStart(6, "0")}`));
|
||||
});
|
||||
|
||||
test("the strength rule matches scripts/password.py", () => {
|
||||
for (const strong of ["tulip orbit canyon ember", "correct horse battery staple", "k7#Rv9!qLm2@Xz4s", "cat dog sun red"])
|
||||
assert.equal(passwordProblem(strong), null, strong);
|
||||
for (const weak of ["short", "old password", "J8m!x2Lq0#vR9tZ", "password password password", "a".repeat(20),
|
||||
"Password12345678!", "qwertyuiop1234567890", "password welcome admin letmein", "dog dog dog dog dog"])
|
||||
assert.notEqual(passwordProblem(weak), null, weak);
|
||||
});
|
||||
|
||||
test("limiter: per-client backoff, success reset, global cap and bounded eviction", () => {
|
||||
let now = 0;
|
||||
const limiter = new LoginLimiter({ now: () => now, freeFailures: 3, baseMs: 1000, maxKeys: 4, globalLimit: 10, globalWindowMs: 60_000 });
|
||||
for (let i = 0; i < 2; i++) limiter.fail("a");
|
||||
assert.equal(limiter.blocked("a"), 0);
|
||||
limiter.fail("a");
|
||||
assert.equal(limiter.blocked("a"), 1000);
|
||||
limiter.fail("a");
|
||||
assert.equal(limiter.blocked("a"), 2000); // doubles
|
||||
assert.equal(limiter.blocked("b"), 0);
|
||||
limiter.succeed("a");
|
||||
assert.equal(limiter.blocked("a"), 0);
|
||||
// Eviction keeps at most maxKeys clients, the least recent leaving first.
|
||||
for (const key of ["k1", "k2", "k3", "k4", "k5"]) limiter.fail(key);
|
||||
assert.equal(limiter.clients.size, 4);
|
||||
assert.ok(!limiter.clients.has("k1"));
|
||||
// The global window: ten failures from anyone block everyone.
|
||||
now = 120_000;
|
||||
for (let i = 0; i < 10; i++) limiter.fail(`spread-${i}`);
|
||||
assert.ok(limiter.blocked("someone-new") > 0);
|
||||
assert.ok(limiter.recent.length <= 10);
|
||||
now += 60_000;
|
||||
assert.equal(limiter.blocked("someone-new"), 0);
|
||||
});
|
||||
|
||||
test("the limiter charges Tailscale users only behind a loopback Tailscale proxy", () => {
|
||||
const req = (address, headers) => ({ socket: { remoteAddress: address }, headers });
|
||||
assert.equal(clientKey(req("127.0.0.1", { "tailscale-user-login": "Alan@Example.com" })), "tailscale:alan@example.com");
|
||||
assert.equal(clientKey(req("::1", { "tailscale-user-name": "x", "x-forwarded-for": "100.64.0.7, 1.1.1.1" })), "forwarded:100.64.0.7");
|
||||
assert.equal(clientKey(req("127.0.0.1", { "x-forwarded-for": "100.64.0.7" })), "address:127.0.0.1");
|
||||
assert.equal(clientKey(req("192.168.1.5", { "tailscale-user-login": "forged@example.com" })), "address:192.168.1.5");
|
||||
});
|
||||
|
||||
test("next targets stay on this origin", () => {
|
||||
for (const good of ["/", "/runs/12", "/chat?x=1#y", "/a/b//c"]) assert.equal(safeNext(good), good);
|
||||
for (const bad of ["//evil.com", "/\\evil.com", "\\\\evil.com", "https://evil.com", "evil", "/ok\\path", "/a\nb", "", null])
|
||||
assert.equal(safeNext(bad), "/", String(bad));
|
||||
});
|
||||
|
||||
test("origin checks, https detection and cookie naming", () => {
|
||||
const req = (headers, encrypted = false) => ({ headers: { host: "pipelines.example:8443", ...headers }, socket: { encrypted } });
|
||||
assert.equal(sameOriginRequest(req({})), true);
|
||||
assert.equal(sameOriginRequest(req({ origin: "https://pipelines.example:8443" })), true);
|
||||
assert.equal(sameOriginRequest(req({ origin: "https://evil.example" })), false);
|
||||
assert.equal(sameOriginRequest(req({ origin: "null" })), false);
|
||||
assert.equal(sameOriginRequest(req({ "sec-fetch-site": "cross-site" })), false);
|
||||
assert.equal(sameOriginRequest(req({ "sec-fetch-site": "same-site", origin: "https://pipelines.example:8443" })), false);
|
||||
assert.equal(isHttps(req({ "x-forwarded-proto": "https" })), true);
|
||||
assert.equal(isHttps(req({})), false);
|
||||
assert.equal(sessionCookieName(req({ "x-forwarded-proto": "https" })), "__Host-pipelines_session");
|
||||
assert.equal(sessionCookieName(req({})), "pipelines_session");
|
||||
});
|
||||
|
||||
test("socket sweep destroys only sockets whose session is gone", async () => {
|
||||
const { EventEmitter } = await import("node:events");
|
||||
const sockets = new SessionSockets();
|
||||
const make = () => Object.assign(new EventEmitter(), { destroyed: false, destroy() { this.destroyed = true; this.emit("close"); } });
|
||||
const keep = make(), drop = make();
|
||||
sockets.track(keep, "good");
|
||||
sockets.track(drop, "bad");
|
||||
assert.equal(sockets.sweep((token) => token === "good"), 1);
|
||||
assert.equal(drop.destroyed, true);
|
||||
assert.equal(keep.destroyed, false);
|
||||
assert.equal(sockets.size, 1);
|
||||
keep.emit("close");
|
||||
assert.equal(sockets.size, 0);
|
||||
});
|
||||
Reference in New Issue
Block a user