Files
indexipro/server/test/e2e.js
T
juli ac77df8a60 Security and robustness fixes from the code review
- Export no longer crashes the server on an unreadable photo (skips it)
- Login limits per username as well as per client; X-Forwarded-For only
  trusted from local/private proxies; constant-time unknown-user path
- Share links: internal fields always removed; values (incl. research
  notes) and notes/locations per link; filters, sort, search and CSV
  cannot reveal hidden fields; questions and stats details hidden
- Password reset/change signs other browsers out
- Comparables keep only http(s) links; CSV cells cannot start a formula
- Phone sign-in redirect stays on this site; browser security headers
- Items belong to accounts (not display names); unique display names
- Uploads go to disk, retried uploads are stored once (app 1.4.1)
- Daily database snapshots, expired-token cleanup, non-root container
2026-11-12 20:13:48 +01:00

307 lines
28 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// End-to-end smoke test: node test/e2e.js (starts its own server on a temp data dir)
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import sharp from 'sharp';
import assert from 'node:assert/strict';
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ipx-'));
const port = 18000 + Math.floor(Math.random() * 1000);
const base = `http://localhost:${port}`;
const srv = spawn('node', ['src/index.js'], { env: { ...process.env, DATA_DIR: dataDir, PORT: port, ADMIN_PASSWORD: 'adminpw1' }, stdio: ['ignore', 'pipe', 'inherit'] });
await new Promise((r) => srv.stdout.on('data', (d) => d.toString().includes('listening') && r()));
let ok = 0;
const step = (name) => { ok++; console.log('✓', name); };
const cookieOf = (r) => r.headers.get('set-cookie').split(';')[0];
try {
let r = await fetch(`${base}/api/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: 'admin', password: 'wrong' }) });
assert.equal(r.status, 401); step('wrong password rejected');
r = await fetch(`${base}/api/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: 'admin', password: 'adminpw1' }) });
assert.equal(r.status, 200); const admin = cookieOf(r); step('admin login (username + password)');
const A = (p, o = {}) => fetch(base + p, { ...o, headers: { cookie: admin, 'content-type': 'application/json', ...(o.headers || {}) } });
const info = await (await fetch(`${base}/api/info`)).json();
if (info.app.available) {
assert.match(info.app.url, /\/download\/IndexiPro-[\d.]+\.apk$/);
const apk = await fetch(info.app.url.replace(/^https?:\/\/[^/]+/, base));
assert.equal(apk.status, 200);
const bytes = Buffer.from(await apk.arrayBuffer());
if (info.app.sha256) assert.equal((await import('node:crypto')).createHash('sha256').update(bytes).digest('hex'), info.app.sha256);
assert.equal((await fetch(`${base}/download/IndexiPro-0.0.1.apk`)).status, 404);
step('APK offered under its versioned name, checksum matches');
}
const join = await (await A('/api/join')).json();
assert.match(join.url, /\/join\/[A-Z0-9]{8}$/); assert.match(join.svg, /<svg/); step('join QR');
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: join.code, name: 'Sam', kind: 'android' }) });
assert.equal(r.status, 400); step('joining requires a password');
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: join.code, name: 'Sam', password: 'secret1', kind: 'android' }) });
const pair = await r.json(); assert.ok(pair.token); assert.equal(pair.username, 'sam'); assert.ok(pair.created); step('phone join creates editor account "sam"');
r = await fetch(`${base}/api/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: 'sam', password: 'secret1' }) });
const samWeb = cookieOf(r); assert.equal(r.status, 200); step('helper can log in on the web');
const S = (p, o = {}) => fetch(base + p, { ...o, headers: { cookie: samWeb, 'content-type': 'application/json', ...(o.headers || {}) } });
assert.equal((await S('/api/users')).status, 403); assert.equal((await S('/api/shares')).status, 403); step('editor cannot manage team or share links');
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: join.code, username: 'sam', password: 'secret1', kind: 'android' }) });
assert.ok((await r.json()).token); step('existing account can sign in a second phone with the join code');
const personal = await (await S('/api/me/pair')).json();
const pcode = personal.url.split('/').pop();
assert.equal((await (await fetch(`${base}/api/invite/${pcode}`)).json()).person, 'Sam');
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: pcode, kind: 'android' }) });
assert.ok((await r.json()).token);
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: pcode, kind: 'android' }) });
assert.equal(r.status, 404); step('personal "pair my phone" code works once');
const P = (p, o = {}) => fetch(base + p, { ...o, headers: { authorization: `Bearer ${pair.token}`, ...(o.headers || {}) } });
const img = await sharp({ create: { width: 1600, height: 1200, channels: 3, background: '#a0522d' } }).jpeg().toBuffer();
const fd = new FormData();
fd.append('photos', new Blob([img], { type: 'image/jpeg' }), 'a.jpg');
fd.append('photos', new Blob([img], { type: 'image/jpeg' }), 'b.jpg');
fd.append('note', 'old book from the attic, looks like a first edition');
fd.append('location', 'Attic box 3'); fd.append('client_id', 'abc-1'); fd.append('condition', 'fair'); fd.append('working', 'untested');
r = await P('/api/items', { method: 'POST', body: fd });
const item = await r.json(); assert.equal(r.status, 201); assert.equal(item.photos.length, 2);
assert.equal(item.condition, 'fair'); assert.equal(item.working, 'untested'); step('upload item with photos, condition and works-status');
r = await P('/api/items', { method: 'POST', body: fd }); assert.equal((await r.json()).id, item.id); step('upload retry is idempotent');
r = await P(`/photos/${item.photos[0].id}/thumb`); assert.equal(r.status, 200); step('photo thumb');
const keyRes = await (await S('/api/aikeys', { method: 'POST', body: JSON.stringify({ label: "Sam's Claude" }) })).json();
const mcpUrl = keyRes.url;
assert.ok(mcpUrl.includes(keyRes.key)); step('editor creates a personal AI connection');
assert.equal((await (await S('/api/aikeys')).json()).connected, false);
let rpcId = 0;
const mcp = async (method, params) => {
const res = await fetch(mcpUrl, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: JSON.stringify({ jsonrpc: '2.0', id: ++rpcId, method, params }) });
const j = await res.json(); if (j.error) throw new Error(JSON.stringify(j.error)); return j.result;
};
for (const probe of ['/.well-known/oauth-protected-resource', '/.well-known/oauth-authorization-server', '/.well-known/openid-configuration']) {
for (const url of [`${base}${probe}`, `${mcpUrl}${probe}`]) {
const pr = await fetch(url);
assert.equal(pr.status, 404, url); assert.match(pr.headers.get('content-type'), /json/, url);
}
}
step('OAuth discovery probes get a clean JSON 404 (no HTML)');
const init = await mcp('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '1' } });
assert.match(init.instructions, /cataloguer/); step('MCP initialize');
const res = await mcp('resources/list', {});
assert.ok(res.resources.some((r) => r.uri === 'indexipro://instructions'));
assert.equal((await mcp('resources/templates/list', {})).resourceTemplates.length, 0); step('MCP resources/list and templates/list answer normally');
const tools = (await mcp('tools/list', {})).tools.map((t) => t.name);
for (const t of ['next_items_to_identify', 'update_item', 'field_conventions', 'add_comparables', 'ask_humans', 'save_listing', 'research_links']) assert.ok(tools.includes(t), t);
step(`MCP tools/list (${tools.length} tools)`);
const call = (name, args) => mcp('tools/call', { name, arguments: args });
const next = await call('next_items_to_identify', { limit: 2 });
assert.ok(next.content.some((c) => c.type === 'image')); step('MCP next items includes images');
let u = await call('update_item', { id: item.id, title: 'J.R.R. Tolkien – The Hobbit (1937)', category: 'Books', tier: 'notable', value_low: 2000, value_high: 6000, attributes: { author: 'J.R.R. Tolkien', isbn: 'n/a', publisher: 'George Allen & Unwin' } });
assert.ok(!u.isError, JSON.stringify(u));
u = await call('update_item', { id: item.id, attributes: { isbn: null, edition: 'First edition, first impression' } });
const full = await (await A(`/api/items/${item.id}`)).json();
assert.equal(full.status, 'identified'); assert.equal(full.attributes.author, 'J.R.R. Tolkien'); assert.equal(full.attributes.isbn, undefined); assert.ok(full.attributes.edition);
step('MCP update_item with custom attributes (merge + delete)');
const conv = await call('field_conventions', {});
assert.match(conv.content[0].text, /publisher/); step('MCP field_conventions');
await call('add_comparables', { item_id: item.id, comparables: [{ source: 'Test', kind: 'sold', title: 'Hobbit 1937', price: 4000, currency: 'EUR' }] });
await call('ask_humans', { item_id: item.id, question: 'Please photograph the title page' });
const links = JSON.parse((await call('research_links', { query: 'Delft plate' })).content[0].text);
assert.ok(links.ebay_sold_by_country.de.includes('ebay.de') && links.marketplaces.marktplaats_nl && links.identify.google_images); step('research_links spans many sites and countries');
const rep = await call('submit_run_report', { report: 'Identified #1 as The Hobbit. Could not verify the printing.', processed: [item.id], uncertain: [item.id] });
assert.ok(!rep.isError);
const reports = await (await A('/api/reports')).json();
assert.equal(reports[0].uncertain[0], item.id); step('AI run report saved and visible to the team');
const todo = await (await P('/api/todo')).json(); assert.equal(todo.total, 1); step('AI question reaches the phone to-do list');
const ans = new FormData(); ans.append('photos', new Blob([img], { type: 'image/jpeg' }), 'c.jpg'); ans.append('note', 'here it is');
r = await P(`/api/items/${item.id}/photos`, { method: 'POST', body: ans });
const answered = await r.json();
assert.equal(answered.status, 'new'); assert.match(answered.human_notes, /Q: Please photograph the title page\nA \(Sam\): here it is \(added 1 photo\)/);
step('answering puts item back in the AI queue, question + answer kept in notes');
const setS = (body) => A('/api/settings', { method: 'PUT', body: JSON.stringify(body) });
const second = await call('ask_humans', { item_id: item.id, question: 'Photograph the spine' });
assert.ok(!second.isError); step('ladder: items estimated 1500+ get unlimited questions');
const onlyPhoto = new FormData(); onlyPhoto.append('photos', new Blob([img], { type: 'image/jpeg' }), 'd.jpg');
const op = await (await P(`/api/items/${item.id}/photos`, { method: 'POST', body: onlyPhoto })).json();
assert.equal(op.status, 'new'); assert.match(op.human_notes, /Q: Photograph the spine\nA \(Sam\): added 1 photo/); step('photo-only answer also records the question');
// a fresh, cheap item to walk up the ladder
const fd2 = new FormData(); fd2.append('photos', new Blob([img], { type: 'image/jpeg' }), 'x.jpg'); fd2.append('note', 'some cables');
const cheap = await (await P('/api/items', { method: 'POST', body: fd2 })).json();
let q = await call('ask_humans', { item_id: cheap.id, question: 'What is it?' });
assert.ok(!q.isError); step('ladder: no value estimate yet → 1 question');
await P(`/api/items/${cheap.id}/answer`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text: 'cables' }) });
await call('update_item', { id: cheap.id, title: 'Box of USB cables', value_low: 2, value_high: 5 });
q = await call('ask_humans', { item_id: cheap.id, question: 'How many?' });
assert.ok(q.isError && /under|0–50|get no questions/.test(q.content[0].text), q.content[0].text); step('ladder: under 50 → no questions');
await call('update_item', { id: cheap.id, value_high: 300 });
for (let i = 0; i < 3; i++) assert.ok(!(await call('ask_humans', { item_id: cheap.id, question: `Q${i}` })).isError);
q = await call('ask_humans', { item_id: cheap.id, question: 'Q4' });
assert.ok(q.isError && /100–500 EUR get 4 question/.test(q.content[0].text), q.content[0].text); step('ladder: 100–500 → 4 questions, then stop');
await call('update_item', { id: cheap.id, ai_confidence: 'low' });
assert.ok(!(await call('ask_humans', { item_id: cheap.id, question: 'Unsure one' })).isError); step('ladder: AI unsure → up to 5');
await setS({ question_ladder: { bands: [{ from: 200, max: 3 }, { from: 0, max: 0 }, { from: 200, max: 9 }], unsure: null, unknown: 2, notable: '' } });
const stg = await (await A("/api/settings")).json();
assert.deepEqual(stg.question_ladder.bands, [{ from: 0, max: 0 }, { from: 200, max: 3 }]); assert.equal(stg.question_ladder.unsure, null);
step('custom ladder saved, sorted and de-duplicated; empty = unlimited');
await setS({ question_ladder: { bands: [{ from: 0, max: 0 }, { from: 50, max: 1 }, { from: 100, max: 4 }, { from: 500, max: 8 }, { from: 1500, max: null }], unsure: 5, unknown: 1, notable: 10 } });
const sk = await (await P(`/api/items/${cheap.id}/skip-question`, { method: 'POST' })).json();
assert.equal(sk.status, 'identified'); assert.equal(sk.question, null);
q = await call('ask_humans', { item_id: cheap.id, question: 'Again?' });
assert.ok(q.isError && /switched off questions for this item/.test(q.content[0].text)); step('skip: "don\'t ask again" sticks for that item');
await setS({ questions_mode: 'off' });
q = await call('ask_humans', { item_id: item.id, question: 'x' });
assert.ok(q.isError && /switched off in Settings/.test(q.content[0].text)); step('policy: questions can be switched off entirely');
await setS({ questions_mode: 'on' });
await call('ask_humans', { item_id: item.id, question: 'One more look please' });
const dis = await (await P('/api/questions/dismiss-all', { method: 'POST' })).json();
assert.ok(dis.dismissed >= 1); assert.equal((await (await P('/api/todo')).json()).total, 0); step('dismiss all open questions');
const instr = (await mcp('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 't', version: '1' } })).instructions;
assert.match(instr, /QUESTIONS TO THE TEAM/); step('AI instructions include the question policy');
const ak = await (await S('/api/aikeys')).json();
assert.ok(ak.connected && !ak.session_prompt.includes(keyRes.key)); step('connection shows as connected; session message holds no secret');
const act = await (await A(`/api/items/${item.id}`)).json();
assert.ok(act.activity.some((a) => a.actor === "AI (Sam's Claude)")); step('AI edits are attributed to the key');
const bearer = await fetch(`${base}/mcp`, { method: 'POST', headers: { authorization: `Bearer ${keyRes.key}`, 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: JSON.stringify({ jsonrpc: '2.0', id: 99, method: 'tools/list' }) });
assert.equal(bearer.status, 200); step('MCP also accepts the key as a Bearer header');
const s = await (await A('/api/items?q=tolkien')).json(); assert.equal(s.total, 1);
const s2 = await (await A('/api/items?q=unwin')).json(); assert.equal(s2.total, 1); step('full-text search incl. custom fields');
// share links
const sh = await (await A('/api/shares', { method: 'POST', body: JSON.stringify({ label: 'Aunt Mia', show_values: false }) })).json();
r = await fetch(sh.url, { redirect: 'manual' }); assert.equal(r.status, 302); const viewer = cookieOf(r);
const V = (p, o = {}) => fetch(base + p, { ...o, headers: { cookie: viewer, 'content-type': 'application/json', ...(o.headers || {}) } });
const vi = await (await V(`/api/items/${item.id}`)).json();
assert.equal(vi.title, full.title); assert.equal(vi.value_high, null); assert.equal(vi.comparables.length, 0); step('share link: read-only view, values hidden');
r = await V(`/api/items/${item.id}`, { method: 'PATCH', body: JSON.stringify({ title: 'x' }) }); assert.equal(r.status, 403); step('share link cannot edit');
r = await V('/api/devices'); assert.equal(r.status, 403); step('share link cannot see admin pages');
r = await V(`/photos/${item.photos[0].id}/medium`); assert.equal(r.status, 200); step('share link sees photos');
const st = await (await V('/api/stats')).json(); assert.equal(st.totals.value_high, null); step('share-link stats redacted');
const shares = await (await A('/api/shares')).json();
await A(`/api/shares/${shares[0].id}`, { method: 'DELETE' });
r = await V(`/api/items/${item.id}`); assert.equal(r.status, 401); step('switched-off link stops working');
await S(`/api/aikeys/${keyRes.id}`, { method: 'DELETE' });
r = await fetch(mcpUrl, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }) });
assert.equal(r.status, 401); step('revoked AI key stops working');
const users = (await (await A('/api/users')).json()).users;
const sam = users.find((u) => u.username === 'sam');
await A(`/api/users/${sam.id}`, { method: 'PATCH', body: JSON.stringify({ disabled: true }) });
assert.equal((await P('/api/me')).status, 401); assert.equal((await S('/api/me')).status, 401); step('disabling an account signs out its phones and browsers');
const adminRow = users.find((u) => u.username === 'admin');
r = await A(`/api/users/${adminRow.id}`, { method: 'PATCH', body: JSON.stringify({ role: 'editor' }) });
assert.equal(r.status, 400); step('cannot remove the last admin');
const presets = await (await A('/api/export/presets')).json();
const books = presets.builtin.find((p) => p.key === 'books');
const pv = await (await A('/api/export/preview', { method: 'POST', body: JSON.stringify(books.spec) })).json();
assert.ok(pv.items >= 1 && pv.pdf_items >= 1); step(`export preview: book dealer preset finds ${pv.items} book(s), ${pv.pdf_items} in PDF`);
const museumish = { name: 'Old or notable', all: { categories: ['Books', 'Furniture'] }, any: { notable: true, year_before: 1900 }, pdf: { include: 'none' } };
assert.equal((await (await A('/api/export/preview', { method: 'POST', body: JSON.stringify(museumish) })).json()).items, 1); step('export: all-of + any-of selection');
const job = await (await A('/api/export', { method: 'POST', body: JSON.stringify({ ...books.spec, name: 'Book dealer', files: { csv: true, json: true, photos: true } }) })).json();
const zr = await A(job.url);
const zbuf = Buffer.from(await zr.arrayBuffer());
assert.equal(zr.headers.get('content-type'), 'application/zip');
for (const f of ['README.txt', 'items.csv', 'items.json', 'catalogue.pdf', 'photos/0001-1-']) assert.ok(zbuf.includes(Buffer.from(f)), f);
step('export zip: README, CSV, JSON, PDF catalogue and photos');
const other = await (await A('/api/users', { method: 'POST', body: JSON.stringify({ display_name: 'Mia' }) })).json();
const lo = await fetch(`${base}/api/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: other.username, password: other.password }) });
assert.equal((await fetch(base + job.url, { headers: { cookie: cookieOf(lo) } })).status, 404); step('export download link only works for the person who built it');
await A('/api/export/presets', { method: 'POST', body: JSON.stringify({ name: 'My dealer', spec: museumish }) });
assert.ok((await (await A('/api/export/presets')).json()).custom.some((p) => p.name === 'My dealer')); step('custom export preset saved');
r = await A('/api/export.csv'); const csv = await r.text(); assert.match(csv, /publisher/); step('CSV export includes custom fields');
/* ---------- security regressions ---------- */
const k2 = await (await A('/api/aikeys', { method: 'POST', body: JSON.stringify({ label: 'sec' }) })).json();
const call2 = (name, args) => fetch(k2.url, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }) }).then((x) => x.json());
const J = { 'content-type': 'application/json' };
const login = (username, password, h = {}) => fetch(`${base}/api/login`, { method: 'POST', headers: { ...J, ...h }, body: JSON.stringify({ username, password }) });
const alive = async () => (await fetch(`${base}/healthz`)).status;
// export must survive a photo file that can't be read
const victim = path.join(dataDir, 'photos', '000', `${item.photos[0].id}-full.jpg`);
fs.chmodSync(victim, 0o000);
const xjob = await (await A('/api/export', { method: 'POST', body: JSON.stringify({ name: 'Broken photo', pdf: { include: 'none' }, files: { csv: true, photos: true } }) })).json();
const xr = await A(xjob.url); const xbuf = Buffer.from(await xr.arrayBuffer());
fs.chmodSync(victim, 0o644);
assert.equal(xr.status, 200); assert.ok(xbuf.includes(Buffer.from('MISSING-PHOTOS.txt'))); assert.equal(await alive(), 200);
step('export skips an unreadable photo instead of crashing the server');
// share links: nothing hidden leaks
await A(`/api/items/${item.id}`, { method: 'PATCH', body: JSON.stringify({ research_notes: 'Sold for EUR 9000 at auction', human_notes: 'from grandma zebrawood attic', location: 'Attic box 3' }) });
const mk = async (body) => { const s2 = await (await A('/api/shares', { method: 'POST', body: JSON.stringify(body) })).json(); return cookieOf(await fetch(s2.url, { redirect: 'manual' })); };
const hidden = await mk({ label: 'hidden', show_values: false });
const HV = (p2) => fetch(base + p2, { headers: { cookie: hidden } }).then((x) => x.json());
const hv = await HV(`/api/items/${item.id}`);
assert.equal(hv.research_notes, null); assert.equal(hv.human_notes, null); assert.equal(hv.location, null); assert.equal(hv.created_by, null); assert.equal(hv.question, null);
assert.equal((await HV(`/api/items?ids=${item.id}&min_value=999999`)).total, 1); assert.equal((await HV(`/api/items?ids=${item.id}&max_value=1`)).total, 1);
step('share link (values hidden): no research notes, notes, location; value filters ignored');
assert.equal((await HV('/api/items?q=zebrawood')).total, 0); assert.equal((await HV('/api/items?q=tolkien')).total, 1);
assert.equal((await HV('/api/todo')).total, 0); assert.deepEqual((await HV('/api/stats')).contributors, []);
assert.ok(!(await (await fetch(`${base}/api/export.csv`, { headers: { cookie: hidden } })).text()).includes('zebrawood'));
step('share link: search, to-do, stats and CSV do not reveal hidden fields');
const open = await mk({ label: 'open', show_values: true, show_details: true });
const ov = await (await fetch(`${base}/api/items/${item.id}`, { headers: { cookie: open } })).json();
assert.equal(ov.location, 'Attic box 3'); assert.match(ov.research_notes, /9000/); assert.equal(ov.question, null);
step('share link with values + details switched on shows them');
// password reset / change signs browsers out
const bob = await (await A('/api/users', { method: 'POST', body: JSON.stringify({ display_name: 'Bob' }) })).json();
const bobId = (await (await A('/api/users')).json()).users.find((u2) => u2.username === bob.username).id;
const bob1 = cookieOf(await login(bob.username, bob.password));
const reset = await (await A(`/api/users/${bobId}/reset`, { method: 'POST', body: '{}' })).json();
assert.equal((await fetch(`${base}/api/me`, { headers: { cookie: bob1 } })).status, 401); step('admin password reset signs that person\'s browsers out');
const bob2 = cookieOf(await login(bob.username, reset.password)); const bob3 = cookieOf(await login(bob.username, reset.password));
r = await fetch(`${base}/api/me`, { method: 'PATCH', headers: { ...J, cookie: bob2 }, body: JSON.stringify({ current_password: reset.password, new_password: 'brandnew1' }) });
assert.equal(r.status, 200);
assert.equal((await fetch(`${base}/api/me`, { headers: { cookie: bob2 } })).status, 200); assert.equal((await fetch(`${base}/api/me`, { headers: { cookie: bob3 } })).status, 401);
step('changing your password signs out your other browsers, not this one');
// login throttle can't be dodged by faking the client address
let last = 0;
for (let i = 0; i < 52; i++) last = (await login(bob.username, 'nope', { 'x-forwarded-for': `10.9.${i}.7` })).status;
assert.equal(last, 429); assert.equal((await login(bob.username, 'brandnew1', { 'x-forwarded-for': '10.250.0.1' })).status, 429);
step('login attempts are limited per username, whatever address the client claims');
// names
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: J, body: JSON.stringify({ code: join.code, name: 'bob', password: 'secret1', kind: 'web' }) });
assert.equal(r.status, 400); assert.match((await r.json()).error, /already has an account/);
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: J, body: JSON.stringify({ code: join.code, name: "AI (Sam's Claude)", password: 'secret1', kind: 'web' }) });
assert.equal(r.status, 400); step('display names are unique and cannot pose as the AI');
// "my items" follows the account, not the name
const cara = await (await fetch(`${base}/api/pair`, { method: 'POST', headers: J, body: JSON.stringify({ code: join.code, name: 'Cara', password: 'secret1', kind: 'android' }) })).json();
const C = (p2, o = {}) => fetch(base + p2, { ...o, headers: { authorization: `Bearer ${cara.token}`, ...(o.headers || {}) } });
const cf = new FormData(); cf.append('photos', new Blob([img], { type: 'image/jpeg' }), 'c.jpg');
const mine1 = await (await C('/api/items', { method: 'POST', body: cf })).json();
await C('/api/me', { method: 'PATCH', headers: J, body: JSON.stringify({ display_name: 'Cara B' }) });
assert.equal((await (await C('/api/items?mine=1')).json()).total, 1); step('"my items" survives renaming yourself');
// retried answer upload is not stored twice
const af = () => { const f = new FormData(); f.append('photos', new Blob([img], { type: 'image/jpeg' }), 'r.jpg'); f.append('note', 'again'); f.append('client_id', 'retry-1'); return f; };
const a1 = await (await C(`/api/items/${mine1.id}/photos`, { method: 'POST', body: af() })).json();
const a2 = await (await C(`/api/items/${mine1.id}/photos`, { method: 'POST', body: af() })).json();
assert.equal(a1.photos.length, 2); assert.equal(a2.photos.length, 2); assert.equal(a2.human_notes, a1.human_notes); step('a retried photo upload is stored once');
assert.equal(fs.readdirSync(path.join(dataDir, 'tmp')).length, 0); step('upload temp files are cleaned up');
// links and spreadsheets
await call2('add_comparables', { item_id: mine1.id, comparables: [{ source: 'x', title: 'bad', url: 'javascript:alert(1)' }, { source: 'x', title: 'good', url: 'https://example.com/a' }] });
const comps = (await (await A(`/api/items/${mine1.id}`)).json()).comparables;
assert.equal(comps[0].url, null); assert.equal(comps[1].url, 'https://example.com/a'); step('comparables only keep http(s) links');
await A(`/api/items/${mine1.id}`, { method: 'PATCH', body: JSON.stringify({ title: '=HYPERLINK("http://evil.example","x")' }) });
const c2 = await (await A(`/api/export.csv?ids=${mine1.id}`)).text();
assert.ok(c2.includes(`"'=HYPERLINK(`)); step('spreadsheet cells can\'t start a formula');
// redirect + headers + snapshot
const wl = await (await C('/api/weblink', { method: 'POST', headers: J, body: JSON.stringify({ next: '/#/item/1' }) })).json();
assert.match(wl.url, /next=/);
r = await fetch(wl.url.split('?')[0] + '?next=' + encodeURIComponent('/\\evil.example'), { redirect: 'manual' });
assert.equal(r.headers.get('location'), '/'); step('phone sign-in link only redirects within this site');
const hd = (await fetch(`${base}/`)).headers;
assert.match(hd.get('content-security-policy'), /frame-ancestors 'none'/); assert.equal(hd.get('x-frame-options'), 'DENY'); assert.equal(hd.get('x-content-type-options'), 'nosniff');
step('browser security headers are set');
assert.ok(fs.readdirSync(path.join(dataDir, 'backups')).some((f) => /^indexipro-\d{4}-\d{2}-\d{2}\.sqlite$/.test(f))); step('daily database snapshot written');
console.log(`\nAll ${ok} checks passed.`);
} catch (e) {
console.error('✗ FAILED:', e); process.exitCode = 1;
} finally {
srv.kill(); fs.rmSync(dataDir, { recursive: true, force: true });
}