Files
indexipro/server/test/e2e.js
T
juli 4fc578f3b5 In-app updates, versioned APK downloads and one-command releases
- App downloads updates itself, verifies SHA-256, opens the installer;
  manual Check for updates menu item
- Server publishes the checksum and serves /download/IndexiPro-<v>.apk
- android/release.sh tags v<version> and publishes IndexiPro-<version>.apk
  to the Gitea release, so F-Droid can track a versioned URL
- Bump app to 1.2.0 (versionCode 3)
2026-11-12 18:10:23 +01:00

146 lines
12 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');
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); step('upload item with photos');
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;
};
const init = await mcp('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '1' } });
assert.match(init.instructions, /cataloguer/); step('MCP initialize');
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 });
assert.equal((await r.json()).status, 'new'); step('answering puts item back in the AI queue');
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');
r = await A('/api/export.csv'); const csv = await r.text(); assert.match(csv, /publisher/); step('CSV export includes custom fields');
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 });
}