Read existing Client catalogs through verified workspace context

This commit is contained in:
khondokartowsif171
2026-10-19 01:34:52 +06:00
parent 6db99f96df
commit 165320cc9f
10 changed files with 189 additions and 17 deletions
+5 -2
View File
@@ -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)) });
}
+38
View File
@@ -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 };
+2 -2
View File
@@ -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 অল্প পরে আবার খুলুন।');
+7 -4
View File
@@ -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') },
+26 -5
View File
@@ -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;
};
}