From 07f711ff2d0b5a1bb8ec43cc64426bbfb20c0fd1 Mon Sep 17 00:00:00 2001 From: khondokartowsif171 Date: Sun, 18 Oct 2026 22:53:29 +0600 Subject: [PATCH] Protect Studio catalog images and expose canonical workspace bootstrap --- docs/runtime-reconciliation.md | 10 +++++ server/api.cjs | 24 ++++++++-- server/images.cjs | 50 +++++++++++++++++++++ server/main.cjs | 4 +- test/api.test.cjs | 15 +++++++ test/images.test.cjs | 80 ++++++++++++++++++++++++++++++++++ 6 files changed, 178 insertions(+), 5 deletions(-) create mode 100644 server/images.cjs create mode 100644 test/images.test.cjs diff --git a/docs/runtime-reconciliation.md b/docs/runtime-reconciliation.md index 1cdf80c..b34fa25 100644 --- a/docs/runtime-reconciliation.md +++ b/docs/runtime-reconciliation.md @@ -29,3 +29,13 @@ Import request pacing defaults to 350 ms between source requests, consistent wit A separate offline Nginx image build reproduces all 11 current web asset files after line-ending normalization and omits backend/test/configuration sentinel files. The candidate Nginx configuration validates. No candidate HTTP backend is running in production. Price format reference: https://developer.woocommerce.com/docs/apis/store-api/resources-endpoints/products/ documents Store API currency/minor-unit fields. https://schema.org/PriceSpecification defines structured price specifications. A parent/range amount remains distinct from a selected variation's selling price. +# Workspace and raster image integration — 18 October 2026 + +The protected API now exposes `GET /api/workspace` for the canonical Client UUID, tenant, display name and catalog permission. It returns no saved catalog or internal namespace. Missing login and owner workspace selection remain explicit failures. + +Catalog list/import/delete responses replace merchant image URLs with a same-origin `/api/catalog-image` reference. That route resolves the product from the authenticated workspace's saved catalog; arbitrary URL parameters are rejected. Its outbound reads use the bounded public fetcher, including DNS/redirect checks, a 5 MiB decoded-body ceiling and ten-second timeout. Four image reads may run concurrently. Only signature-recognized PNG, JPEG, GIF and WebP responses are returned. HTML and SVG are rejected. This is format recognition, not complete image decoding or a claim that every source image is supported. + +The backend candidate is not deployed. Frontend authentication/workspace selection, private browser-state namespacing, imported-text rendering, connected Client catalog access and persistent production configuration remain required release work. The prototype global GT catalog is not a valid default for another client. No Meta connector inspection or modification is part of this work. + +The local branch reference was found zero-filled. Its bytes were retained outside the Git refs directory, the remote branch was read, and the existing local commit object was checked before restoring the reference to `cbe6e0ae94e22e6c34ecc55bad036ff8c165b488`. No working files were reset. The cause of that local reference damage is not established. + diff --git a/server/api.cjs b/server/api.cjs index bd5435d..67d82b7 100644 --- a/server/api.cjs +++ b/server/api.cjs @@ -42,7 +42,7 @@ function readJson(request, maxBytes) { }); } -function createApiHandler({ resolveWorkspace, store, scrape, publicOrigin, maxBodyBytes = 32768, maxConcurrentImports = 1, maxImportsPerMinute = 5 }) { +function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, 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'); @@ -51,6 +51,15 @@ function createApiHandler({ resolveWorkspace, store, scrape, publicOrigin, maxBo const origin = configured.origin, attempts = new Map(); let runningImports = 0; + function browserStore(record, workspace) { + return { ...record, products: record.products.map(product => ({ + ...product, + image: product.image ? '/api/catalog-image?' + new URLSearchParams({ + storeId: record.id, productId: String(product.id), tenant: workspace.tenant + }).toString() : '' + })) }; + } + function writeOrigin(request) { if (request.headers.origin !== origin || (request.headers['sec-fetch-site'] && request.headers['sec-fetch-site'] !== 'same-origin')) { throw fail(403, 'ORIGIN_REJECTED', 'এই request Studio page থেকে পাঠান।'); @@ -69,20 +78,27 @@ function createApiHandler({ resolveWorkspace, store, scrape, publicOrigin, maxBo try { const pathname = new URL(request.url, origin).pathname; const routes = { + '/api/workspace': 'GET', '/api/catalog-image': 'GET', '/api/get-synced-stores': 'GET', '/api/sync-store': 'POST', '/api/delete-synced-store': 'POST' }; if (!routes[pathname]) return sendJson(response, 404, { success: false, code: 'NOT_FOUND', error: 'API পাওয়া যায়নি।' }); if (request.method !== routes[pathname]) return sendJson(response, 405, { success: false, code: 'METHOD_NOT_ALLOWED', error: 'এই method সমর্থিত নয়।' }); if (request.method === 'POST') writeOrigin(request); const workspace = await resolveWorkspace(request); + const publicWorkspace = { clientId: workspace.clientId, name: workspace.displayName, tenant: workspace.tenant, canWriteProducts: workspace.canWriteProducts }; + if (pathname === '/api/workspace') return sendJson(response, 200, { success: true, workspace: publicWorkspace }); + if (pathname === '/api/catalog-image') { + if (!imageHandler) throw fail(503, 'IMAGE_UNAVAILABLE', 'Product image এখন পাওয়া যাচ্ছে না।'); + return await imageHandler(request, response, workspace); + } if (request.method === 'GET') { - return sendJson(response, 200, { success: true, stores: await store.read(workspace), workspace: { name: workspace.displayName, tenant: workspace.tenant, canWriteProducts: workspace.canWriteProducts } }); + return sendJson(response, 200, { success: true, stores: (await store.read(workspace)).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 || body.storeId.length > 160) throw fail(400, 'INVALID_STORE_ID', 'সঠিক store নির্বাচন করুন।'); - return sendJson(response, 200, { success: true, stores: await store.remove(workspace, body.storeId) }); + return sendJson(response, 200, { success: true, stores: (await store.remove(workspace, body.storeId)).map(record => browserStore(record, workspace)) }); } if (runningImports >= maxConcurrentImports) throw fail(503, 'IMPORT_BUSY', 'আরেকটি import চলছে; অল্প পরে আবার চেষ্টা করুন।'); rateLimit(workspace); @@ -94,7 +110,7 @@ function createApiHandler({ resolveWorkspace, store, scrape, publicOrigin, maxBo const imported = await scrape({ url: body.url, storeName: body.storeName, category: body.category }, { signal: controller.signal }); if (controller.signal.aborted) throw fail(499, 'REQUEST_CANCELLED', 'Request বাতিল হয়েছে।'); await store.upsert(workspace, imported); - return sendJson(response, 200, { success: true, store: imported }); + return sendJson(response, 200, { success: true, store: browserStore(imported, workspace) }); } finally { runningImports--; response.off('close', disconnected); } diff --git a/server/images.cjs b/server/images.cjs new file mode 100644 index 0000000..276d913 --- /dev/null +++ b/server/images.cjs @@ -0,0 +1,50 @@ +const { fail } = require('./workspace.cjs'); + +// The browser receives raster bytes, never a redirect to a merchant-supplied URL. +function rasterType(body) { + if (!Buffer.isBuffer(body)) return null; + if (body.length >= 24 && body.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')) && body.toString('ascii', 12, 16) === 'IHDR') return 'image/png'; + if (body.length >= 4 && body[0] === 255 && body[1] === 216 && body[2] === 255) return 'image/jpeg'; + if (body.length >= 10 && ['GIF87a', 'GIF89a'].includes(body.toString('ascii', 0, 6))) return 'image/gif'; + if (body.length >= 16 && body.toString('ascii', 0, 4) === 'RIFF' && body.toString('ascii', 8, 12) === 'WEBP') return 'image/webp'; + return null; +} + +function createImageHandler({ store, fetchPublic, maxConcurrent = 4 }) { + if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1) throw new Error('Invalid image concurrency'); + let running = 0; + return async function image(request, response, workspace) { + const params = new URL(request.url, 'https://studio.invalid').searchParams; + // Look up the image in this workspace's saved catalog. No arbitrary URL proxy. + const storeId = params.get('storeId'), productId = params.get('productId'); + 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 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 অল্প পরে আবার খুলুন।'); + const controller = new AbortController(); + const disconnected = () => { if (!response.writableEnded) controller.abort(); }; + response.on('close', disconnected); + running++; + try { + const result = await fetchPublic(product.image, { signal: controller.signal }); + if (controller.signal.aborted) return; + if (result.status !== 200) throw fail(502, 'IMAGE_SOURCE_FAILED', 'Website-এর image পাওয়া যায়নি।'); + const mime = rasterType(result.body); + if (!mime) throw fail(415, 'UNSUPPORTED_IMAGE', 'এই image format preview সমর্থিত নয়।'); + response.writeHead(200, { + 'Content-Type': mime, 'Content-Length': result.body.length, + 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff', + 'Content-Security-Policy': "default-src 'none'; sandbox", + 'Cross-Origin-Resource-Policy': 'same-origin' + }); + response.end(result.body); + } finally { + running--; response.off('close', disconnected); + } + }; +} + +module.exports = { createImageHandler, rasterType }; diff --git a/server/main.cjs b/server/main.cjs index 8b2ef2e..b16b03a 100644 --- a/server/main.cjs +++ b/server/main.cjs @@ -5,13 +5,15 @@ const { createStore } = require('./store.cjs'); const { createPublicFetcher } = require('./public-fetch.cjs'); const { createScraper } = require('./scraper.cjs'); const { createApiHandler } = require('./api.cjs'); +const { createImageHandler } = require('./images.cjs'); const { createStaticHandler } = require('./static.cjs'); function createStudioServer(config) { const resolveWorkspace = createWorkspaceResolver({ authMeUrl: config.authMeUrl, clientMeUrl: config.clientMeUrl }); const store = createStore(config.dataDirectory); const scrape = createScraper({ fetchPublic: createPublicFetcher(config.fetchLimits), ...config.importLimits }); - const api = createApiHandler({ resolveWorkspace, store, scrape, publicOrigin: config.publicOrigin, ...config.apiLimits }); + 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 staticFiles = createStaticHandler(config.publicDirectory); const server = http.createServer({ maxHeaderSize: 16384 }, async (req, res) => { try { diff --git a/test/api.test.cjs b/test/api.test.cjs index 7c2b34a..93cc085 100644 --- a/test/api.test.cjs +++ b/test/api.test.cjs @@ -129,3 +129,18 @@ test('unknown API paths return JSON rather than an HTML success document', async 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); +}); diff --git a/test/images.test.cjs b/test/images.test.cjs new file mode 100644 index 0000000..4fffb40 --- /dev/null +++ b/test/images.test.cjs @@ -0,0 +1,80 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const http = require('node:http'); +const { createImageHandler, rasterType } = require('../server/images.cjs'); +const { createPublicFetcher } = require('../server/public-fetch.cjs'); +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) { + 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 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 }); + return { tenant: req.headers.cookie === 'a' ? 'a' : 'b' }; + } + }); + const server = http.createServer(api); + 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 } : {} }) }; +} + +test('catalog image is authenticated and cannot be read from another workspace or arbitrary URL', async t => { + let calls = 0; + const f = await fixture(t, async () => { calls++; return { status: 200, body: png }; }); + assert.equal((await f.get('', null)).status, 401); + assert.equal((await f.get('', 'b')).status, 404); + assert.equal((await f.get('&url=http://127.0.0.1')).status, 400); + assert.equal(calls, 0); + const result = await f.get(); + assert.equal(result.status, 200); + assert.equal(result.headers.get('content-type'), 'image/png'); + assert.match(result.headers.get('cache-control'), /no-store/); + assert.equal(result.headers.get('access-control-allow-origin'), null); + assert.equal(result.headers.get('cross-origin-resource-policy'), 'same-origin'); + assert.deepEqual(Buffer.from(await result.arrayBuffer()), png); + assert.equal(calls, 1); +}); + +test('HTML, SVG, fake MIME and source failures never become browser image responses', async t => { + for (const body of [Buffer.from(''), Buffer.from('login')]) { + const f = await fixture(t, async () => ({ status: 200, headers: { 'content-type': 'image/png' }, body })); + const result = await f.get(); + assert.equal(result.status, 415); + assert.match(result.headers.get('content-type'), /application\/json/); + } + const f = await fixture(t, async () => ({ status: 302, body: png })); + assert.equal((await f.get()).status, 502); + assert.equal(rasterType(Buffer.from('GIF89a')), null); +}); + +test('saved private image addresses are rejected before any socket is opened', async t => { + const publicFetcher = createPublicFetcher({ lookup: async () => [{ address: '127.0.0.1', family: 4 }] }); + const f = await fixture(t, publicFetcher); + const result = await f.get(); + assert.equal(result.status, 400); + assert.match((await result.json()).code, /PRIVATE|PUBLIC|SOURCE/); +}); + +test('concurrent image requests are bounded and capacity returns after completion', async t => { + let release; + const gate = new Promise(resolve => { release = resolve; }); + let entered; + const started = new Promise(resolve => { entered = resolve; }); + const f = await fixture(t, async () => { entered(); await gate; return { status: 200, body: png }; }); + const first = f.get(); + await started; + assert.equal((await f.get()).status, 503); + release(); + assert.equal((await first).status, 200); + assert.equal((await f.get()).status, 200); +});