diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b9d8ed8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +.env +.env.* +*.log +coverage/ diff --git a/Dockerfile.api b/Dockerfile.api new file mode 100644 index 0000000..3f143f1 --- /dev/null +++ b/Dockerfile.api @@ -0,0 +1,15 @@ +ARG NODE_IMAGE=node:22-alpine +FROM ${NODE_IMAGE} +WORKDIR /app +ENV NODE_ENV=production PORT=3000 STUDIO_DATA_DIR=/data/studio +COPY package.json package-lock.json ./ +RUN npm ci --omit=dev --ignore-scripts --no-fund --no-audit +COPY server/ ./server/ +COPY index.html app.js style.css sw.js manifest.json gt_full_catalog.json ./public/ +COPY assets/ ./public/assets/ +COPY data/ ./public/data/ +RUN mkdir -p /data/studio && chown -R node:node /app /data/studio +USER node +EXPOSE 3000 +HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 CMD node -e "fetch('http://127.0.0.1:'+process.env.PORT+'/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))" +CMD ["node", "--max-old-space-size=256", "server/main.cjs"] diff --git a/docs/runtime-reconciliation.md b/docs/runtime-reconciliation.md index 3a19ee9..1cdf80c 100644 --- a/docs/runtime-reconciliation.md +++ b/docs/runtime-reconciliation.md @@ -8,18 +8,24 @@ The running Nginx service serves /api/get-synced-stores through its HTML fallbac Do not blindly enable serve.js: it uses one shared store file and contains invented price/compare-price fallbacks. A production repair must retain tenant boundaries, real product values and existing client behavior. No Meta 1-Click flow is included in this reconciliation. -## Backend candidate modules — not yet routed or deployed +## Backend candidate — not deployed -server/workspace.cjs uses the existing Auth active-account endpoint and Client workspace endpoint. Browser client IDs are not accepted as storage identity. An owner must select a workspace explicitly; the Client gate owns the canonical workspace and catalog permission decisions. No database superuser credential or signing key is copied into these modules. +server/workspace.cjs uses the existing Auth active-account endpoint and the additive Client workspace identity contract. Browser client IDs are not accepted as storage identity. An owner must select a workspace explicitly; the Client gate owns the canonical workspace and catalog permission decisions. Storage uses the immutable client ID, not a display slug. Actor ID, email and role must match current Auth state. No database superuser credential or signing key is copied into these modules. The Client identity response must be released first; missing/stale identity fails closed. server/store.cjs persists per-canonical-workspace data using hashed namespace directories, serialized updates, atomic replacement and fsync. It does not load the prototype shared store file into a new tenant. Corrupt saved data fails instead of being silently replaced with an empty list. This store is for a single server process; a multi-replica deployment needs a shared transactional store or cross-process locking before use. server/products.cjs maps structured Shopify, Woo Store API and schema.org data without guessed prices, discounts or currencies. It preserves variant/SKU distinctions and zero prices. Missing selling prices remain unknown; an aggregate starting price or strikethrough price alone is not presented as an exact current selling price. -The Nginx Dockerfile now copies an explicit static asset set instead of publishing all repository files. These candidate modules are not enabled by the static image. HTTP routing, bounded outbound fetching, request protection and frontend integration remain required before claiming that the Studio sync endpoint is repaired. +The Nginx Dockerfile copies an explicit static asset set instead of publishing all repository files. The separate Dockerfile.api builds the Node API/static server as a non-root user. It implements workspace store-list/import/delete routes, origin checks, JSON/body limits, import rate/concurrency limits and public-source fetching with DNS pinning, redirect revalidation, decompressed-byte limits and timeout/cancellation. Static backend/configuration paths are denied. The existing static image is unchanged in production. Frontend integration, the upstream Client identity release and a persistent production mount are still required before claiming the deployed Studio endpoint is repaired. Verification: 17 tests pass on Windows and in an isolated Linux Node 22 container. They exercise canonical tenant selection, active-account rejection, shared owner/staff workspace storage, cross-workspace isolation, concurrent writes, corruption preservation, variant IDs and non-invented prices. Identity replies and product data in these tests are explicit fixtures, not production account/provider results. +Later integration verification: 49 tests pass in the Node 22 API candidate image with networking disabled, a read-only root and all capabilities dropped. The earlier 17-test result describes the initial foundation phase. A separate actual-entrypoint startup check covers health/static serving, unauthenticated JSON errors, unknown API paths and denied backend downloads. The current dependency audit reports zero advisories; this is not an all-security certification. + +A read-only probe against ApplixBD walked eleven public Woo pages and read 1,006 source product records. Three samples were independently reconciled against raw Store API price/currency/minor-unit fields. No catalog data was saved. The GT public HTML probe returned no products; it did not use or test the separately connected Supabase catalog. HTML-only extraction reports discovered-page coverage instead of claiming every product on an arbitrary JavaScript-rendered site. + +Import request pacing defaults to 350 ms between source requests, consistent with the existing host-compatibility policy. Operational caps are configurable through STUDIO_MAX_IMPORT_PAGES, STUDIO_MAX_PRODUCTS, STUDIO_MAX_SOURCE_REQUESTS, STUDIO_IMPORT_TIMEOUT_MS, STUDIO_PAGE_DELAY_MS, STUDIO_MAX_SOURCE_BYTES, STUDIO_SOURCE_TIMEOUT_MS, STUDIO_IMPORTS_PER_MINUTE and STUDIO_MAX_PARALLEL_IMPORTS. Limit or incomplete-page failures do not replace the saved catalog. + 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. diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..94d47ac --- /dev/null +++ b/package-lock.json @@ -0,0 +1,325 @@ +{ + "name": "aura-studio", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "aura-studio", + "version": "1.0.0", + "dependencies": { + "cheerio": "1.2.0", + "ipaddr.js": "2.5.0" + }, + "engines": { + "node": ">=22.19" + } + }, + "node_modules/boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", + "license": "ISC" + }, + "node_modules/cheerio": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.2.0.tgz", + "integrity": "sha512-WDrybc/gKFpTYQutKIK6UvfcuxijIZfMfXaYm8NMsPQxSYvf+13fXUJ4rztGGbJcBQ/GF55gvrZ0Bc0bj/mqvg==", + "license": "MIT", + "dependencies": { + "cheerio-select": "^2.1.0", + "dom-serializer": "^2.0.0", + "domhandler": "^5.0.3", + "domutils": "^3.2.2", + "encoding-sniffer": "^0.2.1", + "htmlparser2": "^10.1.0", + "parse5": "^7.3.0", + "parse5-htmlparser2-tree-adapter": "^7.1.0", + "parse5-parser-stream": "^7.1.2", + "undici": "^7.19.0", + "whatwg-mimetype": "^4.0.0" + }, + "engines": { + "node": ">=20.18.1" + }, + "funding": { + "url": "https://github.com/cheeriojs/cheerio?sponsor=1" + } + }, + "node_modules/cheerio-select": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cheerio-select/-/cheerio-select-2.1.0.tgz", + "integrity": "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-select": "^5.1.0", + "css-what": "^6.1.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/css-select": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.2.2.tgz", + "integrity": "sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-what": "^6.1.0", + "domhandler": "^5.0.2", + "domutils": "^3.0.1", + "nth-check": "^2.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/css-what": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.2.2.tgz", + "integrity": "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/dom-serializer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", + "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.2", + "entities": "^4.2.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause" + }, + "node_modules/domhandler": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", + "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^2.3.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/domutils": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", + "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==", + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^2.0.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/encoding-sniffer": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/encoding-sniffer/-/encoding-sniffer-0.2.1.tgz", + "integrity": "sha512-5gvq20T6vfpekVtqrYQsSCFZ1wEg5+wW0/QaZMWkFr6BqD3NfKs0rLCx4rrVlSWJeZb5NBJgVLswK/w2MWU+Gw==", + "license": "MIT", + "dependencies": { + "iconv-lite": "^0.6.3", + "whatwg-encoding": "^3.1.1" + }, + "funding": { + "url": "https://github.com/fb55/encoding-sniffer?sponsor=1" + } + }, + "node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/htmlparser2": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz", + "integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==", + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.2.2", + "entities": "^7.0.1" + } + }, + "node_modules/htmlparser2/node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ipaddr.js": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.5.0.tgz", + "integrity": "sha512-aq+t5NAc+cS6rZQQVWC2x98CPqGtKKTMDd4Gaodv0wShnItdKg/51djkGJ1hqH+Oy0ivDftCbSLCQob8zso01w==", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/nth-check": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", + "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0" + }, + "funding": { + "url": "https://github.com/fb55/nth-check?sponsor=1" + } + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-htmlparser2-tree-adapter": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-7.1.0.tgz", + "integrity": "sha512-ruw5xyKs6lrpo9x9rCZqZZnIUntICjQAd0Wsmp396Ul9lN/h+ifgVV1x1gZHi8euej6wTfpqX8j+BFQxF0NS/g==", + "license": "MIT", + "dependencies": { + "domhandler": "^5.0.3", + "parse5": "^7.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-parser-stream": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-7.1.2.tgz", + "integrity": "sha512-JyeQc9iwFLn5TbvvqACIF/VXG6abODeB3Fwmv/TGdLk2LfbWkaySGY72at4+Ty7EkPZj854u4CrICqNk2qIbow==", + "license": "MIT", + "dependencies": { + "parse5": "^7.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5/node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/undici": { + "version": "7.30.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.1.tgz", + "integrity": "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==", + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "license": "MIT", + "engines": { + "node": ">=18" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..58154be --- /dev/null +++ b/package.json @@ -0,0 +1,8 @@ +{ + "name": "aura-studio", + "version": "1.0.0", + "private": true, + "engines": { "node": ">=22.19" }, + "scripts": { "test": "node --test test/*.test.cjs", "start": "node server/main.cjs" }, + "dependencies": { "cheerio": "1.2.0", "ipaddr.js": "2.5.0" } +} diff --git a/server/api.cjs b/server/api.cjs new file mode 100644 index 0000000..bd5435d --- /dev/null +++ b/server/api.cjs @@ -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 }; diff --git a/server/main.cjs b/server/main.cjs new file mode 100644 index 0000000..8b2ef2e --- /dev/null +++ b/server/main.cjs @@ -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 }; diff --git a/server/products.cjs b/server/products.cjs index 91c13f8..52451bd 100644 --- a/server/products.cjs +++ b/server/products.cjs @@ -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 }; diff --git a/server/public-fetch.cjs b/server/public-fetch.cjs new file mode 100644 index 0000000..601917c --- /dev/null +++ b/server/public-fetch.cjs @@ -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 }; diff --git a/server/scraper.cjs b/server/scraper.cjs new file mode 100644 index 0000000..448da27 --- /dev/null +++ b/server/scraper.cjs @@ -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 }; diff --git a/server/static.cjs b/server/static.cjs new file mode 100644 index 0000000..ec549bb --- /dev/null +++ b/server/static.cjs @@ -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 }; diff --git a/server/workspace.cjs b/server/workspace.cjs index 61880df..8f9a592 100644 --- a/server/workspace.cjs +++ b/server/workspace.cjs @@ -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, diff --git a/test/api.test.cjs b/test/api.test.cjs new file mode 100644 index 0000000..7c2b34a --- /dev/null +++ b/test/api.test.cjs @@ -0,0 +1,131 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const http = require('node:http'); +const fs = require('node:fs/promises'); +const path = require('node:path'); +const os = require('node:os'); +const { createWorkspaceResolver } = require('../server/workspace.cjs'); +const { createStore } = require('../server/store.cjs'); +const { createScraper } = require('../server/scraper.cjs'); +const { createApiHandler } = require('../server/api.cjs'); +const { createHash } = require('node:crypto'); + +async function serve(t, handler) { + const server = http.createServer(handler); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); }); + return 'http://127.0.0.1:' + server.address().port; +} + +async function setup(t, settings = {}) { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'studio-api-')); + t.after(() => fs.rm(root, { recursive: true, force: true })); + const identities = { + a: { id: 'actor-a', role: 'client', isActive: true, tenant: 'tenant-a', products: true }, + staff: { id: 'staff-a', role: 'team_member', isActive: true, tenant: 'tenant-a', products: true }, + b: { id: 'actor-b', role: 'client', isActive: true, tenant: 'tenant-b', products: true }, + readonly: { id: 'reader', role: 'team_member', isActive: true, tenant: 'tenant-a', products: false }, + owner: { id: 'platform-owner', role: 'owner', isActive: true, products: true } + }; + const counts = { auth: 0, source: 0 }; + const identityService = await serve(t, (req, res) => { + res.setHeader('Content-Type', 'application/json'); + if (req.url === '/auth') { + counts.auth++; + const user = identities[req.headers.authorization?.replace('Bearer ', '')]; + res.writeHead(user ? 200 : 401); return res.end(JSON.stringify({ user: user ? { ...user, email: user.id + '@example.test' } : undefined })); + } + const key = /aura_access=([^;]+)/.exec(req.headers.cookie || '')?.[1]; + const user = identities[key]; + if (!user) { res.writeHead(401); return res.end('{}'); } + // Fixture membership service implements the existing gate's canonical workspace contract. + const tenant = user.role === 'owner' ? req.headers['x-aura-tenant'] : user.tenant; + const hash = createHash('sha256').update(tenant).digest('hex'); + const clientId = [hash.slice(0, 8), hash.slice(8, 12), hash.slice(12, 16), hash.slice(16, 20), hash.slice(20, 32)].join('-'); + return res.end(JSON.stringify({ success: true, tenant, clientId, actor: { id: user.id, email: user.id + '@example.test', role: user.role }, role: user.products ? 'manager' : 'agent', clientName: tenant, perms: { products: user.products } })); + }); + const resolve = createWorkspaceResolver({ authMeUrl: identityService + '/auth', clientMeUrl: identityService + '/client' }); + const store = createStore(root); + const scrape = settings.scrape || createScraper({ fetchPublic: async url => { + counts.source++; + return { url, status: 200, headers: {}, body: Buffer.from(new URL(url).pathname === '/' ? 'Fixture Shop' : JSON.stringify([ + { id: 1, sku: 'REAL-SOURCE-SKU', name: 'Source item', prices: { price: '22000', regular_price: '27000', currency_minor_unit: 2, currency_code: 'BDT' } } + ])) }; + } }); + const handler = createApiHandler({ resolveWorkspace: resolve, store, scrape, publicOrigin: 'https://studio.fixture', ...settings }); + const base = await serve(t, handler); + async function call(token, endpoint, body, extra = {}) { + const headers = { ...(token ? { Cookie: 'aura_access=' + token } : {}), ...extra }; + if (body !== undefined) { headers.Origin ??= 'https://studio.fixture'; headers['Content-Type'] ??= 'application/json'; } + const res = await fetch(base + endpoint, { method: body === undefined ? 'GET' : 'POST', headers, body: body === undefined ? undefined : JSON.stringify(body) }); + return { status: res.status, headers: res.headers, body: await res.json() }; + } + return { root, counts, call, base, store, resolve }; +} + +test('HTTP import persists actual source values for owner/staff and isolates another tenant', async t => { + const f = await setup(t); + const result = await f.call('a', '/api/sync-store', { url: 'https://catalog.fixture', clientId: 'victim', tenant: 'tenant-b', products: [{ price: 999 }] }, { 'x-aura-tenant': 'tenant-b' }); + assert.equal(result.status, 200); + assert.equal(result.body.store.products[0].rawPrice, 220); + assert.equal(result.body.store.products[0].rawRegularPrice, 270); + assert.equal((await f.call('staff', '/api/get-synced-stores')).body.stores.length, 1); + assert.deepEqual((await f.call('b', '/api/get-synced-stores?clientId=victim')).body.stores, []); + await f.call('b', '/api/delete-synced-store', { storeId: result.body.store.id }); + assert.equal((await f.call('a', '/api/get-synced-stores')).body.stores.length, 1); + assert.equal((await f.call('a', '/api/delete-synced-store', { storeId: result.body.store.id })).status, 200); + assert.deepEqual((await f.call('a', '/api/get-synced-stores')).body.stores, []); +}); + +test('missing login and read-only membership cannot trigger source requests', async t => { + const f = await setup(t); + assert.equal((await f.call(null, '/api/get-synced-stores')).status, 401); + assert.equal((await f.call('readonly', '/api/sync-store', { url: 'https://catalog.fixture' })).status, 403); + assert.equal(f.counts.source, 0); + const owner = await f.call('owner', '/api/get-synced-stores'); + assert.equal(owner.status, 409); + assert.equal(owner.body.code, 'WORKSPACE_REQUIRED'); +}); + +test('cross-origin writes are rejected before contacting identity services', async t => { + const f = await setup(t); + const result = await f.call('a', '/api/sync-store', { url: 'https://catalog.fixture' }, { Origin: 'https://attacker.fixture', 'X-Forwarded-Host': 'studio.fixture' }); + assert.equal(result.status, 403); + assert.equal(f.counts.auth, 0); + assert.equal(f.counts.source, 0); + assert.equal(result.headers.get('access-control-allow-origin'), null); +}); + +test('non-JSON and oversized writes fail without storing data', async t => { + const f = await setup(t, { maxBodyBytes: 128 }); + assert.equal((await f.call('a', '/api/sync-store', {}, { 'Content-Type': 'text/plain' })).status, 415); + assert.equal((await f.call('a', '/api/sync-store', { url: 'x'.repeat(200) })).status, 413); + assert.equal(f.counts.source, 0); + assert.deepEqual((await f.call('a', '/api/get-synced-stores')).body.stores, []); +}); + +test('failed source refresh leaves the previous saved catalog intact', async t => { + const f = await setup(t, { scrape: async () => { throw Object.assign(new Error('incomplete fixture'), { status: 502, code: 'INCOMPLETE_CATALOG' }); } }); + const ws = await f.resolve({ url: '/', headers: { cookie: 'aura_access=a' } }); + await f.store.upsert(ws, { id: 'existing', products: [{ rawPrice: 380 }] }); + const result = await f.call('a', '/api/sync-store', { url: 'https://catalog.fixture' }); + assert.equal(result.status, 502); + const saved = await f.call('a', '/api/get-synced-stores'); + assert.equal(saved.body.stores[0].products[0].rawPrice, 380); +}); + +test('rate limits stop repeated authenticated import work', async t => { + const f = await setup(t, { maxImportsPerMinute: 1 }); + assert.equal((await f.call('a', '/api/sync-store', { url: 'https://catalog.fixture' })).status, 200); + const before = f.counts.source; + assert.equal((await f.call('a', '/api/sync-store', { url: 'https://catalog.fixture' })).status, 429); + assert.equal(f.counts.source, before); +}); + +test('unknown API paths return JSON rather than an HTML success document', async t => { + const f = await setup(t); + const result = await f.call('a', '/api/not-real'); + assert.equal(result.status, 404); + assert.match(result.headers.get('content-type'), /application\/json/); + assert.match(result.headers.get('cache-control'), /no-store/); +}); diff --git a/test/products.test.cjs b/test/products.test.cjs index 78ec0f4..47f7b84 100644 --- a/test/products.test.cjs +++ b/test/products.test.cjs @@ -85,3 +85,7 @@ test('Woo variable parent range is not treated as an exact selected variant pric assert.equal(row.requiresVariantSelection, true); assert.deepEqual(row.priceRange, { minimum: 100, maximum: 200 }); }); + +test('a repeated oversized product field cannot expand a small source into an unbounded catalog', () => { + assert.throws(() => shopifyProducts({ products: [{ id: 1, title: 'x'.repeat(1025), variants: [{ id: 1, price: '1' }] }] }, context), { code: 'SOURCE_FIELD_TOO_LARGE' }); +}); diff --git a/test/public-fetch.test.cjs b/test/public-fetch.test.cjs new file mode 100644 index 0000000..c8064cf --- /dev/null +++ b/test/public-fetch.test.cjs @@ -0,0 +1,98 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const http = require('node:http'); +const zlib = require('node:zlib'); +const { createPublicFetcher, publicAddress, websiteUrl } = require('../server/public-fetch.cjs'); + +async function fixture(t, handler) { + const server = http.createServer(handler); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); }); + const port = server.address().port, calls = []; + const requestImpl = (url, options, callback) => { + options.lookup(url.hostname, { all: true }, (error, addresses) => { + assert.ifError(error); + assert.ok(addresses.every(item => publicAddress(item.address))); + calls.push({ pathname: url.pathname, pinned: addresses, headers: options.headers }); + }); + return http.get(new URL(url.pathname + url.search, 'http://127.0.0.1:' + port), { ...options, lookup: undefined }, callback); + }; + return { calls, requestImpl }; +} +const lookup = async () => [{ address: '1.1.1.1', family: 4 }]; + +test('rejects internal, mapped-private, metadata and reserved addresses', () => { + for (const address of ['127.0.0.1', '10.1.2.3', '172.16.0.1', '192.168.1.1', '169.254.169.254', '100.64.0.1', '0.0.0.0', '::1', 'fc00::1', 'fe80::1', '::ffff:127.0.0.1', '64:ff9b::7f00:1', '2001:db8::1']) { + assert.equal(publicAddress(address), false, address); + } + assert.equal(publicAddress('1.1.1.1'), true); + assert.equal(publicAddress('2606:4700:4700::1111'), true); +}); + +test('rejects unsupported schemes, credentials and nonstandard ports', () => { + for (const url of ['file:///etc/passwd', 'http://user:pass@example.com/', 'http://example.com:2375/', 'ftp://example.com/']) { + assert.throws(() => websiteUrl(url), { code: 'INVALID_SOURCE_URL' }); + } +}); + +test('blocks numeric loopback aliases and mixed DNS before opening any request', async () => { + let opened = 0; + const get = createPublicFetcher({ lookup: async () => [{ address: '1.1.1.1', family: 4 }, { address: '10.0.0.1', family: 4 }], requestImpl: () => { opened++; } }); + await assert.rejects(get('http://2130706433/'), { code: 'NON_PUBLIC_SOURCE' }); + await assert.rejects(get('http://mixed.fixture/'), { code: 'NON_PUBLIC_SOURCE' }); + assert.equal(opened, 0); +}); + +test('pins validated DNS and never forwards account credentials to source websites', async t => { + const f = await fixture(t, (_req, res) => { res.end('{"products":[]}'); }); + const result = await createPublicFetcher({ lookup, requestImpl: f.requestImpl })('http://catalog.fixture/products.json'); + assert.equal(result.status, 200); + assert.equal(result.body.toString(), '{"products":[]}'); + assert.deepEqual(f.calls[0].pinned, [{ address: '1.1.1.1', family: 4 }]); + assert.equal(f.calls[0].headers.Cookie, undefined); + assert.equal(f.calls[0].headers.Authorization, undefined); +}); + +test('redirects are revalidated and a private redirect is never requested', async t => { + const f = await fixture(t, (_req, res) => { res.writeHead(302, { Location: 'http://169.254.169.254/latest/' }); res.end(); }); + await assert.rejects(createPublicFetcher({ lookup, requestImpl: f.requestImpl })('http://catalog.fixture/redirect'), { code: 'NON_PUBLIC_SOURCE' }); + assert.equal(f.calls.length, 1); +}); + +test('same-host redirect cannot bypass a DNS rebind to a private address', async t => { + const f = await fixture(t, (_req, res) => { res.writeHead(302, { Location: '/next' }); res.end(); }); + let queries = 0; + const dns = async () => [{ address: ++queries === 1 ? '1.1.1.1' : '127.0.0.1', family: 4 }]; + await assert.rejects(createPublicFetcher({ lookup: dns, requestImpl: f.requestImpl })('http://catalog.fixture/start'), { code: 'NON_PUBLIC_SOURCE' }); + assert.equal(f.calls.length, 1); +}); + +test('redirect loops terminate within the configured request budget', async t => { + const f = await fixture(t, (_req, res) => { res.writeHead(302, { Location: '/again' }); res.end(); }); + await assert.rejects(createPublicFetcher({ lookup, requestImpl: f.requestImpl, maxRedirects: 2 })('http://catalog.fixture/start'), { code: 'SOURCE_REDIRECT_LIMIT' }); + assert.equal(f.calls.length, 3); +}); + +test('body size limits apply to decoded compressed data', async t => { + const payload = zlib.gzipSync('x'.repeat(10000)); + const f = await fixture(t, (_req, res) => { res.writeHead(200, { 'Content-Encoding': 'gzip' }); res.end(payload); }); + await assert.rejects(createPublicFetcher({ lookup, requestImpl: f.requestImpl, maxBytes: 200 })('http://catalog.fixture/large'), { code: 'SOURCE_TOO_LARGE' }); +}); + +test('valid gzip body is decoded and slow sources time out', async t => { + const f = await fixture(t, (req, res) => { + if (req.url === '/slow') { res.writeHead(200); res.write('waiting'); return; } + res.writeHead(200, { 'Content-Encoding': 'gzip' }); res.end(zlib.gzipSync('real fixture data')); + }); + const get = createPublicFetcher({ lookup, requestImpl: f.requestImpl, timeoutMs: 2000 }); + assert.equal((await get('http://catalog.fixture/gzip')).body.toString(), 'real fixture data'); + const short = createPublicFetcher({ lookup, requestImpl: f.requestImpl, timeoutMs: 100 }); + await assert.rejects(short('http://catalog.fixture/slow'), { code: 'SOURCE_TIMEOUT' }); +}); + +test('slow DNS times out without opening a connection', async () => { + let opened = 0; + const get = createPublicFetcher({ lookup: () => new Promise(() => {}), requestImpl: () => { opened++; }, timeoutMs: 30 }); + await assert.rejects(get('http://catalog.fixture/'), { code: 'SOURCE_TIMEOUT' }); + assert.equal(opened, 0); +}); diff --git a/test/scraper.test.cjs b/test/scraper.test.cjs new file mode 100644 index 0000000..b1bf4e9 --- /dev/null +++ b/test/scraper.test.cjs @@ -0,0 +1,109 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { createScraper, htmlProducts } = require('../server/scraper.cjs'); + +function response(url, value, status = 200, headers = {}) { + return { url, status, headers, body: Buffer.from(typeof value === 'string' ? value : JSON.stringify(value)) }; +} +const wooItem = id => ({ id, name: 'Product ' + id, sku: 'SKU-' + id, prices: { price: String(id * 100), regular_price: String(id * 120), currency_code: 'BDT', currency_minor_unit: 2 } }); + +test('reads all advertised Woo pages using a discovered subdirectory REST root', async () => { + const calls = []; + const scrape = createScraper({ fetchPublic: async url => { + calls.push(url); + if (calls.length === 1) return response('https://www.catalog.fixture/shop/', ''); + const u = new URL(url); + assert.equal(u.pathname, '/shop/wp-json/wc/store/v1/products'); + return response(url, u.searchParams.get('page') === '1' ? Array.from({ length: 100 }, (_, i) => wooItem(i)) : [wooItem(100)], 200, { 'x-wp-totalpages': '2' }); + } }); + const result = await scrape({ url: 'https://catalog.fixture/shop/', storeName: 'Own shop' }); + assert.equal(result.count, 101); + assert.equal(result.domain, 'www.catalog.fixture'); + assert.equal(result.products[0].rawPrice, 0); + assert.equal(result.products[100].rawPrice, 100); + assert.equal(calls.length, 3); +}); + +test('Shopify pagination preserves source currency and distinct variant records', async () => { + const calls = []; + const scrape = createScraper({ fetchPublic: async url => { + calls.push(url); const u = new URL(url); + if (u.pathname === '/') return response(url, 'Storefront'); + if (u.pathname.includes('wp-json')) return response(url, {}, 404); + const ids = u.searchParams.get('page') === '1' ? Array.from({ length: 250 }, (_, i) => i) : [250]; + return response(url, { currency: 'USD', products: ids.map(id => ({ id, title: 'Item ' + id, variants: [{ id: 'v-' + id, sku: 'SKU-' + id, price: '1.25' }] })) }); + } }); + const result = await scrape({ url: 'https://catalog.fixture' }); + assert.equal(result.count, 251); + assert.equal(result.products[0].currency, 'USD'); + assert.equal(result.products[0].rawRegularPrice, null); + assert.equal(calls.length, 4); +}); + +test('failed later pages and repeated pages fail without claiming a complete import', async () => { + for (const repeated of [true, false]) { + const scrape = createScraper({ fetchPublic: async url => { + if (new URL(url).pathname === '/') return response(url, 'Shop'); + const second = new URL(url).searchParams.get('page') === '2'; + return response(url, Array.from({ length: 100 }, (_, i) => wooItem(i)), second && !repeated ? 503 : 200, { 'x-wp-totalpages': '2' }); + } }); + await assert.rejects(scrape({ url: 'https://catalog.fixture' }), { code: repeated ? 'PAGINATION_UNSUPPORTED' : 'INCOMPLETE_CATALOG' }); + } +}); + +test('HTML extraction uses actual sale markup and never invents a missing amount', () => { + const html = ``; + const result = htmlProducts(Buffer.from(html), { url: 'https://catalog.fixture/', documentUrl: 'https://catalog.fixture/shop/', name: 'Shop', id: 'own', category: 'general' }); + assert.equal(result.products[0].rawPrice, 220); + assert.equal(result.products[0].rawRegularPrice, 270); + assert.equal(result.products[1].rawPrice, null); +}); + +test('public HTML pagination is followed and its limited coverage is explicit', async () => { + const scrape = createScraper({ fetchPublic: async url => { + const u = new URL(url); + if (u.pathname.includes('wp-json') || u.pathname === '/products.json') return response(url, {}, 404); + const second = u.searchParams.get('page') === '2'; + return response(url, `${second ? '' : ''}`); + } }); + const result = await scrape({ url: 'https://catalog.fixture/catalog' }); + assert.equal(result.count, 2); + assert.equal(result.sourceType, 'public-html-pages'); + assert.match(result.coverage, /not a guarantee/); +}); + +test('request/product limits and private targets fail rather than saving a fabricated catalog', async () => { + const scrape = createScraper({ maxProducts: 1, fetchPublic: async url => new URL(url).pathname === '/' ? response(url, 'Shop') : response(url, [wooItem(1), wooItem(2)]) }); + await assert.rejects(scrape({ url: 'https://catalog.fixture' }), { code: 'IMPORT_LIMIT' }); + let calls = 0; + const blocked = createScraper({ fetchPublic: async () => { calls++; throw Object.assign(new Error('blocked fixture'), { status: 400, code: 'NON_PUBLIC_SOURCE' }); } }); + await assert.rejects(blocked({ url: 'http://127.0.0.1/' }), { code: 'NON_PUBLIC_SOURCE' }); + assert.equal(calls, 1); +}); + +test('an empty authoritative public catalog does not fabricate products from unrelated home markup', async () => { + const scrape = createScraper({ fetchPublic: async url => new URL(url).pathname === '/' ? response(url, '

Sale!

') : response(url, []) }); + await assert.rejects(scrape({ url: 'https://catalog.fixture' }), { code: 'NO_PUBLIC_PRODUCTS' }); +}); + +test('an advertised second page is read even when the first page is shorter than the requested page size', async () => { + let pages = 0; + const scrape = createScraper({ pageDelayMs: 0, fetchPublic: async url => { + if (new URL(url).pathname === '/') return response(url, 'Shop'); + pages++; + return response(url, [wooItem(pages)], 200, { 'x-wp-totalpages': '2' }); + } }); + assert.equal((await scrape({ url: 'https://catalog.fixture/' })).count, 2); + assert.equal(pages, 2); +}); + +test('request pacing can be cancelled before the next website request', async () => { + let requests = 0; + const controller = new AbortController(); + const scrape = createScraper({ pageDelayMs: 1000, fetchPublic: async url => { requests++; return response(url, 'Shop'); } }); + setTimeout(() => controller.abort(), 20); + await assert.rejects(scrape({ url: 'https://catalog.fixture/' }, { signal: controller.signal }), { code: 'IMPORT_TIMEOUT' }); + assert.equal(requests, 1); +}); diff --git a/test/static-main.test.cjs b/test/static-main.test.cjs new file mode 100644 index 0000000..774d190 --- /dev/null +++ b/test/static-main.test.cjs @@ -0,0 +1,54 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const path = require('node:path'); +const os = require('node:os'); +const { createStudioServer } = require('../server/main.cjs'); + +async function app(t) { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'studio-main-')); + const publicDirectory = path.join(root, 'public'); + await fs.mkdir(publicDirectory); + await fs.writeFile(path.join(publicDirectory, 'index.html'), '

Fixture Studio

'); + await fs.writeFile(path.join(publicDirectory, 'app.js'), '/* fixture */\n'.repeat(200)); + await fs.writeFile(path.join(root, 'private.txt'), 'PRIVATE-FIXTURE-NOT-A-WEB-ASSET'); + const server = createStudioServer({ publicDirectory, dataDirectory: path.join(root, 'state'), publicOrigin: 'https://studio.fixture', authMeUrl: 'http://127.0.0.1:1/auth', clientMeUrl: 'http://127.0.0.1:1/client' }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + t.after(async () => { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); await fs.rm(root, { recursive: true, force: true }); }); + return 'http://127.0.0.1:' + server.address().port; +} + +test('server serves existing static assets, compression and revalidation without starting a provider', async t => { + const base = await app(t); + const root = await fetch(base); + assert.equal(root.status, 200); + assert.match(await root.text(), /Fixture Studio/); + assert.match(root.headers.get('cache-control'), /no-store/); + const js = await fetch(base + '/app.js'); + assert.equal(js.headers.get('content-encoding'), 'gzip'); + assert.equal((await js.text()).length, '/* fixture */\n'.repeat(200).length); + assert.equal((await fetch(base + '/app.js', { headers: { 'If-None-Match': js.headers.get('etag') } })).status, 304); + const head = await fetch(base + '/app.js', { method: 'HEAD' }); + assert.equal(head.status, 200); assert.equal(await head.text(), ''); +}); + +test('backend source, private files and traversal paths are not static downloads', async t => { + const base = await app(t); + for (const route of ['/server/main.cjs', '/.env', '/docs', '/node_modules/x', '/%2e%2e%2fprivate.txt', '/assets/..%5cprivate.txt']) { + const result = await fetch(base + route, { headers: { Accept: 'text/html' } }); + assert.equal(result.status, 404, route); + assert.doesNotMatch(await result.text(), /PRIVATE-FIXTURE/); + } +}); + +test('API failures stay JSON and service health is distinct from authenticated workspace availability', async t => { + const base = await app(t); + assert.equal((await fetch(base + '/health')).status, 200); + const denied = await fetch(base + '/api/get-synced-stores'); + assert.equal(denied.status, 401); + assert.match(denied.headers.get('content-type'), /application\/json/); + assert.equal((await denied.json()).code, 'LOGIN_REQUIRED'); + const unknown = await fetch(base + '/api/missing'); + assert.equal(unknown.status, 404); + assert.match(unknown.headers.get('content-type'), /application\/json/); +}); diff --git a/test/workspace-store.test.cjs b/test/workspace-store.test.cjs index 2daf4be..959661a 100644 --- a/test/workspace-store.test.cjs +++ b/test/workspace-store.test.cjs @@ -5,14 +5,20 @@ const os = require('node:os'); const path = require('node:path'); const { createWorkspaceResolver, requireProductWrite } = require('../server/workspace.cjs'); const { createStore } = require('../server/store.cjs'); +const { createHash } = require('node:crypto'); -function resolver({ role = 'client', tenant = 'verified-tenant', products = true, active = true, status = 200, captures = [] } = {}) { +function fixtureClientId(tenant) { + const h = createHash('sha256').update(tenant).digest('hex'); + return [h.slice(0, 8), h.slice(8, 12), h.slice(12, 16), h.slice(16, 20), h.slice(20, 32)].join('-'); +} + +function resolver({ role = 'client', tenant = 'verified-tenant', clientId, clientActor, products = true, active = true, status = 200, captures = [] } = {}) { return createWorkspaceResolver({ authMeUrl: 'http://auth.test/api/auth/me', clientMeUrl: 'http://client.test/api/me', fetchImpl: async (url, options) => { captures.push({ url, options }); - if (url.includes('auth.test')) return new Response(JSON.stringify({ user: { id: 'fixture-user', role, isActive: active } }), { status }); - return Response.json({ success: true, tenant, role: 'manager', perms: { products } }); + if (url.includes('auth.test')) return new Response(JSON.stringify({ user: { id: 'fixture-user', email: 'actor@example.test', role, isActive: active } }), { status }); + return Response.json({ success: true, tenant, clientId: clientId === undefined ? fixtureClientId(tenant) : clientId, actor: clientActor || { id: 'fixture-user', email: 'actor@example.test', role }, role: 'manager', perms: { products } }); } }); } @@ -24,6 +30,7 @@ test('uses canonical server tenant, not client-supplied IDs or requested tenant' assert.equal(ws.tenant, 'verified-tenant'); assert.match(ws.namespace, /^[a-f0-9]{64}$/); assert.equal(captures[1].options.headers['x-client-id'], undefined); + assert.equal(captures[1].options.headers['x-aura-tenant'], undefined); assert.equal(captures[0].options.redirect, 'error'); }); @@ -88,3 +95,21 @@ test('untrusted namespaces cannot become file paths', async t => { t.after(() => fs.rm(root, { recursive: true, force: true })); await assert.rejects(createStore(root).read({ namespace: '../other-client' }), /namespace/); }); + +test('storage identity survives tenant renaming and cannot alias another client with the same label', async () => { + const clientId = fixtureClientId('original'); + const before = await resolver({ clientId, tenant: 'old-name' })(request()); + const after = await resolver({ clientId, tenant: 'new-name' })(request()); + const other = await resolver({ clientId: fixtureClientId('other'), tenant: 'old-name' })(request()); + assert.equal(before.namespace, after.namespace); + assert.notEqual(before.namespace, other.namespace); + await assert.rejects(resolver({ clientId: null })(request()), { code: 'WORKSPACE_UNAVAILABLE' }); +}); + +test('stale role, email or user identity across Auth and Client cannot select storage', async () => { + for (const clientActor of [ + { id: 'fixture-user', email: 'actor@example.test', role: 'owner' }, + { id: 'fixture-user', email: 'old@example.test', role: 'client' }, + { id: 'different-user', email: 'actor@example.test', role: 'client' } + ]) await assert.rejects(resolver({ clientActor })(request()), { code: 'SESSION_CHANGED' }); +});