Files
juli a18f992fc1 Bulk delete selected items (admins), with confirmation
Also fix the demo seed script for event-stream MCP answers.
2026-11-14 21:04:48 +01:00

364 lines
32 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}`;
let srv;
async function startServer() {
srv = spawn('node', ['src/index.js'], { env: { ...process.env, DATA_DIR: dataDir, PORT: port, PUBLIC_URL: base, ADMIN_PASSWORD: 'adminpw1' }, stdio: ['ignore', 'pipe', 'inherit'] });
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error('Test server startup timed out')), 15000);
srv.once('error', reject);
srv.once('exit', (code) => { clearTimeout(timeout); reject(new Error(`Test server exited: ${code}`)); });
srv.stdout.on('data', (d) => { if (d.toString().includes('listening')) { clearTimeout(timeout); resolve(); } });
});
}
async function restart() {
await new Promise((resolve) => { srv.once('exit', resolve); srv.kill(); });
await startServer();
}
await startServer();
let ok = 0;
/** Reads a JSON-RPC answer whether it came as plain JSON or as an event stream. */
async function rpcBody(res) {
const t = await res.text();
if (/^\s*[\[{]/.test(t)) return JSON.parse(t);
const data = t.split('\n').filter((l) => l.startsWith('data:')).map((l) => l.slice(5).trim()).filter(Boolean);
return JSON.parse(data[data.length - 1]);
}
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 || {}) } });
await (await import('./oauth.js')).testOAuth({ base, admin, step, restart, dataDir });
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 rpcBody(res); 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']) {
assert.equal((await fetch(`${base}${probe}`)).status, 200);
assert.equal((await fetch(`${mcpUrl}${probe}`)).status, 404);
}
const noAuth = await fetch(`${base}/mcp`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
assert.equal(noAuth.status, 401); assert.match(noAuth.headers.get('www-authenticate'), /resource_metadata/);
// A valid key with a bad protocol request is not a connected AI.
await fetch(mcpUrl, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'text/plain' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'bad', version: '1' } } }) });
const failedSetup = await (await S('/api/aikeys')).json();
assert.equal(failedSetup.connected, false); assert.ok(failedSetup.keys[0].last_error);
step('OAuth discovery and actionable 401; failed handshake is not connected');
const jsonInit = await fetch(mcpUrl, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'json-only', version: '1' } } }) });
assert.equal(jsonInit.status, 200); assert.match(jsonInit.headers.get('content-type'), /application\/json/); assert.ok((await jsonInit.json()).result);
assert.equal((await (await S('/api/aikeys')).json()).connected, false);
step('JSON-only compatibility; handshake alone is not tool discovery');
const init = await mcp('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '1' } });
assert.match(init.instructions, /cataloguer/); assert.match(init.instructions, /get_instructions/);
assert.ok(init.instructions.length < 2000, `handshake instructions are ${init.instructions.length} chars`); step('MCP initialize (short instructions)');
const fullInstr = await mcp('tools/call', { name: 'get_instructions', arguments: {} });
assert.match(fullInstr.content[0].text, /QUESTIONS TO THE TEAM/); assert.match(fullInstr.content[0].text, /submit_run_report/); step('get_instructions returns the full workflow');
const { Client } = await import('@modelcontextprotocol/sdk/client/index.js');
const { StreamableHTTPClientTransport } = await import('@modelcontextprotocol/sdk/client/streamableHttp.js');
const sdkTransport = new StreamableHTTPClientTransport(new URL(mcpUrl));
const sdkClient = new Client({ name: 'e2e', version: '1' });
await sdkClient.connect(sdkTransport);
assert.ok(sdkTransport.sessionId, 'server should hand out a session id');
assert.ok((await sdkClient.listTools()).tools.some((t) => t.name === 'get_instructions'));
assert.ok(!(await sdkClient.callTool({ name: 'collection_overview', arguments: {} })).isError);
const sid = sdkTransport.sessionId;
await sdkTransport.terminateSession(); await sdkClient.close();
const gone = await fetch(mcpUrl, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'mcp-session-id': sid }, body: JSON.stringify({ jsonrpc: '2.0', id: 5, method: 'tools/list' }) });
assert.equal(gone.status, 404); step('MCP sessions: id handed out, reused for calls, 404 after it ends');
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('tools/call', { name: 'get_instructions', arguments: {} })).content[0].text;
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(rpcBody);
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');
// bulk delete: admin only, removes items and their photo files
const mkItem = async () => { const f = new FormData(); f.append('photos', new Blob([img], { type: 'image/jpeg' }), 'd.jpg'); return (await (await fetch(`${base}/api/items`, { method: 'POST', body: f, headers: { cookie: admin } })).json()); };
const d1 = await mkItem(); const d2 = await mkItem();
const d1photo = path.join(dataDir, 'photos', '000', `${d1.photos[0].id}-full.jpg`);
assert.ok(fs.existsSync(d1photo));
r = await C('/api/items/bulk-delete', { method: 'POST', headers: J, body: JSON.stringify({ ids: [d1.id, d2.id] }) });
assert.equal(r.status, 403);
r = await A('/api/items/bulk-delete', { method: 'POST', body: JSON.stringify({ ids: [d1.id, d2.id, 999999] }) });
assert.equal((await r.json()).deleted, 2);
assert.equal((await A(`/api/items/${d1.id}`)).status, 404); assert.ok(!fs.existsSync(d1photo));
step('bulk delete (admin only) removes items and their photo files');
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 });
}