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 };