taper / client /test-browser.mjs
abr00kx's picture
Round 2 security fixes
b6ae8c3 verified
Raw History Blame Contribute Delete
29.9 kB
/* global document, indexedDB */
// Headless browser test of the dev client: two users in separate browser
// contexts register, share a room and exchange end-to-end encrypted messages
// through the real UI, server and WebAssembly crypto.
//
// node client/test-browser.mjs (from the repo root)
//
// Uses the system Chromium (TAPER_CHROMIUM overrides the path). Fails on any
// page error or Content-Security-Policy violation, and if plaintext ever
// appears in a WebSocket frame.
import { spawn } from 'node:child_process';
import { existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import assert from 'node:assert/strict';
import { chromium } from 'playwright-core';
import { padme, TaperCrypto, verifyRoomState } from './crypto.js';
import { solveChallenge } from './pow.js';
import { randomBytes } from 'node:crypto';
const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..');
const GW_PORT = 20000 + Math.floor(Math.random() * 1000);
// The server hosts the client under its secret gateway path, as it does in
// production: one link, and the page connects back to the same path.
const SECRET_PATH = `/${randomBytes(18).toString('base64url')}`;
// `localhost`, not 127.0.0.1: a security key's site must be a domain name, never an IP address.
const APP = `http://localhost:${GW_PORT}${SECRET_PATH}/`;
const CHROMIUM = process.env.TAPER_CHROMIUM ?? ['/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/google-chrome'].find(existsSync);
const SECRET = 'secret hello from alice 🦊';
const toasts = [];
const binaryFrames = [];
// A real 1x1 PNG, sent as an encrypted attachment.
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', 'base64');
const PNG_NAME = 'taper-attachment-marker.png';
const REPLY = 'bob got it';
function startProcess(cmd, args, opts, ready) {
const proc = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], ...opts });
return new Promise((resolve, reject) => {
const onData = (d) => { if (ready.test(String(d))) resolve(proc); };
proc.stdout.on('data', onData);
proc.stderr.on('data', onData);
proc.once('exit', (code) => reject(new Error(`${cmd} exited with ${code}`)));
setTimeout(() => resolve(proc), 3000); // python's http.server prints nothing until a request
});
}
async function waitUntil(pred, describe, ms = 30_000) {
const end = Date.now() + ms;
while (!(await pred())) {
if (Date.now() > end) throw new Error(await describe());
await new Promise((r) => setTimeout(r, 100));
}
}
// One user = one browser context (separate storage), with error and frame capture.
async function openUser(browser, name, problems, frames, action = 'register') {
const context = await browser.newContext();
const page = await context.newPage();
page.on('pageerror', (e) => problems.push(`${name}: page error: ${e.message}`));
page.on('console', (m) => {
if (m.type() === 'error' && /Content Security Policy|CSP|Refused to/i.test(m.text())) problems.push(`${name}: ${m.text()}`);
if (m.text().startsWith('[taper]')) toasts.push(`${name}: ${m.text()}`);
});
page.on('websocket', (ws) => {
const record = (f) => (typeof f.payload === 'string' ? frames.push(f.payload) : binaryFrames.push(Buffer.from(f.payload)));
ws.on('framesent', record);
ws.on('framereceived', record);
});
await page.goto(APP);
await page.fill('#username', name);
await page.fill('#password', `${name}-password-1`);
await page.click(`button[data-action="${action}"]`);
await page.waitForSelector('#app-view:not([hidden])');
await page.waitForSelector('#conn-status.online');
await page.waitForSelector('body[data-crypto="ready"]', { timeout: 30_000 });
return { context, page };
}
async function main() {
assert.ok(CHROMIUM, 'No Chromium found; set TAPER_CHROMIUM');
// Registration difficulty is lowered to keep the test fast; the client still solves it.
const server = await startProcess(process.execPath, ['server/index.js'], { cwd: ROOT, env: { ...process.env, PORT: String(GW_PORT), TAPER_REGISTER_POW_BITS: '12', TAPER_GATEWAY_PATH: SECRET_PATH } }, /Taper gateway/);
const browser = await chromium.launch({ executablePath: CHROMIUM, headless: true });
const problems = [];
const frames = [];
const results = [];
const test = async (name, fn) => {
try { await fn(); results.push(['PASS', name]); } catch (e) { results.push(['FAIL', name, e.message.split('\n')[0]]); }
};
let alice, bob, roomId;
try {
await test('decrypt rejects a session the shield says is someone else\'s, before any key query', async () => {
const calls = [];
const code = { MismatchedSender: 5, VerificationViolation: 6 };
const sdk = { RoomId: class {}, DecryptionSettings: class {}, TrustRequirement: {}, ShieldStateCode: code };
const machine = {
decryptRoomEvent: async () => ({ event: '{}', sender: { toString: () => '@mallory:x' }, shieldState: () => ({ code: machine.code }) }),
getUserDevices: async () => { calls.push('devices'); throw new Error('looked up devices'); },
};
const tc = new TaperCrypto(sdk, machine, async (m) => { calls.push(m); return {}; }, '@me:x');
const ev = { room_id: '!r', sender: '@mallory:x', origin_server_ts: Date.now(), content: { algorithm: 't.megolm.v1.aes-sha2', session_id: 's' } };
machine.code = code.MismatchedSender;
await assert.rejects(tc.decrypt(ev), /someone else/);
let told;
tc.onTrustChanged = (u) => { told = u; };
machine.code = code.VerificationViolation;
await assert.rejects(tc.decrypt(ev), /changed identity/);
assert.equal(told, '@mallory:x');
assert.deepEqual(calls, [], 'no key refresh or device lookup for a mismatched session');
await assert.rejects(tc.decrypt({ ...ev, origin_server_ts: undefined }), /valid timestamp/);
});
await test('backup keys older than retention are not imported, and keep their backup day', async () => {
const imported = [];
const tc = new TaperCrypto({}, { importExportedRoomKeys: async (j) => { imported.push(j); } }, null, '@me:x');
const keys = JSON.stringify([{ session_id: 'a' }, { session_id: 'b' }]);
assert.deepEqual(await tc.importRoomKeys(keys, { seenAtMs: Date.now() - tc.maxKeyAgeMs - 1 }), []);
tc.sessionSeenAt.set('b', 0); // tombstoned here: stays dead
const day = Date.now() - 5 * 86_400_000;
assert.deepEqual(await tc.importRoomKeys(keys, { seenAtMs: day }), ['a']);
assert.equal(tc.sessionSeenAt.get('a'), day);
assert.equal(tc.sessionSeenAt.get('b'), 0);
assert.equal(imported.length, 1);
});
await test('room state without encryption or history settings is flagged; a forged room is fatal', async () => {
const create = { type: 't.room.create', state_key: '', sender: '@a:x', content: { room_version: '13' } };
const r = await verifyRoomState('!forged', [create]);
assert.equal(r.fatal, true);
assert.ok(r.warnings.some((w) => /encryption settings/.test(w)) && r.warnings.some((w) => /History visibility/.test(w)), r.warnings.join(' | '));
await assert.rejects(solveChallenge({ type: 't.pow.sha256', nonce: 'n', difficulty: 29 }, 'b'), /out of range/);
});
await test('alice and bob register in separate browsers', async () => {
alice = await openUser(browser, 'alice', problems, frames);
bob = await openUser(browser, 'bob', problems, frames);
assert.equal(await alice.page.textContent('#me-id'), '@alice:localhost');
assert.equal(await bob.page.textContent('#me-id'), '@bob:localhost');
});
await test('alice creates a room and invites bob; bob accepts', async () => {
const a = alice.page;
await a.click('details.tools summary');
await a.fill('#create-name', 'browser e2ee');
await a.click('#create-form button[type="submit"]');
await a.waitForSelector('#room-pane:not([hidden])');
roomId = (await a.textContent('#room-id')).trim();
assert.match(roomId, /^!/);
await a.fill('#invite-user', '@bob:localhost');
await a.click('#invite-form button[type="submit"]');
const b = bob.page;
await b.click('#invite-list .invite button:has-text("Accept")');
await b.waitForSelector('#room-pane:not([hidden])');
assert.equal((await b.textContent('#room-id')).trim(), roomId);
});
await test('the room name is encrypted state, readable by members', async () => {
const header = async (p) => (await p.textContent('#room-name')).trim();
await alice.page.waitForSelector('#room-name:text-is("browser e2ee")', { timeout: 20_000 })
.catch(async () => { throw new Error(`alice's header shows ${await header(alice.page)}`); });
// Bob joined after the name was set; alice's client sends it again for him.
await bob.page.waitForSelector('#room-name:text-is("browser e2ee")', { timeout: 20_000 })
.catch(async () => { throw new Error(`bob's header shows ${await header(bob.page)}; toasts: ${toasts.join(' | ')}`); });
});
await test('alice sends an encrypted message; bob reads it', async () => {
await alice.page.fill('#message', SECRET);
await alice.page.press('#message', 'Enter');
await bob.page.waitForSelector(`.msg .body:text-is("${SECRET}")`, { timeout: 20_000 });
await alice.page.waitForSelector(`.msg.own .body:text-is("${SECRET}")`, { timeout: 20_000 });
});
await test('bob replies; alice reads it', async () => {
await bob.page.fill('#message', REPLY);
await bob.page.press('#message', 'Enter');
await alice.page.waitForSelector(`.msg .body:text-is("${REPLY}")`, { timeout: 20_000 });
});
await test('alice sends an encrypted image; bob decrypts and shows it', async () => {
await alice.page.setInputFiles('#file-input', { name: PNG_NAME, mimeType: 'image/png', buffer: PNG });
const sel = `.msg:has(.body:text-is("📎 ${PNG_NAME}"))`;
await bob.page.click(`${sel} button:has-text("Show image")`, { timeout: 20_000 });
const img = bob.page.locator(`${sel} img.attachment`);
await img.waitFor({ timeout: 20_000 });
await bob.page.waitForFunction((el) => el.complete && el.naturalWidth === 1, await img.elementHandle());
assert.ok(binaryFrames.length >= 2, 'expected binary upload and download frames');
assert.equal(binaryFrames.some((f) => f.includes(PNG)), false, 'the image crossed the WebSocket unencrypted');
});
await test("an unverified sender's messages carry an 'unverified' badge", async () => {
await alice.page.waitForSelector(`.msg:has(.body:text-is("${REPLY}")) .badge.unverified`, { timeout: 10_000 });
});
await test('alice and bob verify each other by comparing emoji in the UI', async () => {
const a = alice.page;
const b = bob.page;
await a.click('#members summary');
await a.click('#member-list .member:has-text("@bob:localhost") button:has-text("Verify")');
await b.click('#verify-dialog:not([hidden]) button:has-text("Accept")', { timeout: 15_000 });
await a.waitForSelector('#verify-dialog ol.emoji li', { timeout: 15_000 });
await b.waitForSelector('#verify-dialog ol.emoji li', { timeout: 15_000 });
const symbols = (p) => p.$$eval('#verify-dialog ol.emoji .symbol', (els) => els.map((e) => e.textContent));
const ea = await symbols(a);
assert.equal(ea.length, 7);
assert.deepEqual(ea, await symbols(b), 'both sides must show the same emoji');
await a.click('#verify-dialog button:has-text("They match")');
await b.click('#verify-dialog button:has-text("They match")');
await a.waitForSelector('#verify-dialog .verified', { timeout: 15_000 });
await b.waitForSelector('#verify-dialog .verified', { timeout: 15_000 });
await a.click('#verify-dialog button:has-text("Done")');
await b.click('#verify-dialog button:has-text("Done")');
await a.waitForSelector('#member-list .member:has-text("@bob:localhost") .badge.verified', { timeout: 15_000 });
});
await test("after verification, bob's new messages are not marked unverified", async () => {
await bob.page.fill('#message', 'verified now');
await bob.page.press('#message', 'Enter');
const sel = '.msg:has(.body:text-is("verified now"))';
await alice.page.waitForSelector(sel, { timeout: 20_000 });
const badges = alice.page.locator(`${sel} .badge`);
const detail = (await badges.count()) ? `${await badges.first().textContent()} (${await badges.first().getAttribute('title')})` : '';
assert.equal(await badges.count(), 0, `unexpected badge: ${detail}`);
});
await test('messages show their retention expiry', async () => {
const meta = await bob.page.textContent('.msg .meta');
assert.match(meta, /expires in 20d/);
});
await test('plaintext never crosses the WebSocket', async () => {
assert.ok(frames.length > 10, `only ${frames.length} frames captured`);
const leaked = frames.filter((f) => f.includes(SECRET) || f.includes(REPLY) || f.includes('browser e2ee') || f.includes(PNG_NAME));
assert.equal(leaked.length, 0, `plaintext found in ${leaked.length} frame(s)`);
assert.ok(frames.some((f) => f.includes('"t.room.encrypted"')), 'no encrypted events seen');
});
await test('every frame in both directions is padded', async () => {
const unpadded = frames.map((f) => Buffer.byteLength(f)).filter((n) => n !== padme(n));
assert.equal(unpadded.length, 0, `unpadded text frame sizes: ${unpadded.slice(0, 5)}`);
const sizes = new Set(binaryFrames.map((f) => f.length));
assert.deepEqual([...sizes], [21 + 65_536], 'every media frame should be one full chunk');
});
await test('after a reload, bob still decrypts from his stored keys', async () => {
await bob.page.reload();
await bob.page.waitForSelector('#conn-status.online');
await bob.page.waitForSelector('body[data-crypto="ready"]', { timeout: 30_000 });
await bob.page.click(`#room-list button[title="${roomId}"]`);
await bob.page.waitForSelector(`.msg .body:text-is("${SECRET}")`, { timeout: 20_000 });
});
await test("bob logs in on a second browser; his identity is restored and alice sees no change", async () => {
const laptop = await openUser(browser, 'bob', problems, frames, 'login');
await waitUntil(() => toasts.some((t) => t.startsWith('bob:') && t.includes('restored with your password')),
() => `no recovery toast; toasts: ${toasts.join(' | ')}`);
await laptop.page.click(`#room-list button[title="${roomId}"]`);
const LATER = 'for both of your browsers';
await alice.page.fill('#message', LATER);
await alice.page.press('#message', 'Enter');
await laptop.page.waitForSelector(`.msg .body:text-is("${LATER}")`, { timeout: 20_000 });
// No identity-change warning, and alice's view of bob's message stays clean.
assert.equal(await alice.page.locator('#room-warnings .warning').count(), 0, await alice.page.textContent('#room-warnings'));
assert.equal(await laptop.page.locator(`.msg:has(.body:text-is("${LATER}")) .badge`).count(), 0, 'alice should look verified to bob');
await laptop.context.close();
});
// --- backup, security keys, password change, a device that stays signed in ---
await test("a new browser reads old messages from the room-key backup", async () => {
// Bob's first browser backed up the keys it received (4 s after they arrived).
const laptop = await openUser(browser, 'bob', problems, frames, 'login');
await laptop.page.click(`#room-list button[title="${roomId}"]`);
await laptop.page.waitForSelector(`.msg .body:text-is("${SECRET}")`, { timeout: 30_000 })
.catch((e) => { throw new Error(`${e.message.split('\n')[0]}; toasts: ${toasts.join(' | ')}`); });
await laptop.context.close();
});
await test('bob adds a security key, turns on the badge, and alice sees it on his name', async () => {
const cdp = await bob.context.newCDPSession(bob.page);
await cdp.send('WebAuthn.enable');
await cdp.send('WebAuthn.addVirtualAuthenticator', {
options: { protocol: 'ctap2', transport: 'usb', hasResidentKey: false, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true },
});
const b = bob.page;
await b.click('#open-settings');
await b.fill('#settings-password', 'bob-password-1');
await b.fill('#key-nickname', 'test key');
await b.click('#key-add-form button[type="submit"]');
await b.waitForSelector('#keys-list .keyrow:has-text("test key")', { timeout: 20_000 })
.catch(async () => { throw new Error(`no key listed: ${await b.textContent('#settings-error')}`); });
assert.equal(await alice.page.locator('#member-list .badge.hw').count(), 0, 'a badge appeared before bob asked for one');
await b.check('#opt-indicator');
await alice.page.evaluate(() => { document.querySelector('#members').open = true; });
await alice.page.waitForSelector('#member-list .member:has-text("@bob:localhost") .badge.hw', { timeout: 20_000 });
const title = await alice.page.getAttribute('#member-list .member:has-text("@bob:localhost") .badge.hw', 'title');
assert.match(title, /doesn't prove a person wrote/);
});
await test('changing the password needs the key, signs the old password out, and keeps identity and backup', async () => {
const b = bob.page;
await b.fill('#settings-password', 'bob-password-1');
await b.fill('#new-password', 'bob-new-password-2');
await b.fill('#new-password2', 'bob-new-password-2');
await b.click('#pw-form button[type="submit"]');
await waitUntil(async () => (await b.inputValue('#new-password')) === '', async () => `not changed: ${await b.textContent('#settings-error')}`, 30_000);
await b.click('#settings-close');
// The old password no longer works; the new one does, and the identity comes back.
const context = await browser.newContext();
const page = await context.newPage();
await page.goto(APP);
await page.fill('#username', 'bob');
await page.fill('#password', 'bob-password-1');
await page.click('button[data-action="login"]');
await page.waitForFunction(() => /Invalid username or password/.test(document.querySelector('#login-error').textContent));
await page.fill('#password', 'bob-new-password-2');
await page.click('button[data-action="login"]');
await page.waitForSelector('#app-view:not([hidden])');
await page.waitForSelector('body[data-crypto="ready"]', { timeout: 30_000 });
await page.click(`#room-list button[title="${roomId}"]`);
await page.waitForSelector(`.msg .body:text-is("${SECRET}")`, { timeout: 30_000 });
await context.close();
});
await test('a device that stays signed in: sealed on disk, locked on reload, wiped on request', async () => {
const context = await browser.newContext();
const page = await context.newPage();
page.on('pageerror', (e) => problems.push(`carol: page error: ${e.message}`));
await page.goto(APP);
await page.fill('#username', 'carol');
await page.fill('#password', 'carol-password-1');
await page.check('#remember');
await page.fill('#device-pass', 'correct horse staple');
await page.click('button[data-action="register"]');
await page.waitForSelector('#app-view:not([hidden])');
await page.waitForSelector('body[data-crypto="ready"]', { timeout: 30_000 });
await page.click('details.tools summary');
await page.fill('#create-name', 'carol notes');
await page.click('#create-form button[type="submit"]');
await page.waitForSelector('#room-pane:not([hidden])');
await page.fill('#message', 'a note to myself');
await page.press('#message', 'Enter');
await page.waitForSelector('.msg.own .body:text-is("a note to myself")', { timeout: 20_000 });
await waitUntil(() => page.evaluate(() => Boolean(localStorage.getItem('taper-device'))), () => 'no sealed record was saved');
const stored = await page.evaluate(() => ({
local: JSON.stringify({ ...localStorage }), session: JSON.stringify({ ...sessionStorage }),
}));
for (const secret of [SECRET_PATH.slice(1), 'tp_', 'carol', 'correct horse staple']) {
assert.ok(!stored.local.includes(secret), `localStorage holds ${secret}`);
assert.ok(!stored.session.includes(secret), `sessionStorage holds ${secret}`);
}
// Reloading asks for the passphrase.
await page.reload();
await page.waitForSelector('#unlock-view:not([hidden])');
await page.fill('#unlock-pass', 'wrong passphrase!');
await page.click('#unlock-go');
await page.waitForFunction(() => /Wrong passphrase/.test(document.querySelector('#unlock-error').textContent));
await page.fill('#unlock-pass', 'correct horse staple');
await page.click('#unlock-go');
await page.waitForSelector('#app-view:not([hidden])', { timeout: 30_000 });
await page.waitForSelector('body[data-crypto="ready"]', { timeout: 30_000 });
await page.click('#room-list button');
await page.waitForSelector('.msg .body:text-is("a note to myself")', { timeout: 20_000 });
// Lock, then unlock again. Typed secrets don't survive the lock either.
await page.click('#open-settings');
await page.fill('#settings-password', 'carol-password-1');
await page.click('#lock-now');
await page.waitForSelector('#unlock-view:not([hidden])');
assert.equal(await page.locator('#app-view').isHidden(), true);
assert.equal(await page.locator('#events li').count(), 0, 'decrypted messages stayed in the page behind the lock');
assert.equal(await page.locator('#member-list li, #room-list li').count(), 0);
assert.equal(await page.inputValue('#settings-password'), '');
assert.equal(await page.textContent('#me-id'), '');
await page.fill('#unlock-pass', 'correct horse staple');
await page.click('#unlock-go');
await page.waitForSelector('#app-view:not([hidden])', { timeout: 30_000 });
await page.waitForSelector('body[data-crypto="ready"]', { timeout: 30_000 });
// Wipe: two clicks, then nothing is left.
await page.click('#open-settings');
await page.click('#wipe-now');
await page.click('#wipe-now');
await page.waitForSelector('#login-view:not([hidden])');
const left = () => page.evaluate(async () => ({
record: localStorage.getItem('taper-device'),
stores: (await indexedDB.databases()).filter((d) => d.name?.startsWith('taper-crypto-')).length,
}));
// A database can't be removed while a connection to it is open; the browser finishes
// the job when the connection closes. The passphrase that opens it is already gone.
await page.reload();
await page.waitForSelector('#login-view:not([hidden])');
await waitUntil(async () => (await left()).stores === 0, async () => `still there: ${JSON.stringify(await left())}`, 10_000);
assert.deepEqual(await left(), { record: null, stores: 0 });
await context.close();
});
await test('with WebAssembly blocked (as in Tor Browser Safer), the page says so', async () => {
assert.equal(await alice.page.locator('#wasm-blocked').isHidden(), true, 'warning shown although WebAssembly works');
// A blocker may remove WebAssembly entirely, or make compiling fail.
const blockers = [
() => { delete globalThis.WebAssembly; },
() => {
const fail = () => Promise.reject(new Error('blocked'));
globalThis.WebAssembly.instantiate = fail;
globalThis.WebAssembly.compile = fail;
},
];
for (const block of blockers) {
const context = await browser.newContext();
try {
const page = await context.newPage();
await page.addInitScript(block);
await page.goto(APP);
await page.waitForSelector('#wasm-blocked:not([hidden])', { timeout: 10_000 });
assert.match(await page.textContent('#wasm-blocked'), /Standard/);
} finally {
await context.close();
}
}
});
await test('verified-only mode blocks sending when an unverified member joins, and shows a warning', async () => {
const a = alice.page;
// Enable verified-only mode in the room with verified bob.
await a.evaluate(() => { document.querySelector('#members').open = true; });
await a.check('#opt-verified-only');
// The setting and its badge survive a reload.
await a.reload();
await a.waitForSelector('body[data-crypto="ready"]', { timeout: 30_000 });
await a.click(`#room-list button[title="${roomId}"]`);
await a.waitForSelector('#verified-only-badge:not([hidden])');
await a.evaluate(() => { document.querySelector('#members').open = true; });
assert.equal(await a.isChecked('#opt-verified-only'), true);
// Verified bob can still receive messages.
await a.fill('#message', 'verified-only ok');
await a.press('#message', 'Enter');
await bob.page.waitForSelector('.msg .body:text-is("verified-only ok")', { timeout: 20_000 });
// Invite unverified dave; once dave joins, alice gets a new-unverified-member warning and sending is blocked!
const dave = await openUser(browser, 'dave', problems, frames);
await a.fill('#invite-user', '@dave:localhost');
await a.click('#invite-form button[type="submit"]');
await dave.page.click('#invite-list .invite button:has-text("Accept")', { timeout: 15_000 });
await a.waitForSelector('#room-warnings .warning:has-text("@dave:localhost")', { timeout: 15_000 });
await a.fill('#message', 'blocked while unverified');
await a.press('#message', 'Enter');
await waitUntil(() => toasts.some((t) => t.startsWith('alice:') && t.includes('Verified-only room')), () => `no verified-only refusal toast: ${toasts.join(' | ')}`);
// Alice kicks dave via the UI button; verified-only sending works again!
await a.click('#member-list .member:has-text("@dave:localhost") button:has-text("Kick")');
await waitUntil(async () => (await a.locator('#member-list .member:has-text("@dave:localhost")').count()) === 0, () => 'dave still in member list');
await a.uncheck('#opt-verified-only');
await dave.context.close();
});
await test('active devices can be reviewed and revoked from Settings, and kept devices auto-lock on idle', async () => {
const context = await browser.newContext();
const page = await context.newPage();
page.on('pageerror', (e) => problems.push(`erin: page error: ${e.message}`));
await page.goto(APP);
await page.fill('#username', 'erin');
await page.fill('#password', 'erin-password-1');
await page.check('#remember');
await page.fill('#device-pass', 'correct horse staple');
await page.click('button[data-action="register"]');
await page.waitForSelector('#app-view:not([hidden])');
await page.waitForSelector('body[data-crypto="ready"]', { timeout: 30_000 });
// Open a second device for erin and revoke it from the first device's Settings.
const second = await openUser(browser, 'erin', problems, frames, 'login');
await page.click('#open-settings');
await page.fill('#settings-password', 'erin-password-1');
await page.waitForSelector('#devices-list .keyrow button:has-text("Revoke")', { timeout: 15_000 });
await page.click('#devices-list .keyrow button:has-text("Revoke")');
await second.page.waitForSelector('#login-view:not([hidden])', { timeout: 15_000 });
await second.context.close();
await page.click('#settings-close');
// Idle auto-lock by wall clock: after 600 ms with no activity (as after a
// suspend, when timers didn't run), the next wake-up locks instead of resetting.
await page.evaluate(() => { localStorage.setItem('taper-idle-ms', '600'); });
await new Promise((r) => setTimeout(r, 800));
await page.evaluate(() => document.dispatchEvent(new Event('visibilitychange')));
await page.waitForSelector('#unlock-view:not([hidden])', { timeout: 10_000 });
assert.match(await page.textContent('#unlock-error'), /inactivity/i);
await context.close();
});
await test('the client refuses a clearnet ws:// gateway', async () => {
const context = await browser.newContext();
const page = await context.newPage();
await page.goto(APP);
await page.evaluate(() => { document.querySelector('#gateway-adv').open = true; });
await page.fill('#gateway-url', 'ws://example.com/gateway');
await page.fill('#username', 'nobody');
await page.fill('#password', 'nobody-password-1');
await page.click('button[data-action="login"]');
await page.waitForFunction(() => /wss:\/\//.test(document.querySelector('#login-error').textContent));
await context.close();
});
await test('no page errors or CSP violations', async () => {
assert.equal(problems.length, 0, problems.join(' | ').slice(0, 600));
});
} finally {
await browser.close();
server.kill('SIGTERM');
}
for (const [status, name, msg] of results) console.log(`${status} ${name}${msg ? `\n ${msg}` : ''}`);
const failed = results.filter((r) => r[0] === 'FAIL').length;
console.log(`\n${results.length - failed}/${results.length} passed`);
process.exit(failed ? 1 : 0);
}
main().catch((e) => { console.error(e); process.exit(1); });