const test = require('node:test'); const assert = require('node:assert/strict'); const http = require('node:http'); const fs = require('node:fs/promises'); const path = require('node:path'); const os = require('node:os'); const { createWorkspaceResolver } = require('../server/workspace.cjs'); const { createStore } = require('../server/store.cjs'); const { createScraper } = require('../server/scraper.cjs'); const { createApiHandler } = require('../server/api.cjs'); const { createHash } = require('node:crypto'); async function serve(t, handler) { const server = http.createServer(handler); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); }); return 'http://127.0.0.1:' + server.address().port; } async function setup(t, settings = {}) { const root = await fs.mkdtemp(path.join(os.tmpdir(), 'studio-api-')); t.after(() => fs.rm(root, { recursive: true, force: true })); const identities = { a: { id: 'actor-a', role: 'client', isActive: true, tenant: 'tenant-a', products: true }, staff: { id: 'staff-a', role: 'team_member', isActive: true, tenant: 'tenant-a', products: true }, b: { id: 'actor-b', role: 'client', isActive: true, tenant: 'tenant-b', products: true }, readonly: { id: 'reader', role: 'team_member', isActive: true, tenant: 'tenant-a', products: false }, owner: { id: 'platform-owner', role: 'owner', isActive: true, products: true } }; const counts = { auth: 0, source: 0 }; const identityService = await serve(t, (req, res) => { res.setHeader('Content-Type', 'application/json'); if (req.url === '/auth') { counts.auth++; const user = identities[req.headers.authorization?.replace('Bearer ', '')]; res.writeHead(user ? 200 : 401); return res.end(JSON.stringify({ user: user ? { ...user, email: user.id + '@example.test' } : undefined })); } const key = /aura_access=([^;]+)/.exec(req.headers.cookie || '')?.[1]; const user = identities[key]; if (!user) { res.writeHead(401); return res.end('{}'); } // Fixture membership service implements the existing gate's canonical workspace contract. const tenant = user.role === 'owner' ? req.headers['x-aura-tenant'] : user.tenant; const hash = createHash('sha256').update(tenant).digest('hex'); const clientId = [hash.slice(0, 8), hash.slice(8, 12), hash.slice(12, 16), hash.slice(16, 20), hash.slice(20, 32)].join('-'); return res.end(JSON.stringify({ success: true, tenant, clientId, actor: { id: user.id, email: user.id + '@example.test', role: user.role }, role: user.products ? 'manager' : 'agent', clientName: tenant, perms: { products: user.products } })); }); const resolve = createWorkspaceResolver({ authMeUrl: identityService + '/auth', clientMeUrl: identityService + '/client' }); const store = createStore(root); const scrape = settings.scrape || createScraper({ fetchPublic: async url => { counts.source++; return { url, status: 200, headers: {}, body: Buffer.from(new URL(url).pathname === '/' ? 'Fixture Shop' : JSON.stringify([ { id: 1, sku: 'REAL-SOURCE-SKU', name: 'Source item', prices: { price: '22000', regular_price: '27000', currency_minor_unit: 2, currency_code: 'BDT' } } ])) }; } }); const handler = createApiHandler({ resolveWorkspace: resolve, store, scrape, publicOrigin: 'https://studio.fixture', ...settings }); const base = await serve(t, handler); async function call(token, endpoint, body, extra = {}) { const headers = { ...(token ? { Cookie: 'aura_access=' + token } : {}), ...extra }; if (body !== undefined) { headers.Origin ??= 'https://studio.fixture'; headers['Content-Type'] ??= 'application/json'; } const res = await fetch(base + endpoint, { method: body === undefined ? 'GET' : 'POST', headers, body: body === undefined ? undefined : JSON.stringify(body) }); return { status: res.status, headers: res.headers, body: await res.json() }; } return { root, counts, call, base, store, resolve }; } test('HTTP import persists actual source values for owner/staff and isolates another tenant', async t => { const f = await setup(t); const result = await f.call('a', '/api/sync-store', { url: 'https://catalog.fixture', clientId: 'victim', tenant: 'tenant-b', products: [{ price: 999 }] }, { 'x-aura-tenant': 'tenant-b' }); assert.equal(result.status, 200); assert.equal(result.body.store.products[0].rawPrice, 220); assert.equal(result.body.store.products[0].rawRegularPrice, 270); assert.equal((await f.call('staff', '/api/get-synced-stores')).body.stores.length, 1); assert.deepEqual((await f.call('b', '/api/get-synced-stores?clientId=victim')).body.stores, []); await f.call('b', '/api/delete-synced-store', { storeId: result.body.store.id }); assert.equal((await f.call('a', '/api/get-synced-stores')).body.stores.length, 1); assert.equal((await f.call('a', '/api/delete-synced-store', { storeId: result.body.store.id })).status, 200); assert.deepEqual((await f.call('a', '/api/get-synced-stores')).body.stores, []); }); test('missing login and read-only membership cannot trigger source requests', async t => { const f = await setup(t); assert.equal((await f.call(null, '/api/get-synced-stores')).status, 401); assert.equal((await f.call('readonly', '/api/sync-store', { url: 'https://catalog.fixture' })).status, 403); assert.equal(f.counts.source, 0); const owner = await f.call('owner', '/api/get-synced-stores'); assert.equal(owner.status, 409); assert.equal(owner.body.code, 'WORKSPACE_REQUIRED'); }); test('cross-origin writes are rejected before contacting identity services', async t => { const f = await setup(t); const result = await f.call('a', '/api/sync-store', { url: 'https://catalog.fixture' }, { Origin: 'https://attacker.fixture', 'X-Forwarded-Host': 'studio.fixture' }); assert.equal(result.status, 403); assert.equal(f.counts.auth, 0); assert.equal(f.counts.source, 0); assert.equal(result.headers.get('access-control-allow-origin'), null); }); test('non-JSON and oversized writes fail without storing data', async t => { const f = await setup(t, { maxBodyBytes: 128 }); assert.equal((await f.call('a', '/api/sync-store', {}, { 'Content-Type': 'text/plain' })).status, 415); assert.equal((await f.call('a', '/api/sync-store', { url: 'x'.repeat(200) })).status, 413); assert.equal(f.counts.source, 0); assert.deepEqual((await f.call('a', '/api/get-synced-stores')).body.stores, []); }); test('failed source refresh leaves the previous saved catalog intact', async t => { const f = await setup(t, { scrape: async () => { throw Object.assign(new Error('incomplete fixture'), { status: 502, code: 'INCOMPLETE_CATALOG' }); } }); const ws = await f.resolve({ url: '/', headers: { cookie: 'aura_access=a' } }); await f.store.upsert(ws, { id: 'existing', products: [{ rawPrice: 380 }] }); const result = await f.call('a', '/api/sync-store', { url: 'https://catalog.fixture' }); assert.equal(result.status, 502); const saved = await f.call('a', '/api/get-synced-stores'); assert.equal(saved.body.stores[0].products[0].rawPrice, 380); }); test('rate limits stop repeated authenticated import work', async t => { const f = await setup(t, { maxImportsPerMinute: 1 }); assert.equal((await f.call('a', '/api/sync-store', { url: 'https://catalog.fixture' })).status, 200); const before = f.counts.source; assert.equal((await f.call('a', '/api/sync-store', { url: 'https://catalog.fixture' })).status, 429); assert.equal(f.counts.source, before); }); test('unknown API paths return JSON rather than an HTML success document', async t => { const f = await setup(t); const result = await f.call('a', '/api/not-real'); assert.equal(result.status, 404); assert.match(result.headers.get('content-type'), /application\/json/); assert.match(result.headers.get('cache-control'), /no-store/); });