Implement protected Studio catalog API and bounded public source reader
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
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('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/);
|
||||
});
|
||||
@@ -85,3 +85,7 @@ test('Woo variable parent range is not treated as an exact selected variant pric
|
||||
assert.equal(row.requiresVariantSelection, true);
|
||||
assert.deepEqual(row.priceRange, { minimum: 100, maximum: 200 });
|
||||
});
|
||||
|
||||
test('a repeated oversized product field cannot expand a small source into an unbounded catalog', () => {
|
||||
assert.throws(() => shopifyProducts({ products: [{ id: 1, title: 'x'.repeat(1025), variants: [{ id: 1, price: '1' }] }] }, context), { code: 'SOURCE_FIELD_TOO_LARGE' });
|
||||
});
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const http = require('node:http');
|
||||
const zlib = require('node:zlib');
|
||||
const { createPublicFetcher, publicAddress, websiteUrl } = require('../server/public-fetch.cjs');
|
||||
|
||||
async function fixture(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)); });
|
||||
const port = server.address().port, calls = [];
|
||||
const requestImpl = (url, options, callback) => {
|
||||
options.lookup(url.hostname, { all: true }, (error, addresses) => {
|
||||
assert.ifError(error);
|
||||
assert.ok(addresses.every(item => publicAddress(item.address)));
|
||||
calls.push({ pathname: url.pathname, pinned: addresses, headers: options.headers });
|
||||
});
|
||||
return http.get(new URL(url.pathname + url.search, 'http://127.0.0.1:' + port), { ...options, lookup: undefined }, callback);
|
||||
};
|
||||
return { calls, requestImpl };
|
||||
}
|
||||
const lookup = async () => [{ address: '1.1.1.1', family: 4 }];
|
||||
|
||||
test('rejects internal, mapped-private, metadata and reserved addresses', () => {
|
||||
for (const address of ['127.0.0.1', '10.1.2.3', '172.16.0.1', '192.168.1.1', '169.254.169.254', '100.64.0.1', '0.0.0.0', '::1', 'fc00::1', 'fe80::1', '::ffff:127.0.0.1', '64:ff9b::7f00:1', '2001:db8::1']) {
|
||||
assert.equal(publicAddress(address), false, address);
|
||||
}
|
||||
assert.equal(publicAddress('1.1.1.1'), true);
|
||||
assert.equal(publicAddress('2606:4700:4700::1111'), true);
|
||||
});
|
||||
|
||||
test('rejects unsupported schemes, credentials and nonstandard ports', () => {
|
||||
for (const url of ['file:///etc/passwd', 'http://user:pass@example.com/', 'http://example.com:2375/', 'ftp://example.com/']) {
|
||||
assert.throws(() => websiteUrl(url), { code: 'INVALID_SOURCE_URL' });
|
||||
}
|
||||
});
|
||||
|
||||
test('blocks numeric loopback aliases and mixed DNS before opening any request', async () => {
|
||||
let opened = 0;
|
||||
const get = createPublicFetcher({ lookup: async () => [{ address: '1.1.1.1', family: 4 }, { address: '10.0.0.1', family: 4 }], requestImpl: () => { opened++; } });
|
||||
await assert.rejects(get('http://2130706433/'), { code: 'NON_PUBLIC_SOURCE' });
|
||||
await assert.rejects(get('http://mixed.fixture/'), { code: 'NON_PUBLIC_SOURCE' });
|
||||
assert.equal(opened, 0);
|
||||
});
|
||||
|
||||
test('pins validated DNS and never forwards account credentials to source websites', async t => {
|
||||
const f = await fixture(t, (_req, res) => { res.end('{"products":[]}'); });
|
||||
const result = await createPublicFetcher({ lookup, requestImpl: f.requestImpl })('http://catalog.fixture/products.json');
|
||||
assert.equal(result.status, 200);
|
||||
assert.equal(result.body.toString(), '{"products":[]}');
|
||||
assert.deepEqual(f.calls[0].pinned, [{ address: '1.1.1.1', family: 4 }]);
|
||||
assert.equal(f.calls[0].headers.Cookie, undefined);
|
||||
assert.equal(f.calls[0].headers.Authorization, undefined);
|
||||
});
|
||||
|
||||
test('redirects are revalidated and a private redirect is never requested', async t => {
|
||||
const f = await fixture(t, (_req, res) => { res.writeHead(302, { Location: 'http://169.254.169.254/latest/' }); res.end(); });
|
||||
await assert.rejects(createPublicFetcher({ lookup, requestImpl: f.requestImpl })('http://catalog.fixture/redirect'), { code: 'NON_PUBLIC_SOURCE' });
|
||||
assert.equal(f.calls.length, 1);
|
||||
});
|
||||
|
||||
test('same-host redirect cannot bypass a DNS rebind to a private address', async t => {
|
||||
const f = await fixture(t, (_req, res) => { res.writeHead(302, { Location: '/next' }); res.end(); });
|
||||
let queries = 0;
|
||||
const dns = async () => [{ address: ++queries === 1 ? '1.1.1.1' : '127.0.0.1', family: 4 }];
|
||||
await assert.rejects(createPublicFetcher({ lookup: dns, requestImpl: f.requestImpl })('http://catalog.fixture/start'), { code: 'NON_PUBLIC_SOURCE' });
|
||||
assert.equal(f.calls.length, 1);
|
||||
});
|
||||
|
||||
test('redirect loops terminate within the configured request budget', async t => {
|
||||
const f = await fixture(t, (_req, res) => { res.writeHead(302, { Location: '/again' }); res.end(); });
|
||||
await assert.rejects(createPublicFetcher({ lookup, requestImpl: f.requestImpl, maxRedirects: 2 })('http://catalog.fixture/start'), { code: 'SOURCE_REDIRECT_LIMIT' });
|
||||
assert.equal(f.calls.length, 3);
|
||||
});
|
||||
|
||||
test('body size limits apply to decoded compressed data', async t => {
|
||||
const payload = zlib.gzipSync('x'.repeat(10000));
|
||||
const f = await fixture(t, (_req, res) => { res.writeHead(200, { 'Content-Encoding': 'gzip' }); res.end(payload); });
|
||||
await assert.rejects(createPublicFetcher({ lookup, requestImpl: f.requestImpl, maxBytes: 200 })('http://catalog.fixture/large'), { code: 'SOURCE_TOO_LARGE' });
|
||||
});
|
||||
|
||||
test('valid gzip body is decoded and slow sources time out', async t => {
|
||||
const f = await fixture(t, (req, res) => {
|
||||
if (req.url === '/slow') { res.writeHead(200); res.write('waiting'); return; }
|
||||
res.writeHead(200, { 'Content-Encoding': 'gzip' }); res.end(zlib.gzipSync('real fixture data'));
|
||||
});
|
||||
const get = createPublicFetcher({ lookup, requestImpl: f.requestImpl, timeoutMs: 2000 });
|
||||
assert.equal((await get('http://catalog.fixture/gzip')).body.toString(), 'real fixture data');
|
||||
const short = createPublicFetcher({ lookup, requestImpl: f.requestImpl, timeoutMs: 100 });
|
||||
await assert.rejects(short('http://catalog.fixture/slow'), { code: 'SOURCE_TIMEOUT' });
|
||||
});
|
||||
|
||||
test('slow DNS times out without opening a connection', async () => {
|
||||
let opened = 0;
|
||||
const get = createPublicFetcher({ lookup: () => new Promise(() => {}), requestImpl: () => { opened++; }, timeoutMs: 30 });
|
||||
await assert.rejects(get('http://catalog.fixture/'), { code: 'SOURCE_TIMEOUT' });
|
||||
assert.equal(opened, 0);
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createScraper, htmlProducts } = require('../server/scraper.cjs');
|
||||
|
||||
function response(url, value, status = 200, headers = {}) {
|
||||
return { url, status, headers, body: Buffer.from(typeof value === 'string' ? value : JSON.stringify(value)) };
|
||||
}
|
||||
const wooItem = id => ({ id, name: 'Product ' + id, sku: 'SKU-' + id, prices: { price: String(id * 100), regular_price: String(id * 120), currency_code: 'BDT', currency_minor_unit: 2 } });
|
||||
|
||||
test('reads all advertised Woo pages using a discovered subdirectory REST root', async () => {
|
||||
const calls = [];
|
||||
const scrape = createScraper({ fetchPublic: async url => {
|
||||
calls.push(url);
|
||||
if (calls.length === 1) return response('https://www.catalog.fixture/shop/', '<link rel="https://api.w.org/" href="https://www.catalog.fixture/shop/wp-json/">');
|
||||
const u = new URL(url);
|
||||
assert.equal(u.pathname, '/shop/wp-json/wc/store/v1/products');
|
||||
return response(url, u.searchParams.get('page') === '1' ? Array.from({ length: 100 }, (_, i) => wooItem(i)) : [wooItem(100)], 200, { 'x-wp-totalpages': '2' });
|
||||
} });
|
||||
const result = await scrape({ url: 'https://catalog.fixture/shop/', storeName: 'Own shop' });
|
||||
assert.equal(result.count, 101);
|
||||
assert.equal(result.domain, 'www.catalog.fixture');
|
||||
assert.equal(result.products[0].rawPrice, 0);
|
||||
assert.equal(result.products[100].rawPrice, 100);
|
||||
assert.equal(calls.length, 3);
|
||||
});
|
||||
|
||||
test('Shopify pagination preserves source currency and distinct variant records', async () => {
|
||||
const calls = [];
|
||||
const scrape = createScraper({ fetchPublic: async url => {
|
||||
calls.push(url); const u = new URL(url);
|
||||
if (u.pathname === '/') return response(url, '<html>Storefront</html>');
|
||||
if (u.pathname.includes('wp-json')) return response(url, {}, 404);
|
||||
const ids = u.searchParams.get('page') === '1' ? Array.from({ length: 250 }, (_, i) => i) : [250];
|
||||
return response(url, { currency: 'USD', products: ids.map(id => ({ id, title: 'Item ' + id, variants: [{ id: 'v-' + id, sku: 'SKU-' + id, price: '1.25' }] })) });
|
||||
} });
|
||||
const result = await scrape({ url: 'https://catalog.fixture' });
|
||||
assert.equal(result.count, 251);
|
||||
assert.equal(result.products[0].currency, 'USD');
|
||||
assert.equal(result.products[0].rawRegularPrice, null);
|
||||
assert.equal(calls.length, 4);
|
||||
});
|
||||
|
||||
test('failed later pages and repeated pages fail without claiming a complete import', async () => {
|
||||
for (const repeated of [true, false]) {
|
||||
const scrape = createScraper({ fetchPublic: async url => {
|
||||
if (new URL(url).pathname === '/') return response(url, '<html>Shop</html>');
|
||||
const second = new URL(url).searchParams.get('page') === '2';
|
||||
return response(url, Array.from({ length: 100 }, (_, i) => wooItem(i)), second && !repeated ? 503 : 200, { 'x-wp-totalpages': '2' });
|
||||
} });
|
||||
await assert.rejects(scrape({ url: 'https://catalog.fixture' }), { code: repeated ? 'PAGINATION_UNSUPPORTED' : 'INCOMPLETE_CATALOG' });
|
||||
}
|
||||
});
|
||||
|
||||
test('HTML extraction uses actual sale markup and never invents a missing amount', () => {
|
||||
const html = `<ul><li class="product"><a href="/item"><h2 class="woocommerce-loop-product__title">Own item</h2></a>
|
||||
<span class="price"><del><span class="amount">৳ 270</span></del><ins><span class="amount">৳ 220</span></ins></span></li>
|
||||
<li class="product"><h2 class="woocommerce-loop-product__title">Call for price</h2><span class="price">Contact us</span></li></ul>`;
|
||||
const result = htmlProducts(Buffer.from(html), { url: 'https://catalog.fixture/', documentUrl: 'https://catalog.fixture/shop/', name: 'Shop', id: 'own', category: 'general' });
|
||||
assert.equal(result.products[0].rawPrice, 220);
|
||||
assert.equal(result.products[0].rawRegularPrice, 270);
|
||||
assert.equal(result.products[1].rawPrice, null);
|
||||
});
|
||||
|
||||
test('public HTML pagination is followed and its limited coverage is explicit', async () => {
|
||||
const scrape = createScraper({ fetchPublic: async url => {
|
||||
const u = new URL(url);
|
||||
if (u.pathname.includes('wp-json') || u.pathname === '/products.json') return response(url, {}, 404);
|
||||
const second = u.searchParams.get('page') === '2';
|
||||
return response(url, `<script type="application/ld+json">${JSON.stringify({ '@type': 'Product', name: second ? 'Second' : 'First', sku: second ? 'B' : 'A', offers: { price: second ? 200 : 100, priceCurrency: 'BDT' } })}</script>${second ? '' : '<a rel="next" href="?page=2">Next</a>'}`);
|
||||
} });
|
||||
const result = await scrape({ url: 'https://catalog.fixture/catalog' });
|
||||
assert.equal(result.count, 2);
|
||||
assert.equal(result.sourceType, 'public-html-pages');
|
||||
assert.match(result.coverage, /not a guarantee/);
|
||||
});
|
||||
|
||||
test('request/product limits and private targets fail rather than saving a fabricated catalog', async () => {
|
||||
const scrape = createScraper({ maxProducts: 1, fetchPublic: async url => new URL(url).pathname === '/' ? response(url, '<html>Shop</html>') : response(url, [wooItem(1), wooItem(2)]) });
|
||||
await assert.rejects(scrape({ url: 'https://catalog.fixture' }), { code: 'IMPORT_LIMIT' });
|
||||
let calls = 0;
|
||||
const blocked = createScraper({ fetchPublic: async () => { calls++; throw Object.assign(new Error('blocked fixture'), { status: 400, code: 'NON_PUBLIC_SOURCE' }); } });
|
||||
await assert.rejects(blocked({ url: 'http://127.0.0.1/' }), { code: 'NON_PUBLIC_SOURCE' });
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test('an empty authoritative public catalog does not fabricate products from unrelated home markup', async () => {
|
||||
const scrape = createScraper({ fetchPublic: async url => new URL(url).pathname === '/' ? response(url, '<h1>Sale!</h1>') : response(url, []) });
|
||||
await assert.rejects(scrape({ url: 'https://catalog.fixture' }), { code: 'NO_PUBLIC_PRODUCTS' });
|
||||
});
|
||||
|
||||
test('an advertised second page is read even when the first page is shorter than the requested page size', async () => {
|
||||
let pages = 0;
|
||||
const scrape = createScraper({ pageDelayMs: 0, fetchPublic: async url => {
|
||||
if (new URL(url).pathname === '/') return response(url, '<html>Shop</html>');
|
||||
pages++;
|
||||
return response(url, [wooItem(pages)], 200, { 'x-wp-totalpages': '2' });
|
||||
} });
|
||||
assert.equal((await scrape({ url: 'https://catalog.fixture/' })).count, 2);
|
||||
assert.equal(pages, 2);
|
||||
});
|
||||
|
||||
test('request pacing can be cancelled before the next website request', async () => {
|
||||
let requests = 0;
|
||||
const controller = new AbortController();
|
||||
const scrape = createScraper({ pageDelayMs: 1000, fetchPublic: async url => { requests++; return response(url, '<html>Shop</html>'); } });
|
||||
setTimeout(() => controller.abort(), 20);
|
||||
await assert.rejects(scrape({ url: 'https://catalog.fixture/' }, { signal: controller.signal }), { code: 'IMPORT_TIMEOUT' });
|
||||
assert.equal(requests, 1);
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const os = require('node:os');
|
||||
const { createStudioServer } = require('../server/main.cjs');
|
||||
|
||||
async function app(t) {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'studio-main-'));
|
||||
const publicDirectory = path.join(root, 'public');
|
||||
await fs.mkdir(publicDirectory);
|
||||
await fs.writeFile(path.join(publicDirectory, 'index.html'), '<!doctype html><h1>Fixture Studio</h1>');
|
||||
await fs.writeFile(path.join(publicDirectory, 'app.js'), '/* fixture */\n'.repeat(200));
|
||||
await fs.writeFile(path.join(root, 'private.txt'), 'PRIVATE-FIXTURE-NOT-A-WEB-ASSET');
|
||||
const server = createStudioServer({ publicDirectory, dataDirectory: path.join(root, 'state'), publicOrigin: 'https://studio.fixture', authMeUrl: 'http://127.0.0.1:1/auth', clientMeUrl: 'http://127.0.0.1:1/client' });
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
t.after(async () => { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); await fs.rm(root, { recursive: true, force: true }); });
|
||||
return 'http://127.0.0.1:' + server.address().port;
|
||||
}
|
||||
|
||||
test('server serves existing static assets, compression and revalidation without starting a provider', async t => {
|
||||
const base = await app(t);
|
||||
const root = await fetch(base);
|
||||
assert.equal(root.status, 200);
|
||||
assert.match(await root.text(), /Fixture Studio/);
|
||||
assert.match(root.headers.get('cache-control'), /no-store/);
|
||||
const js = await fetch(base + '/app.js');
|
||||
assert.equal(js.headers.get('content-encoding'), 'gzip');
|
||||
assert.equal((await js.text()).length, '/* fixture */\n'.repeat(200).length);
|
||||
assert.equal((await fetch(base + '/app.js', { headers: { 'If-None-Match': js.headers.get('etag') } })).status, 304);
|
||||
const head = await fetch(base + '/app.js', { method: 'HEAD' });
|
||||
assert.equal(head.status, 200); assert.equal(await head.text(), '');
|
||||
});
|
||||
|
||||
test('backend source, private files and traversal paths are not static downloads', async t => {
|
||||
const base = await app(t);
|
||||
for (const route of ['/server/main.cjs', '/.env', '/docs', '/node_modules/x', '/%2e%2e%2fprivate.txt', '/assets/..%5cprivate.txt']) {
|
||||
const result = await fetch(base + route, { headers: { Accept: 'text/html' } });
|
||||
assert.equal(result.status, 404, route);
|
||||
assert.doesNotMatch(await result.text(), /PRIVATE-FIXTURE/);
|
||||
}
|
||||
});
|
||||
|
||||
test('API failures stay JSON and service health is distinct from authenticated workspace availability', async t => {
|
||||
const base = await app(t);
|
||||
assert.equal((await fetch(base + '/health')).status, 200);
|
||||
const denied = await fetch(base + '/api/get-synced-stores');
|
||||
assert.equal(denied.status, 401);
|
||||
assert.match(denied.headers.get('content-type'), /application\/json/);
|
||||
assert.equal((await denied.json()).code, 'LOGIN_REQUIRED');
|
||||
const unknown = await fetch(base + '/api/missing');
|
||||
assert.equal(unknown.status, 404);
|
||||
assert.match(unknown.headers.get('content-type'), /application\/json/);
|
||||
});
|
||||
@@ -5,14 +5,20 @@ const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { createWorkspaceResolver, requireProductWrite } = require('../server/workspace.cjs');
|
||||
const { createStore } = require('../server/store.cjs');
|
||||
const { createHash } = require('node:crypto');
|
||||
|
||||
function resolver({ role = 'client', tenant = 'verified-tenant', products = true, active = true, status = 200, captures = [] } = {}) {
|
||||
function fixtureClientId(tenant) {
|
||||
const h = createHash('sha256').update(tenant).digest('hex');
|
||||
return [h.slice(0, 8), h.slice(8, 12), h.slice(12, 16), h.slice(16, 20), h.slice(20, 32)].join('-');
|
||||
}
|
||||
|
||||
function resolver({ role = 'client', tenant = 'verified-tenant', clientId, clientActor, products = true, active = true, status = 200, captures = [] } = {}) {
|
||||
return createWorkspaceResolver({
|
||||
authMeUrl: 'http://auth.test/api/auth/me', clientMeUrl: 'http://client.test/api/me',
|
||||
fetchImpl: async (url, options) => {
|
||||
captures.push({ url, options });
|
||||
if (url.includes('auth.test')) return new Response(JSON.stringify({ user: { id: 'fixture-user', role, isActive: active } }), { status });
|
||||
return Response.json({ success: true, tenant, role: 'manager', perms: { products } });
|
||||
if (url.includes('auth.test')) return new Response(JSON.stringify({ user: { id: 'fixture-user', email: 'actor@example.test', role, isActive: active } }), { status });
|
||||
return Response.json({ success: true, tenant, clientId: clientId === undefined ? fixtureClientId(tenant) : clientId, actor: clientActor || { id: 'fixture-user', email: 'actor@example.test', role }, role: 'manager', perms: { products } });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -24,6 +30,7 @@ test('uses canonical server tenant, not client-supplied IDs or requested tenant'
|
||||
assert.equal(ws.tenant, 'verified-tenant');
|
||||
assert.match(ws.namespace, /^[a-f0-9]{64}$/);
|
||||
assert.equal(captures[1].options.headers['x-client-id'], undefined);
|
||||
assert.equal(captures[1].options.headers['x-aura-tenant'], undefined);
|
||||
assert.equal(captures[0].options.redirect, 'error');
|
||||
});
|
||||
|
||||
@@ -88,3 +95,21 @@ test('untrusted namespaces cannot become file paths', async t => {
|
||||
t.after(() => fs.rm(root, { recursive: true, force: true }));
|
||||
await assert.rejects(createStore(root).read({ namespace: '../other-client' }), /namespace/);
|
||||
});
|
||||
|
||||
test('storage identity survives tenant renaming and cannot alias another client with the same label', async () => {
|
||||
const clientId = fixtureClientId('original');
|
||||
const before = await resolver({ clientId, tenant: 'old-name' })(request());
|
||||
const after = await resolver({ clientId, tenant: 'new-name' })(request());
|
||||
const other = await resolver({ clientId: fixtureClientId('other'), tenant: 'old-name' })(request());
|
||||
assert.equal(before.namespace, after.namespace);
|
||||
assert.notEqual(before.namespace, other.namespace);
|
||||
await assert.rejects(resolver({ clientId: null })(request()), { code: 'WORKSPACE_UNAVAILABLE' });
|
||||
});
|
||||
|
||||
test('stale role, email or user identity across Auth and Client cannot select storage', async () => {
|
||||
for (const clientActor of [
|
||||
{ id: 'fixture-user', email: 'actor@example.test', role: 'owner' },
|
||||
{ id: 'fixture-user', email: 'old@example.test', role: 'client' },
|
||||
{ id: 'different-user', email: 'actor@example.test', role: 'client' }
|
||||
]) await assert.rejects(resolver({ clientActor })(request()), { code: 'SESSION_CHANGED' });
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user