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:
2026-11-10 01:21:28 +00:00
parent f11ff8650d
commit e43f9fa50c
17 changed files with 1353 additions and 125 deletions
+233
View File
@@ -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();
}
}
+79
View File
@@ -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}`;
}
+76
View File
@@ -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;
}
+2
View File
@@ -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, {
+1 -1
View File
@@ -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("; ");
}
+30
View File
@@ -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;
}
}
+72
View File
@@ -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,
};
}