'use strict'; const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); const {isDeepStrictEqual} = require('node:util'); const C = require('../server/catalog.cjs'); const K = require('../server/kernel.cjs'); const D = require('../domain/model.js'); const T = require('../server/templates.cjs'); const U = require('../server/util.cjs'); const {createApp} = require('../server/app.cjs'); const NOW = '2026-10-22T12:00:00.000Z'; const PASSWORD = 'Fictional catalog test password 2026!'; const STAGES = ['review', 'listed', 'negotiating', 'agreement', 'settlement', 'reconciled', 'cancelled', 'issue']; const TYPES = ['factsheet', 'mandate', 'ownership', 'checklist', 'costs', 'negotiation', 'instructions', 'cash', 'delivery', 'reconciliation']; let encodedPassword; const error = (code, status) => e => { assert.equal(e.code, code); if (status !== undefined) assert.equal(e.status, status); return true; }; const nonempty = value => assert.equal(typeof value === 'string' && value.trim().length > 0, true); const rounded = (numerator, denominator) => Number((numerator + denominator / 2n) / denominator); const units = value => D.decimal(String(value), 6); const money = cents => (cents / 100).toFixed(2); function database(store) { return store.all("SELECT name FROM sqlite_schema WHERE type='table' ORDER BY name").map(({name}) => ({ name, rows: store.all('SELECT * FROM "' + name.replaceAll('"', '""') + '" ORDER BY rowid') })); } function assertUnchangedExcept(before, after, allowed) { assert.deepEqual(after.map(table => table.name), before.map(table => table.name), 'views cannot change the table set'); for (let i = 0; i < after.length; i++) { if (!allowed.has(after[i].name)) assert.deepEqual(after[i], before[i], 'catalog GET changed ' + after[i].name); } } function assertContext(state, offer) { assert.deepEqual(state.catalogContext, { version: C.catalog().version, fictional: true, offer, seller: C.getCompany(offer.sellerId), buyer: C.getCompany(offer.referenceBuyerId) }); const p = state.core.positions[0]; assert.equal(p.asset, offer.name); assert.equal(p.assetId, offer.id); assert.equal(p.category, offer.category); assert.equal(p.country, offer.country); assert.equal(p.city, offer.city); assert.equal(p.issuer, offer.issuer.name); assert.deepEqual(p.policy.countries, offer.permittedBuyerCountries); } function assertExample(example, offer) { assert.equal(example.simulation, true); assert.equal(example.generatedExample, true); assert.equal(example.readOnly, true); assert.deepEqual(example.offer, offer); assert.deepEqual(example.seller, C.getCompany(offer.sellerId)); assert.deepEqual(example.buyer, C.getCompany(offer.referenceBuyerId)); const {state, artifacts} = example; assert.equal(K.valid(state), true, offer.id + ' must pass the shared kernel validator'); assert.equal(D.valid(state.core), true); assertContext(state, offer); const r = K.request(state), p = state.core.positions[0]; assert(r); assert.equal(r.status, offer.stage === 'issue' ? 'settlement' : offer.stage); assert.equal(Boolean(r.issue), offer.stage === 'issue'); assert.equal(r.quantity, units(offer.offerUnits)); assert.equal(r.priceCents, offer.unitPriceCents); assert.equal(r.issuer, offer.issuer.name); assert.equal(r.originalDeal, p.originalDeal); assert.notEqual(r.issuer, example.seller.name); assert.notEqual(r.issuer, example.buyer.name); assert.equal(state.messages.length, 0); assert.equal(state.feedback.length, 0); const e = K.economy(state); const expectedPrincipal = rounded(BigInt(r.quantity) * BigInt(r.proposal?.priceCents || r.priceCents), 1000000n); assert.equal(e.currency, 'USD'); assert.equal(e.principal, expectedPrincipal); assert.equal(e.glemo, rounded(BigInt(expectedPrincipal) * 100n, 10000n)); assert.equal(e.agent, r.agent ? e.glemo : 0); assert.equal(e.thirdPartyCents, null); assert.equal(e.taxCents, null); assert.equal(e.netBeforeUnknownCostsAndTax, e.principal - e.glemo - e.agent); assert(e.principal >= offer.minimumTicketCents && e.principal <= offer.maximumTicketCents); if (r.instructions) assert.deepEqual(r.instructions.economics, e); if (r.settlement) assert.deepEqual(r.settlement.economics, e); if (r.cash) assert.equal(r.cash.amountCents, expectedPrincipal); const initialQuantity = BigInt(units(offer.inventoryUnits)); if (r.receipt) { assert(r.cash && r.delivery && r.signatures.holder && r.signatures.buyer); assert.equal(r.receipt.allCostsKnown, false); assert.notEqual(r.receipt.actor.id, r.cash.actor.id); assert.notEqual(r.receipt.actor.id, r.delivery.actor.id); assert.equal(BigInt(p.quantity), initialQuantity - BigInt(r.quantity)); const acquired = state.core.positions.find(position => position.ownerId === r.buyerId); assert(acquired); assert.equal(acquired.quantity, r.quantity); assert.equal(acquired.costCents, expectedPrincipal); assert.equal(acquired.issuer, offer.issuer.name); assert.equal(BigInt(p.quantity) + BigInt(acquired.quantity), initialQuantity); } else { assert.equal(state.core.positions.length, 1); assert.equal(BigInt(p.quantity), initialQuantity); } assert.equal(artifacts.length, 10); assert.equal(new Set(artifacts.map(a => a.id)).size, 10); assert.deepEqual(artifacts.map(a => a.type).sort(), [...TYPES].sort()); const readiness = { factsheet: true, mandate: true, ownership: true, costs: true, checklist: Boolean(r.verification), negotiation: Boolean(r.proposal), instructions: Boolean(r.instructions), cash: Boolean(r.cash), delivery: Boolean(r.delivery), reconciliation: Boolean(r.receipt) }; for (const artifact of artifacts) { nonempty(artifact.id); nonempty(artifact.labelKey); assert.equal(artifact.status, readiness[artifact.type] ? 'generated_fixture' : 'pending', artifact.type); assert(Array.isArray(artifact.rows) && artifact.rows.length > 0); assert.equal(new Set(artifact.rows.map(row => row.key)).size, artifact.rows.length); for (const row of artifact.rows) { nonempty(row.key); assert(Object.hasOwn(row, 'value')); assert.notEqual(row.value, undefined); if (row.format !== undefined) nonempty(row.format); if (row.format === 'money') assert(Number.isSafeInteger(row.value) && row.value >= 0); } if (artifact.status === 'pending') { assert.deepEqual(artifact.rows, [{key: 'artifactStatus', value: 'evidenceNotRecorded', format: 'key'}]); } } const rows = type => Object.fromEntries(artifacts.find(a => a.type === type).rows.map(row => [row.key, row.value])); assert.equal(rows('factsheet').originalIssuer, offer.issuer.name); assert.equal(rows('ownership').originalIssuer, offer.issuer.name); assert.equal(rows('costs').principal, expectedPrincipal); assert.equal(rows('costs').glemoFee, e.glemo); assert.equal(rows('costs').agentFee, e.agent); assert.equal(rows('costs').net, e.netBeforeUnknownCostsAndTax); assert.equal(rows('costs').otherFees, 'unknown'); assert.equal(rows('costs').tax, 'unknown'); assert.equal(rows('costs').artifactStatus, 'notCollected'); for (const [type, evidence] of [['cash', r.cash], ['delivery', r.delivery], ['reconciliation', r.receipt]]) { if (evidence) assert.equal(rows(type).reference, evidence.reference); else assert.equal(rows(type).reference, undefined, 'missing evidence must never receive a completed reference'); } } async function fixture(t) { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'glemo-catalog-')); let instant = Date.parse(NOW); const app = await createApp({dataDir: dir, now: () => new Date(instant).toISOString()}); t.after(async () => { await app.close(); fs.rmSync(dir, {recursive: true, force: true}); }); encodedPassword ||= U.passwordHash(PASSWORD); const passwordHash = await encodedPassword; function person(alias, role) { const id = U.id(), orgId = U.id(); app.store.run('INSERT INTO organizations VALUES (?,?,?)', orgId, 'DEMO ' + alias, NOW); app.store.run('INSERT INTO users VALUES (?,?,?,?,?,?,?)', id, alias, role, orgId, passwordHash, 1, NOW); app.store.run('INSERT INTO profiles VALUES (?,?,?,?)', id, JSON.stringify({completed: true, preferences: {inApp: true}}), 1, NOW); return app.auth.publicUser(app.store.get('SELECT * FROM users WHERE id=?', id)); } const admin = person('catalog-owner', 'admin'); const people = Object.fromEntries(K.ROLES.map(role => [role, person('catalog-' + role, role)])); const outsider = person('catalog-outsider', 'buyer'); const members = Object.fromEntries(K.ROLES.map(role => [role, people[role].id])); const input = offer => ({title: 'DEMO catalog copy', template: offer.templateId, offerId: offer.id, members}); const command = (user, id, action, payload) => { const state = app.store.verifyCase(app.service.access(user, id)); return app.service.commands(user, id, {action, payload, expectedRevision: state.revision, expectedDealVersion: K.request(state)?.version ?? null, idempotencyKey: U.id()}); }; let base; function client() { let cookie = '', csrf = ''; return {async request(method, route, body, extra = {}) { const res = await fetch(base + route, {method, headers: { Origin: base, ...(cookie ? {Cookie: cookie} : {}), ...(csrf ? {'X-CSRF-Token': csrf} : {}), ...(body === undefined ? {} : {'Content-Type': 'application/json'}), ...extra }, body: body === undefined ? undefined : JSON.stringify(body)}); const setCookie = res.headers.get('set-cookie'); if (setCookie) cookie = setCookie.split(';')[0]; const value = await res.json(); if (value.csrf) csrf = value.csrf; return {status: res.status, value}; }}; } async function login(user) { const c = client(); const res = await c.request('POST', '/api/auth/login', {alias: user.alias, password: PASSWORD}); assert.equal(res.status, 200, JSON.stringify(res.value)); return c; } return {...app, admin, people, outsider, members, input, command, client, login, listen: async () => { base = await app.listen(); return base; }, advance: ms => { instant += ms; }}; } test('catalog declares 20 sellers, 20 buyers and 24 consistent fictional offers', () => { const catalog = C.catalog(); assert.equal(catalog.simulation, true); nonempty(catalog.version); assert.equal(catalog.companies.length, 40); assert.equal(catalog.offers.length, 24); assert.equal(new Set(catalog.companies.map(c => c.id)).size, 40); assert.equal(new Set(catalog.offers.map(o => o.id)).size, 24); assert.equal(catalog.companies.filter(c => c.role === 'seller').length, 20); assert.equal(catalog.companies.filter(c => c.role === 'buyer').length, 20); assert.deepEqual([...new Set(catalog.offers.map(o => o.stage))].sort(), [...STAGES].sort()); for (const company of catalog.companies) { for (const key of ['id', 'name', 'country', 'city']) nonempty(company[key]); assert.match(company.id, /^DEMO-(SELLER|BUYER)-\d+$/); assert.equal(company.fictional, true); assert.equal(company.realIdentityVerified, false); assert(['seller', 'buyer'].includes(company.role)); assert(Array.isArray(company.categories) && company.categories.length > 0); company.categories.forEach(nonempty); assert(Array.isArray(company.history) && company.history.length > 0); for (const history of company.history) { assert.equal(history.fictional, true); assert.equal(history.verified, false); } } for (const offer of catalog.offers) { assert.match(offer.id, /^DEMO-OFFER-\d+$/); for (const key of ['name', 'category', 'country', 'city', 'rightsKey', 'image']) nonempty(offer[key]); assert.equal(offer.fictional, true); assert.equal(offer.issuer.fictional, true); nonempty(offer.issuer.id); nonempty(offer.issuer.name); assert(T.templates.some(t => t.id === offer.templateId)); const seller = C.getCompany(offer.sellerId), buyer = C.getCompany(offer.referenceBuyerId); assert.equal(seller.role, 'seller'); assert.equal(buyer.role, 'buyer'); assert(seller.categories.includes(offer.category) && buyer.categories.includes(offer.category)); assert.equal(seller.country, offer.country); assert.equal(seller.city, offer.city); assert(offer.permittedBuyerCountries.includes(buyer.country)); for (const key of ['unitPriceCents', 'minimumTicketCents', 'maximumTicketCents']) { assert(Number.isSafeInteger(offer[key]) && offer[key] > 0, key); } assert(BigInt(units(offer.offerUnits)) > 0n); assert(BigInt(units(offer.offerUnits)) <= BigInt(units(offer.inventoryUnits))); assert(offer.minimumTicketCents <= offer.maximumTicketCents); assert(offer.tenorMonths === null || Number.isInteger(offer.tenorMonths) && offer.tenorMonths > 0); } }); test('catalog lookups reject unknown IDs and return detached fixture data', () => { const baseline = C.catalog(), offer = baseline.offers[0], company = baseline.companies[0]; for (const id of ['DEMO-OFFER-999', '', undefined, null, '../cases', {id: offer.id}]) { assert.throws(() => C.getOffer(id), error('missing', 404)); assert.throws(() => C.example(id, NOW), error('missing', 404)); } for (const id of ['DEMO-SELLER-999', '', undefined, null, {id: company.id}]) { assert.throws(() => C.getCompany(id), error('missing', 404)); } assert.throws(() => C.example(offer.id, 'not-a-date'), error('invalid')); const selected = C.getOffer(offer.id), selectedCompany = C.getCompany(company.id), returned = C.catalog(); Reflect.set(selected.issuer, 'name', 'DEMO caller mutation'); Reflect.set(selectedCompany.categories, '0', 'DEMO caller category'); Reflect.set(returned.offers, '0', null); assert.deepEqual(C.catalog(), baseline); assert.deepEqual(C.getOffer(offer.id), offer); assert.deepEqual(C.getCompany(company.id), company); }); test('all 24 examples replay through the kernel and expose 240 truthful artifact slots', async t => { const catalog = C.catalog(), artifactIds = new Set(); let pending = 0, generated = 0; for (const offer of catalog.offers) await t.test(offer.id + ' ' + offer.country + ' ' + offer.stage, () => { const example = C.example(offer.id, NOW); assertExample(example, offer); let replay = T.create(example.state.id, offer.templateId, example.state.createdAt, offer.id); for (const event of example.state.events) { const recorded = JSON.parse(event.fingerprint); assert.equal(recorded.action, event.action); assert.equal(recorded.role, event.role); assert.equal(recorded.expectedRevision, replay.revision); replay = K.command(replay, recorded.action, recorded.input, recorded.role, replay.revision, event.commandId, event.at, recorded.actor); } assert.deepEqual(replay, example.state, 'the complete example must be reproducible from genuine commands'); assert.deepEqual(C.example(offer.id, NOW), example); assert(example.state.events.every(event => Date.parse(event.at) <= Date.parse(NOW))); for (const artifact of example.artifacts) { assert.equal(artifactIds.has(artifact.id), false); artifactIds.add(artifact.id); if (artifact.status === 'pending') pending++; else generated++; } Reflect.set(example.state.catalogContext.offer.issuer, 'name', 'DEMO example mutation'); Reflect.set(example.artifacts[0].rows[0], 'value', 'DEMO artifact mutation'); assertExample(C.example(offer.id, NOW), offer); }); assert.equal(artifactIds.size, 240); assert.equal(pending + generated, 240); assert(pending > 0 && generated > 0, 'slots include pending evidence, never 240 completed executions'); }); test('catalog reads are pure and do not populate any SQLite table', async t => { const f = await fixture(t), before = database(f.store); const catalog = C.catalog(); for (const company of catalog.companies) C.getCompany(company.id); for (const offer of catalog.offers) { C.getOffer(offer.id); C.example(offer.id, NOW); } assert.deepEqual(database(f.store), before); for (const table of ['cases', 'commands', 'external_evidence', 'members', 'case_audit', 'notifications']) { assert.equal(f.store.get('SELECT count(*) AS n FROM ' + table).n, 0); } }); test('case copies snapshot all offers without participant commands; legacy cases and units stay independent', async t => { const f = await fixture(t); const legacy = f.service.createCase(f.admin, {title: 'DEMO legacy template', template: 'ae-property', members: f.members}); const legacyBefore = f.store.get('SELECT * FROM cases WHERE id=?', legacy.meta.id); assert.equal(Object.hasOwn(legacy.state, 'catalogContext'), false); assert.deepEqual(legacy.state, require('../server/privacy.cjs').state(T.create(legacy.meta.id, 'ae-property', NOW),'admin')); const copies = []; for (const offer of C.catalog().offers) { const view = f.service.createCase(f.admin, f.input(offer)); const stored = f.store.verifyCase(f.service.access(f.admin, view.meta.id)); assert.equal(K.valid(stored), true); assert.equal(stored.revision, 0); assert.equal(stored.core.revision, 0); assert.equal(stored.core.requests.length, 0); assert.deepEqual(stored.events, []); assert.deepEqual(stored.core.events, []); assert.equal(stored.mandate, null); assertContext(stored, offer); assert.equal(stored.core.positions[0].quantity, units(offer.inventoryUnits)); assert.equal(view.meta.offerId, offer.id); assert.equal(view.meta.template.asset, offer.name); assert.equal(view.meta.template.country, offer.country); assert.deepEqual(view.participants.map(p => p.id).sort(), Object.values(f.members).sort()); assert.equal(view.participants.some(p => p.id === offer.sellerId || p.id === offer.referenceBuyerId), false); copies.push(view); } assert.equal(f.store.get('SELECT count(*) AS n FROM commands').n, 0); assert.equal(f.store.get('SELECT count(*) AS n FROM external_evidence').n, 0); const offer = C.catalog().offers[0], first = copies[0]; const second = f.service.createCase(f.admin, f.input(offer)); const secondBefore = f.store.get('SELECT * FROM cases WHERE id=?', second.meta.id); const catalogBefore = C.catalog(); const exampleBefore = C.example(offer.id, NOW); const result = f.command(f.people.holder, first.meta.id, 'offer', { quantity: offer.offerUnits, price: money(offer.unitPriceCents), agent: false, thirdParty: '', acknowledged: true }); assert.equal(result.state.revision, 1); assert.equal(K.request(result.state).issuer, offer.issuer.name); const saved = f.store.verifyCase(f.service.access(f.admin, first.meta.id)); assert.equal(saved.core.events[0].actor.id, f.people.holder.id); assert.deepEqual(require('../server/privacy.cjs').state(saved,'admin').catalogContext, first.state.catalogContext); assert.deepEqual(f.store.get('SELECT * FROM cases WHERE id=?', second.meta.id), secondBefore); assert.deepEqual(f.store.get('SELECT * FROM cases WHERE id=?', legacy.meta.id), legacyBefore); assert.deepEqual(C.catalog(), catalogBefore); assert.equal(D.reserved(second.state.core, second.state.core.positions[0].id), 0n); assert.equal(D.reserved(saved.core, saved.core.positions[0].id), BigInt(units(offer.offerUnits))); assert.deepEqual(C.example(offer.id, NOW), exampleBefore); }); test('case copy rejects metadata spoofing, unknown offers and mismatched templates atomically', async t => { const f = await fixture(t), offer = C.catalog().offers[0], input = f.input(offer); const before = database(f.store); const otherTemplate = T.templates.find(template => template.id !== offer.templateId).id; for (const addition of [ {catalogContext: {version: 'spoof', offer: {...offer, unitPriceCents: 1}}}, {offer: {...offer, issuer: {id: f.admin.id, name: 'DEMO spoof', fictional: true}}}, {state: C.example(offer.id, NOW).state}, {sellerId: f.people.holder.id}, {buyerId: f.people.buyer.id}, {issuer: f.admin.id}, {unitPriceCents: 1}, {revision: 20}, {role: 'holder'}, {templateId: offer.templateId}, JSON.parse('{"__proto__":{"catalogContext":{"fictional":false}}}') ]) { assert.throws(() => f.service.createCase(f.admin, {...input, ...addition}), error('invalid', 422)); assert.deepEqual(database(f.store), before); } assert.throws(() => f.service.createCase(f.admin, {...input, template: otherTemplate}), error('invalid', 422)); for (const offerId of ['', null, 1, {}, []]) { assert.throws(() => f.service.createCase(f.admin, {...input, offerId}), error('invalid', 422)); } assert.throws(() => f.service.createCase(f.admin, {...input, offerId: 'DEMO-OFFER-999'}), error('missing', 404)); for (const member of Object.values(f.people)) { assert.throws(() => f.service.createCase(member, input), error('forbidden', 403)); } assert.deepEqual(database(f.store), before); }); test('catalog ticket limits remain server-owned even if the buyer declares a broader mandate', async t => { const f=await fixture(t); for(const country of ['AE','SG','US','HK','GB']){ const offer=C.catalog().offers.find(o=>o.country===country); const view=f.service.createCase(f.admin,f.input(offer)),id=view.meta.id; const before=f.store.get('SELECT state FROM cases WHERE id=?',id).state; assert.throws(()=>f.command(f.people.holder,id,'offer',{quantity:'1',price:money(offer.unitPriceCents),agent:false,thirdParty:'',acknowledged:true}),error('ticketRange',422)); assert.equal(f.store.get('SELECT state FROM cases WHERE id=?',id).state,before); f.command(f.people.holder,id,'offer',{quantity:offer.offerUnits,price:money(offer.unitPriceCents),agent:false,thirdParty:'',acknowledged:true}); f.command(f.people.buyer,id,'mandate',{country,qualified:true,min:'0',max:'10000000'}); f.command(f.people.compliance,id,'verify',{ownership:true,transfer:true,issuer:true,jurisdiction:true,unencumbered:true,gateway:true,documents:true,buyerReview:true,reference:'DEMO-REVIEW-'+country}); f.command(f.people.holder,id,'publish',{}); const frozen=f.store.get('SELECT state FROM cases WHERE id=?',id).state; assert.throws(()=>f.command(f.people.buyer,id,'propose',{price:'1'}),error('ticketRange',422)); assert.equal(f.store.get('SELECT state FROM cases WHERE id=?',id).state,frozen); assert.equal(f.command(f.people.buyer,id,'propose',{price:money(offer.unitPriceCents)}).state.core.requests[0].status,'negotiating'); } }); test('catalog API requires authentication and keeps fixtures separate from private cases', async t => { const f = await fixture(t); await f.listen(); const catalog = C.catalog(), offer = catalog.offers[0]; const route = id => '/api/catalog/offers/' + id + '/example'; const privateCase = f.service.createCase(f.admin, {title: 'DEMO PRIVATE CATALOG SENTINEL', template: 'ae-property', members: f.members}); f.command(f.people.buyer, privateCase.meta.id, 'feedback', {score: 3, body: 'DEMO PRIVATE FEEDBACK SENTINEL'}); const anonymous = f.client(); await t.test('every example and the index reject anonymous requests', async () => { for (const url of ['/api/catalog', ...catalog.offers.map(o => route(o.id))]) { const res = await anonymous.request('GET', url); assert.equal(res.status, 401, url); assert.equal(res.value.error.code, 'sessionExpired'); assert.equal(res.value.offers, undefined); assert.equal(res.value.state, undefined); } }); const admin = await f.login(f.admin), outsider = await f.login(f.outsider); await t.test('authenticated roles can browse fixtures without access to other private cases', async () => { for (const user of Object.values(f.people)) { const c = await f.login(user), res = await c.request('GET', '/api/catalog'); assert.equal(res.status, 200); assert.deepEqual(res.value, require('../server/privacy.cjs').catalog(catalog)); } const index = await outsider.request('GET', '/api/catalog'); assert.equal(index.status, 200); assert.deepEqual(index.value, require('../server/privacy.cjs').catalog(catalog)); for (const o of catalog.offers) { const res = await outsider.request('GET', route(o.id)); assert.equal(res.status, 200, JSON.stringify(res.value)); assert.equal(res.value.offer.id,o.id);assert.equal(res.value.buyer,null);assert.equal(res.value.artifacts.length,4);assert.equal(res.value.state.catalogContext,undefined);assert.equal(res.value.seller.name,C.getCompany(o.sellerId).name); const serialized = JSON.stringify(res.value); for (const secret of [privateCase.meta.id, privateCase.meta.title, 'DEMO PRIVATE FEEDBACK SENTINEL', PASSWORD, f.admin.id, f.people.holder.id, f.outsider.id, 'password_hash', 'token_hash', 'csrf']) { assert.equal(serialized.includes(secret), false, 'catalog leaked ' + secret); } } assert.equal((await outsider.request('GET', '/api/cases/' + privateCase.meta.id)).status, 404); assert.deepEqual((await outsider.request('GET', '/api/cases')).value.cases, []); const example = (await outsider.request('GET', route(offer.id))).value; assert.equal(example.state.id,undefined);assert.equal((await admin.request('GET', '/api/cases/PILOT-CATALOG-'+offer.id.slice(-3))).status, 404); assert.equal((await admin.request('GET', route('DEMO-OFFER-999'))).status, 404); }); await t.test('GET index and all example views preserve business data and do not extend idle sessions', async () => { const before = database(f.store); assert.equal((await admin.request('GET', '/api/catalog')).status, 200); for (const o of catalog.offers) assert.equal((await admin.request('GET', route(o.id))).status, 200); const after = database(f.store); // Authenticated GETs must retain rate limiting; ordinary polling cannot touch sessions. assertUnchangedExcept(before, after, new Set(['rate_limits'])); const changed = after.filter((table, i) => !isDeepStrictEqual(table, before[i])).map(table => table.name); assert.deepEqual(changed, ['rate_limits'], 'security rate accounting must remain active'); }); await t.test('explicit user activity may update only rate limits and session last_seen', async () => { const before = database(f.store); f.advance(1000); const res = await admin.request('GET', route(offer.id), undefined, {'X-User-Activity': '1'}); assert.equal(res.status, 200); const after = database(f.store); // This header deliberately renews idle activity; it grants no business write authority. assertUnchangedExcept(before, after, new Set(['rate_limits', 'sessions'])); const previousSessions = before.find(table => table.name === 'sessions').rows; const sessions = after.find(table => table.name === 'sessions').rows; const withoutActivity = rows => rows.map(({last_seen, ...row}) => row); assert.deepEqual(withoutActivity(sessions), withoutActivity(previousSessions)); const changed = sessions.filter((session, i) => !isDeepStrictEqual(session, previousSessions[i])); assert.equal(changed.length, 1); assert.equal(changed[0].user_id, f.admin.id); assert.equal(changed[0].last_seen, '2026-10-22T12:00:01.000Z'); }); await t.test('fixture endpoints reject writes and case copy metadata remains server-owned', async () => { const before = f.store.all('SELECT * FROM cases ORDER BY id'); for (const url of ['/api/catalog', route(offer.id)]) { const res = await admin.request('POST', url, {}); assert([404, 405].includes(res.status)); } const spoof = await admin.request('POST', '/api/cases', {...f.input(offer), catalogContext: {offer: {unitPriceCents: 1}}}); assert.equal(spoof.status, 422); const mismatch = await admin.request('POST', '/api/cases', {...f.input(offer), template: T.templates.find(t => t.id !== offer.templateId).id}); assert.equal(mismatch.status, 422); const denied = await outsider.request('POST', '/api/cases', f.input(offer)); assert.equal(denied.status, 403); assert.deepEqual(f.store.all('SELECT * FROM cases ORDER BY id'), before); const created = await admin.request('POST', '/api/cases', f.input(offer)); assert.equal(created.status, 201, JSON.stringify(created.value)); assertContext(f.store.verifyCase(f.service.access(f.admin,created.value.meta.id)), offer); assert.equal(created.value.state.revision, 0); assert.deepEqual(created.value.state.core.requests, []); assert.equal(f.store.get('SELECT count(*) AS n FROM commands WHERE case_id=?', created.value.meta.id).n, 0); assert.equal((await outsider.request('GET', '/api/cases/' + created.value.meta.id)).status, 404); }); });