Implement protected Studio catalog API and bounded public source reader

This commit is contained in:
khondokartowsif171
2026-10-18 21:10:07 +06:00
parent 3847a5e6a1
commit cbe6e0ae94
18 changed files with 1391 additions and 18 deletions
+112
View File
@@ -0,0 +1,112 @@
const { fail, requireProductWrite } = require('./workspace.cjs');
function sendJson(response, status, value) {
if (response.destroyed || response.writableEnded) return;
const body = JSON.stringify(value);
response.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff', 'Content-Length': Buffer.byteLength(body)
});
response.end(body);
}
function readJson(request, maxBytes) {
const contentType = String(request.headers['content-type'] || '').split(';')[0].trim().toLowerCase();
if (contentType !== 'application/json') throw fail(415, 'JSON_REQUIRED', 'JSON request প্রয়োজন।');
if (Number(request.headers['content-length']) > maxBytes) throw fail(413, 'REQUEST_TOO_LARGE', 'Request অতিরিক্ত বড়।');
return new Promise((resolve, reject) => {
const chunks = []; let bytes = 0, done = false;
function cleanup() {
request.off('data', data); request.off('end', end); request.off('error', error); request.off('aborted', aborted);
}
function finish(problem, value) {
if (done) return;
done = true; cleanup();
if (problem) { request.resume(); reject(problem); } else resolve(value);
}
function data(chunk) {
bytes += chunk.length;
if (bytes > maxBytes) return finish(fail(413, 'REQUEST_TOO_LARGE', 'Request অতিরিক্ত বড়।'));
chunks.push(chunk);
}
function end() {
let value;
try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
catch { return finish(fail(400, 'INVALID_JSON', 'Request-এর JSON সঠিক নয়।')); }
if (!value || typeof value !== 'object' || Array.isArray(value)) return finish(fail(400, 'INVALID_JSON', 'JSON object প্রয়োজন।'));
finish(null, value);
}
function error() { finish(fail(400, 'INCOMPLETE_REQUEST', 'Request সম্পূর্ণ আসেনি।')); }
function aborted() { error(); }
request.on('data', data); request.on('end', end); request.on('error', error); request.on('aborted', aborted);
});
}
function createApiHandler({ resolveWorkspace, store, scrape, 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');
}
if (![maxBodyBytes, maxConcurrentImports, maxImportsPerMinute].every(n => Number.isInteger(n) && n > 0)) throw new Error('Invalid API limits');
const origin = configured.origin, attempts = new Map();
let runningImports = 0;
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 থেকে পাঠান।');
}
}
function rateLimit(workspace) {
const now = Date.now(), key = workspace.namespace + ':' + workspace.userId;
for (const [id, item] of attempts) if (item.until <= now) attempts.delete(id);
const item = attempts.get(key) || { count: 0, until: now + 60000 };
if (item.count >= maxImportsPerMinute) throw fail(429, 'IMPORT_RATE_LIMIT', 'অল্প পরে আবার import করুন।');
item.count++; attempts.set(key, item);
if (attempts.size > 10000) attempts.delete(attempts.keys().next().value);
}
return async function api(request, response) {
try {
const pathname = new URL(request.url, origin).pathname;
const routes = {
'/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);
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 } });
}
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) });
}
if (runningImports >= maxConcurrentImports) throw fail(503, 'IMPORT_BUSY', 'আরেকটি import চলছে; অল্প পরে আবার চেষ্টা করুন।');
rateLimit(workspace);
const controller = new AbortController();
const disconnected = () => { if (!response.writableEnded) controller.abort(); };
response.on('close', disconnected);
runningImports++;
try {
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 });
} finally {
runningImports--; response.off('close', disconnected);
}
} catch (error) {
const status = Number.isInteger(error.status) && error.status >= 400 && error.status <= 599 ? error.status : 500;
if (status === 413) { response.setHeader('Connection', 'close'); request.resume(); }
return sendJson(response, status, {
success: false, code: status === 500 ? 'INTERNAL_ERROR' : (error.code || 'REQUEST_FAILED'),
error: status === 500 ? 'কাজটি সম্পন্ন হয়নি; আগের data মুছে দেওয়া হয়নি।' : error.message
});
}
};
}
module.exports = { createApiHandler };
+72
View File
@@ -0,0 +1,72 @@
const http = require('node:http');
const path = require('node:path');
const { createWorkspaceResolver } = require('./workspace.cjs');
const { createStore } = require('./store.cjs');
const { createPublicFetcher } = require('./public-fetch.cjs');
const { createScraper } = require('./scraper.cjs');
const { createApiHandler } = require('./api.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 staticFiles = createStaticHandler(config.publicDirectory);
const server = http.createServer({ maxHeaderSize: 16384 }, async (req, res) => {
try {
const pathname = new URL(req.url, config.publicOrigin).pathname;
if (pathname === '/health' && ['GET', 'HEAD'].includes(req.method)) {
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
return res.end(req.method === 'HEAD' ? undefined : JSON.stringify({ ok: true, service: 'aura-studio' }));
}
if (pathname === '/api' || pathname.startsWith('/api/')) return await api(req, res);
return await staticFiles(req, res);
} catch {
if (!res.destroyed && !res.writableEnded) { res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('Request failed'); }
}
});
server.headersTimeout = 15000;
server.requestTimeout = 20000;
server.keepAliveTimeout = 5000;
server.maxHeadersCount = 50;
return server;
}
if (require.main === module) {
try {
const required = ['STUDIO_PUBLIC_ORIGIN', 'STUDIO_AUTH_ME_URL', 'STUDIO_CLIENT_ME_URL', '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');
function limit(name, minimum = 1) {
if (process.env[name] === undefined) return undefined;
const n = Number(process.env[name]);
if (!Number.isInteger(n) || n < minimum) throw new Error('Invalid Studio resource limit');
return n;
}
const server = createStudioServer({
publicOrigin: process.env.STUDIO_PUBLIC_ORIGIN,
authMeUrl: process.env.STUDIO_AUTH_ME_URL, clientMeUrl: process.env.STUDIO_CLIENT_ME_URL,
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') },
importLimits: {
maxPages: limit('STUDIO_MAX_IMPORT_PAGES'), maxProducts: limit('STUDIO_MAX_PRODUCTS'),
maxRequests: limit('STUDIO_MAX_SOURCE_REQUESTS'), timeoutMs: limit('STUDIO_IMPORT_TIMEOUT_MS'),
pageDelayMs: limit('STUDIO_PAGE_DELAY_MS', 0)
},
apiLimits: { maxImportsPerMinute: limit('STUDIO_IMPORTS_PER_MINUTE'), maxConcurrentImports: limit('STUDIO_MAX_PARALLEL_IMPORTS') }
});
server.listen(port, '0.0.0.0', () => console.log('Aura Studio service started'));
process.on('SIGTERM', () => {
server.close();
setTimeout(() => server.closeAllConnections(), 10000).unref();
});
} catch {
console.error('Aura Studio startup failed: verify required service URLs, data directory and port');
process.exitCode = 1;
}
}
module.exports = { createStudioServer };
+17 -7
View File
@@ -1,10 +1,12 @@
const { createHash } = require('node:crypto');
const { fail } = require('./workspace.cjs');
const BN_DIGITS = '০১২৩৪৫৬৭৮৯';
function amount(value) {
if (typeof value === 'number') return Number.isFinite(value) && value >= 0 ? value : null;
if (typeof value !== 'number' && typeof value !== 'string') return null;
const text = String(value).trim().replace(/[০-৯]/g, digit => String(BN_DIGITS.indexOf(digit)));
if (text.length > 64) return null;
if (!/^(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(text)) return null;
const number = Number(text.replace(/,/g, ''));
return Number.isFinite(number) && number >= 0 ? number : null;
@@ -33,9 +35,15 @@ function publicLink(value, base) {
}
function product(record, context) {
for (const [name, maximum] of Object.entries({ title: 1024, sku: 256, sourceId: 8192, brand: 256, link: 4096, image: 4096 })) {
if (typeof record[name] === 'string' && record[name].length > maximum) {
throw fail(502, 'SOURCE_FIELD_TOO_LARGE', 'Website-এর product field অতিরিক্ত বড়; আগের catalog বদলায়নি।');
}
}
const price = amount(record.price), regular = amount(record.regular);
const currency = currencyCode(record.currency);
const link = publicLink(record.link, context.url) || context.url;
const base = context.documentUrl || context.url;
const link = publicLink(record.link, base) || context.url;
const sourceId = String(record.sourceId || record.sku || link + ':' + record.title);
return {
id: createHash('sha256').update(context.url + '\0' + sourceId).digest('hex'),
@@ -44,7 +52,7 @@ function product(record, context) {
brand: typeof record.brand === 'string' ? record.brand : context.name,
price: displayPrice(price, currency), rawPrice: price, currency,
regularPrice: regular === null ? '' : displayPrice(regular, currency), rawRegularPrice: regular,
image: publicLink(record.image, context.url), link,
image: publicLink(record.image, base), link,
storeName: context.name, storeId: context.id, category: context.category,
...(typeof record.inStock === 'boolean' ? { inStock: record.inStock } : {})
};
@@ -54,12 +62,13 @@ function shopifyProducts(payload, context, currency) {
if (!Array.isArray(payload?.products)) return [];
return payload.products.flatMap(item => {
if (!item || typeof item.title !== 'string' || !item.title.trim()) return [];
const variants = Array.isArray(item.variants) && item.variants.length ? item.variants : [{}];
const valid = Array.isArray(item.variants) ? item.variants.filter(v => v && typeof v === 'object') : [];
const variants = valid.length ? valid : [{}];
return variants.map((variant, index) => product({
sourceId: (item.id ?? item.handle ?? item.title) + ':' + (variant.id ?? (variant.sku || variant.title || index)), sku: variant.sku,
title: item.title + (variant.title && variant.title !== 'Default Title' ? ' — ' + variant.title : ''),
title: item.title + (typeof variant.title === 'string' && variant.title && variant.title !== 'Default Title' ? ' — ' + variant.title : ''),
brand: item.vendor, price: variant.price, regular: variant.compare_at_price,
currency, image: variant.featured_image?.src || item.images?.[0]?.src || item.image?.src,
currency: variant.currency || item.currency || currency, image: variant.featured_image?.src || item.images?.[0]?.src || item.image?.src,
link: item.handle ? '/products/' + encodeURIComponent(item.handle) : context.url,
inStock: typeof variant.available === 'boolean' ? variant.available : undefined
}, context));
@@ -103,7 +112,8 @@ function schemaProducts(payload, context) {
if (Array.isArray(node)) { for (const item of node) visit(item, depth + 1); return; }
const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']];
if (types.includes('Product') && typeof node.name === 'string' && node.name.trim()) {
const offers = Array.isArray(node.offers) && node.offers.length ? node.offers : [node.offers || {}];
const validOffers = Array.isArray(node.offers) ? node.offers.filter(o => o && typeof o === 'object') : [];
const offers = validOffers.length ? validOffers : [node.offers && typeof node.offers === 'object' && !Array.isArray(node.offers) ? node.offers : {}];
for (const [offerIndex, offer] of offers.entries()) {
const image = Array.isArray(node.image) ? node.image[0] : node.image;
const isRegularSpecification = offer.priceSpecification?.priceType === 'https://schema.org/StrikethroughPrice';
@@ -125,4 +135,4 @@ function schemaProducts(payload, context) {
return products;
}
module.exports = { amount, publicLink, product, shopifyProducts, wooProducts, schemaProducts };
module.exports = { amount, displayPrice, publicLink, product, shopifyProducts, wooProducts, schemaProducts };
+151
View File
@@ -0,0 +1,151 @@
const http = require('node:http');
const https = require('node:https');
const dns = require('node:dns/promises');
const net = require('node:net');
const zlib = require('node:zlib');
const ipaddr = require('ipaddr.js');
const { fail } = require('./workspace.cjs');
function publicAddress(address) {
try { return ipaddr.process(address).range() === 'unicast'; }
catch { return false; }
}
function websiteUrl(input) {
let url;
try { url = new URL(input); }
catch { throw fail(400, 'INVALID_SOURCE_URL', 'সঠিক website URL দিন।'); }
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.port) {
throw fail(400, 'INVALID_SOURCE_URL', 'সাধারণ HTTP বা HTTPS website URL প্রয়োজন।');
}
url.hash = '';
return url;
}
function pinnedLookup(addresses) {
return (_hostname, options, callback) => {
if (typeof options === 'function') { callback = options; options = {}; }
const family = typeof options === 'number' ? options : options?.family;
const eligible = addresses.filter(item => !family || item.family === family);
if (!eligible.length) return callback(new Error('No validated address for this family'));
if (options?.all) callback(null, eligible);
else callback(null, eligible[0].address, eligible[0].family);
};
}
function createPublicFetcher({ lookup = dns.lookup, requestImpl, timeoutMs = 15000, maxBytes = 8 * 1024 * 1024, maxRedirects = 4 } = {}) {
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || !Number.isInteger(maxBytes) || maxBytes <= 0 ||
!Number.isInteger(maxRedirects) || maxRedirects < 0) throw new Error('Invalid public fetch limits');
async function addressesFor(url, remaining, signal) {
const hostname = url.hostname.replace(/^\[|\]$/g, '');
let addresses;
if (net.isIP(hostname)) addresses = [{ address: hostname, family: net.isIP(hostname) }];
else {
let timer, onAbort;
try {
addresses = await Promise.race([
lookup(hostname, { all: true, verbatim: true }),
new Promise((_, reject) => { timer = setTimeout(() => reject(fail(504, 'SOURCE_TIMEOUT', 'Website পড়ার সময় শেষ হয়েছে।')), remaining); }),
new Promise((_, reject) => {
onAbort = () => reject(fail(504, 'SOURCE_TIMEOUT', 'Website পড়ার সময় শেষ হয়েছে।'));
signal.addEventListener('abort', onAbort, { once: true });
if (signal.aborted) onAbort();
})
]);
} finally { clearTimeout(timer); if (onAbort) signal.removeEventListener('abort', onAbort); }
}
if (!Array.isArray(addresses) || !addresses.length || addresses.some(item => !publicAddress(item.address))) {
throw fail(400, 'NON_PUBLIC_SOURCE', 'শুধু public website থেকে product পড়া যাবে।');
}
return addresses.map(item => ({ address: item.address, family: net.isIP(item.address) }));
}
function request(url, addresses, signal) {
return new Promise((resolve, reject) => {
let settled = false, req;
function finish(error, result) {
if (settled) return;
settled = true;
if (error) { req?.destroy(); reject(error); } else resolve(result);
}
const options = {
method: 'GET', agent: false, signal, lookup: pinnedLookup(addresses), autoSelectFamily: true,
headers: {
'User-Agent': 'AuraStudioCatalog/1.0',
Accept: 'text/html,application/json,application/ld+json;q=0.9,*/*;q=0.1',
'Accept-Encoding': 'gzip, br, deflate'
}
};
const send = requestImpl || ((target, opts, callback) => (target.protocol === 'https:' ? https : http).get(target, opts, callback));
try {
req = send(url, options, response => {
const status = response.statusCode;
const headers = response.headers;
if ([301, 302, 303, 307, 308].includes(status) && headers.location) {
finish(null, { status, headers, body: Buffer.alloc(0) });
response.destroy();
return;
}
if (Number(headers['content-length']) > maxBytes) {
finish(fail(502, 'SOURCE_TOO_LARGE', 'Website response নির্ধারিত সীমার চেয়ে বড়।'));
response.destroy();
req?.destroy();
return;
}
const encoding = String(headers['content-encoding'] || 'identity').toLowerCase();
let stream = response;
if (encoding === 'gzip') stream = response.pipe(zlib.createGunzip());
else if (encoding === 'br') stream = response.pipe(zlib.createBrotliDecompress());
else if (encoding === 'deflate') stream = response.pipe(zlib.createInflate());
else if (encoding !== 'identity') {
finish(fail(502, 'UNSUPPORTED_SOURCE_ENCODING', 'Website response format সমর্থিত নয়।'));
response.destroy();
return;
}
const chunks = []; let bytes = 0;
response.on('aborted', () => finish(fail(502, 'SOURCE_INCOMPLETE', 'Website response সম্পূর্ণ আসেনি।')));
response.on('error', error => { if (stream !== response) stream.destroy(); finish(error); });
stream.on('data', chunk => {
bytes += chunk.length;
if (bytes > maxBytes) {
finish(fail(502, 'SOURCE_TOO_LARGE', 'Website response নির্ধারিত সীমার চেয়ে বড়।'));
stream.destroy(); response.destroy(); req?.destroy();
} else chunks.push(chunk);
});
stream.on('error', error => finish(error));
stream.on('end', () => finish(null, { status, headers, body: Buffer.concat(chunks) }));
});
req.on('error', error => finish(error));
} catch (error) { finish(error); }
});
}
return async function fetchPublic(input, options = {}) {
const deadline = Date.now() + timeoutMs;
const ownTimeout = AbortSignal.timeout(timeoutMs);
const signal = options.signal ? AbortSignal.any([ownTimeout, options.signal]) : ownTimeout;
let url = websiteUrl(input);
try {
for (let hop = 0; hop <= maxRedirects; hop++) {
const remaining = deadline - Date.now();
if (remaining <= 0 || signal.aborted) throw fail(504, 'SOURCE_TIMEOUT', 'Website পড়ার সময় শেষ হয়েছে।');
const addresses = await addressesFor(url, remaining, signal);
if (signal.aborted) throw fail(504, 'SOURCE_TIMEOUT', 'Website পড়ার সময় শেষ হয়েছে।');
const result = await request(url, addresses, signal);
if ([301, 302, 303, 307, 308].includes(result.status) && result.headers.location) {
if (hop === maxRedirects) throw fail(502, 'SOURCE_REDIRECT_LIMIT', 'Website redirect সীমা ছাড়িয়েছে।');
url = websiteUrl(new URL(result.headers.location, url).href);
continue;
}
return { ...result, url: url.href };
}
} catch (error) {
if (error.status) throw error;
if (signal.aborted || error.name === 'AbortError') throw fail(504, 'SOURCE_TIMEOUT', 'Website পড়ার সময় শেষ হয়েছে।');
throw fail(502, 'SOURCE_FETCH_FAILED', 'Website থেকে product data পড়া যায়নি।');
}
};
}
module.exports = { createPublicFetcher, websiteUrl, publicAddress, pinnedLookup };
+173
View File
@@ -0,0 +1,173 @@
const cheerio = require('cheerio');
const { createHash } = require('node:crypto');
const { fail } = require('./workspace.cjs');
const { websiteUrl } = require('./public-fetch.cjs');
const { amount, displayPrice, product, publicLink, shopifyProducts, wooProducts, schemaProducts } = require('./products.cjs');
function loadHtml(buffer, contentType = '') {
const charset = /charset\s*=\s*["']?([^\s;"']+)/i.exec(contentType)?.[1];
return cheerio.loadBuffer(buffer, { encoding: { defaultEncoding: 'utf-8', ...(charset ? { transportLayerEncodingLabel: charset } : {}) } });
}
function htmlProducts(buffer, context, { maxProducts = 10000 } = {}) {
const $ = loadHtml(buffer, context.contentType);
const results = [], byIdentity = new Map();
function append(row) {
const key = row.title.trim().toLowerCase().replace(/\s+/g, ' ') + '\0' + row.link;
const candidates = byIdentity.get(key) || [];
const existing = candidates.find(old => !old.sku || !row.sku || old.sku === row.sku);
if (existing) {
if (existing.rawPrice === null && row.rawPrice !== null) {
existing.rawPrice = row.rawPrice; existing.currency ||= row.currency;
existing.price = displayPrice(existing.rawPrice, existing.currency);
}
if (!existing.image) existing.image = row.image;
if (!existing.sku) existing.sku = row.sku;
return;
}
if (results.length >= maxProducts) throw fail(422, 'IMPORT_LIMIT', 'Product সংখ্যা import সীমা ছাড়িয়েছে।');
results.push(row); candidates.push(row); byIdentity.set(key, candidates);
}
$('script[type="application/ld+json"]').each((_i, element) => {
let data;
try { data = JSON.parse($(element).text()); } catch { return; }
for (const row of schemaProducts(data, context)) append(row);
});
$('[itemtype$="/Product"], li.product, .product-item, .product-card').each((_i, element) => {
const card = $(element);
const name = card.find('[itemprop="name"], .woocommerce-loop-product__title, .product-title, .product-card__title, .card__heading').first().text().trim();
if (!name) return;
let selling = card.find('[itemprop="price"]').first();
if (!selling.length) selling = card.find('.price ins .amount, .price ins').first();
if (!selling.length) selling = card.find('.price .amount').filter((_i, el) => !$(el).closest('del').length).first();
if (!selling.length) { selling = card.find('.price').first().clone(); selling.find('del').remove(); }
const explicit = selling.attr('content') || selling.text().trim();
const price = amount(explicit.replace(/\p{Sc}|\b(?:BDT|USD|EUR|GBP|CAD|AUD|SGD|INR)\b|\bTk\.?/giu, '').trim());
const currency = card.find('[itemprop="priceCurrency"]').first().attr('content') || (/৳|\b(?:BDT|Tk\.?)\b/i.test(explicit) ? 'BDT' : undefined);
const regularText = card.find('.price del .amount, .price del').first().text().trim();
const regular = amount(regularText.replace(/\p{Sc}|\b(?:BDT|USD|EUR|GBP|CAD|AUD|SGD|INR)\b|\bTk\.?/giu, '').trim());
const image = card.find('img').first();
const link = card.find('a[href]').first().attr('href');
append(product({
sourceId: card.attr('data-product-id') || publicLink(link, context.documentUrl || context.url) || name,
title: name, price, regular, currency, link,
image: image.attr('data-src') || image.attr('data-lazy-src') || image.attr('src')
}, context));
});
const next = $('a[rel="next"], link[rel="next"], .pagination a.next, .woocommerce-pagination a.next').first().attr('href');
return { products: results, next: publicLink(next, context.documentUrl || context.url), title: $('title').text().trim() };
}
function createScraper({ fetchPublic, maxRequests = 80, maxPages = 20, maxProducts = 10000, timeoutMs = 60000, pageDelayMs = 350 }) {
if (typeof fetchPublic !== 'function' || ![maxRequests, maxPages, maxProducts, timeoutMs].every(n => Number.isInteger(n) && n > 0) || !Number.isInteger(pageDelayMs) || pageDelayMs < 0) {
throw new Error('Invalid scraper limits');
}
return async function scrape(input, options = {}) {
const raw = typeof input.url === 'string' ? input.url.trim() : '';
if (!raw || raw.length > 2048) throw fail(400, 'INVALID_SOURCE_URL', 'সঠিক website URL দিন।');
const url = websiteUrl(/^[a-z][a-z0-9+.-]*:/i.test(raw) ? raw : 'https://' + raw);
const name = typeof input.storeName === 'string' ? input.storeName.trim() : '';
const category = typeof input.category === 'string' ? input.category.trim() : 'general';
if (name.length > 160 || category.length > 80) throw fail(400, 'INVALID_STORE_DETAILS', 'Store-এর নাম বা category অতিরিক্ত বড়।');
const context = {
url: url.origin + '/', name: name || url.hostname,
id: 'store_' + createHash('sha256').update(url.origin).digest('hex'), category
};
const signal = options.signal ? AbortSignal.any([AbortSignal.timeout(timeoutMs), options.signal]) : AbortSignal.timeout(timeoutMs);
let requests = 0;
const evidence = [];
async function read(target) {
if (signal.aborted) throw fail(504, 'IMPORT_TIMEOUT', 'Product import-এর সময় শেষ হয়েছে।');
if (requests >= maxRequests) throw fail(422, 'IMPORT_LIMIT', 'এই store-এর জন্য import সীমা বাড়ানো প্রয়োজন; আগের data বদলায়নি।');
if (requests && pageDelayMs) await new Promise((resolve, reject) => {
const aborted = () => { clearTimeout(timer); signal.removeEventListener('abort', aborted); reject(fail(504, 'IMPORT_TIMEOUT', 'Product import বাতিল বা সময় শেষ হয়েছে।')); };
const timer = setTimeout(() => { signal.removeEventListener('abort', aborted); resolve(); }, pageDelayMs);
signal.addEventListener('abort', aborted, { once: true });
if (signal.aborted) aborted();
});
requests++;
const result = await fetchPublic(target, { signal });
evidence.push({ url: result.url || target, status: result.status, sha256: createHash('sha256').update(result.body).digest('hex') });
return result;
}
async function optional(target) {
try { return await read(target); }
catch (error) {
if (['NON_PUBLIC_SOURCE', 'INVALID_SOURCE_URL', 'IMPORT_LIMIT', 'SOURCE_TOO_LARGE'].includes(error.code) || signal.aborted) throw error;
return null;
}
}
function json(result) { try { return JSON.parse(result.body.toString('utf8')); } catch { return null; } }
function bounded(rows) {
if (rows.length > maxProducts) throw fail(422, 'IMPORT_LIMIT', 'Product সংখ্যা import সীমা ছাড়িয়েছে; আগের data বদলায়নি।');
return rows;
}
function finished(products, sourceType, extra = {}) {
const unique = [...new Map(bounded(products).map(item => [item.id, item])).values()];
if (!unique.length) throw fail(422, 'NO_PUBLIC_PRODUCTS', 'এই public source-এ product পাওয়া যায়নি; আগের data বদলায়নি।');
return { ...context, domain: new URL(context.url).hostname, syncedAt: new Date().toISOString(), count: unique.length, products: unique, sourceType, sources: evidence, ...extra };
}
async function pages(first, makeUrl, field, pageSize, map) {
const products = [], hashes = new Set();
let result = first;
for (let page = 1; page <= maxPages; page++) {
if (page > 1) result = await read(makeUrl(page));
if (result.status !== 200) throw fail(502, 'INCOMPLETE_CATALOG', 'Catalog-এর সব page পড়া যায়নি; আগের data বদলায়নি।');
const payload = json(result), rows = field ? payload?.[field] : payload;
if (!Array.isArray(rows)) throw fail(502, 'INCOMPLETE_CATALOG', 'Catalog response সঠিক নয়; আগের data বদলায়নি।');
const hash = createHash('sha256').update(result.body).digest('hex');
if (rows.length && hashes.has(hash)) throw fail(422, 'PAGINATION_UNSUPPORTED', 'Website একই catalog page বারবার দিচ্ছে; আগের data বদলায়নি।');
hashes.add(hash);
if (rows.length > maxProducts) throw fail(422, 'IMPORT_LIMIT', 'Product সংখ্যা import সীমা ছাড়িয়েছে।');
for (const row of map(payload)) { products.push(row); bounded(products); }
const totalPages = Number(result.headers['x-wp-totalpages']);
const hasTotal = Number.isInteger(totalPages) && totalPages > 0;
if (hasTotal ? page >= totalPages : rows.length < pageSize) return products;
if (page === maxPages) throw fail(422, 'IMPORT_LIMIT', 'Catalog page সংখ্যা সীমা ছাড়িয়েছে; আগের data বদলায়নি।');
}
return products;
}
const home = await optional(url.href);
const origin = websiteUrl(home?.url || url.href).origin;
context.url = origin + '/'; context.id = 'store_' + createHash('sha256').update(origin).digest('hex');
if (!name) context.name = new URL(origin).hostname;
let apiRoot = new URL('/wp-json/', origin);
if (home?.status === 200) {
const $ = loadHtml(home.body, home.headers['content-type']);
const discovered = publicLink($('link[rel="https://api.w.org/"]').first().attr('href'), home.url || url.href);
if (discovered && new URL(discovered).origin === origin) apiRoot = new URL(discovered);
}
const wooUrl = page => {
const target = apiRoot.searchParams.has('rest_route') ? new URL(apiRoot) : new URL('wc/store/v1/products', apiRoot.href.endsWith('/') ? apiRoot : apiRoot.href + '/');
if (target.searchParams.has('rest_route')) target.searchParams.set('rest_route', '/wc/store/v1/products');
target.searchParams.set('per_page', '100'); target.searchParams.set('page', String(page)); return target.href;
};
const woo = await optional(wooUrl(1));
if (woo?.status === 200 && Array.isArray(json(woo))) {
const rows = await pages(woo, wooUrl, null, 100, payload => wooProducts(payload, context));
return finished(rows, 'woo-store-api', { requiresVariantSelection: rows.some(row => row.requiresVariantSelection) });
}
const shopifyUrl = page => { const target = new URL('/products.json', origin); target.searchParams.set('limit', '250'); target.searchParams.set('page', String(page)); return target.href; };
const shopify = await optional(shopifyUrl(1));
if (shopify?.status === 200 && Array.isArray(json(shopify)?.products)) {
return finished(await pages(shopify, shopifyUrl, 'products', 250, payload => shopifyProducts(payload, context, payload.currency)), 'shopify-public-products');
}
if (!home || home.status !== 200) throw fail(422, 'NO_PUBLIC_PRODUCTS', 'Public product data পাওয়া যায়নি; অনুমোদিত store connection প্রয়োজন হতে পারে।');
let current = home, products = [], seen = new Set();
for (let page = 1; page <= maxPages; page++) {
const pageUrl = current.url || url.href;
if (seen.has(pageUrl)) throw fail(422, 'PAGINATION_UNSUPPORTED', 'Website-এর next page বারবার একই page-এ ফিরছে।');
seen.add(pageUrl);
const parsed = htmlProducts(current.body, { ...context, documentUrl: pageUrl, contentType: current.headers['content-type'] }, { maxProducts });
for (const row of parsed.products) { products.push(row); bounded(products); }
if (!parsed.next) return finished(products, 'public-html-pages', { coverage: 'Products found in public pages, not a guarantee of the entire site inventory' });
if (new URL(parsed.next).origin !== origin) throw fail(422, 'CROSS_ORIGIN_PAGINATION', 'Catalog-এর next page অন্য website-এ যাচ্ছে।');
if (page === maxPages) throw fail(422, 'IMPORT_LIMIT', 'Catalog page সংখ্যা সীমা ছাড়িয়েছে; আগের data বদলায়নি।');
current = await read(parsed.next);
if (current.status !== 200) throw fail(502, 'INCOMPLETE_CATALOG', 'Catalog-এর পরের page পড়া যায়নি; আগের data বদলায়নি।');
}
};
}
module.exports = { createScraper, htmlProducts };
+69
View File
@@ -0,0 +1,69 @@
const fs = require('node:fs/promises');
const path = require('node:path');
const { createHash } = require('node:crypto');
const { gzipSync } = require('node:zlib');
const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'application/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.woff': 'font/woff', '.woff2': 'font/woff2' };
const ROOT_FILES = new Set(['index.html', 'app.js', 'style.css', 'sw.js', 'manifest.json', 'gt_full_catalog.json']);
function createStaticHandler(publicDirectory, { maxCacheBytes = 16 * 1024 * 1024 } = {}) {
const root = path.resolve(publicDirectory), cache = new Map();
let cachedBytes = 0;
function missing(response, status = 404) {
response.writeHead(status, { 'Content-Type': 'text/plain; charset=utf-8', 'X-Content-Type-Options': 'nosniff' });
response.end(status === 404 ? 'Not found' : 'Method not allowed');
}
return async function serve(request, response) {
if (!['GET', 'HEAD'].includes(request.method)) return missing(response, 405);
let pathname;
try { pathname = decodeURIComponent(request.url.split('?')[0]); } catch { return missing(response); }
if (pathname.includes('\\') || pathname.includes('\0') || pathname.split('/').some(p => p.startsWith('.'))) return missing(response);
let relative = pathname === '/' ? 'index.html' : pathname.replace(/^\/+/, '');
const asset = relative.startsWith('assets/') && MIME[path.extname(relative).toLowerCase()];
const legacyData = relative === 'data/synced_stores.json';
if (!ROOT_FILES.has(relative) && !asset && !legacyData) {
if (!path.extname(relative) && !/^(?:server|docs|test|data|node_modules)(?:\/|$)/.test(relative) && String(request.headers.accept || '').includes('text/html')) relative = 'index.html';
else return missing(response);
}
try {
const resolved = await fs.realpath(path.join(root, relative));
const actualRoot = await fs.realpath(root);
if (!resolved.startsWith(actualRoot + path.sep)) return missing(response);
const stat = await fs.stat(resolved);
if (!stat.isFile()) return missing(response);
const version = stat.mtimeMs + ':' + stat.size;
let entry = cache.get(relative);
if (!entry || entry.version !== version) {
if (entry) { cachedBytes -= entry.bytes; cache.delete(relative); }
const body = await fs.readFile(resolved);
const compressible = /\.(?:html|js|css|json|svg)$/.test(relative);
const gzip = compressible && body.length > 1024 ? gzipSync(body) : null;
entry = { version, body, gzip, bytes: body.length + (gzip?.length || 0), etag: 'W/"' + createHash('sha256').update(body).digest('hex') + '"' };
if (entry.bytes <= maxCacheBytes) {
while (cache.size && cachedBytes + entry.bytes > maxCacheBytes) {
const key = cache.keys().next().value; cachedBytes -= cache.get(key).bytes; cache.delete(key);
}
cache.set(relative, entry); cachedBytes += entry.bytes;
}
}
const html = relative.endsWith('.html');
const gzip = entry.gzip && /\bgzip\b/.test(request.headers['accept-encoding'] || '');
const body = gzip ? entry.gzip : entry.body;
const headers = {
'Content-Type': MIME[path.extname(relative).toLowerCase()] || 'application/octet-stream',
'Cache-Control': html || relative === 'sw.js' ? 'no-cache, no-store, must-revalidate, max-age=0' : 'no-cache, must-revalidate, max-age=0',
'X-Content-Type-Options': 'nosniff', 'X-Frame-Options': 'SAMEORIGIN',
'Access-Control-Allow-Origin': '*', Vary: 'Accept-Encoding', ETag: entry.etag,
...(gzip ? { 'Content-Encoding': 'gzip' } : {})
};
if (!html && request.headers['if-none-match'] === entry.etag) { response.writeHead(304, headers); return response.end(); }
response.writeHead(200, { ...headers, 'Content-Length': body.length });
response.end(request.method === 'HEAD' ? undefined : body);
} catch (error) {
if (['ENOENT', 'ENOTDIR', 'EACCES'].includes(error.code)) return missing(response);
throw error;
}
};
}
module.exports = { createStaticHandler };
+11 -5
View File
@@ -49,7 +49,7 @@ function createWorkspaceResolver({ authMeUrl, clientMeUrl, fetchImpl = fetch, ti
}
const identity = await read(authUrl, { Authorization: 'Bearer ' + token, Accept: 'application/json' });
const user = identity?.user;
if (!user || typeof user.id !== 'string' || !user.id || user.isActive !== true) {
if (!user || typeof user.id !== 'string' || !user.id || typeof user.email !== 'string' || !user.email || user.isActive !== true) {
throw fail(401, 'INACTIVE_ACCOUNT', 'সক্রিয় Aura account প্রয়োজন।');
}
@@ -66,15 +66,21 @@ function createWorkspaceResolver({ authMeUrl, clientMeUrl, fetchImpl = fetch, ti
// Client's existing gate owns membership/owner-switch decisions. Never trust a supplied client ID.
const headers = { Cookie: 'aura_access=' + encodeURIComponent(token), Accept: 'application/json' };
if (requested) headers['x-aura-tenant'] = requested;
if (privileged && requested) headers['x-aura-tenant'] = requested;
const context = await read(clientUrl, headers);
if (context?.success !== true || typeof context.tenant !== 'string' || !context.tenant.trim() || context.tenant.length > 256) {
if (context?.success !== true || typeof context.tenant !== 'string' || !context.tenant.trim() || context.tenant.length > 256 ||
typeof context.clientId !== 'string' || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(context.clientId)) {
throw fail(403, 'WORKSPACE_UNAVAILABLE', 'আপনার workspace প্রস্তুত বা অনুমোদিত নয়।');
}
if (!context.actor || context.actor.id !== user.id || context.actor.role !== user.role ||
typeof context.actor.email !== 'string' || context.actor.email.trim().toLowerCase() !== user.email.trim().toLowerCase()) {
throw fail(401, 'SESSION_CHANGED', 'Account-এর তথ্য বদলেছে; আবার login করুন।');
}
const tenant = context.tenant.trim().toLowerCase();
const clientId = context.clientId.toLowerCase();
return {
tenant,
namespace: createHash('sha256').update(tenant).digest('hex'),
tenant, clientId,
namespace: createHash('sha256').update('client:' + clientId).digest('hex'),
userId: user.id,
role: context.role,
canWriteProducts: context.perms?.products === true,