From 165320cc9f8c787cfddfe572afd755b2cfb030ea Mon Sep 17 00:00:00 2001 From: khondokartowsif171 Date: Mon, 19 Oct 2026 01:34:52 +0600 Subject: [PATCH] Read existing Client catalogs through verified workspace context --- app.js | 2 +- docs/connected-catalog.md | 11 ++++++ server/api.cjs | 7 ++-- server/connected.cjs | 38 ++++++++++++++++++++ server/images.cjs | 4 +-- server/main.cjs | 11 +++--- server/workspace.cjs | 31 ++++++++++++++--- test/api.test.cjs | 11 ++++++ test/connected.test.cjs | 73 +++++++++++++++++++++++++++++++++++++++ test/images.test.cjs | 18 ++++++++-- 10 files changed, 189 insertions(+), 17 deletions(-) create mode 100644 docs/connected-catalog.md create mode 100644 server/connected.cjs create mode 100644 test/connected.test.cjs diff --git a/app.js b/app.js index f69a753..64c3c44 100644 --- a/app.js +++ b/app.js @@ -6661,7 +6661,7 @@ async function initCatalogBrowser() { badge: catBadge, count: s.count || (s.products ? s.products.length : 0), products: s.products || [], - isMaster: false + isMaster: s.readOnly === true }; }); } diff --git a/docs/connected-catalog.md b/docs/connected-catalog.md new file mode 100644 index 0000000..7611e89 --- /dev/null +++ b/docs/connected-catalog.md @@ -0,0 +1,11 @@ +# Client catalog read-through + +Studio can read the current Client workspace catalog through the configured trusted `STUDIO_CLIENT_CATALOG_URL`. `STUDIO_CLIENT_PUBLIC_ORIGIN` identifies the public Client origin for relative image references; neither setting is inferred from an arbitrary browser URL. Both are required by the service entrypoint before production startup. + +The workspace resolver first verifies the active Auth identity and canonical Client membership. Its server-only catalog reader forwards the selected access cookie and canonical tenant to Client, then checks that the response's client UUID and tenant match the resolved workspace. Browser-supplied client IDs and unrelated cookies are not forwarded. Responses are bounded in size and time; redirects are rejected. Provider/database credentials remain in Client. + +The connected catalog is a read-only store alongside imports. Studio does not copy it to the private import JSON file, change its prices, write products back, or remove it through the import deletion endpoint. Source zero/unknown prices and optional currency remain distinct. Products use the same-origin image route; another connected client identifier cannot select an image. + +A bounded per-client cache keeps a successful connected read for 30 seconds. It is capped at 100 entries/64 MiB, coalesces simultaneous reads for one client, and allows at most two cold reads across clients. Every API/image request still resolves its authenticated workspace before looking at the cache. Expired/failed reads do not silently become an empty catalog or stale success. The source fetch timestamp is retained. + +The candidate image passes 65 tests, including the prior catalog/import/image/frontend checks. Tests use explicit source fixtures and no network during execution. This is not a production merchant read or a released service. Client's matching gated catalog endpoint must be deployed first, after full build/startup/recovery checks. Persistent Studio configuration and post-release verification remain open. Meta 1-Click Connector is excluded. diff --git a/server/api.cjs b/server/api.cjs index 67d82b7..1f595c5 100644 --- a/server/api.cjs +++ b/server/api.cjs @@ -42,7 +42,7 @@ function readJson(request, maxBytes) { }); } -function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, publicOrigin, maxBodyBytes = 32768, maxConcurrentImports = 1, maxImportsPerMinute = 5 }) { +function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getConnected, publicOrigin, maxBodyBytes = 32768, maxConcurrentImports = 1, maxImportsPerMinute = 5 }) { const configured = new URL(publicOrigin); if (!['http:', 'https:'].includes(configured.protocol) || configured.pathname !== '/' || configured.search || configured.hash || configured.username || configured.password) { throw new Error('A public Studio origin without path or credentials is required'); @@ -92,11 +92,14 @@ function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, publi return await imageHandler(request, response, workspace); } if (request.method === 'GET') { - return sendJson(response, 200, { success: true, stores: (await store.read(workspace)).map(record => browserStore(record, workspace)), workspace: publicWorkspace }); + const records = await store.read(workspace); + if (getConnected) records.unshift(await getConnected(workspace)); + return sendJson(response, 200, { success: true, stores: records.map(record => browserStore(record, workspace)), workspace: publicWorkspace }); } requireProductWrite(workspace); const body = await readJson(request, maxBodyBytes); if (pathname === '/api/delete-synced-store') { + if (typeof body.storeId === 'string' && body.storeId.startsWith('connected:')) throw fail(403, 'CONNECTED_CATALOG_READ_ONLY', 'Connected catalog মূল Client dashboard থেকে পরিচালনা করুন।'); if (typeof body.storeId !== 'string' || !body.storeId || body.storeId.length > 160) throw fail(400, 'INVALID_STORE_ID', 'সঠিক store নির্বাচন করুন।'); return sendJson(response, 200, { success: true, stores: (await store.remove(workspace, body.storeId)).map(record => browserStore(record, workspace)) }); } diff --git a/server/connected.cjs b/server/connected.cjs new file mode 100644 index 0000000..f2906b9 --- /dev/null +++ b/server/connected.cjs @@ -0,0 +1,38 @@ +const { product, publicLink } = require('./products.cjs'); +const { fail } = require('./workspace.cjs'); + +function createConnectedCatalog({ publicClientOrigin, ttlMs = 30000, maxCacheBytes = 64 * 1024 * 1024, maxEntries = 100, maxConcurrentReads = 2 } = {}) { + const base = new URL(publicClientOrigin); + if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password || base.pathname !== '/' || base.search || base.hash) throw new Error('A public Client origin is required'); + const cache = new Map(), inflight = new Map(); let cachedBytes = 0; + return async function connected(workspace) { + const key = workspace.namespace, now = Date.now(); + for (const [id, item] of cache) if (item.expires <= now) { cache.delete(id); cachedBytes -= item.bytes; } + if (cache.has(key)) return cache.get(key).store; + if (inflight.has(key)) return inflight.get(key); + if (inflight.size >= maxConcurrentReads) throw fail(503, 'CONNECTED_CATALOG_BUSY', 'Catalog পড়ার কাজ চলছে; অল্প পরে আবার চেষ্টা করুন।'); + const task = (async () => { + if (typeof workspace.readConnectedCatalog !== 'function') throw fail(503, 'CONNECTED_CATALOG_UNAVAILABLE', 'Connected catalog service প্রস্তুত নয়।'); + const source = await workspace.readConnectedCatalog(); + if (!Array.isArray(source.products) || source.products.length > 20000 || !['supabase', 'database'].includes(source.source)) throw fail(502, 'INVALID_CONNECTED_CATALOG', 'Connected catalog সঠিক তালিকা দেয়নি।'); + const id = 'connected:' + workspace.clientId; + const context = { id, url: base.origin, documentUrl: base.origin, name: workspace.displayName || workspace.tenant, category: 'general' }; + const products = source.products.map(row => ({ ...product({ + sourceId: row.id, sku: row.sku, title: row.title, brand: row.brand, + price: row.rawPrice, regular: row.rawRegularPrice, currency: row.currency, + image: row.image, link: row.link, inStock: row.inStock + }, context), link: publicLink(row.link, base.origin) })); + const store = { id, name: context.name, url: '', domain: '', category: 'general', readOnly: true, + sourceType: 'connected-' + source.source, fetchedAt: source.fetchedAt, count: products.length, products }; + const bytes = Buffer.byteLength(JSON.stringify(store)); + if (bytes <= maxCacheBytes && maxEntries > 0 && ttlMs > 0) { + while (cache.size && (cache.size >= maxEntries || cachedBytes + bytes > maxCacheBytes)) { const oldest = cache.keys().next().value; cachedBytes -= cache.get(oldest).bytes; cache.delete(oldest); } + cache.set(key, { store, bytes, expires: Date.now() + ttlMs }); cachedBytes += bytes; + } + return store; + })(); + inflight.set(key, task); + try { return await task; } finally { if (inflight.get(key) === task) inflight.delete(key); } + }; +} +module.exports = { createConnectedCatalog }; diff --git a/server/images.cjs b/server/images.cjs index 276d913..14e418b 100644 --- a/server/images.cjs +++ b/server/images.cjs @@ -10,7 +10,7 @@ function rasterType(body) { return null; } -function createImageHandler({ store, fetchPublic, maxConcurrent = 4 }) { +function createImageHandler({ store, fetchPublic, getConnected, maxConcurrent = 4 }) { if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1) throw new Error('Invalid image concurrency'); let running = 0; return async function image(request, response, workspace) { @@ -20,7 +20,7 @@ function createImageHandler({ store, fetchPublic, maxConcurrent = 4 }) { if (!storeId || storeId.length > 160 || !productId || productId.length > 8192 || params.has('url')) { throw fail(400, 'INVALID_IMAGE_REFERENCE', 'Catalog-এর product image নির্বাচন করুন।'); } - const records = await store.read(workspace); + const records = storeId.startsWith('connected:') && getConnected ? [await getConnected(workspace)] : await store.read(workspace); const product = records.find(item => item.id === storeId)?.products?.find(item => String(item.id) === productId); if (!product || typeof product.image !== 'string' || !product.image) throw fail(404, 'IMAGE_NOT_FOUND', 'Product image পাওয়া যায়নি।'); if (running >= maxConcurrent) throw fail(503, 'IMAGE_BUSY', 'Image অল্প পরে আবার খুলুন।'); diff --git a/server/main.cjs b/server/main.cjs index ac7e112..026f13e 100644 --- a/server/main.cjs +++ b/server/main.cjs @@ -6,6 +6,7 @@ const { createPublicFetcher } = require('./public-fetch.cjs'); const { createScraper } = require('./scraper.cjs'); const { createApiHandler } = require('./api.cjs'); const { createImageHandler } = require('./images.cjs'); +const { createConnectedCatalog } = require('./connected.cjs'); const { createStaticHandler } = require('./static.cjs'); function createStudioServer(config) { @@ -15,11 +16,12 @@ function createStudioServer(config) { if (!['https:', 'http:'].includes(parsed.protocol) || parsed.username || parsed.password || parsed.hash) throw new Error('Invalid public login URL'); loginUrl = parsed.href; } - const resolveWorkspace = createWorkspaceResolver({ authMeUrl: config.authMeUrl, clientMeUrl: config.clientMeUrl }); + const resolveWorkspace = createWorkspaceResolver({ authMeUrl: config.authMeUrl, clientMeUrl: config.clientMeUrl, clientCatalogUrl: config.clientCatalogUrl }); + const getConnected = config.clientCatalogUrl ? createConnectedCatalog({ publicClientOrigin: config.publicClientOrigin }) : undefined; const store = createStore(config.dataDirectory); const scrape = createScraper({ fetchPublic: createPublicFetcher(config.fetchLimits), ...config.importLimits }); - const imageHandler = createImageHandler({ store, fetchPublic: createPublicFetcher({ maxBytes: 5 * 1024 * 1024, timeoutMs: 10000 }) }); - const api = createApiHandler({ resolveWorkspace, store, scrape, imageHandler, publicOrigin: config.publicOrigin, ...config.apiLimits }); + const imageHandler = createImageHandler({ store, getConnected, fetchPublic: createPublicFetcher({ maxBytes: 5 * 1024 * 1024, timeoutMs: 10000 }) }); + const api = createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getConnected, publicOrigin: config.publicOrigin, ...config.apiLimits }); const staticFiles = createStaticHandler(config.publicDirectory); const server = http.createServer({ maxHeaderSize: 16384 }, async (req, res) => { try { @@ -47,7 +49,7 @@ function createStudioServer(config) { if (require.main === module) { try { - const required = ['STUDIO_PUBLIC_ORIGIN', 'STUDIO_LOGIN_URL', 'STUDIO_AUTH_ME_URL', 'STUDIO_CLIENT_ME_URL', 'STUDIO_DATA_DIR']; + const required = ['STUDIO_PUBLIC_ORIGIN', 'STUDIO_LOGIN_URL', 'STUDIO_AUTH_ME_URL', 'STUDIO_CLIENT_ME_URL', 'STUDIO_CLIENT_CATALOG_URL', 'STUDIO_CLIENT_PUBLIC_ORIGIN', 'STUDIO_DATA_DIR']; if (required.some(name => !process.env[name])) throw new Error('Required Studio service configuration is missing'); const port = Number(process.env.PORT || 3000); if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid Studio port'); @@ -61,6 +63,7 @@ if (require.main === module) { publicOrigin: process.env.STUDIO_PUBLIC_ORIGIN, loginUrl: process.env.STUDIO_LOGIN_URL, authMeUrl: process.env.STUDIO_AUTH_ME_URL, clientMeUrl: process.env.STUDIO_CLIENT_ME_URL, + clientCatalogUrl: process.env.STUDIO_CLIENT_CATALOG_URL, publicClientOrigin: process.env.STUDIO_CLIENT_PUBLIC_ORIGIN, dataDirectory: process.env.STUDIO_DATA_DIR, publicDirectory: process.env.STUDIO_PUBLIC_DIR || path.join(__dirname, '../public'), fetchLimits: { maxBytes: limit('STUDIO_MAX_SOURCE_BYTES'), timeoutMs: limit('STUDIO_SOURCE_TIMEOUT_MS') }, diff --git a/server/workspace.cjs b/server/workspace.cjs index 8f9a592..59778eb 100644 --- a/server/workspace.cjs +++ b/server/workspace.cjs @@ -21,15 +21,16 @@ function configuredUrl(value) { return url.href; } -function createWorkspaceResolver({ authMeUrl, clientMeUrl, fetchImpl = fetch, timeoutMs = 5000 }) { +function createWorkspaceResolver({ authMeUrl, clientMeUrl, clientCatalogUrl, fetchImpl = fetch, timeoutMs = 5000 }) { const authUrl = configuredUrl(authMeUrl); const clientUrl = configuredUrl(clientMeUrl); + const catalogUrl = clientCatalogUrl ? configuredUrl(clientCatalogUrl) : null; - async function read(url, headers) { + async function read(url, headers, maxBytes = 256 * 1024, deadlineMs = timeoutMs) { let response; try { response = await fetchImpl(url, { - method: 'GET', headers, redirect: 'error', signal: AbortSignal.timeout(timeoutMs) + method: 'GET', headers, redirect: 'error', signal: AbortSignal.timeout(deadlineMs) }); } catch { throw fail(503, 'IDENTITY_SERVICE_UNAVAILABLE', 'Workspace যাচাইয়ের service এখন পাওয়া যাচ্ছে না।'); @@ -38,7 +39,17 @@ function createWorkspaceResolver({ authMeUrl, clientMeUrl, fetchImpl = fetch, ti throw fail(401, 'LOGIN_REQUIRED', 'আপনার Aura account-এ আবার login করুন।'); } if (!response.ok) throw fail(503, 'IDENTITY_SERVICE_UNAVAILABLE', 'Workspace যাচাই করা যায়নি।'); - try { return await response.json(); } + try { + if (Number(response.headers?.get('content-length')) > maxBytes) throw new Error('Response limit'); + if (response.body) { + const chunks = []; let size = 0; + for await (const chunk of response.body) { size += chunk.length; if (size > maxBytes) throw new Error('Response limit'); chunks.push(Buffer.from(chunk)); } + return JSON.parse(Buffer.concat(chunks).toString('utf8')); + } + const value = await response.json(); + if (Buffer.byteLength(JSON.stringify(value)) > maxBytes) throw new Error('Response limit'); + return value; + } catch { throw fail(503, 'INVALID_IDENTITY_RESPONSE', 'Workspace service সঠিক উত্তর দেয়নি।'); } } @@ -78,7 +89,7 @@ function createWorkspaceResolver({ authMeUrl, clientMeUrl, fetchImpl = fetch, ti } const tenant = context.tenant.trim().toLowerCase(); const clientId = context.clientId.toLowerCase(); - return { + const workspace = { tenant, clientId, namespace: createHash('sha256').update('client:' + clientId).digest('hex'), userId: user.id, @@ -86,6 +97,16 @@ function createWorkspaceResolver({ authMeUrl, clientMeUrl, fetchImpl = fetch, ti canWriteProducts: context.perms?.products === true, displayName: typeof context.clientName === 'string' ? context.clientName : '' }; + if (catalogUrl) workspace.readConnectedCatalog = async () => { + let catalog; + try { catalog = await read(catalogUrl, { ...headers, 'x-aura-tenant': tenant }, 16 * 1024 * 1024, 35000); } + catch { throw fail(503, 'CONNECTED_CATALOG_UNAVAILABLE', 'Connected catalog এখন পড়া যায়নি; আগের data মুছে দেওয়া হয়নি।'); } + if (catalog?.success !== true || typeof catalog.clientId !== 'string' || catalog.clientId.toLowerCase() !== clientId || typeof catalog.tenant !== 'string' || catalog.tenant.toLowerCase() !== tenant) { + throw fail(403, 'CATALOG_WORKSPACE_MISMATCH', 'Catalog-এর workspace মেলেনি।'); + } + return catalog; + }; + return workspace; }; } diff --git a/test/api.test.cjs b/test/api.test.cjs index 93cc085..179f902 100644 --- a/test/api.test.cjs +++ b/test/api.test.cjs @@ -144,3 +144,14 @@ test('workspace bootstrap returns canonical client identity without reading save 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'); +}); diff --git a/test/connected.test.cjs b/test/connected.test.cjs new file mode 100644 index 0000000..4df5767 --- /dev/null +++ b/test/connected.test.cjs @@ -0,0 +1,73 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { createWorkspaceResolver } = require('../server/workspace.cjs'); +const { createConnectedCatalog } = require('../server/connected.cjs'); +const clientId = '11111111-1111-4111-8111-111111111111'; +function workspace(name = 'a', readConnectedCatalog) { + return { clientId: name === 'a' ? clientId : '22222222-2222-4222-8222-222222222222', tenant: name, displayName: 'Fixture ' + name, namespace: name.repeat(64), readConnectedCatalog }; +} +function catalog(products = []) { return { source: 'supabase', fetchedAt: '2026-10-19T00:00:00Z', products }; } + +test('connected catalog preserves zero/unknown prices, image URLs and source timestamps without persistent writes', async () => { + const get = createConnectedCatalog({ publicClientOrigin: 'https://client.fixture' }); + const store = await get(workspace('a', async () => catalog([ + { id: 'one', title: 'Source ', rawPrice: 0, rawRegularPrice: 270, currency: 'BDT', image: 'https://images.fixture/product.png' }, + { id: 'two', title: 'Missing price', rawPrice: null, currency: null } + ]))); + assert.equal(store.readOnly, true); assert.equal(store.id, 'connected:' + clientId); + assert.equal(store.products[0].rawPrice, 0); assert.equal(store.products[0].image, 'https://images.fixture/product.png'); + assert.equal(store.products[1].rawPrice, null); assert.equal(store.products[1].currency, null); + assert.equal(store.products[1].link, ''); assert.equal(store.fetchedAt, '2026-10-19T00:00:00Z'); +}); + +test('connected cache shares one source read for the same client and separates other workspaces', async () => { + let reads = 0; + const get = createConnectedCatalog({ publicClientOrigin: 'https://client.fixture' }); + const read = async () => { reads++; return catalog([{ id: 'one', title: 'Product', rawPrice: 380 }]); }; + const same = workspace('a', read); + await Promise.all([get(same), get(same), get(same)]); + assert.equal(reads, 1); + await get(workspace('b', read)); assert.equal(reads, 2); +}); + +test('failed connected reads never become empty success and can be retried after recovery', async () => { + const get = createConnectedCatalog({ publicClientOrigin: 'https://client.fixture', ttlMs: 0 }); + let broken = true; + const same = workspace('a', async () => { if (broken) throw Error('fixture outage'); return catalog(); }); + await assert.rejects(get(same), /fixture outage/); + broken = false; + assert.equal((await get(same)).products.length, 0); +}); + +test('simultaneous cold catalog reads across clients are bounded', async () => { + const get = createConnectedCatalog({ publicClientOrigin: 'https://client.fixture', maxConcurrentReads: 1 }); + let release, entered; + const started = new Promise(resolve => { entered = resolve; }); + const wait = new Promise(resolve => { release = resolve; }); + const first = get(workspace('a', async () => { entered(); await wait; return catalog(); })); + await started; + await assert.rejects(get(workspace('b', async () => catalog())), { code: 'CONNECTED_CATALOG_BUSY' }); + release(); await first; + assert.equal((await get(workspace('b', async () => catalog()))).products.length, 0); +}); + +test('Client catalog read forwards only server identity and rejects another canonical client response', async () => { + const calls = []; + let mismatch = false; + const resolve = createWorkspaceResolver({ authMeUrl: 'https://auth.fixture/me', clientMeUrl: 'https://client.fixture/me', clientCatalogUrl: 'https://client.fixture/studio/catalog', + fetchImpl: async (url, options) => { + calls.push({ url, headers: options.headers }); + const actor = { id: 'actor', email: 'actor@example.test', role: 'client' }; + if (url.includes('auth.fixture')) return Response.json({ user: { ...actor, isActive: true } }); + if (url.endsWith('/studio/catalog')) return Response.json({ success: true, clientId: mismatch ? 'other-client' : clientId, tenant: 'canonical', ...catalog() }); + return Response.json({ success: true, clientId, tenant: 'canonical', actor, perms: { products: true } }); + } + }); + const ws = await resolve({ url: '/api/get-synced-stores?tenant=victim', headers: { cookie: 'aura_access=fixture-token; unrelated=must-not-forward', 'x-client-id': 'victim' } }); + await ws.readConnectedCatalog(); + assert.equal(calls.at(-1).headers.Cookie, 'aura_access=fixture-token'); + assert.equal(calls.at(-1).headers['x-aura-tenant'], 'canonical'); + assert.equal(calls.at(-1).headers['x-client-id'], undefined); + mismatch = true; + await assert.rejects(ws.readConnectedCatalog(), { code: 'CATALOG_WORKSPACE_MISMATCH' }); +}); diff --git a/test/images.test.cjs b/test/images.test.cjs index 4fffb40..df74426 100644 --- a/test/images.test.cjs +++ b/test/images.test.cjs @@ -8,13 +8,13 @@ const { createApiHandler } = require('../server/api.cjs'); // Public-domain 1x1 transparent PNG, used only as a binary response fixture. const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9p8AAAAASUVORK5CYII=', 'base64'); -async function fixture(t, fetchPublic) { +async function fixture(t, fetchPublic, options = {}) { const reads = []; const store = { read: async workspace => { reads.push(workspace.tenant); return workspace.tenant === 'a' ? [{ id: 'shop', products: [{ id: 'product', image: 'https://images.fixture/p.png' }] }] : []; } }; - const imageHandler = createImageHandler({ store, fetchPublic, maxConcurrent: 1 }); + const imageHandler = createImageHandler({ store, fetchPublic, maxConcurrent: 1, ...options }); const api = createApiHandler({ store, imageHandler, publicOrigin: 'https://studio.fixture', scrape: async () => {}, resolveWorkspace: async req => { if (!req.headers.cookie) throw Object.assign(new Error('Login required'), { status: 401 }); @@ -25,7 +25,7 @@ async function fixture(t, fetchPublic) { await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); }); const base = 'http://127.0.0.1:' + server.address().port; - return { reads, get: (suffix = '', cookie = 'a') => fetch(base + '/api/catalog-image?storeId=shop&productId=product' + suffix, { headers: cookie ? { cookie } : {} }) }; + return { base, reads, get: (suffix = '', cookie = 'a') => fetch(base + '/api/catalog-image?storeId=shop&productId=product' + suffix, { headers: cookie ? { cookie } : {} }) }; } test('catalog image is authenticated and cannot be read from another workspace or arbitrary URL', async t => { @@ -78,3 +78,15 @@ test('concurrent image requests are bounded and capacity returns after completio assert.equal((await first).status, 200); assert.equal((await f.get()).status, 200); }); + +test('connected image lookup cannot use another client catalog identifier', async t => { + let sourceCalls = 0; + const f = await fixture(t, async () => { sourceCalls++; return { status: 200, body: png }; }, { + getConnected: async () => ({ id: 'connected:own', products: [{ id: 'p', image: 'https://images.fixture/p.png' }] }) + }); + const call = storeId => fetch(f.base + '/api/catalog-image?' + new URLSearchParams({ storeId, productId: 'p' }), { headers: { cookie: 'a' } }); + assert.equal((await call('connected:other-client')).status, 404); + assert.equal(sourceCalls, 0); + assert.equal((await call('connected:own')).status, 200); + assert.equal(sourceCalls, 1); +});