Files

252 lines
17 KiB
JavaScript

// Passkey (WebAuthn) sign-in that gates the whole app, for one admin and the people they add.
// The first passkey (the admin) is enrolled with a setup code (HUB_SETUP_CODE, or a random one printed to the server log).
// Everyone else enrols with a one-time invite code the admin creates; a signed-in person can also invite one of their own devices.
const crypto = require('crypto');
const fs = require('fs');
const atomicWrite = require('./atomic');
const path = require('path');
const {
generateRegistrationOptions, verifyRegistrationResponse,
generateAuthenticationOptions, verifyAuthenticationResponse,
} = require('@simplewebauthn/server');
const users = require('./users');
const audit = require('./audit');
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
fs.mkdirSync(DATA_DIR, { recursive: true });
const readJson = (f, d) => { try { return JSON.parse(fs.readFileSync(path.join(DATA_DIR, f), 'utf8')); } catch { return d; } };
const writeJson = (f, v) => atomicWrite(path.join(DATA_DIR, f), JSON.stringify(v, null, 2), { mode: 0o600 });
// Signing secret for cookies: env wins, otherwise generated once and kept so sessions survive restarts.
let secret = process.env.COOKIE_SECRET;
if (secret && secret.length < 24) console.warn('[auth] COOKIE_SECRET is short; use at least 32 random characters (openssl rand -hex 32).');
if (secret && process.env.HUB_SETUP_CODE && secret === process.env.HUB_SETUP_CODE) console.warn('[auth] COOKIE_SECRET equals HUB_SETUP_CODE. Anyone who knows the setup code could forge sessions. Use different random values.');
if (!secret) {
secret = readJson('secret.json', {}).secret;
if (!secret) { secret = crypto.randomBytes(32).toString('hex'); writeJson('secret.json', { secret }); }
}
const store = readJson('passkeys.json', { creds: [] });
if (!Array.isArray(store.creds)) store.creds = [];
const save = () => writeJson('passkeys.json', store);
// Passkeys made before there were accounts belong to the admin.
{ const admin = users.firstAdmin(); let changed = false; for (const c of store.creds) if (!c.uid && admin) { c.uid = admin.id; changed = true; } if (changed) save(); }
const SETUP_CODE = process.env.HUB_SETUP_CODE || crypto.randomBytes(4).toString('hex');
if (!users.all().length) console.log(`[auth] No accounts yet. Setup code: ${SETUP_CODE}`);
// Sessions last SESSION_DAYS and slide forward: using the app renews them, so you only sign in again after that long idle.
const SESSION_DAYS = Math.max(1, parseInt(process.env.SESSION_DAYS, 10) || 180);
const LIFETIME = SESSION_DAYS * 864e5;
const mac = v => crypto.createHmac('sha256', secret).update(v).digest('base64url');
const cookies = req => Object.fromEntries((req.headers.cookie || '').split(/; */).filter(Boolean).map(c => { const i = c.indexOf('='); return [c.slice(0, i), decodeURIComponent(c.slice(i + 1))]; }));
const isHttps = req => (req.headers['x-forwarded-proto'] || '') === 'https' || (process.env.PUBLIC_URL || '').startsWith('https://');
const safeEq = (a, b) => a.length === b.length && crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b));
/** Session cookie: uid.epoch.expiry.signature. (Older single-user cookies, expiry.signature, count as the admin.) */
const rejectedAt = new Map();
const whyRejected = (req, why) => { // explain a refused session in the log (at most once a minute per reason), without printing the cookie
const k = why, last = rejectedAt.get(k) || 0; if (Date.now() - last < 60e3) return; rejectedAt.set(k, Date.now());
console.warn(`[auth] session refused: ${why} (${req.method} ${req.url.split('?')[0]})`);
};
function currentUser(req) {
const raw = cookies(req).hub_session;
if (!raw) return null;
const parts = String(raw).split('.');
let user = null, exp;
if (parts.length === 4) {
const [uid, epoch, e, sig] = parts; exp = Number(e);
const u = users.get(uid);
if (!u) whyRejected(req, 'unknown account ' + uid);
else if (u.disabled) whyRejected(req, 'account is turned off');
else if (String(u.epoch) !== epoch) whyRejected(req, `signed out everywhere (cookie epoch ${epoch}, account epoch ${u.epoch})`);
else if (!safeEq(sig, mac(`s${uid}.${epoch}.${e}`))) whyRejected(req, 'bad signature (the cookie secret changed, or the cookie was altered)');
else user = u;
} else if (parts.length === 2) {
const [e, sig] = parts; exp = Number(e);
if (safeEq(sig, mac('s' + e))) { user = users.firstAdmin(); if (!user) whyRejected(req, 'old-style cookie but no admin account exists'); }
else whyRejected(req, 'bad signature on an old-style cookie (the cookie secret changed?)');
} else whyRejected(req, 'cookie is not in a known format');
if (user && !(exp > Date.now())) { whyRejected(req, 'session expired'); return null; }
return user;
}
const isAuthed = req => !!currentUser(req);
const sessionCookie = (req, user) => { const exp = Date.now() + LIFETIME;
return `hub_session=${user.id}.${user.epoch}.${exp}.${mac(`s${user.id}.${user.epoch}.${exp}`)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_DAYS * 86400}${isHttps(req) ? '; Secure' : ''}`; };
// Add a Set-Cookie without clobbering ones other code already set on this response.
const addCookie = (res, c) => { const cur = res.getHeader('Set-Cookie'); res.setHeader('Set-Cookie', cur ? [].concat(cur, c) : c); };
function startSession(req, res, user) { addCookie(res, sessionCookie(req, user)); }
/** Renew the cookie when it is more than a day old (and upgrade old-style cookies), so an active session never runs out. */
function refresh(req, res, user) {
const parts = String(cookies(req).hub_session || '').split('.');
const exp = Number(parts.length === 4 ? parts[2] : parts[0]);
if (parts.length !== 4 || exp - Date.now() < LIFETIME - 864e5) addCookie(res, sessionCookie(req, user));
}
const challenges = new Map(); // cid -> { challenge, kind, extra, exp }
const newChallenge = (challenge, kind, extra) => {
for (const [k, v] of challenges) if (v.exp < Date.now()) challenges.delete(k);
const cid = crypto.randomBytes(16).toString('base64url');
challenges.set(cid, { challenge, kind, extra, exp: Date.now() + 5 * 60e3 });
return cid;
};
const takeRecord = cid => { const c = challenges.get(cid); challenges.delete(cid); return c && c.exp > Date.now() ? c : null; };
// One-time invite codes: they let a device enrol its own passkey for a particular person.
const invites = new Map(); // code -> { uid, exp }
const INVITE_MINUTES = 10;
function newInvite(uid) {
for (const [k, v] of invites) if (v.exp < Date.now()) invites.delete(k);
const a = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'; // no look-alike characters
let code = ''; for (const b of crypto.randomBytes(8)) code += a[b % a.length];
code = code.slice(0, 4) + '-' + code.slice(4);
invites.set(code, { uid, exp: Date.now() + INVITE_MINUTES * 60e3 });
return code;
}
const normInvite = c => { const t = String(c || '').toUpperCase().replace(/[^A-Z0-9]/g, ''); return t.length === 8 ? t.slice(0, 4) + '-' + t.slice(4) : ''; };
const inviteFor = c => { const k = normInvite(c), v = k && invites.get(k); return v && v.exp > Date.now() && users.get(v.uid) && !users.get(v.uid).disabled ? { code: k, uid: v.uid } : null; };
// Recovery codes: 8 one-time codes per person, made in Settings. Each can enrol a new passkey (like an invite) if every device is lost.
// Only keyed hashes are stored, so the file does not reveal them.
const recovery = readJson('recovery.json', {}); // uid -> [hash]
const saveRecovery = () => writeJson('recovery.json', recovery);
const recHash = code => mac('r' + normInvite(code));
function newRecoveryCodes(uid) {
const a = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789', codes = [];
for (let i = 0; i < 8; i++) { let c = ''; for (const b of crypto.randomBytes(8)) c += a[b % a.length]; codes.push(c.slice(0, 4) + '-' + c.slice(4)); }
recovery[uid] = codes.map(recHash); saveRecovery();
return codes;
}
const recoveryFor = c => { const k = normInvite(c); if (!k) return null; const h = recHash(k); const uid = Object.keys(recovery).find(u => recovery[u].includes(h)); const u = uid && users.get(uid); return u && !u.disabled ? { code: k, uid, recovery: true } : null; };
const useRecovery = c => { const h = recHash(c), uid = Object.keys(recovery).find(u => recovery[u].includes(h)); if (uid) { recovery[uid] = recovery[uid].filter(x => x !== h); saveRecovery(); } };
/** An invite or a recovery code, whichever this is. */
const claimFor = c => inviteFor(c) || recoveryFor(c);
const RATE_LIMIT = Math.max(1, parseInt(process.env.AUTH_RATE_LIMIT, 10) || 10); // attempts per minute per address; raised only by the tests
const hits = new Map(); // crude per-IP throttle on anything that checks a secret
const throttled = req => {
const ip = (req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
const h = hits.get(ip) || { n: 0, t: Date.now() };
if (Date.now() - h.t > 60e3) { h.n = 0; h.t = Date.now(); }
h.n++; hits.set(ip, h);
return h.n > RATE_LIMIT;
};
// When PUBLIC_URL is set it is the source of truth for the passkey origin, so a reverse proxy that
// forgets Host / X-Forwarded-Proto cannot break passkeys. Otherwise derive it from the request.
const PUBLIC = (process.env.PUBLIC_URL || '').replace(/\/$/, '');
const rp = req => {
if (PUBLIC) { const u = new URL(PUBLIC); return { rpID: u.hostname, origin: u.origin }; }
const host = req.headers['x-forwarded-host'] || req.headers.host || 'localhost';
const proto = req.headers['x-forwarded-proto'] || 'http';
return { rpID: host.split(':')[0], origin: `${proto}://${host}` };
};
const equalStr = (a, b) => { const x = Buffer.from(String(a)), y = Buffer.from(String(b)); return x.length === y.length && crypto.timingSafeEqual(x, y); };
const readBody = req => new Promise((ok, no) => { const c = []; req.on('data', d => c.push(d)); req.on('end', () => ok(Buffer.concat(c).toString())); req.on('error', no); });
const send = (res, code, obj) => { res.writeHead(code, { 'content-type': 'application/json', ...(res.getHeader('Set-Cookie') ? { 'Set-Cookie': res.getHeader('Set-Cookie') } : {}) }); res.end(JSON.stringify(obj)); };
const credsOf = uid => store.creds.filter(c => c.uid === uid);
async function handle(req, res) {
const url = new URL(req.url, 'http://x'), p = url.pathname;
try {
const me = currentUser(req);
if (p === '/api/auth/state') return send(res, 200, { registered: store.creds.length > 0, authed: !!me });
if (p === '/api/auth/logout' && req.method === 'POST') {
if (me) audit.log('sign-out', { who: me.name }, req);
addCookie(res, 'hub_session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0');
return send(res, 200, { ok: true });
}
const body = req.method === 'POST' || req.method === 'DELETE' ? JSON.parse((await readBody(req)) || '{}') : {};
const { rpID, origin } = rp(req);
if (p === '/api/auth/register/options' && req.method === 'POST') {
let kind, uid, name, handle;
if (me) { kind = 'reg-authed'; uid = me.id; name = me.name; handle = me.handle; }
else {
if (throttled(req)) return send(res, 429, { error: 'Too many attempts. Wait a minute.' });
const inv = body.inviteCode && claimFor(body.inviteCode);
if (!users.all().length && equalStr(body.setupCode || '', SETUP_CODE)) { kind = 'reg-setup'; name = 'Admin'; handle = crypto.randomBytes(32).toString('base64url'); }
else if (inv) { kind = 'reg-invite'; uid = inv.uid; const u = users.get(uid); name = u.name; handle = u.handle; }
else return send(res, 403, { error: body.inviteCode ? 'That invite code is wrong or has expired' : 'Wrong setup code' });
}
const options = await generateRegistrationOptions({
rpName: 'NE Hub', rpID, userName: name, userID: Buffer.from(handle, 'base64url'),
attestationType: 'none',
excludeCredentials: (uid ? credsOf(uid) : []).map(c => ({ id: c.id, transports: c.transports })),
authenticatorSelection: { residentKey: 'required', userVerification: 'preferred' },
});
return send(res, 200, { cid: newChallenge(options.challenge, kind, { uid, handle, code: body.inviteCode && claimFor(body.inviteCode) ? claimFor(body.inviteCode).code : undefined }), options });
}
if (p === '/api/auth/register/verify' && req.method === 'POST') {
if (!me && throttled(req)) return send(res, 429, { error: 'Too many attempts. Wait a minute.' });
const rec = takeRecord(body.cid);
if (!rec) return send(res, 400, { error: 'Request expired, try again' });
const ex = rec.extra || {};
const okKind = rec.kind === 'reg-authed' ? !!me && me.id === ex.uid
: rec.kind === 'reg-setup' ? !users.all().length
: rec.kind === 'reg-invite' ? !!claimFor(ex.code) && !!users.get(ex.uid) : false;
if (!okKind) return send(res, 403, { error: 'Not allowed' });
const v = await verifyRegistrationResponse({ response: body.response, expectedChallenge: rec.challenge, expectedOrigin: origin, expectedRPID: rpID });
if (!v.verified) return send(res, 400, { error: 'Could not verify passkey' });
let user = ex.uid ? users.get(ex.uid) : null;
if (rec.kind === 'reg-setup') user = users.create({ name: 'Admin', role: 'admin', handle: ex.handle });
const c = v.registrationInfo.credential;
store.creds.push({ id: c.id, publicKey: Buffer.from(c.publicKey).toString('base64url'), counter: c.counter, transports: c.transports || [],
name: String(body.name || 'Passkey').slice(0, 40), created: Date.now(), uid: user.id });
save();
if (rec.kind === 'reg-invite') { const wasRecovery = !inviteFor(ex.code); invites.delete(ex.code); useRecovery(ex.code); audit.log(wasRecovery ? 'recovery code used' : 'passkey added with invite', { who: user.name, detail: String(body.name || '').slice(0, 40) }, req); } // single use
else if (rec.kind === 'reg-setup') audit.log('first admin created', { who: user.name }, req);
else audit.log('passkey added', { who: user.name, detail: String(body.name || '').slice(0, 40) }, req);
if (!me) startSession(req, res, user);
return send(res, 200, { ok: true });
}
if (p === '/api/auth/login/options' && req.method === 'POST') {
if (!store.creds.length) return send(res, 400, { error: 'No passkeys set up yet' });
const options = await generateAuthenticationOptions({ rpID, userVerification: 'preferred' });
return send(res, 200, { cid: newChallenge(options.challenge, 'login'), options });
}
if (p === '/api/auth/login/verify' && req.method === 'POST') {
if (throttled(req)) return send(res, 429, { error: 'Too many attempts. Wait a minute.' });
const rec = takeRecord(body.cid);
const cred = store.creds.find(c => c.id === body.response?.id);
const user = cred && users.get(cred.uid);
if (!rec || rec.kind !== 'login' || !cred || !user) { audit.log('sign-in failed', { detail: 'passkey not recognised' }, req); return send(res, 400, { error: 'Passkey not recognised' }); }
if (user.disabled) return send(res, 403, { error: 'This account has been turned off' });
const v = await verifyAuthenticationResponse({
response: body.response, expectedChallenge: rec.challenge, expectedOrigin: origin, expectedRPID: rpID,
credential: { id: cred.id, publicKey: Buffer.from(cred.publicKey, 'base64url'), counter: cred.counter, transports: cred.transports },
});
if (!v.verified) { audit.log('sign-in failed', { who: user.name, detail: 'verification failed' }, req); return send(res, 401, { error: 'Sign-in failed' }); }
cred.counter = v.authenticationInfo.newCounter; cred.lastUsed = Date.now(); save();
startSession(req, res, user);
audit.log('sign-in', { who: user.name, detail: cred.name }, req);
return send(res, 200, { ok: true });
}
// Everything below needs a signed-in session.
if (!me) return send(res, 401, { error: 'Not signed in' });
if (p === '/api/auth/invite' && req.method === 'POST') { // an invite for one of my own devices
audit.log('invite created for a device', { who: me.name }, req);
return send(res, 200, { code: newInvite(me.id), minutes: INVITE_MINUTES });
}
if (p === '/api/auth/recovery' && req.method === 'GET') return send(res, 200, { remaining: (recovery[me.id] || []).length });
if (p === '/api/auth/recovery' && req.method === 'POST') { audit.log('recovery codes created', { who: me.name }, req); return send(res, 200, { codes: newRecoveryCodes(me.id) }); }
if (p === '/api/auth/passkeys' && req.method === 'GET') {
return send(res, 200, credsOf(me.id).map(c => ({ id: c.id, name: c.name, created: c.created, lastUsed: c.lastUsed || null })));
}
if (p === '/api/auth/passkeys' && req.method === 'DELETE') {
const mine = credsOf(me.id); if (!mine.some(c => c.id === body.id)) return send(res, 404, { error: 'Passkey not found' });
audit.log('passkey removed', { who: me.name, detail: (mine.find(c => c.id === body.id) || {}).name }, req);
store.creds = store.creds.filter(c => c.id !== body.id); save();
return send(res, 200, { ok: true, remaining: credsOf(me.id).length });
}
send(res, 404, { error: 'Not found' });
} catch (e) { send(res, 400, { error: e.message }); }
}
const passkeyCount = uid => credsOf(uid).length;
function removeCredsOf(uid) { store.creds = store.creds.filter(c => c.uid !== uid); save(); delete recovery[uid]; saveRecovery(); }
module.exports = { handle, currentUser, isAuthed, refresh, addCookie, secret, SESSION_DAYS, newInvite, INVITE_MINUTES, passkeyCount, removeCredsOf };