Files
2026-10-19 11:54:13 +06:00

186 lines
11 KiB
JavaScript

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 === '/' ? '<html>Fixture Shop</html>' : 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('workspace branding is shared only by the same verified client and never defaults another business contact', async t => {
const f = await setup(t);
const initial = await f.call('a', '/api/workspace');
assert.deepEqual(initial.body.workspace.brand, { name: 'tenant-a', website: '', phone: '' });
const saved = await f.call('a', '/api/brand', { name: 'Client A', website: 'https://shop.example/', phone: '+44 20 7946 0958', clientId: 'victim', tenant: 'tenant-b' });
assert.equal(saved.status, 200);
assert.deepEqual((await f.call('staff', '/api/workspace')).body.workspace.brand, { name: 'Client A', website: 'https://shop.example', phone: '+442079460958' });
assert.deepEqual((await f.call('b', '/api/workspace')).body.workspace.brand, { name: 'tenant-b', website: '', phone: '' });
assert.equal((await f.call('readonly', '/api/brand', { name: 'Overwrite' })).status, 403);
assert.equal((await f.call('a', '/api/brand', { phone: '01712345678' })).status, 400);
assert.equal((await f.call('a', '/api/brand', { website: 'https://user:secret@shop.example' })).status, 400);
assert.equal((await f.call('a', '/api/brand', { website: 'javascript:alert(1)' })).status, 400);
assert.equal((await f.call('a', '/api/brand', { name: 'Overwrite' }, { Origin: 'https://other.example' })).status, 403);
assert.equal((await f.call(null, '/api/brand', { name: 'Overwrite' })).status, 401);
assert.equal((await f.call('a', '/api/workspace')).body.workspace.brand.name, 'Client A');
});
test('corrupt saved branding is reported instead of silently replaced', async t => {
const f = await setup(t);
await f.call('a', '/api/brand', { name: 'Saved name' });
const directories = await fs.readdir(f.root);
assert.equal(directories.length, 1);
await fs.writeFile(path.join(f.root, directories[0], 'brand.json'), '{broken');
assert.equal((await f.call('a', '/api/workspace')).status, 500);
assert.equal((await f.call('a', '/api/brand', { name: 'Erase' })).status, 500);
assert.equal(await fs.readFile(path.join(f.root, directories[0], 'brand.json'), 'utf8'), '{broken');
});
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/);
});
test('workspace bootstrap returns canonical client identity without reading saved catalogs', async t => {
const f = await setup(t);
const a = await f.call('a', '/api/workspace?clientId=victim&tenant=tenant-b');
assert.equal(a.status, 200);
assert.equal(a.body.workspace.tenant, 'tenant-a');
assert.match(a.body.workspace.clientId, /^[a-f0-9-]{36}$/);
assert.equal(a.body.workspace.canWriteProducts, true);
assert.equal(a.body.stores, undefined);
assert.equal(a.body.workspace.namespace, undefined);
assert.equal((await f.call(null, '/api/workspace')).status, 401);
const owner = await f.call('owner', '/api/workspace');
assert.equal(owner.status, 409);
assert.equal((await f.call('readonly', '/api/workspace')).body.workspace.canWriteProducts, false);
});
test('connected catalog remains read-only and returns same-origin image references', async t => {
const f = await setup(t, { getConnected: async ws => ({ id: 'connected:' + ws.clientId, readOnly: true, products: [{ id: 'connected-product', title: 'Source', rawPrice: 380, image: 'https://images.fixture/a.png' }] }) });
const result = await f.call('a', '/api/get-synced-stores');
assert.equal(result.body.stores[0].readOnly, true);
assert.match(result.body.stores[0].products[0].image, /^\/api\/catalog-image\?/);
assert.doesNotMatch(result.body.stores[0].products[0].image, /https:/);
const removed = await f.call('a', '/api/delete-synced-store', { storeId: result.body.stores[0].id });
assert.equal(removed.status, 403);
assert.equal(removed.body.code, 'CONNECTED_CATALOG_READ_ONLY');
});