Protect Studio catalog images and expose canonical workspace bootstrap
This commit is contained in:
+20
-4
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
+3
-1
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user