865 lines
49 KiB
JavaScript
865 lines
49 KiB
JavaScript
import { test, before, after } from 'node:test';
|
||
import assert from 'node:assert/strict';
|
||
import fs from 'node:fs';
|
||
import os from 'node:os';
|
||
import path from 'node:path';
|
||
|
||
process.env.PIKKIE_DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'pikkie-test-'));
|
||
process.env.PIKKIE_KEY_FILE = process.env.PIKKIE_DATA + '.key'; // exercise the key-file path
|
||
delete process.env.PIKKIE_SECRET_KEY;
|
||
const APKDIR = fs.mkdtempSync(path.join(os.tmpdir(), 'pikkie-apk-'));
|
||
process.env.PIKKIE_APK_DIRS = APKDIR;
|
||
process.env.PIKKIE_UNFURL_ALLOW_PRIVATE = '1';
|
||
const { default: app } = await import('../src/index.js');
|
||
const { hotp } = await import('../src/security.js');
|
||
|
||
let server, base;
|
||
before(async () => {
|
||
server = app.listen(0);
|
||
await new Promise((r) => server.once('listening', r));
|
||
base = `http://127.0.0.1:${server.address().port}`;
|
||
});
|
||
after(() => server.close());
|
||
|
||
const jar = {};
|
||
async function call(who, method, url, body, extra = {}) {
|
||
const headers = { ...(extra.headers || {}) };
|
||
if (jar[who]) headers.cookie = jar[who];
|
||
let payload = body;
|
||
if (body && !(body instanceof FormData)) {
|
||
headers['content-type'] = 'application/json';
|
||
payload = JSON.stringify(body);
|
||
}
|
||
const res = await fetch(base + url, { method, headers, body: payload });
|
||
const sc = res.headers.get('set-cookie');
|
||
if (sc) jar[who] = sc.split(';')[0];
|
||
const text = await res.text();
|
||
let json;
|
||
try { json = JSON.parse(text); } catch { json = text; }
|
||
return { status: res.status, json };
|
||
}
|
||
const mcp = (key, method, params, id = 1) =>
|
||
fetch(base + '/mcp', { method: 'POST', headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id, method, params }) }).then(async (r) => ({ status: r.status, json: await r.json().catch(() => null) }));
|
||
|
||
const PW = 'correct horse battery';
|
||
let itemId, adminKey, testerKey;
|
||
|
||
test('first-run setup creates admin, signup closed by default', async () => {
|
||
let r = await call('anon', 'GET', '/api/status');
|
||
assert.equal(r.json.needs_setup, true);
|
||
assert.equal(r.json.signup_enabled, false);
|
||
r = await call('admin', 'POST', '/api/setup', { email: 'admin@x.io', name: 'Boss', password: PW });
|
||
assert.equal(r.status, 200);
|
||
assert.equal(r.json.user.role, 'admin');
|
||
r = await call('anon', 'POST', '/api/setup', { email: 'b@x.io', password: PW });
|
||
assert.equal(r.status, 409);
|
||
r = await call('anon', 'POST', '/api/signup', { email: 't@x.io', name: 'T', password: PW });
|
||
assert.equal(r.status, 403);
|
||
});
|
||
|
||
test('open signup when enabled', async () => {
|
||
await call('admin', 'PUT', '/api/admin/settings', { signup_enabled: '1' });
|
||
const r = await call('tester', 'POST', '/api/signup', { email: 't@x.io', name: 'Tess', password: PW });
|
||
assert.equal(r.status, 200);
|
||
assert.equal(r.json.user.role, 'tester');
|
||
const r2 = await call('tester', 'GET', '/api/admin/users');
|
||
assert.equal(r2.status, 403);
|
||
});
|
||
|
||
test('submit bullets with files, public overview', async () => {
|
||
const fd = new FormData();
|
||
fd.append('bullets', '- Button is ugly\n* Crash on rotate\n stack trace below\n\n1. Typo in footer');
|
||
fd.append('version', '0.3.1');
|
||
fd.append('files', new Blob([Buffer.from([0x89, 0x50, 0x4e, 0x47])], { type: 'image/png' }), 'shot.png');
|
||
fd.append('files', new Blob(['log line'], { type: 'text/plain' }), 'log.txt');
|
||
const r = await call('tester', 'POST', '/api/reports', fd);
|
||
assert.equal(r.status, 200, JSON.stringify(r.json));
|
||
assert.equal(r.json.ids.length, 3);
|
||
itemId = r.json.ids[1];
|
||
const list = await call('admin', 'GET', '/api/items');
|
||
assert.equal(list.json.total, 3);
|
||
const it = await call('admin', 'GET', `/api/items/${itemId}`);
|
||
assert.equal(it.json.text, 'Crash on rotate\nstack trace below');
|
||
assert.equal(it.json.attachments.length, 2);
|
||
assert.equal(it.json.via, 'web');
|
||
const att = await fetch(base + it.json.attachments[1].url, { headers: { cookie: jar.tester } });
|
||
assert.equal(att.headers.get('content-type'), 'application/octet-stream');
|
||
assert.equal(await att.text(), 'log line');
|
||
});
|
||
|
||
test('admin flags status with message + file', async () => {
|
||
const fd = new FormData();
|
||
fd.append('status', 'fixed');
|
||
fd.append('message', 'Fixed in 0.3.2');
|
||
fd.append('files', new Blob(['diff'], { type: 'text/plain' }), 'fix.patch');
|
||
const r = await call('admin', 'POST', `/api/items/${itemId}/status`, fd);
|
||
assert.equal(r.status, 200, JSON.stringify(r.json));
|
||
assert.equal(r.json.status, 'fixed');
|
||
assert.equal(r.json.comments[0].attachments[0].filename, 'fix.patch');
|
||
const fd2 = new FormData();
|
||
fd2.append('status', 'fixed');
|
||
const bad = await call('tester', 'POST', `/api/items/${itemId}/status`, fd2);
|
||
assert.equal(bad.status, 403);
|
||
});
|
||
|
||
test('API keys + MCP for users and admins', async () => {
|
||
let r = await call('admin', 'POST', '/api/keys', { name: 'fixbot' });
|
||
adminKey = r.json.key;
|
||
assert.match(adminKey, /^pk_/);
|
||
r = await call('tester', 'POST', '/api/keys', { name: 'my agent' });
|
||
testerKey = r.json.key;
|
||
|
||
assert.equal((await mcp('pk_nope', 'tools/list')).status, 401);
|
||
const init = await mcp(testerKey, 'initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 't', version: '1' } });
|
||
assert.equal(init.json.result.serverInfo.name, 'pikkie');
|
||
|
||
const tl = await mcp(testerKey, 'tools/list');
|
||
const names = tl.json.result.tools.map((t) => t.name);
|
||
assert.ok(names.includes('submit_bullets'));
|
||
assert.ok(!names.includes('set_status'));
|
||
const atl = await mcp(adminKey, 'tools/list');
|
||
assert.ok(atl.json.result.tools.some((t) => t.name === 'set_status'));
|
||
|
||
const sub = await mcp(testerKey, 'tools/call', { name: 'submit_bullets', arguments: { bullets: ['Bot found a leak'], attachments: [{ filename: 'a.txt', content_base64: Buffer.from('hi').toString('base64') }] } });
|
||
const created = JSON.parse(sub.json.result.content[0].text).created[0];
|
||
const it = await call('admin', 'GET', `/api/items/${created.id}`);
|
||
assert.equal(it.json.via, 'mcp');
|
||
assert.equal(it.json.via_label, 'my agent');
|
||
|
||
const denied = await mcp(testerKey, 'tools/call', { name: 'set_status', arguments: { id: created.id, status: 'fixed' } });
|
||
assert.equal(denied.json.result.isError, true);
|
||
|
||
const ok = await mcp(adminKey, 'tools/call', { name: 'set_status', arguments: { id: created.id, status: 'finished', message: 'patched the leak', attachments: [{ filename: 'p.diff', content_base64: Buffer.from('+fix').toString('base64') }] } });
|
||
assert.equal(ok.json.result.isError, undefined, JSON.stringify(ok.json));
|
||
const got = await mcp(testerKey, 'tools/call', { name: 'get_issue', arguments: { id: created.id } });
|
||
const detail = JSON.parse(got.json.result.content[0].text);
|
||
assert.equal(detail.status, 'finished');
|
||
assert.equal(detail.comments[0].via, 'mcp');
|
||
assert.equal(detail.comments[0].body, 'patched the leak');
|
||
|
||
const changed = await mcp(adminKey, 'tools/call', { name: 'list_issues', arguments: { status: 'finished,fixed' } });
|
||
assert.equal(JSON.parse(changed.json.result.content[0].text).total, 2);
|
||
|
||
const att = await mcp(adminKey, 'tools/call', { name: 'get_attachment', arguments: { id: detail.attachments[0].id } });
|
||
assert.equal(JSON.parse(att.json.result.content[0].text).content_base64, Buffer.from('hi').toString('base64'));
|
||
});
|
||
|
||
test('MCP reads large attachments in bounded chunks', async () => {
|
||
const data = Buffer.alloc(8_000_001, 0x41);
|
||
data[0] = 0x42;
|
||
data[data.length - 1] = 0x43;
|
||
const fd = new FormData();
|
||
fd.append('bullets', 'Large attachment evidence');
|
||
fd.append('files', new Blob([data], { type: 'application/octet-stream' }), 'large.bin');
|
||
const report = await call('tester', 'POST', '/api/reports', fd);
|
||
assert.equal(report.status, 200, JSON.stringify(report.json));
|
||
const issue = await call('tester', 'GET', `/api/items/${report.json.ids[0]}`);
|
||
const id = issue.json.attachments[0].id;
|
||
const get = async (arguments_) => {
|
||
const result = await mcp(testerKey, 'tools/call', { name: 'get_attachment', arguments: { id, ...arguments_ } });
|
||
assert.equal(result.status, 200);
|
||
return result.json.result;
|
||
};
|
||
const info = JSON.parse((await get({})).content[0].text);
|
||
assert.equal(info.size, data.length);
|
||
assert.match(info.note, /offset and length/);
|
||
const first = JSON.parse((await get({ offset: 0, length: 5 })).content[0].text);
|
||
assert.equal(Buffer.from(first.content_base64, 'base64').toString(), 'BAAAA');
|
||
assert.equal(first.next_offset, 5);
|
||
assert.equal(first.complete, false);
|
||
const last = JSON.parse((await get({ offset: data.length - 2, length: 10 })).content[0].text);
|
||
assert.equal(Buffer.from(last.content_base64, 'base64').toString(), 'AC');
|
||
assert.equal(last.complete, true);
|
||
assert.equal((await get({ offset: -1 })).isError, true);
|
||
assert.equal((await get({ length: 1_000_001 })).isError, true);
|
||
});
|
||
|
||
test('message board posts + polls', async () => {
|
||
let r = await call('tester', 'POST', '/api/posts', { type: 'poll', title: 'Dark or darker?', options: ['dark', 'darker', 'dark'] });
|
||
const id = r.json.id;
|
||
r = await call('tester', 'GET', `/api/posts/${id}`);
|
||
assert.equal(r.json.options.length, 2);
|
||
const opt = r.json.options[1].id;
|
||
r = await call('admin', 'POST', `/api/posts/${id}/vote`, { option_id: opt });
|
||
assert.equal(r.json.total_votes, 1);
|
||
r = await call('admin', 'POST', `/api/posts/${id}/vote`, { option_id: opt });
|
||
assert.equal(r.json.total_votes, 1);
|
||
r = await call('tester', 'POST', `/api/posts/${id}/replies`, { body: 'darker obviously' });
|
||
assert.equal(r.status, 200);
|
||
});
|
||
|
||
test('2FA enrol, login challenge, enforcement', async () => {
|
||
let r = await call('tester', 'POST', '/api/2fa/setup');
|
||
const secret = r.json.secret;
|
||
assert.match(r.json.qr_svg, /<svg/);
|
||
const code = hotp(secret, Math.floor(Date.now() / 30000));
|
||
r = await call('tester', 'POST', '/api/2fa/enable', { code });
|
||
assert.equal(r.json.recovery_codes.length, 8);
|
||
const recovery = r.json.recovery_codes[0];
|
||
|
||
r = await call('t2', 'POST', '/api/login', { email: 't@x.io', password: PW, client: 'mobile' });
|
||
assert.equal(r.json.need_2fa, true);
|
||
const bad = await call('t2', 'POST', '/api/login/2fa', { challenge: r.json.challenge, code: '000000' });
|
||
assert.equal(bad.status, 401);
|
||
r = await call('t2', 'POST', '/api/login/2fa', { challenge: r.json.challenge, code: recovery });
|
||
assert.equal(r.status, 200);
|
||
assert.ok(r.json.token);
|
||
const me = await fetch(base + '/api/me', { headers: { authorization: `Bearer ${r.json.token}` } }).then((x) => x.json());
|
||
assert.equal(me.email, 't@x.io');
|
||
|
||
// enforce for all → admin without 2FA is blocked except setup
|
||
await call('admin', 'PUT', '/api/admin/settings', { enforce_2fa: 'all' });
|
||
r = await call('admin', 'GET', '/api/items');
|
||
assert.equal(r.status, 403);
|
||
assert.equal(r.json.error, '2fa_setup_required');
|
||
r = await call('admin', 'GET', '/api/me');
|
||
assert.equal(r.json.needs_2fa_setup, true);
|
||
r = await call('tester', 'GET', '/api/items');
|
||
assert.equal(r.status, 200);
|
||
});
|
||
|
||
test('wrong password rejected; SMTP password never returned', async () => {
|
||
const r = await call('x', 'POST', '/api/login', { email: 'admin@x.io', password: 'nope nope nope' });
|
||
assert.equal(r.status, 401);
|
||
});
|
||
|
||
test('projects: admin creates, users default to last-used project', async () => {
|
||
let r = await call('admin2', 'POST', '/api/login', { email: 'admin@x.io', password: PW });
|
||
// admin is blocked by 2FA policy from the earlier test; relax it for this test
|
||
jar.admin = jar.admin2;
|
||
const { db } = await import('../src/db.js');
|
||
db.prepare("UPDATE settings SET value='off' WHERE key='enforce_2fa'").run();
|
||
r = await call('admin', 'POST', '/api/admin/projects', { name: 'Android app', color: '#00ff00' });
|
||
assert.equal(r.status, 200, JSON.stringify(r.json));
|
||
const pid = r.json.id;
|
||
const tester = await call('tester', 'GET', '/api/projects');
|
||
assert.equal(tester.json.projects.length, 2);
|
||
const fd = new FormData();
|
||
fd.append('bullets', '- in android');
|
||
fd.append('project_id', String(pid));
|
||
r = await call('tester', 'POST', '/api/reports', fd);
|
||
assert.equal(r.json.project.id, pid);
|
||
// next submit without project goes to the same project
|
||
const fd2 = new FormData();
|
||
fd2.append('bullets', '- also android');
|
||
r = await call('tester', 'POST', '/api/reports', fd2);
|
||
assert.equal(r.json.project.id, pid);
|
||
const proj = await call('tester', 'GET', '/api/projects');
|
||
assert.equal(proj.json.current_id, pid);
|
||
const list = await call('tester', 'GET', `/api/items?project=${pid}`);
|
||
assert.equal(list.json.total, 2);
|
||
assert.equal(list.json.items[0].project.name, 'Android app');
|
||
// MCP: by name, and default
|
||
const sub = await mcp(testerKey, 'tools/call', { name: 'submit_bullets', arguments: { bullets: ['general bug'], project: 'general' } });
|
||
assert.equal(JSON.parse(sub.json.result.content[0].text).project.name, 'General');
|
||
const lp = await mcp(testerKey, 'tools/call', { name: 'list_projects', arguments: {} });
|
||
assert.equal(JSON.parse(lp.json.result.content[0].text).projects.length, 2);
|
||
// archive
|
||
r = await call('admin', 'PATCH', `/api/admin/projects/${pid}`, { archived: true });
|
||
assert.equal(r.status, 200);
|
||
assert.equal((await call('tester', 'GET', '/api/projects')).json.projects.length, 1);
|
||
});
|
||
|
||
test('status change e-mails the reporter via SMTP', async () => {
|
||
const net = await import('node:net');
|
||
const mails = [];
|
||
const smtp = net.createServer((sock) => {
|
||
let data = false, buf = '';
|
||
sock.write('220 fake ESMTP\r\n');
|
||
sock.on('data', (chunk) => {
|
||
buf += chunk.toString();
|
||
let i;
|
||
while ((i = buf.indexOf('\r\n')) >= 0) {
|
||
const line = buf.slice(0, i);
|
||
buf = buf.slice(i + 2);
|
||
if (data) {
|
||
if (line === '.') { data = false; sock.write('250 ok\r\n'); } else mails[mails.length - 1] += line + '\n';
|
||
continue;
|
||
}
|
||
const cmd = line.slice(0, 4).toUpperCase();
|
||
if (cmd === 'EHLO' || cmd === 'HELO') sock.write('250 fake\r\n');
|
||
else if (cmd === 'DATA') { data = true; mails.push(''); sock.write('354 go\r\n'); }
|
||
else if (cmd === 'QUIT') { sock.write('221 bye\r\n'); sock.end(); }
|
||
else sock.write('250 ok\r\n');
|
||
}
|
||
});
|
||
});
|
||
await new Promise((r) => smtp.listen(0, '127.0.0.1', r));
|
||
await call('admin', 'PUT', '/api/admin/settings', { smtp_host: '127.0.0.1', smtp_port: String(smtp.address().port), smtp_from: 'pikkie@x.io', notify_admins_new: '0' });
|
||
const t = await call('admin', 'POST', '/api/admin/smtp-test', {});
|
||
assert.equal(t.status, 200, JSON.stringify(t.json));
|
||
// e-mail is opt-in: the reporter opts in to "needs info" mails only
|
||
await call('tester', 'PUT', '/api/me/prefs', { prefs: { needs_info: { email: true } } });
|
||
const fd = new FormData();
|
||
fd.append('status', 'needs_info');
|
||
fd.append('message', 'Which screen?');
|
||
await call('admin', 'POST', `/api/items/${itemId}/status`, fd);
|
||
for (let i = 0; i < 50 && mails.length < 2; i++) await new Promise((r) => setTimeout(r, 50));
|
||
smtp.close();
|
||
assert.equal(mails.length, 2);
|
||
assert.match(mails[1], /Needs more info/);
|
||
assert.match(mails[1], /To: t@x\.io/);
|
||
});
|
||
|
||
test('APK download serves the newest apk in the repo folders', async () => {
|
||
let r = await call('tester', 'GET', '/api/apk');
|
||
assert.equal(r.json.available, false);
|
||
fs.mkdirSync(path.join(APKDIR, 'release'));
|
||
fs.writeFileSync(path.join(APKDIR, 'pikkie-1.0.0.apk'), 'old');
|
||
const t = new Date(Date.now() - 60_000);
|
||
fs.utimesSync(path.join(APKDIR, 'pikkie-1.0.0.apk'), t, t);
|
||
fs.writeFileSync(path.join(APKDIR, 'release', 'app-release.apk'), 'newest');
|
||
fs.writeFileSync(path.join(APKDIR, 'release', 'output-metadata.json'), JSON.stringify({ elements: [{ outputFile: 'app-release.apk', versionName: '1.1.0' }] }));
|
||
r = await call('tester', 'GET', '/api/apk');
|
||
assert.equal(r.json.version, '1.1.0');
|
||
// a newer DEBUG build next to it is never offered
|
||
fs.mkdirSync(path.join(APKDIR, 'debug'));
|
||
fs.writeFileSync(path.join(APKDIR, 'debug', 'app-debug.apk'), 'debug build');
|
||
fs.writeFileSync(path.join(APKDIR, 'pikkie-9.9.9-debug.apk'), 'debug build');
|
||
assert.equal((await call('tester', 'GET', '/api/apk')).json.version, '1.1.0');
|
||
assert.equal(r.json.path, undefined);
|
||
const dl = await fetch(base + '/api/apk/download', { headers: { cookie: jar.tester } });
|
||
assert.match(dl.headers.get('content-disposition'), /pikkie-1\.1\.0\.apk/);
|
||
assert.equal(await dl.text(), 'newest');
|
||
});
|
||
|
||
test('forum-style discussion: threaded replies, edit/delete, me-too', async () => {
|
||
const c1 = new FormData();
|
||
c1.append('body', 'I see this too on Pixel');
|
||
let r = await call('admin', 'POST', `/api/items/${itemId}/comments`, c1);
|
||
const top = r.json.id;
|
||
const c2 = new FormData();
|
||
c2.append('body', 'same here');
|
||
c2.append('parent_id', String(top));
|
||
r = await call('tester', 'POST', `/api/items/${itemId}/comments`, c2);
|
||
const child = r.json.id;
|
||
// reply to a reply is flattened into the same thread
|
||
const c3 = new FormData();
|
||
c3.append('body', 'and me');
|
||
c3.append('parent_id', String(child));
|
||
await call('admin', 'POST', `/api/items/${itemId}/comments`, c3);
|
||
let it = await call('tester', 'GET', `/api/items/${itemId}`);
|
||
const replies = it.json.comments.filter((c) => c.parent_id === top);
|
||
assert.equal(replies.length, 2);
|
||
assert.equal(it.json.comments.find((c) => c.id === top).reply_count, 2);
|
||
// edit own, not others
|
||
assert.equal((await call('tester', 'PATCH', `/api/comments/${child}`, { body: 'same here (edited)' })).status, 200);
|
||
assert.equal((await call('tester', 'PATCH', `/api/comments/${top}`, { body: 'hijack' })).status, 404);
|
||
// me too toggle
|
||
r = await call('tester', 'POST', `/api/items/${itemId}/metoo`);
|
||
assert.equal(r.json.metoo, 1);
|
||
assert.equal(r.json.my_metoo, true);
|
||
r = await call('admin', 'POST', `/api/items/${itemId}/metoo`);
|
||
assert.equal(r.json.metoo, 2);
|
||
r = await call('tester', 'POST', `/api/items/${itemId}/metoo`);
|
||
assert.equal(r.json.metoo, 1);
|
||
// tester cannot delete status-change comments, can delete own
|
||
const statusComment = it.json.comments.find((c) => c.status_to);
|
||
assert.equal((await call('tester', 'DELETE', `/api/comments/${statusComment.id}`)).status, 404);
|
||
assert.equal((await call('tester', 'DELETE', `/api/comments/${child}`)).status, 200);
|
||
// deleting the thread root removes its replies
|
||
assert.equal((await call('admin', 'DELETE', `/api/comments/${top}`)).status, 200);
|
||
it = await call('tester', 'GET', `/api/items/${itemId}`);
|
||
assert.equal(it.json.comments.filter((c) => c.id === top || c.parent_id === top).length, 0);
|
||
// MCP threaded reply
|
||
const m = await mcp(testerKey, 'tools/call', { name: 'add_comment', arguments: { id: itemId, message: 'bot agrees', parent_id: statusComment.id } });
|
||
assert.equal(m.json.result.isError, undefined, JSON.stringify(m.json));
|
||
});
|
||
|
||
test('weights: calibers .22 → 12 gauge, inline tags, sticky default, sort', async () => {
|
||
const fd = new FormData();
|
||
fd.append('bullets', '- [12g] app crashes on launch\n- !4 sync loses data\n- [.22] kerning is off\n- plain one');
|
||
fd.append('weight', '9mm');
|
||
let r = await call('tester', 'POST', '/api/reports', fd);
|
||
assert.deepEqual(r.json.weights, [5, 4, 1, 2]);
|
||
const crash = await call('tester', 'GET', `/api/items/${r.json.ids[0]}`);
|
||
assert.equal(crash.json.text, 'app crashes on launch');
|
||
assert.equal(crash.json.weight, 5);
|
||
// sticky: next report without weight uses 9mm
|
||
const fd2 = new FormData();
|
||
fd2.append('bullets', '- sticky?');
|
||
r = await call('tester', 'POST', '/api/reports', fd2);
|
||
assert.deepEqual(r.json.weights, [2]);
|
||
const list = await call('tester', 'GET', '/api/items?sort=weight&limit=3');
|
||
assert.equal(list.json.items[0].weight, 5);
|
||
const only = await call('tester', 'GET', '/api/items?weight=12g');
|
||
assert.ok(only.json.items.every((i) => i.weight === 5));
|
||
// re-weigh: owner yes, other tester no (admin yes)
|
||
assert.equal((await call('tester', 'PATCH', `/api/items/${r.json.ids[0]}/weight`, { weight: '.45' })).json.weight, 3);
|
||
assert.equal((await call('tester', 'PATCH', `/api/items/${r.json.ids[0]}/weight`, { weight: 'bazooka' })).status, 400);
|
||
const m = await mcp(adminKey, 'tools/call', { name: 'set_weight', arguments: { id: r.json.ids[0], weight: '7.62' } });
|
||
assert.equal(JSON.parse(m.json.result.content[0].text).weight, 4);
|
||
const sub = await mcp(testerKey, 'tools/call', { name: 'submit_bullets', arguments: { bullets: ['[12 gauge] boom', 'meh'], weight: 1 } });
|
||
assert.deepEqual(JSON.parse(sub.json.result.content[0].text).created.map((c) => c.weight), ['12 GAUGE', '.22']);
|
||
});
|
||
|
||
test('admins invite testers by e-mail; invite works with sign-up closed', async () => {
|
||
await call('admin', 'PUT', '/api/admin/settings', { signup_enabled: '0', smtp_host: '' });
|
||
let r = await call('tester', 'POST', '/api/admin/invites', { emails: 'x@y.io' });
|
||
assert.equal(r.status, 403);
|
||
r = await call('admin', 'POST', '/api/admin/invites', { emails: 'new1@x.io, new2@x.io\nt@x.io bogus', message: 'Welcome!' });
|
||
const st = Object.fromEntries(r.json.results.map((x) => [x.email, x.status]));
|
||
assert.deepEqual(st, { 'new1@x.io': 'link_only', 'new2@x.io': 'link_only', 't@x.io': 'exists', bogus: 'invalid' });
|
||
const link = r.json.results[0].link;
|
||
const token = link.split('/invite/')[1];
|
||
r = await call('anon', 'POST', '/api/invite/lookup', { token });
|
||
assert.equal(r.json.email, 'new1@x.io');
|
||
assert.equal(r.json.message, 'Welcome!');
|
||
r = await call('new1', 'POST', '/api/invite/accept', { token, name: 'Newbie', password: PW });
|
||
assert.equal(r.status, 200, JSON.stringify(r.json));
|
||
assert.equal(r.json.user.email, 'new1@x.io');
|
||
assert.equal((await call('new1', 'GET', '/api/items')).status, 200);
|
||
// single use
|
||
r = await call('anon', 'POST', '/api/invite/accept', { token, name: 'Again', password: PW });
|
||
assert.equal(r.status, 404);
|
||
// resend rotates the token
|
||
const list = await call('admin', 'GET', '/api/admin/invites');
|
||
const pending = list.json.find((i) => i.email === 'new2@x.io');
|
||
assert.equal(pending.state, 'pending');
|
||
const old = r.json; void old;
|
||
const rs = await call('admin', 'POST', `/api/admin/invites/${pending.id}/resend`);
|
||
assert.ok(rs.json.link);
|
||
assert.equal(list.json.find((i) => i.email === 'new1@x.io').state, 'accepted');
|
||
assert.equal((await call('admin', 'DELETE', `/api/admin/invites/${pending.id}`)).status, 200);
|
||
assert.equal((await call('anon', 'POST', '/api/invite/lookup', { token: rs.json.link.split('/invite/')[1] })).status, 404);
|
||
});
|
||
|
||
test('QR connect: one-time code logs the phone in, landing page + APK, single use', async () => {
|
||
let r = await call('anon', 'POST', '/api/connect/new');
|
||
assert.equal(r.status, 401);
|
||
r = await call('tester', 'POST', '/api/connect/new');
|
||
assert.equal(r.status, 200, JSON.stringify(r.json));
|
||
assert.match(r.json.qr_svg, /<svg/);
|
||
const code = r.json.url.split('/connect/')[1];
|
||
assert.match(r.json.app_url, /^pikkie:\/\/connect\?s=.+&c=[a-f0-9]{32}$/);
|
||
// landing page works without login and offers app + APK
|
||
const page = await fetch(`${base}/connect/${code}`, { headers: { 'user-agent': 'Mozilla/5.0 (Linux; Android 15; Pixel 7)' } }).then((x) => x.text());
|
||
assert.match(page, /intent:\/\/connect/);
|
||
assert.match(page, /\/apk"/);
|
||
const apk = await fetch(`${base}/connect/${code}/apk`);
|
||
assert.equal(apk.status, 200);
|
||
// exchange → session token for the app
|
||
r = await call('phone', 'POST', '/api/connect/exchange', { code });
|
||
assert.equal(r.status, 200);
|
||
const me = await fetch(base + '/api/me', { headers: { authorization: `Bearer ${r.json.token}` } }).then((x) => x.json());
|
||
assert.equal(me.email, 't@x.io');
|
||
// single use
|
||
assert.equal((await call('phone', 'POST', '/api/connect/exchange', { code })).status, 401);
|
||
assert.equal((await fetch(`${base}/connect/${code}`)).status, 404);
|
||
});
|
||
|
||
test('behind an HTTPS reverse proxy: secure cookies + forwarded origin in links', async () => {
|
||
const res = await fetch(base + '/api/login', {
|
||
method: 'POST',
|
||
headers: { 'content-type': 'application/json', 'x-forwarded-proto': 'https', 'x-forwarded-host': 'pikkie.example.com', 'x-forwarded-for': '203.0.113.9' },
|
||
body: JSON.stringify({ email: 'admin@x.io', password: PW }),
|
||
});
|
||
assert.equal(res.status, 200);
|
||
assert.match(res.headers.get('set-cookie'), /; Secure/);
|
||
assert.match(res.headers.get('strict-transport-security'), /max-age/);
|
||
const cookie = res.headers.get('set-cookie').split(';')[0];
|
||
const c = await fetch(base + '/api/connect/new', { method: 'POST', headers: { cookie, 'x-forwarded-proto': 'https', 'x-forwarded-host': 'pikkie.example.com' } }).then((x) => x.json());
|
||
assert.match(c.url, /^https:\/\/pikkie\.example\.com\/connect\//);
|
||
// plain http request: no Secure flag
|
||
const plain = await fetch(base + '/api/login', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email: 'admin@x.io', password: PW }) });
|
||
assert.doesNotMatch(plain.headers.get('set-cookie'), /Secure/);
|
||
});
|
||
|
||
test('log in on a computer by scanning its QR with the app', async () => {
|
||
let r = await call('desk', 'POST', '/api/weblogin/new');
|
||
const { id, secret } = r.json;
|
||
assert.match(r.json.qr_svg, /<svg/);
|
||
assert.equal((await call('desk', 'POST', '/api/weblogin/poll', { id, secret })).json.pending, true);
|
||
// app (tester session) sees what it approves, then approves
|
||
r = await call('tester', 'GET', `/api/weblogin/${id}`);
|
||
assert.ok(r.json.agent);
|
||
assert.equal((await call('anon', 'POST', `/api/weblogin/${id}/approve`)).status, 401);
|
||
assert.equal((await call('tester', 'POST', `/api/weblogin/${id}/approve`)).status, 200);
|
||
// wrong secret cannot steal it
|
||
assert.equal((await call('thief', 'POST', '/api/weblogin/poll', { id, secret: 'nope' })).status, 410);
|
||
r = await call('desk', 'POST', '/api/weblogin/poll', { id, secret });
|
||
assert.equal(r.status, 200);
|
||
assert.equal(r.json.user.email, 't@x.io');
|
||
assert.equal((await call('desk', 'GET', '/api/me')).json.email, 't@x.io');
|
||
// one shot
|
||
assert.equal((await call('desk', 'POST', '/api/weblogin/poll', { id, secret })).status, 410);
|
||
});
|
||
|
||
test('forged Host headers from anonymous requests never end up in e-mail links', async () => {
|
||
const { siteUrl } = await import('../src/services.js');
|
||
await call('admin', 'PUT', '/api/admin/settings', { site_url: '' });
|
||
await fetch(base + '/api/status', { headers: { 'x-forwarded-host': 'evil.example', host: 'evil.example' } });
|
||
assert.doesNotMatch(siteUrl(), /evil/);
|
||
});
|
||
|
||
test('notification prefs are opt-in; inbox always records; push only when opted in', async () => {
|
||
const { db } = await import('../src/db.js');
|
||
db.prepare("UPDATE settings SET value='off' WHERE key='enforce_2fa'").run();
|
||
let r = await call('riot', 'POST', '/api/signup', { email: 'riot@x.io', name: 'Riot', password: PW }).catch(() => null);
|
||
if (!r || r.status !== 200) {
|
||
await call('admin', 'PUT', '/api/admin/settings', { signup_enabled: '1' });
|
||
r = await call('riot', 'POST', '/api/signup', { email: 'riot@x.io', name: 'Riot', password: PW });
|
||
}
|
||
const prefs = (await call('riot', 'GET', '/api/me/prefs')).json;
|
||
assert.ok(Object.values(prefs.prefs).every((p) => p.email === false && p.app === false));
|
||
assert.ok(!prefs.events.some((e) => e.admin));
|
||
const fd = new FormData();
|
||
fd.append('bullets', '- riot bug');
|
||
const id = (await call('riot', 'POST', '/api/reports', fd)).json.ids[0];
|
||
const s1 = new FormData(); s1.append('status', 'in_progress');
|
||
await call('admin', 'POST', `/api/items/${id}/status`, s1);
|
||
let inbox = (await call('riot', 'GET', '/api/notifications')).json;
|
||
assert.equal(inbox.unread, 1);
|
||
assert.match(inbox.items[0].title, /In progress/);
|
||
assert.equal((await call('riot', 'GET', '/api/notifications/push?since=0')).json.length, 0);
|
||
// opt in to app pushes for resolved
|
||
await call('riot', 'PUT', '/api/me/prefs', { prefs: { resolved: { app: true }, bogus: { app: true } } });
|
||
const s2 = new FormData(); s2.append('status', 'fixed'); s2.append('message', 'done!');
|
||
await call('admin', 'POST', `/api/items/${id}/status`, s2);
|
||
const push = (await call('riot', 'GET', '/api/notifications/push?since=0')).json;
|
||
assert.equal(push.length, 1);
|
||
assert.equal(push[0].link, `#/item/${id}`);
|
||
await call('riot', 'POST', '/api/notifications/read', { all: true });
|
||
assert.equal((await call('riot', 'GET', '/api/notifications')).json.unread, 0);
|
||
});
|
||
|
||
test('profiles: avatar upload, bio, public profile page', async () => {
|
||
const png = Buffer.from('89504e470d0a1a0a0000000d4948445200000001000000010806000000', 'hex');
|
||
const fd = new FormData();
|
||
fd.append('avatar', new Blob([png], { type: 'image/png' }), 'me.png');
|
||
let r = await call('riot', 'POST', '/api/me/avatar', fd);
|
||
assert.equal(r.status, 200, JSON.stringify(r.json));
|
||
assert.match(r.json.avatar, /^\/api\/avatars\/\d+\?v=/);
|
||
const bad = new FormData();
|
||
bad.append('avatar', new Blob(['<svg/>'], { type: 'image/svg+xml' }), 'x.svg');
|
||
assert.equal((await call('riot', 'POST', '/api/me/avatar', bad)).status, 400);
|
||
assert.equal((await call('riot', 'PATCH', '/api/me', { bio: 'I break things', website: 'javascript:alert(1)' })).status, 400);
|
||
r = await call('riot', 'PATCH', '/api/me', { bio: 'I break things', website: 'https://riot.example' });
|
||
assert.equal(r.json.bio, 'I break things');
|
||
const prof = await call('tester', 'GET', `/api/users/${r.json.id}`);
|
||
assert.equal(prof.json.bio, 'I break things');
|
||
assert.ok(prof.json.stats.bullets >= 1);
|
||
const av = await fetch(base + prof.json.avatar, { headers: { cookie: jar.tester } });
|
||
assert.equal(av.headers.get('content-type'), 'image/png');
|
||
});
|
||
|
||
test('off-topic board with images + link previews (SSRF-safe unfurling)', async () => {
|
||
const { isPublicIp } = await import('../src/unfurl.js');
|
||
for (const ip of ['127.0.0.1', '10.1.2.3', '192.168.1.1', '172.16.0.1', '169.254.169.254', '::1', 'fd00::1', '100.64.0.1', '::ffff:127.0.0.1']) assert.equal(isPublicIp(ip), false, ip);
|
||
assert.equal(isPublicIp('93.184.216.34'), true);
|
||
const http = await import('node:http');
|
||
const png = Buffer.concat([Buffer.from('89504e470d0a1a0a', 'hex'), Buffer.alloc(200)]);
|
||
const site = http.createServer((req, res) => {
|
||
if (req.url === '/img.png') { res.writeHead(200, { 'content-type': 'image/png' }); return res.end(png); }
|
||
res.writeHead(200, { 'content-type': 'text/html' });
|
||
res.end(`<html><head><title>fallback</title><meta property="og:title" content="Punk & Pixels"><meta property="og:description" content="A cool page"><meta property="og:image" content="/img.png"></head></html>`);
|
||
});
|
||
await new Promise((r) => site.listen(0, '127.0.0.1', r));
|
||
const url = `http://127.0.0.1:${site.address().port}/page`;
|
||
const fd = new FormData();
|
||
fd.append('board', 'offtopic');
|
||
fd.append('title', 'look at this');
|
||
fd.append('body', `check ${url} lol`);
|
||
fd.append('files', new Blob([png], { type: 'image/png' }), 'cat.png');
|
||
const r = await call('riot', 'POST', '/api/posts', fd);
|
||
assert.equal(r.status, 200, JSON.stringify(r.json));
|
||
site.close();
|
||
const off = (await call('riot', 'GET', '/api/posts?board=offtopic')).json;
|
||
assert.equal(off.length, 1);
|
||
assert.equal(off[0].attachments.length, 1);
|
||
assert.equal(off[0].previews[0].title, 'Punk & Pixels');
|
||
assert.ok(off[0].previews[0].image);
|
||
const img = await fetch(base + off[0].previews[0].image, { headers: { cookie: jar.riot } });
|
||
assert.equal(img.headers.get('content-type'), 'image/png');
|
||
assert.ok(!(await call('riot', 'GET', '/api/posts')).json.some((p) => p.board === 'offtopic'));
|
||
// non-images are refused on the board
|
||
const bad = new FormData();
|
||
bad.append('title', 'x');
|
||
bad.append('files', new Blob(['x'], { type: 'application/zip' }), 'x.zip');
|
||
assert.equal((await call('riot', 'POST', '/api/posts', bad)).status, 400);
|
||
// replying notifies the post author's inbox
|
||
const rep = new FormData();
|
||
rep.append('body', 'haha nice');
|
||
await call('tester', 'POST', `/api/posts/${off[0].id}/replies`, rep);
|
||
assert.ok((await call('riot', 'GET', '/api/notifications')).json.items.some((n) => n.event === 'board'));
|
||
});
|
||
|
||
test('tutorial: shown until finished, can be reset for replay', async () => {
|
||
let me = (await call('riot', 'GET', '/api/me')).json;
|
||
assert.equal(me.tutorial_done, false);
|
||
me = (await call('riot', 'PATCH', '/api/me', { tutorial_done: true })).json;
|
||
assert.equal(me.tutorial_done, true);
|
||
me = (await call('riot', 'PATCH', '/api/me', { tutorial_done: false })).json;
|
||
assert.equal(me.tutorial_done, false);
|
||
});
|
||
|
||
/* ===================== security regression tests ===================== */
|
||
|
||
test('SEC: the last active admin can never be demoted or disabled (also not with a junk role)', async () => {
|
||
const me = (await call('admin', 'GET', '/api/me')).json;
|
||
assert.equal((await call('admin', 'PATCH', `/api/admin/users/${me.id}`, { role: 'banana' })).status, 400);
|
||
assert.equal((await call('admin', 'PATCH', `/api/admin/users/${me.id}`, { role: 'tester' })).status, 400);
|
||
assert.equal((await call('admin', 'PATCH', `/api/admin/users/${me.id}`, { disabled: true })).status, 400);
|
||
assert.equal((await call('admin', 'GET', '/api/me')).json.role, 'admin');
|
||
});
|
||
|
||
test('SEC: bullet limits hold for JSON arrays too (50 bullets, 2000 chars, strings only)', async () => {
|
||
const before = (await call('riot', 'GET', '/api/items?limit=1')).json.total;
|
||
const r = await call('riot', 'POST', '/api/reports', { bullets: [...Array.from({ length: 300 }, (_, i) => 'y'.repeat(2500) + i), { evil: 1 }, 42] });
|
||
assert.equal(r.status, 200, JSON.stringify(r.json));
|
||
assert.equal(r.json.ids.length, 50);
|
||
const it = await call('riot', 'GET', `/api/items/${r.json.ids[0]}`);
|
||
assert.equal(it.json.text.length, 2000);
|
||
assert.equal((await call('riot', 'GET', '/api/items?limit=1')).json.total, before + 50);
|
||
assert.equal((await call('riot', 'POST', '/api/reports', { bullets: [{ a: 1 }] })).status, 400);
|
||
});
|
||
|
||
test('SEC: MCP checks the key before reading the body, survives junk, and batching cannot multiply writes', async () => {
|
||
// no key + broken JSON → 401 (auth first), not 400 (body parsed first)
|
||
const noKey = await fetch(base + '/mcp', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{not json' });
|
||
assert.equal(noKey.status, 401);
|
||
const post = (body) => fetch(base + '/mcp', { method: 'POST', headers: { authorization: `Bearer ${testerKey}`, 'content-type': 'application/json' }, body: JSON.stringify(body) });
|
||
assert.equal((await post({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: null })).status, 200);
|
||
assert.equal((await post([null, 5, 'x'])).status, 200);
|
||
assert.equal((await post({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'get_issue', arguments: 'nope' } })).status, 200);
|
||
const big = await post(Array.from({ length: 500 }, (_, i) => ({ jsonrpc: '2.0', id: i, method: 'tools/call', params: { name: 'submit_bullets', arguments: { bullets: ['batch spam ' + i] } } })));
|
||
assert.equal(big.status, 400);
|
||
assert.equal((await call('tester', 'GET', '/api/items?q=batch%20spam')).json.total, 0);
|
||
});
|
||
|
||
test('SEC: second-factor codes cannot be brute-forced (per-user lockout across challenges and endpoints)', async () => {
|
||
// tester has 2FA from the earlier test
|
||
let wrong = 0, locked = 0;
|
||
for (let i = 0; i < 4 && !locked; i++) {
|
||
const c = (await call('bf' + i, 'POST', '/api/login', { email: 't@x.io', password: PW })).json.challenge;
|
||
if (!c) break;
|
||
for (let k = 0; k < 5; k++) {
|
||
const g = await call('bf' + i, 'POST', '/api/login/2fa', { challenge: c, code: String(300000 + i * 10 + k) });
|
||
if (g.status === 401) wrong++;
|
||
if (g.status === 429) { locked++; break; }
|
||
}
|
||
}
|
||
assert.ok(wrong <= 8, `only a handful of guesses allowed, got ${wrong}`);
|
||
assert.ok(locked > 0, 'locked out after repeated wrong codes');
|
||
// the same lockout protects "turn off 2FA" for someone holding a stolen session
|
||
assert.equal((await call('tester', 'POST', '/api/2fa/disable', { password: PW, code: '123456' })).status, 429);
|
||
});
|
||
|
||
test('SEC: the current password cannot be guessed without limit through a stolen session', async () => {
|
||
const st = [];
|
||
for (let i = 0; i < 12; i++) st.push((await call('riot', 'POST', '/api/me/password', { current: 'wrong-guess-' + i, password: 'another good password' })).status);
|
||
assert.ok(st.filter((x) => x === 401).length <= 8);
|
||
assert.equal(st.at(-1), 429);
|
||
});
|
||
|
||
test('SEC: evidence is removed when the last bullet of its report is deleted', async () => {
|
||
const fd = new FormData();
|
||
fd.append('bullets', '- one\n- two');
|
||
fd.append('files', new Blob(['private log']), 'log.txt');
|
||
const ids = (await call('new1', 'POST', '/api/reports', fd)).json.ids;
|
||
const att = (await call('new1', 'GET', `/api/items/${ids[0]}`)).json.attachments[0];
|
||
await call('admin', 'DELETE', `/api/items/${ids[0]}`);
|
||
assert.equal((await call('new1', 'GET', att.url)).status, 200, 'still there while a sibling bullet uses it');
|
||
await call('admin', 'DELETE', `/api/items/${ids[1]}`);
|
||
assert.equal((await call('new1', 'GET', att.url)).status, 404);
|
||
});
|
||
|
||
test('SEC: malformed cookies and hostile Host headers are harmless', async () => {
|
||
assert.equal((await fetch(base + '/api/status', { headers: { cookie: 'pikkie_session=%E0%A4%A' } })).status, 200);
|
||
const { requestOrigin, siteUrl } = await import('../src/services.js');
|
||
const fake = (host) => ({ app: { get: () => () => false }, socket: {}, protocol: 'https', get: (h) => (h === 'host' ? host : undefined) });
|
||
assert.equal(requestOrigin(fake('pikkie.example.com:8443')), 'https://pikkie.example.com:8443');
|
||
assert.equal(requestOrigin(fake('evil.com/"><script>')), 'https://localhost');
|
||
// a tester cannot steer the fallback origin used in e-mail links
|
||
await call('admin', 'PUT', '/api/admin/settings', { site_url: '' });
|
||
await fetch(base + '/api/me', { headers: { cookie: jar.new1, 'x-forwarded-host': 'evil.example' } });
|
||
assert.doesNotMatch(siteUrl(), /evil/);
|
||
assert.equal((await call('admin', 'PUT', '/api/admin/settings', { site_url: 'javascript:alert(1)' })).status, 400);
|
||
});
|
||
|
||
test('SEC: link previews have a hard total deadline and refuse credentials / odd address forms', async () => {
|
||
const http = await import('node:http');
|
||
const { unfurl, isPublicIp } = await import('../src/unfurl.js');
|
||
const drip = http.createServer((q, s2) => { s2.writeHead(200, { 'content-type': 'text/html' }); const iv = setInterval(() => s2.write('a'), 500); q.on('close', () => clearInterval(iv)); });
|
||
await new Promise((r) => drip.listen(0, '127.0.0.1', r));
|
||
const t0 = Date.now();
|
||
assert.equal(await unfurl(`http://127.0.0.1:${drip.address().port}/slow`), null);
|
||
assert.ok(Date.now() - t0 < 10_000, 'gave up at the deadline');
|
||
drip.closeAllConnections?.(); drip.close();
|
||
for (const ip of ['2002:7f00:1::', '64:ff9b::7f00:1', '2001:db8::1', '0.0.0.0', '224.0.0.1', '198.18.0.1']) assert.equal(isPublicIp(ip), false, ip);
|
||
});
|
||
|
||
test('SEC: invite tokens are never part of a URL the server sees', async () => {
|
||
const r = await call('admin', 'POST', '/api/admin/invites', { emails: 'pathcheck@x.io' });
|
||
const token = r.json.results[0].link.split('/invite/')[1];
|
||
assert.equal((await call('anon', 'GET', `/api/invite/${token}`)).status, 404);
|
||
assert.equal((await call('anon', 'POST', '/api/invite/lookup', { token })).status, 200);
|
||
});
|
||
|
||
test('SEC: an admin password reset revokes the sessions AND API keys of that account', async () => {
|
||
const users = (await call('admin', 'GET', '/api/admin/users')).json;
|
||
const t = users.find((u) => u.email === 't@x.io');
|
||
assert.equal((await mcp(testerKey, 'tools/list')).status, 200);
|
||
await call('admin', 'PATCH', `/api/admin/users/${t.id}`, { password: 'a brand new password' });
|
||
assert.equal((await mcp(testerKey, 'tools/list')).status, 401);
|
||
assert.equal((await call('tester', 'GET', '/api/me')).status, 401);
|
||
});
|
||
|
||
test('SEC: per-user upload budget stops one account from filling the disk', async () => {
|
||
const { chargeUpload } = await import('../src/security.js');
|
||
assert.equal(chargeUpload(987654, 900 * 1024 * 1024), true);
|
||
assert.equal(chargeUpload(987654, 200 * 1024 * 1024), false);
|
||
assert.equal(chargeUpload(987654, 50 * 1024 * 1024), true);
|
||
});
|
||
|
||
/* ===================== second audit pass ===================== */
|
||
|
||
test('SEC2: a stranger typing wrong passwords cannot lock a tester out of their account', async () => {
|
||
const from = (ip) => ({ headers: { 'x-forwarded-for': ip } });
|
||
for (let i = 0; i < 12; i++) await call('stranger', 'POST', '/api/login', { email: 'riot@x.io', password: 'guess-' + i }, from('203.0.113.50'));
|
||
// the attacker's own address is throttled…
|
||
assert.equal((await call('stranger', 'POST', '/api/login', { email: 'riot@x.io', password: PW }, from('203.0.113.50'))).status, 429);
|
||
// …but the real user, coming from elsewhere, still gets in with the right password
|
||
assert.equal((await call('riot2', 'POST', '/api/login', { email: 'riot@x.io', password: PW }, from('198.51.100.7'))).status, 200);
|
||
});
|
||
|
||
test('SEC2: a QR login page left open keeps working (polling is limited per request, not per address)', async () => {
|
||
const w = (await call('desk2', 'POST', '/api/weblogin/new')).json;
|
||
let limited = 0;
|
||
for (let i = 0; i < 100; i++) if ((await call('desk2', 'POST', '/api/weblogin/poll', { id: w.id, secret: w.secret })).status === 429) limited++;
|
||
assert.equal(limited, 0);
|
||
// five more pages behind the same address
|
||
for (let k = 0; k < 5; k++) {
|
||
const x = (await call('desk3', 'POST', '/api/weblogin/new')).json;
|
||
for (let i = 0; i < 60; i++) if ((await call('desk3', 'POST', '/api/weblogin/poll', { id: x.id, secret: x.secret })).status === 429) limited++;
|
||
}
|
||
assert.equal(limited, 0);
|
||
});
|
||
|
||
test('SEC2: display names are unique and cannot hide direction/invisible characters', async () => {
|
||
await call('admin', 'PUT', '/api/admin/settings', { signup_enabled: '1' });
|
||
const from = (ip) => ({ headers: { 'x-forwarded-for': ip } });
|
||
assert.equal((await call('imp', 'POST', '/api/signup', { email: 'imp@x.io', name: 'boss', password: PW }, from('192.0.2.21'))).status, 409, 'cannot reuse the admin name (case-insensitive)');
|
||
const r = await call('imp', 'POST', '/api/signup', { email: 'imp@x.io', name: 'Imp', password: PW }, from('192.0.2.22'));
|
||
assert.equal(r.json.user.name, 'Imp');
|
||
assert.equal((await call('imp', 'PATCH', '/api/me', { name: 'BOSS' })).status, 409);
|
||
assert.equal((await call('imp', 'PATCH', '/api/me', { name: 'Imp' })).status, 200, 'keeping your own name is fine');
|
||
await call('admin', 'PUT', '/api/admin/settings', { signup_enabled: '0' });
|
||
});
|
||
|
||
test('SEC2: API answers are never cached; data files are private to the server user', async () => {
|
||
const r = await fetch(base + '/api/me', { headers: { cookie: jar.admin } });
|
||
assert.equal(r.headers.get('cache-control'), 'no-store');
|
||
const mode = (p) => fs.statSync(p).mode & 0o777;
|
||
assert.equal(mode(path.join(process.env.PIKKIE_DATA, 'pikkie.db')), 0o600);
|
||
assert.equal(mode(path.join(process.env.PIKKIE_DATA, 'uploads')), 0o700);
|
||
const fd = new FormData();
|
||
fd.append('bullets', '- perms');
|
||
fd.append('files', new Blob(['x']), 'x.txt');
|
||
await call('admin', 'POST', '/api/reports', fd);
|
||
const newest = fs.readdirSync(path.join(process.env.PIKKIE_DATA, 'uploads')).map((f) => path.join(process.env.PIKKIE_DATA, 'uploads', f)).filter((f) => fs.statSync(f).isFile()).sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)[0];
|
||
assert.equal(mode(newest), 0o600);
|
||
});
|
||
|
||
test('SEC2: switching on 2FA ends every other session of that account', async () => {
|
||
const other = await call('imp-other', 'POST', '/api/login', { email: 'imp@x.io', password: PW });
|
||
assert.equal(other.status, 200);
|
||
const secret = (await call('imp', 'POST', '/api/2fa/setup')).json.secret;
|
||
await call('imp', 'POST', '/api/2fa/enable', { code: hotp(secret, Math.floor(Date.now() / 30000)) });
|
||
assert.equal((await call('imp-other', 'GET', '/api/me')).status, 401);
|
||
assert.equal((await call('imp', 'GET', '/api/me')).status, 200);
|
||
});
|
||
|
||
/* ===================== encryption at rest ===================== */
|
||
|
||
test('ENC: 2FA secrets and the SMTP password are stored encrypted, bound to their owner', async () => {
|
||
const { db } = await import('../src/db.js');
|
||
const { openTotp, getSmtpPassword, isSealed } = await import('../src/secrets.js');
|
||
// a key file was created next to (not inside) the data folder, readable by the owner only
|
||
assert.ok(fs.existsSync(process.env.PIKKIE_KEY_FILE));
|
||
assert.equal(fs.statSync(process.env.PIKKIE_KEY_FILE).mode & 0o777, 0o600);
|
||
assert.ok(!process.env.PIKKIE_KEY_FILE.startsWith(process.env.PIKKIE_DATA + path.sep));
|
||
|
||
// fresh 2FA set-up
|
||
const signup = await call('admin', 'POST', '/api/admin/users', { email: 'enc@x.io', name: 'Enc', password: PW });
|
||
await call('enc', 'POST', '/api/login', { email: 'enc@x.io', password: PW });
|
||
const secret = (await call('enc', 'POST', '/api/2fa/setup')).json.secret;
|
||
let row = db.prepare('SELECT * FROM users WHERE id=?').get(signup.json.id);
|
||
assert.ok(isSealed(row.totp_secret), 'encrypted in the database');
|
||
assert.ok(!row.totp_secret.includes(secret), 'the secret itself is not in the row');
|
||
assert.equal(openTotp(row), secret);
|
||
// …and the whole login flow still works on the encrypted value
|
||
await call('enc', 'POST', '/api/2fa/enable', { code: hotp(secret, Math.floor(Date.now() / 30000)) });
|
||
const c = (await call('enc2', 'POST', '/api/login', { email: 'enc@x.io', password: PW })).json.challenge;
|
||
const { checkTotp } = await import('../src/security.js');
|
||
db.prepare('UPDATE users SET totp_last=0 WHERE id=?').run(signup.json.id); // allow the same 30 s step again in this test
|
||
assert.equal((await call('enc2', 'POST', '/api/login/2fa', { challenge: c, code: hotp(secret, Math.floor(Date.now() / 30000)) })).status, 200);
|
||
assert.ok(checkTotp);
|
||
|
||
// a ciphertext moved to another account does not decrypt (so one user's secret can't be planted on another)
|
||
const other = db.prepare("SELECT * FROM users WHERE email='riot@x.io'").get();
|
||
assert.equal(openTotp({ id: other.id, totp_secret: row.totp_secret }), null);
|
||
|
||
// SMTP password
|
||
await call('admin', 'PUT', '/api/admin/settings', { smtp_pass: 'mail-pass-123!' });
|
||
const stored = db.prepare("SELECT value FROM settings WHERE key='smtp_pass'").get().value;
|
||
assert.ok(isSealed(stored) && !stored.includes('mail-pass-123!'));
|
||
assert.equal(getSmtpPassword(), 'mail-pass-123!');
|
||
const s = (await call('admin', 'GET', '/api/admin/settings')).json;
|
||
assert.equal(s.smtp_pass_set, true);
|
||
assert.equal(s.smtp_pass, undefined);
|
||
assert.equal(JSON.stringify(s).includes('enc:v1:'), false, 'not even the ciphertext leaves the server');
|
||
await call('admin', 'PUT', '/api/admin/settings', { smtp_pass: '' }); // blank keeps it
|
||
assert.equal(getSmtpPassword(), 'mail-pass-123!');
|
||
});
|
||
|
||
test('ENC: plain values from older versions are encrypted on start-up', async () => {
|
||
const { db } = await import('../src/db.js');
|
||
const { initSecrets, openTotp, getSmtpPassword, isSealed } = await import('../src/secrets.js');
|
||
const u = db.prepare("SELECT * FROM users WHERE email='enc@x.io'").get();
|
||
db.prepare('UPDATE users SET totp_secret=? WHERE id=?').run('JBSWY3DPEHPK3PXP', u.id);
|
||
db.prepare("UPDATE settings SET value='legacy-plain' WHERE key='smtp_pass'").run();
|
||
initSecrets();
|
||
const after = db.prepare('SELECT * FROM users WHERE id=?').get(u.id);
|
||
assert.ok(isSealed(after.totp_secret));
|
||
assert.equal(openTotp(after), 'JBSWY3DPEHPK3PXP');
|
||
assert.ok(isSealed(db.prepare("SELECT value FROM settings WHERE key='smtp_pass'").get().value));
|
||
assert.equal(getSmtpPassword(), 'legacy-plain');
|
||
});
|
||
|
||
test('ENC: a wrong or missing key refuses to start (never silently orphans data); keys can be rotated', async () => {
|
||
const { spawnSync } = await import('node:child_process');
|
||
const { db } = await import('../src/db.js');
|
||
db.exec('PRAGMA wal_checkpoint(TRUNCATE)');
|
||
// work on a copy so the running test server keeps its own key
|
||
const copy = fs.mkdtempSync(path.join(os.tmpdir(), 'pikkie-keytest-'));
|
||
fs.cpSync(process.env.PIKKIE_DATA, path.join(copy, 'data'), { recursive: true });
|
||
const material = fs.readFileSync(process.env.PIKKIE_KEY_FILE, 'utf8').trim();
|
||
const start = (env) => spawnSync(process.execPath, ['-e', "import('./src/secrets.js').then(async (m) => { const { db } = await import('./src/db.js'); const u = db.prepare(\"SELECT * FROM users WHERE email='enc@x.io'\").get(); console.log('TOTP=' + m.openTotp(u)); })"], {
|
||
cwd: path.resolve('.'), encoding: 'utf8', env: { ...process.env, PIKKIE_DATA: path.join(copy, 'data'), PIKKIE_KEY_FILE: path.join(copy, 'nokey'), PIKKIE_SECRET_KEY: '', PIKKIE_OLD_SECRET_KEY: '', ...env },
|
||
});
|
||
let r = start({});
|
||
assert.notEqual(r.status, 0);
|
||
assert.match(r.stderr, /encryption key is missing/);
|
||
assert.equal(fs.existsSync(path.join(copy, 'nokey')), false, 'no new key was invented');
|
||
r = start({ PIKKIE_SECRET_KEY: 'x'.repeat(40) });
|
||
assert.notEqual(r.status, 0);
|
||
assert.match(r.stderr, /does not match this database/);
|
||
r = start({ PIKKIE_SECRET_KEY: 'short' });
|
||
assert.match(r.stderr, /at least 32 characters/);
|
||
// rotation: new key + the old one once
|
||
const NEW = 'a brand new secret key of plenty length 123';
|
||
r = start({ PIKKIE_SECRET_KEY: NEW, PIKKIE_OLD_SECRET_KEY: material });
|
||
assert.equal(r.status, 0, r.stderr);
|
||
assert.match(r.stdout, /TOTP=JBSWY3DPEHPK3PXP/);
|
||
r = start({ PIKKIE_SECRET_KEY: NEW }); // afterwards the new key alone is enough
|
||
assert.match(r.stdout, /TOTP=JBSWY3DPEHPK3PXP/);
|
||
r = start({ PIKKIE_SECRET_KEY: material }); // …and the old one no longer opens it
|
||
assert.match(r.stderr, /does not match this database/);
|
||
// key lost for good: the documented reset discards what cannot be read and starts over with a new key
|
||
r = start({ PIKKIE_KEY_FILE: path.join(copy, 'fresh.key'), PIKKIE_RESET_SECRETS: 'wipe-2fa-and-smtp-password' });
|
||
assert.equal(r.status, 0, r.stderr);
|
||
assert.match(r.stdout, /TOTP=null/);
|
||
assert.ok(fs.existsSync(path.join(copy, 'fresh.key')));
|
||
});
|