security(auth,ws): fix Auth/TOTP/WebAuthn/bootstrap vulnerabilities, session idle TTL & real-time WS revocation

This commit is contained in:
tyuXX 2026-11-27 22:31:37 +00:00
parent e3f716d24f
commit 1b2e425a00
13 changed files with 1248 additions and 477 deletions

View file

@ -1,5 +1,6 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import * as OTPAuth from 'otpauth';
@ -152,6 +153,7 @@ function buildSyntheticAuthenticator(rpID: string, expectedOrigin: string) {
}
afterEach(async () => {
vi.useRealTimers();
while (cleanups.length > 0) {
await cleanups.pop()!();
}
@ -172,7 +174,6 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => {
fs.rmSync(dataDir, { recursive: true, force: true });
});
const baseUrl = `http://127.0.0.1:${server.port}`;
const origin = `http://localhost:${server.port}`;
const jar = new CookieJar();
let csrfToken = '';
@ -186,16 +187,57 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => {
Host: `localhost:${server.port}`,
};
if (jar.header()) headers.Cookie = jar.header();
if (opts.body !== undefined) headers['Content-Type'] = 'application/json';
const payload = opts.body !== undefined ? JSON.stringify(opts.body) : undefined;
if (payload !== undefined) {
headers['Content-Type'] = 'application/json';
headers['Content-Length'] = String(Buffer.byteLength(payload));
}
if (csrfToken) headers['X-CSRF-Token'] = csrfToken;
const res = await fetch(`${baseUrl}${pathname}`, {
method: opts.method ?? 'GET',
headers,
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
});
jar.updateFrom(res);
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
const res = await new Promise<{ status: number; setCookies: string[]; text: string }>(
(resolve, reject) => {
const req = http.request(
{
host: '127.0.0.1',
port: server.port,
path: pathname,
method: opts.method ?? 'GET',
headers,
},
(incoming) => {
const chunks: Buffer[] = [];
incoming.on('data', (c) => chunks.push(Buffer.from(c)));
incoming.on('end', () => {
const rawSetCookie = incoming.headers['set-cookie'];
resolve({
status: incoming.statusCode ?? 0,
setCookies: Array.isArray(rawSetCookie) ? rawSetCookie : [],
text: Buffer.concat(chunks).toString('utf8'),
});
});
},
);
req.on('error', reject);
if (payload !== undefined) req.write(payload);
req.end();
},
);
for (const line of res.setCookies) {
const first = line.split(';')[0] ?? '';
const eq = first.indexOf('=');
if (eq > 0) {
const name = first.slice(0, eq).trim();
const val = first.slice(eq + 1).trim();
if (val === '') jar['cookies'].delete(name);
else jar['cookies'].set(name, val);
}
}
let data: Record<string, unknown> = {};
try {
data = JSON.parse(res.text) as Record<string, unknown>;
} catch {
data = {};
}
if (typeof data.csrfToken === 'string' && data.csrfToken) {
csrfToken = data.csrfToken;
}
@ -316,7 +358,38 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => {
});
expect(loginVerify2.status).toBe(200);
// 3. Step-Up Verification via Passkey
// 3. Step-Up Verification via Passkey requires stepUpMethod === 'passkey'
await api('/api/auth/drop-elevation', { method: 'POST' });
expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(403);
const deniedOpts = await api('/api/auth/passkeys/step-up/options', { method: 'POST', body: {} });
expect(deniedOpts.status).toBe(200);
const deniedVerify = await api('/api/auth/passkeys/step-up/verify', {
method: 'POST',
body: {
challengeId: String(deniedOpts.data.challengeId),
response: authn.createAuthenticationResponse(
String((deniedOpts.data.options as { challenge: string }).challenge),
),
},
});
expect(deniedVerify.status).toBe(403);
expect(deniedVerify.data.reason).toBe('passkey_stepup_not_enabled');
// Step up with TOTP in next step, enable stepUpMethod = 'passkey', then drop & verify passkey step-up
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() + 35_000);
expect(
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200);
expect(
(
await api('/api/auth/security-policy', {
method: 'PUT',
body: { stepUpMethod: 'passkey' },
})
).status,
).toBe(200);
await api('/api/auth/drop-elevation', { method: 'POST' });
expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(403);
@ -335,7 +408,22 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => {
expect(typeof stepVerify.data.elevatedUntil).toBe('number');
expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(200);
// 4. Delete passkey factor
// 4. Cannot delete the last passkey while stepUpMethod === 'passkey'
const blockedDel = await api(`/api/auth/factors/passkeys/${encodeURIComponent(authn.credId)}`, {
method: 'DELETE',
});
expect(blockedDel.status).toBe(400);
// Switch stepUpMethod back to 'totp', then delete passkey cleanly
expect(
(
await api('/api/auth/security-policy', {
method: 'PUT',
body: { stepUpMethod: 'totp' },
})
).status,
).toBe(200);
const delRes = await api(`/api/auth/factors/passkeys/${encodeURIComponent(authn.credId)}`, {
method: 'DELETE',
});