Compare commits

..

7 Commits

Author SHA1 Message Date
khondokartowsif171 54091f4578 Keep Studio business branding in verified client storage 2026-10-19 11:54:13 +06:00
khondokartowsif171 165320cc9f Read existing Client catalogs through verified workspace context 2026-10-19 01:34:52 +06:00
khondokartowsif171 6db99f96df Gate Studio frontend by workspace and isolate browser catalog state 2026-10-19 01:20:55 +06:00
khondokartowsif171 07f711ff2d Protect Studio catalog images and expose canonical workspace bootstrap 2026-10-18 22:53:29 +06:00
khondokartowsif171 cbe6e0ae94 Implement protected Studio catalog API and bounded public source reader 2026-10-18 21:10:07 +06:00
khondokartowsif171 3847a5e6a1 Add tenant-scoped Studio backend primitives and static asset allowlist 2026-10-18 20:21:08 +06:00
khondokartowsif171 d5c004a27e Preserve deployed Studio renderer before runtime reconciliation 2026-10-18 20:03:23 +06:00
31 changed files with 4478 additions and 724 deletions
+11
View File
@@ -0,0 +1,11 @@
.git
.gitignore
.env
.env.*
node_modules
test
docs
*.log
*.tar
*.tar.gz
outputs
+5
View File
@@ -0,0 +1,5 @@
node_modules/
.env
.env.*
*.log
coverage/
+6 -4
View File
@@ -1,5 +1,6 @@
# Lightweight Alpine Nginx for Opal iOS Web App # Lightweight Alpine Nginx for Opal iOS Web App
FROM nginx:alpine ARG NGINX_IMAGE=nginx:alpine
FROM ${NGINX_IMAGE}
# Remove default nginx static assets # Remove default nginx static assets
RUN rm -rf /usr/share/nginx/html/* RUN rm -rf /usr/share/nginx/html/*
@@ -7,9 +8,10 @@ RUN rm -rf /usr/share/nginx/html/*
# Copy custom nginx configuration # Copy custom nginx configuration
COPY nginx.conf /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d/default.conf
# Copy all web assets, catalogs, and images # Publish web assets only. Backend source, tests and local configuration are not static downloads.
COPY . /usr/share/nginx/html/ COPY index.html app.js workspace.js style.css sw.js manifest.json gt_full_catalog.json /usr/share/nginx/html/
RUN rm -f /usr/share/nginx/html/Dockerfile /usr/share/nginx/html/docker-compose.yml /usr/share/nginx/html/nginx.conf COPY assets/ /usr/share/nginx/html/assets/
COPY data/ /usr/share/nginx/html/data/
# Expose port 80 for Coolify Traefik reverse proxy # Expose port 80 for Coolify Traefik reverse proxy
EXPOSE 80 EXPOSE 80
+14
View File
@@ -0,0 +1,14 @@
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 workspace.js style.css sw.js manifest.json ./public/
COPY assets/ ./public/assets/
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"]
+1909 -658
View File
File diff suppressed because it is too large Load Diff
+11
View File
@@ -0,0 +1,11 @@
# Client catalog read-through
Studio can read the current Client workspace catalog through the configured trusted `STUDIO_CLIENT_CATALOG_URL`. `STUDIO_CLIENT_PUBLIC_ORIGIN` identifies the public Client origin for relative image references; neither setting is inferred from an arbitrary browser URL. Both are required by the service entrypoint before production startup.
The workspace resolver first verifies the active Auth identity and canonical Client membership. Its server-only catalog reader forwards the selected access cookie and canonical tenant to Client, then checks that the response's client UUID and tenant match the resolved workspace. Browser-supplied client IDs and unrelated cookies are not forwarded. Responses are bounded in size and time; redirects are rejected. Provider/database credentials remain in Client.
The connected catalog is a read-only store alongside imports. Studio does not copy it to the private import JSON file, change its prices, write products back, or remove it through the import deletion endpoint. Source zero/unknown prices and optional currency remain distinct. Products use the same-origin image route; another connected client identifier cannot select an image.
A bounded per-client cache keeps a successful connected read for 30 seconds. It is capped at 100 entries/64 MiB, coalesces simultaneous reads for one client, and allows at most two cold reads across clients. Every API/image request still resolves its authenticated workspace before looking at the cache. Expired/failed reads do not silently become an empty catalog or stale success. The source fetch timestamp is retained.
The candidate image passes 65 tests, including the prior catalog/import/image/frontend checks. Tests use explicit source fixtures and no network during execution. This is not a production merchant read or a released service. Client's matching gated catalog endpoint must be deployed first, after full build/startup/recovery checks. Persistent Studio configuration and post-release verification remain open. Meta 1-Click Connector is excluded.
+46
View File
@@ -0,0 +1,46 @@
# Frontend workspace integration — 19 October 2026
The candidate now gates app startup on verified workspace identity, scopes browser private state by client UUID, removes prototype merchant catalog/default policy for new clients, and escapes imported catalog markup. Local and Linux image tests pass 58/58. Separate loopback browser QA confirms inert HTML-like product names, source price transfer without a fabricated discount, and an empty second workspace. The large poster renderer section is unchanged. CLI configuration now requires STUDIO_LOGIN_URL.
Connected Client catalog brokerage, full Client startup/recovery, persistent Studio service configuration and actual release remain open. No Meta 1-Click Connector inspection or change was made.
# Studio runtime source reconciliation
Captured on 2026-10-18 from the running Aura Studio static application. app.js is restored byte-for-byte from the privately preserved live file, SHA-256 025a1d94971361944cc3a3197bb894255d96cc824f603da3425466fab4cbdf74. The remaining checked static entry/config files match repository main after line-ending normalization.
The runtime includes substantial poster-renderer changes not represented by main. This branch preserves those existing changes before any packaging or API repair. Syntax is checked separately; preserving this file does not certify generation providers or all UI actions.
The running Nginx service serves /api/get-synced-stores through its HTML fallback. A fresh no-cache GET reproduced HTML rather than JSON. This is the standalone Studio endpoint, not the separate Aura Admin URL-sync or Client catalog path.
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 — not deployed
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 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.
# Workspace and raster image integration — 18 October 2026
The protected API now exposes `GET /api/workspace` for the canonical Client UUID, tenant, display name and catalog permission. It returns no saved catalog or internal namespace. Missing login and owner workspace selection remain explicit failures.
Catalog list/import/delete responses replace merchant image URLs with a same-origin `/api/catalog-image` reference. That route resolves the product from the authenticated workspace's saved catalog; arbitrary URL parameters are rejected. Its outbound reads use the bounded public fetcher, including DNS/redirect checks, a 5 MiB decoded-body ceiling and ten-second timeout. Four image reads may run concurrently. Only signature-recognized PNG, JPEG, GIF and WebP responses are returned. HTML and SVG are rejected. This is format recognition, not complete image decoding or a claim that every source image is supported.
The backend candidate is not deployed. Frontend authentication/workspace selection, private browser-state namespacing, imported-text rendering, connected Client catalog access and persistent production configuration remain required release work. The prototype global GT catalog is not a valid default for another client. No Meta connector inspection or modification is part of this work.
The local branch reference was found zero-filled. Its bytes were retained outside the Git refs directory, the remote branch was read, and the existing local commit object was checked before restoring the reference to `cbe6e0ae94e22e6c34ecc55bad036ff8c165b488`. No working files were reset. The cause of that local reference damage is not established.
+51 -62
View File
@@ -22,6 +22,17 @@
<link rel="stylesheet" href="style.css?v=6"> <link rel="stylesheet" href="style.css?v=6">
</head> </head>
<body> <body>
<section id="studioWorkspaceGate" role="dialog" aria-modal="true" aria-labelledby="workspaceTitle" style="position:fixed;inset:0;z-index:99999;background:#0b1020;color:#eef2ff;padding:10vh 8vw;overflow:auto">
<h1 id="workspaceTitle">Aura Studio</h1>
<p id="workspaceStatus" role="status">আপনার workspace যাচাই হচ্ছে…</p>
<a id="workspaceLogin" class="pill-btn primary" hidden>Login করুন</a>
<form id="workspaceForm" hidden>
<label for="workspaceTenant">Client workspace ID</label>
<input id="workspaceTenant" name="tenant" maxlength="256" required autocomplete="off" placeholder="আপনার client workspace ID">
<button type="submit" class="pill-btn primary">Workspace খুলুন</button>
</form>
<button id="workspaceRetry" type="button" class="pill-btn">আবার চেষ্টা করুন</button>
</section>
<!-- Top App Header --> <!-- Top App Header -->
<header class="app-header"> <header class="app-header">
@@ -246,16 +257,7 @@
<option value="1:1" selected>Square (1:1 • 1080x1080) — Facebook/Instagram Feed</option> <option value="1:1" selected>Square (1:1 • 1080x1080) — Facebook/Instagram Feed</option>
<option value="9:16">Portrait (9:16 • 1080x1920) — Stories & Reels</option> <option value="9:16">Portrait (9:16 • 1080x1920) — Stories & Reels</option>
</select> </select>
<select id="brandWatermarkSelect"> <select id="brandWatermarkSelect"><option value="workspace">আপনার workspace</option></select>
<option value="glamourstouch" selected>✨ Glamour's Touch (Cosmetics & K-Beauty)</option>
<option value="snehalata">👗 Snehalata (Fashion, Saree & Lifestyle)</option>
<option value="panjabi">👑 Aura Heritage (Royal Designer Panjabi & Kabli)</option>
<option value="techvolt">📱 TechVolt (Gadgets & Smart Electronics)</option>
<option value="organic">🍯 Pranon Organic (Pure Honey & Natural Food)</option>
<option value="sneakerlab">👟 SneakerLab (Footwear & Streetwear)</option>
<option value="royale">💎 Aura Royale (Luxury Jewelry & Fragrance)</option>
<option value="custom">🛍️ Universal E-Commerce Merchant</option>
</select>
</div> </div>
</div> </div>
@@ -277,37 +279,29 @@
<!-- Trending Google Search Suggestions --> <!-- Trending Google Search Suggestions -->
<div class="form-group"> <div class="form-group">
<label style="display:flex; justify-content:space-between; align-items:center;"> <label style="display:flex; justify-content:space-between; align-items:center;">
<span data-i18n="trends_label">🔥 গুগল ট্রেন্ডিং সার্চ (Google Trends 1-Click Load):</span> <span data-i18n="trends_label">🛍️ আপনার catalog থেকে বাছুন:</span>
<span style="font-size:10.5px; color:var(--primary); font-weight:600;" data-i18n="trends_badge">Realtime BD Trends</span> <span style="font-size:10.5px; color:var(--primary); font-weight:600;" data-i18n="trends_badge">Workspace catalog</span>
</label> </label>
<div class="trending-chips-bar" id="trendingPosterChips"> <div class="trending-chips-bar" id="trendingPosterChips"></div>
<button type="button" class="trend-chip active" data-brand="glamourstouch" data-title="Medicube Collagen Jelly Cream" data-price="৳ ১,০৬০ (৳ ১,৪৭০) 28% OFF" data-badge="🛡️ 100% Authentic Korean Seal">✨ K-Beauty Cream</button>
<button type="button" class="trend-chip" data-brand="panjabi" data-title="Royal Platinum Silk Designer Panjabi" data-price="৳ ২,৯৫০ (৳ ৩,৮০০) 22% OFF" data-badge="👑 100% Pre-Shrunk Weave">👑 Royal Panjabi</button>
<button type="button" class="trend-chip" data-brand="snehalata" data-title="Katan Silk Handloom Party Saree" data-price="৳ ৩,৪৫০ (৳ ৪,৫০০) 23% OFF" data-badge="👗 Authentic Handloom Weave">👗 Silk Saree</button>
<button type="button" class="trend-chip" data-brand="techvolt" data-title="T900 Ultra Smartwatch Series 9" data-price="৳ ১,৬৫০ (৳ ২,২০০) 25% OFF" data-badge="⚡ 1 Year Official Warranty">⚡ Smartwatch</button>
<button type="button" class="trend-chip" data-brand="organic" data-title="Sundarban Pure Raw Khalsi Honey 1kg" data-price="৳ ১,২৫০ (৳ ১,৫০০) 16% OFF" data-badge="🍯 100% Pure Lab Tested">🍯 Pure Honey</button>
<button type="button" class="trend-chip" data-brand="sneakerlab" data-title="Air Cushion Streetwear Sneaker 2026" data-price="৳ ২,৪৫০ (৳ ৩,২০০) 23% OFF" data-badge="👟 Memory Foam Cushion">👟 Street Sneaker</button>
<button type="button" class="trend-chip" data-brand="royale" data-title="Oud Al Layl 24h Signature Perfume 100ml" data-price="৳ ৩,২০০ (৳ ৪,০০০) 20% OFF" data-badge="💎 24h Long Lasting Sillage">💎 Luxury Perfume</button>
</div>
</div> </div>
<div class="form-group" style="position: relative;"> <div class="form-group" style="position: relative;">
<label for="productInput" style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:6px;"> <label for="productInput" style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:6px;">
<span data-i18n="product_input_label">প্রডাক্ট লিংক বা নাম (Product Link or Name):</span> <span data-i18n="product_input_label">প্রডাক্ট লিংক বা নাম (Product Link or Name):</span>
<button type="button" id="openCatalogModalBtn" class="pill-btn primary" style="padding:4px 10px; font-size:11px; cursor:pointer;" data-i18n="open_catalog_btn">🛍️ GT ক্যাটালগ লিস্ট (560+)</button> <button type="button" id="openCatalogModalBtn" class="pill-btn primary" style="padding:4px 10px; font-size:11px; cursor:pointer;" data-i18n="open_catalog_btn">🛍️ আপনার catalog</button>
</label> </label>
<input type="text" id="productInput" data-i18n-ph="product_input_ph" placeholder="e.g. Silk Saree, Smartwatch, Pure Honey, Sneaker or Skincare" value="Medicube Collagen Jelly Cream" autocomplete="off"> <input type="text" id="productInput" data-i18n-ph="product_input_ph" placeholder="e.g. Silk Saree, Smartwatch, Pure Honey, Sneaker or Skincare" value="" autocomplete="off">
<div id="productAutocompleteList" class="autocomplete-dropdown hidden"></div> <div id="productAutocompleteList" class="autocomplete-dropdown hidden"></div>
</div> </div>
<div class="form-row"> <div class="form-row">
<div class="form-group"> <div class="form-group">
<label for="productPrice" data-i18n="product_price_label">মূল্য ও অফার (Price & Discount):</label> <label for="productPrice" data-i18n="product_price_label">মূল্য ও অফার (Price & Discount):</label>
<input type="text" id="productPrice" data-i18n-ph="product_price_ph" placeholder="e.g. ৳ ১,০৬০ (৳ ১,৪৭০) 28% OFF" value="৳ ১,০৬০ (৳ ১,৪৭০) 28% OFF"> <input type="text" id="productPrice" data-i18n-ph="product_price_ph" placeholder="e.g. ৳ ১,০৬০ (৳ ১,৪৭০) 28% OFF" value="">
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="customBadgeInput" data-i18n="product_badge_label">কাস্টম ব্যাজ টেক্সট (Trust Badge):</label> <label for="customBadgeInput" data-i18n="product_badge_label">কাস্টম ব্যাজ টেক্সট (Trust Badge):</label>
<input type="text" id="customBadgeInput" data-i18n-ph="product_badge_ph" placeholder="e.g. 🛡️ 100% Original Guarantee" value="🛡️ 100% Original Guarantee"> <input type="text" id="customBadgeInput" data-i18n-ph="product_badge_ph" placeholder="e.g. 🛡️ 100% Original Guarantee" value="">
</div> </div>
</div> </div>
@@ -348,13 +342,7 @@
<span data-i18n="multi_combos_label">🎁 ট্রেন্ডিং মাল্টি-প্যাক কম্বো (1-Click Multi Combos):</span> <span data-i18n="multi_combos_label">🎁 ট্রেন্ডিং মাল্টি-প্যাক কম্বো (1-Click Multi Combos):</span>
<span style="font-size:10.5px; color:var(--primary); font-weight:600;" data-i18n="multi_combos_badge">Full Catalog Combos</span> <span style="font-size:10.5px; color:var(--primary); font-weight:600;" data-i18n="multi_combos_badge">Full Catalog Combos</span>
</label> </label>
<div class="trending-chips-bar" id="multiComboChips"> <div class="trending-chips-bar" id="multiComboChips"></div>
<button type="button" class="trend-chip active" data-combo="kbeauty_4">🌸 K-Beauty 4-Pack</button>
<button type="button" class="trend-chip" data-combo="panjabi_3">👑 Royal Panjabi Trio</button>
<button type="button" class="trend-chip" data-combo="tech_3">📱 TechVolt Trio</button>
<button type="button" class="trend-chip" data-combo="organic_3">🍯 Pure Nature Trio</button>
<button type="button" class="trend-chip" data-combo="sneaker_4">👟 SneakerLab 4-Pack</button>
</div>
</div> </div>
<!-- 4 Interactive Product Slots --> <!-- 4 Interactive Product Slots -->
@@ -370,10 +358,10 @@
<span id="slotPlaceholder1" style="font-size:11px; color:#64748B;" data-i18n="slot_placeholder_text">ছবি সিলেক্ট করুন</span> <span id="slotPlaceholder1" style="font-size:11px; color:#64748B;" data-i18n="slot_placeholder_text">ছবি সিলেক্ট করুন</span>
</div> </div>
<div class="slot-inputs-row"> <div class="slot-inputs-row">
<input type="text" id="slotTitle1" class="slot-input" data-i18n-ph="slot_title_ph" placeholder="প্রোডাক্ট নাম" value="Medicube Collagen Jelly Cream"> <input type="text" id="slotTitle1" class="slot-input" data-i18n-ph="slot_title_ph" placeholder="প্রোডাক্ট নাম" value="">
<input type="text" id="slotPrice1" class="slot-input" data-i18n-ph="slot_price_ph" placeholder="মূল্য" value="৳ ১,০৬০"> <input type="text" id="slotPrice1" class="slot-input" data-i18n-ph="slot_price_ph" placeholder="মূল্য" value="">
</div> </div>
<input type="text" id="slotBadge1" class="slot-input" data-i18n-ph="slot_badge_ph" placeholder="ব্যাজ" value="🛡️ 100% Original"> <input type="text" id="slotBadge1" class="slot-input" data-i18n-ph="slot_badge_ph" placeholder="ব্যাজ" value="">
</div> </div>
<!-- SLOT 2 --> <!-- SLOT 2 -->
@@ -387,10 +375,10 @@
<span id="slotPlaceholder2" style="font-size:11px; color:#64748B;" data-i18n="slot_placeholder_text">ছবি সিলেক্ট করুন</span> <span id="slotPlaceholder2" style="font-size:11px; color:#64748B;" data-i18n="slot_placeholder_text">ছবি সিলেক্ট করুন</span>
</div> </div>
<div class="slot-inputs-row"> <div class="slot-inputs-row">
<input type="text" id="slotTitle2" class="slot-input" data-i18n-ph="slot_title_ph" placeholder="প্রোডাক্ট নাম" value="Anua Heartleaf 77% Toner"> <input type="text" id="slotTitle2" class="slot-input" data-i18n-ph="slot_title_ph" placeholder="প্রোডাক্ট নাম" value="">
<input type="text" id="slotPrice2" class="slot-input" data-i18n-ph="slot_price_ph" placeholder="মূল্য" value="৳ ১,৪৮০"> <input type="text" id="slotPrice2" class="slot-input" data-i18n-ph="slot_price_ph" placeholder="মূল্য" value="">
</div> </div>
<input type="text" id="slotBadge2" class="slot-input" data-i18n-ph="slot_badge_ph" placeholder="ব্যাজ" value="🌿 Soothing Care"> <input type="text" id="slotBadge2" class="slot-input" data-i18n-ph="slot_badge_ph" placeholder="ব্যাজ" value="">
</div> </div>
<!-- SLOT 3 --> <!-- SLOT 3 -->
@@ -404,10 +392,10 @@
<span id="slotPlaceholder3" style="font-size:11px; color:#64748B;" data-i18n="slot_placeholder_text">ছবি সিলেক্ট করুন</span> <span id="slotPlaceholder3" style="font-size:11px; color:#64748B;" data-i18n="slot_placeholder_text">ছবি সিলেক্ট করুন</span>
</div> </div>
<div class="slot-inputs-row"> <div class="slot-inputs-row">
<input type="text" id="slotTitle3" class="slot-input" data-i18n-ph="slot_title_ph" placeholder="প্রোডাক্ট নাম" value="COSRX Snail 96 Mucin Essence"> <input type="text" id="slotTitle3" class="slot-input" data-i18n-ph="slot_title_ph" placeholder="প্রোডাক্ট নাম" value="">
<input type="text" id="slotPrice3" class="slot-input" data-i18n-ph="slot_price_ph" placeholder="মূল্য" value="৳ ১,৩৫০"> <input type="text" id="slotPrice3" class="slot-input" data-i18n-ph="slot_price_ph" placeholder="মূল্য" value="">
</div> </div>
<input type="text" id="slotBadge3" class="slot-input" data-i18n-ph="slot_badge_ph" placeholder="ব্যাজ" value="✨ Glass Skin Glow"> <input type="text" id="slotBadge3" class="slot-input" data-i18n-ph="slot_badge_ph" placeholder="ব্যাজ" value="">
</div> </div>
<!-- SLOT 4 --> <!-- SLOT 4 -->
@@ -421,10 +409,10 @@
<span id="slotPlaceholder4" style="font-size:11px; color:#64748B;" data-i18n="slot_placeholder_text">ছবি সিলেক্ট করুন</span> <span id="slotPlaceholder4" style="font-size:11px; color:#64748B;" data-i18n="slot_placeholder_text">ছবি সিলেক্ট করুন</span>
</div> </div>
<div class="slot-inputs-row"> <div class="slot-inputs-row">
<input type="text" id="slotTitle4" class="slot-input" data-i18n-ph="slot_title_ph" placeholder="প্রোডাক্ট নাম" value="Beauty of Joseon Sun Relief"> <input type="text" id="slotTitle4" class="slot-input" data-i18n-ph="slot_title_ph" placeholder="প্রোডাক্ট নাম" value="">
<input type="text" id="slotPrice4" class="slot-input" data-i18n-ph="slot_price_ph" placeholder="মূল্য" value="৳ ১,১৫০"> <input type="text" id="slotPrice4" class="slot-input" data-i18n-ph="slot_price_ph" placeholder="মূল্য" value="">
</div> </div>
<input type="text" id="slotBadge4" class="slot-input" data-i18n-ph="slot_badge_ph" placeholder="ব্যাজ" value="☀️ SPF50+ PA++++"> <input type="text" id="slotBadge4" class="slot-input" data-i18n-ph="slot_badge_ph" placeholder="ব্যাজ" value="">
</div> </div>
</div> </div>
</div> </div>
@@ -649,11 +637,11 @@ Format with clear bullet points, emojis, and a call-to-action.</textarea>
<div class="form-row"> <div class="form-row">
<div class="form-group"> <div class="form-group">
<label for="ugcProductName" data-i18n="ugc_prod_label">প্রডাক্টের নাম ও ব্র্যান্ড (Product):</label> <label for="ugcProductName" data-i18n="ugc_prod_label">প্রডাক্টের নাম ও ব্র্যান্ড (Product):</label>
<input type="text" id="ugcProductName" data-i18n-ph="ugc_prod_ph" placeholder="e.g. Medicube Collagen Jelly Cream" value="Medicube Collagen Jelly Cream"> <input type="text" id="ugcProductName" data-i18n-ph="ugc_prod_ph" placeholder="e.g. Medicube Collagen Jelly Cream" value="">
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="ugcTargetAudience" data-i18n="ugc_aud_label">টার্গেট অডিয়েন্স ও সমস্যা (Audience/Problem):</label> <label for="ugcTargetAudience" data-i18n="ugc_aud_label">টার্গেট অডিয়েন্স ও সমস্যা (Audience/Problem):</label>
<input type="text" id="ugcTargetAudience" data-i18n-ph="ugc_aud_ph" placeholder="e.g. যাদের ত্বক খসখসে ও রোদে পোড়া দাগ রয়েছে" value="যাদের ত্বক খসখসে ও রোদে পোড়া দাগ রয়েছে"> <input type="text" id="ugcTargetAudience" data-i18n-ph="ugc_aud_ph" placeholder="e.g. যাদের ত্বক খসখসে ও রোদে পোড়া দাগ রয়েছে" value="">
</div> </div>
</div> </div>
@@ -777,7 +765,7 @@ Format with clear bullet points, emojis, and a call-to-action.</textarea>
<div class="form-group"> <div class="form-group">
<label for="inboxStoreContext" data-i18n="inbox_store_label">দোকানের পলিসি ও হটলাইন (Store Info):</label> <label for="inboxStoreContext" data-i18n="inbox_store_label">দোকানের পলিসি ও হটলাইন (Store Info):</label>
<input type="text" id="inboxStoreContext" data-i18n-ph="inbox_store_ph" value="Store: Glamour's Touch (glamourstouch.com), Hotline: 01712-426871, 100% Authentic Korean Skincare, Delivery: Dhaka ৳70, Outside Dhaka ৳130, Free delivery on ৳2000+"> <input type="text" id="inboxStoreContext" data-i18n-ph="inbox_store_ph" value="">
</div> </div>
<button id="generateInboxReplyBtn" class="btn-primary"> <button id="generateInboxReplyBtn" class="btn-primary">
@@ -830,6 +818,15 @@ Format with clear bullet points, emojis, and a call-to-action.</textarea>
<!-- TAB 6: Settings & Gemini Configuration --> <!-- TAB 6: Settings & Gemini Configuration -->
<section id="tabSettings" class="tab-page"> <section id="tabSettings" class="tab-page">
<form id="workspaceBrandForm" class="card">
<h2>এই workspace-এর Business তথ্য</h2>
<p>Poster ও WhatsApp link-এর জন্য নিজের business তথ্য দিন। নম্বর না দিলে WhatsApp link তৈরি হবে না।</p>
<div class="form-group"><label for="workspaceBrandName">Business name</label><input id="workspaceBrandName" name="name" maxlength="256" type="text"></div>
<div class="form-group"><label for="workspaceBrandWebsite">Website URL</label><input id="workspaceBrandWebsite" name="website" maxlength="2048" type="url" placeholder="https://your-store.example"></div>
<div class="form-group"><label for="workspaceBrandPhone">WhatsApp number (country code সহ)</label><input id="workspaceBrandPhone" name="phone" maxlength="32" type="tel" placeholder="+880…"></div>
<button type="submit" class="btn-primary">Business তথ্য সংরক্ষণ</button>
<p id="workspaceBrandStatus" role="status"></p>
</form>
<div class="card"> <div class="card">
<div class="card-header"> <div class="card-header">
<span class="icon">⚙️</span> <span class="icon">⚙️</span>
@@ -856,8 +853,8 @@ Format with clear bullet points, emojis, and a call-to-action.</textarea>
<div class="form-group"> <div class="form-group">
<label for="n8nWebhookInput" data-i18n="settings_webhook_label">n8n Auto-Post Webhook URL (Aura Ajentic AI):</label> <label for="n8nWebhookInput" data-i18n="settings_webhook_label">n8n Auto-Post Webhook URL (Aura Ajentic AI):</label>
<input type="text" id="n8nWebhookInput" placeholder="https://n8n.auraajenticai.cloud/webhook/gt-auto-post" value="https://n8n.auraajenticai.cloud/webhook/gt-auto-post"> <input type="text" id="n8nWebhookInput" placeholder="আপনার অনুমোদিত n8n webhook URL" value="">
<small class="hint-text" data-i18n="settings_webhook_hint">Pre-configured with your n8n cloud instance at n8n.auraajenticai.cloud</small> <small class="hint-text" data-i18n="settings_webhook_hint">নিজের workspace-এর অনুমোদিত webhook URL দিন।</small>
</div> </div>
<button id="saveApiKeyBtn" class="btn-primary" data-i18n="btn_save_settings"> <button id="saveApiKeyBtn" class="btn-primary" data-i18n="btn_save_settings">
@@ -983,15 +980,7 @@ Format with clear bullet points, emojis, and a call-to-action.</textarea>
</div> </div>
<!-- Store Switcher Box Tabs --> <!-- Store Switcher Box Tabs -->
<div class="store-switcher-bar" id="storeSwitcherBar"> <div class="store-switcher-bar" id="storeSwitcherBar"></div>
<button type="button" class="store-chip-btn active" data-store-id="glamourstouch">
<span>✨</span> Glamour's Touch (563)
</button>
<!-- Synced Store chips will be injected here -->
<button type="button" class="store-chip-btn add-store-btn" id="toggleSyncPanelBtn">
<span>➕</span> <span data-i18n="btn_sync_new_store">নতুন ক্লায়েন্ট স্টোর সিঙ্ক</span>
</button>
</div>
<!-- Client URL Sync Input Panel (Collapsible) --> <!-- Client URL Sync Input Panel (Collapsible) -->
<div id="storeSyncPanel" class="store-sync-panel hidden"> <div id="storeSyncPanel" class="store-sync-panel hidden">
@@ -1024,11 +1013,11 @@ Format with clear bullet points, emojis, and a call-to-action.</textarea>
<div id="storeInfoBanner" class="store-info-banner"> <div id="storeInfoBanner" class="store-info-banner">
<div class="store-info-left"> <div class="store-info-left">
<span id="activeStoreIcon">✨</span> <span id="activeStoreIcon">✨</span>
<strong id="activeStoreTitle">Glamour's Touch (GT)</strong> <strong id="activeStoreTitle">আপনার workspace</strong>
<span id="activeStoreBadge" class="store-badge-tag">KOREAN COSMETICS</span> <span id="activeStoreBadge" class="store-badge-tag">CATALOG</span>
</div> </div>
<div style="display:flex; align-items:center; gap:8px;"> <div style="display:flex; align-items:center; gap:8px;">
<a id="activeStoreUrlLink" href="https://glamourstouch.com" target="_blank" style="font-size:11px; color:#38BDF8; text-decoration:none;">🔗 Visit Store</a> <a id="activeStoreUrlLink" target="_blank" rel="noopener noreferrer" style="font-size:11px; color:#38BDF8; text-decoration:none;">🔗 Visit Store</a>
<button type="button" id="deleteCurrentStoreBtn" class="btn-delete-store hidden" data-i18n="btn_delete_store">🗑️ মুছুন</button> <button type="button" id="deleteCurrentStoreBtn" class="btn-delete-store hidden" data-i18n="btn_delete_store">🗑️ মুছুন</button>
</div> </div>
</div> </div>
@@ -1052,7 +1041,7 @@ Format with clear bullet points, emojis, and a call-to-action.</textarea>
<!-- Hidden container for generating QR code SVG/Canvas --> <!-- Hidden container for generating QR code SVG/Canvas -->
<div id="qrcodeHidden" style="display:none;"></div> <div id="qrcodeHidden" style="display:none;"></div>
<script src="app.js?v=8"></script> <script src="workspace.js?v=1"></script>
<script> <script>
if ('serviceWorker' in navigator) { if ('serviceWorker' in navigator) {
window.addEventListener('load', () => { window.addEventListener('load', () => {
+325
View File
@@ -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"
}
}
}
}
+8
View File
@@ -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" }
}
+140
View File
@@ -0,0 +1,140 @@
const { fail, requireProductWrite } = require('./workspace.cjs');
const { normalizeBrand } = require('./brand.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, imageHandler, getConnected, publicOrigin, maxBodyBytes = 32768, maxConcurrentImports = 1, maxImportsPerMinute = 5 }) {
const configured = new URL(publicOrigin);
if (!['http:', 'https:'].includes(configured.protocol) || configured.pathname !== '/' || configured.search || configured.hash || configured.username || configured.password) {
throw new Error('A public Studio origin without path or credentials is required');
}
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 browserStore(record, workspace) {
return { ...record, products: record.products.map(product => ({
...product,
image: product.image ? '/api/catalog-image?' + new URLSearchParams({
storeId: record.id, productId: String(product.id), tenant: workspace.tenant
}).toString() : ''
})) };
}
function writeOrigin(request) {
if (request.headers.origin !== origin || (request.headers['sec-fetch-site'] && request.headers['sec-fetch-site'] !== 'same-origin')) {
throw fail(403, 'ORIGIN_REJECTED', 'এই request Studio page থেকে পাঠান।');
}
}
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/workspace': 'GET', '/api/brand': 'POST', '/api/catalog-image': 'GET',
'/api/get-synced-stores': 'GET', '/api/sync-store': 'POST', '/api/delete-synced-store': 'POST'
};
if (!routes[pathname]) return sendJson(response, 404, { success: false, code: 'NOT_FOUND', error: 'API পাওয়া যায়নি।' });
if (request.method !== routes[pathname]) return sendJson(response, 405, { success: false, code: 'METHOD_NOT_ALLOWED', error: 'এই method সমর্থিত নয়।' });
if (request.method === 'POST') writeOrigin(request);
const workspace = await resolveWorkspace(request);
const publicWorkspace = { clientId: workspace.clientId, name: workspace.displayName, tenant: workspace.tenant, canWriteProducts: workspace.canWriteProducts };
if (pathname === '/api/workspace') {
publicWorkspace.brand = normalizeBrand(await store.readBrand(workspace) || {}, workspace.displayName);
return sendJson(response, 200, { success: true, workspace: publicWorkspace });
}
if (pathname === '/api/catalog-image') {
if (!imageHandler) throw fail(503, 'IMAGE_UNAVAILABLE', 'Product image এখন পাওয়া যাচ্ছে না।');
return await imageHandler(request, response, workspace);
}
if (request.method === 'GET') {
const records = await store.read(workspace);
if (getConnected) records.unshift(await getConnected(workspace));
return sendJson(response, 200, { success: true, stores: records.map(record => browserStore(record, workspace)), workspace: publicWorkspace });
}
requireProductWrite(workspace);
const body = await readJson(request, maxBodyBytes);
if (pathname === '/api/brand') {
const brand = normalizeBrand(body, workspace.displayName);
await store.saveBrand(workspace, brand);
return sendJson(response, 200, { success: true, brand });
}
if (pathname === '/api/delete-synced-store') {
if (typeof body.storeId === 'string' && body.storeId.startsWith('connected:')) throw fail(403, 'CONNECTED_CATALOG_READ_ONLY', 'Connected catalog মূল Client dashboard থেকে পরিচালনা করুন।');
if (typeof body.storeId !== 'string' || !body.storeId || body.storeId.length > 160) throw fail(400, 'INVALID_STORE_ID', 'সঠিক store নির্বাচন করুন।');
return sendJson(response, 200, { success: true, stores: (await store.remove(workspace, body.storeId)).map(record => browserStore(record, workspace)) });
}
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: browserStore(imported, workspace) });
} 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 };
+24
View File
@@ -0,0 +1,24 @@
const { fail } = require('./workspace.cjs');
function normalizeBrand(input, defaultName = '') {
if (!input || typeof input !== 'object' || Array.isArray(input)) throw fail(400, 'INVALID_BRAND', 'Business তথ্য সঠিক নয়।');
const text = (key, max) => {
if (input[key] !== undefined && typeof input[key] !== 'string') throw fail(400, 'INVALID_BRAND', 'Business তথ্য text হতে হবে।');
const value = (input[key] || '').trim();
if (value.length > max || /[\u0000-\u001f\u007f]/.test(value)) throw fail(400, 'INVALID_BRAND', 'Business তথ্য সঠিক নয়।');
return value;
};
const name = text('name', 256) || defaultName;
let website = text('website', 2048);
if (website) {
let url;
try { url = new URL(website); } catch { throw fail(400, 'INVALID_WEBSITE', 'সম্পূর্ণ http/https website URL দিন।'); }
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw fail(400, 'INVALID_WEBSITE', 'Website URL-এ password, query বা fragment ব্যবহার করবেন না।');
website = url.href.replace(/\/$/, '');
}
const phone = text('phone', 32).replace(/[\s().-]/g, '');
if (phone && !/^\+[1-9]\d{6,14}$/.test(phone)) throw fail(400, 'INVALID_PHONE', 'Country code সহ international WhatsApp নম্বর দিন, যেমন +880…।');
return { name, website, phone };
}
module.exports = { normalizeBrand };
+38
View File
@@ -0,0 +1,38 @@
const { product, publicLink } = require('./products.cjs');
const { fail } = require('./workspace.cjs');
function createConnectedCatalog({ publicClientOrigin, ttlMs = 30000, maxCacheBytes = 64 * 1024 * 1024, maxEntries = 100, maxConcurrentReads = 2 } = {}) {
const base = new URL(publicClientOrigin);
if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password || base.pathname !== '/' || base.search || base.hash) throw new Error('A public Client origin is required');
const cache = new Map(), inflight = new Map(); let cachedBytes = 0;
return async function connected(workspace) {
const key = workspace.namespace, now = Date.now();
for (const [id, item] of cache) if (item.expires <= now) { cache.delete(id); cachedBytes -= item.bytes; }
if (cache.has(key)) return cache.get(key).store;
if (inflight.has(key)) return inflight.get(key);
if (inflight.size >= maxConcurrentReads) throw fail(503, 'CONNECTED_CATALOG_BUSY', 'Catalog পড়ার কাজ চলছে; অল্প পরে আবার চেষ্টা করুন।');
const task = (async () => {
if (typeof workspace.readConnectedCatalog !== 'function') throw fail(503, 'CONNECTED_CATALOG_UNAVAILABLE', 'Connected catalog service প্রস্তুত নয়।');
const source = await workspace.readConnectedCatalog();
if (!Array.isArray(source.products) || source.products.length > 20000 || !['supabase', 'database'].includes(source.source)) throw fail(502, 'INVALID_CONNECTED_CATALOG', 'Connected catalog সঠিক তালিকা দেয়নি।');
const id = 'connected:' + workspace.clientId;
const context = { id, url: base.origin, documentUrl: base.origin, name: workspace.displayName || workspace.tenant, category: 'general' };
const products = source.products.map(row => ({ ...product({
sourceId: row.id, sku: row.sku, title: row.title, brand: row.brand,
price: row.rawPrice, regular: row.rawRegularPrice, currency: row.currency,
image: row.image, link: row.link, inStock: row.inStock
}, context), link: publicLink(row.link, base.origin) }));
const store = { id, name: context.name, url: '', domain: '', category: 'general', readOnly: true,
sourceType: 'connected-' + source.source, fetchedAt: source.fetchedAt, count: products.length, products };
const bytes = Buffer.byteLength(JSON.stringify(store));
if (bytes <= maxCacheBytes && maxEntries > 0 && ttlMs > 0) {
while (cache.size && (cache.size >= maxEntries || cachedBytes + bytes > maxCacheBytes)) { const oldest = cache.keys().next().value; cachedBytes -= cache.get(oldest).bytes; cache.delete(oldest); }
cache.set(key, { store, bytes, expires: Date.now() + ttlMs }); cachedBytes += bytes;
}
return store;
})();
inflight.set(key, task);
try { return await task; } finally { if (inflight.get(key) === task) inflight.delete(key); }
};
}
module.exports = { createConnectedCatalog };
+50
View File
@@ -0,0 +1,50 @@
const { fail } = require('./workspace.cjs');
// The browser receives raster bytes, never a redirect to a merchant-supplied URL.
function rasterType(body) {
if (!Buffer.isBuffer(body)) return null;
if (body.length >= 24 && body.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')) && body.toString('ascii', 12, 16) === 'IHDR') return 'image/png';
if (body.length >= 4 && body[0] === 255 && body[1] === 216 && body[2] === 255) return 'image/jpeg';
if (body.length >= 10 && ['GIF87a', 'GIF89a'].includes(body.toString('ascii', 0, 6))) return 'image/gif';
if (body.length >= 16 && body.toString('ascii', 0, 4) === 'RIFF' && body.toString('ascii', 8, 12) === 'WEBP') return 'image/webp';
return null;
}
function createImageHandler({ store, fetchPublic, getConnected, maxConcurrent = 4 }) {
if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1) throw new Error('Invalid image concurrency');
let running = 0;
return async function image(request, response, workspace) {
const params = new URL(request.url, 'https://studio.invalid').searchParams;
// Look up the image in this workspace's saved catalog. No arbitrary URL proxy.
const storeId = params.get('storeId'), productId = params.get('productId');
if (!storeId || storeId.length > 160 || !productId || productId.length > 8192 || params.has('url')) {
throw fail(400, 'INVALID_IMAGE_REFERENCE', 'Catalog-এর product image নির্বাচন করুন।');
}
const records = storeId.startsWith('connected:') && getConnected ? [await getConnected(workspace)] : await store.read(workspace);
const product = records.find(item => item.id === storeId)?.products?.find(item => String(item.id) === productId);
if (!product || typeof product.image !== 'string' || !product.image) throw fail(404, 'IMAGE_NOT_FOUND', 'Product image পাওয়া যায়নি।');
if (running >= maxConcurrent) throw fail(503, 'IMAGE_BUSY', 'Image অল্প পরে আবার খুলুন।');
const controller = new AbortController();
const disconnected = () => { if (!response.writableEnded) controller.abort(); };
response.on('close', disconnected);
running++;
try {
const result = await fetchPublic(product.image, { signal: controller.signal });
if (controller.signal.aborted) return;
if (result.status !== 200) throw fail(502, 'IMAGE_SOURCE_FAILED', 'Website-এর image পাওয়া যায়নি।');
const mime = rasterType(result.body);
if (!mime) throw fail(415, 'UNSUPPORTED_IMAGE', 'এই image format preview সমর্থিত নয়।');
response.writeHead(200, {
'Content-Type': mime, 'Content-Length': result.body.length,
'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff',
'Content-Security-Policy': "default-src 'none'; sandbox",
'Cross-Origin-Resource-Policy': 'same-origin'
});
response.end(result.body);
} finally {
running--; response.off('close', disconnected);
}
};
}
module.exports = { createImageHandler, rasterType };
+88
View File
@@ -0,0 +1,88 @@
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 { createImageHandler } = require('./images.cjs');
const { createConnectedCatalog } = require('./connected.cjs');
const { createStaticHandler } = require('./static.cjs');
function createStudioServer(config) {
let loginUrl = null;
if (config.loginUrl) {
const parsed = new URL(config.loginUrl);
if (!['https:', 'http:'].includes(parsed.protocol) || parsed.username || parsed.password || parsed.hash) throw new Error('Invalid public login URL');
loginUrl = parsed.href;
}
const resolveWorkspace = createWorkspaceResolver({ authMeUrl: config.authMeUrl, clientMeUrl: config.clientMeUrl, clientCatalogUrl: config.clientCatalogUrl });
const getConnected = config.clientCatalogUrl ? createConnectedCatalog({ publicClientOrigin: config.publicClientOrigin }) : undefined;
const store = createStore(config.dataDirectory);
const scrape = createScraper({ fetchPublic: createPublicFetcher(config.fetchLimits), ...config.importLimits });
const imageHandler = createImageHandler({ store, getConnected, fetchPublic: createPublicFetcher({ maxBytes: 5 * 1024 * 1024, timeoutMs: 10000 }) });
const api = createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getConnected, publicOrigin: config.publicOrigin, ...config.apiLimits });
const staticFiles = createStaticHandler(config.publicDirectory);
const server = http.createServer({ maxHeaderSize: 16384 }, async (req, res) => {
try {
const pathname = new URL(req.url, config.publicOrigin).pathname;
if (pathname === '/api/studio-config' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
return res.end(JSON.stringify({ loginUrl }));
}
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_LOGIN_URL', 'STUDIO_AUTH_ME_URL', 'STUDIO_CLIENT_ME_URL', 'STUDIO_CLIENT_CATALOG_URL', 'STUDIO_CLIENT_PUBLIC_ORIGIN', 'STUDIO_DATA_DIR'];
if (required.some(name => !process.env[name])) throw new Error('Required Studio service configuration is missing');
const port = Number(process.env.PORT || 3000);
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid Studio port');
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,
loginUrl: process.env.STUDIO_LOGIN_URL,
authMeUrl: process.env.STUDIO_AUTH_ME_URL, clientMeUrl: process.env.STUDIO_CLIENT_ME_URL,
clientCatalogUrl: process.env.STUDIO_CLIENT_CATALOG_URL, publicClientOrigin: process.env.STUDIO_CLIENT_PUBLIC_ORIGIN,
dataDirectory: process.env.STUDIO_DATA_DIR,
publicDirectory: process.env.STUDIO_PUBLIC_DIR || path.join(__dirname, '../public'),
fetchLimits: { maxBytes: limit('STUDIO_MAX_SOURCE_BYTES'), timeoutMs: limit('STUDIO_SOURCE_TIMEOUT_MS') },
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 };
+138
View File
@@ -0,0 +1,138 @@
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;
}
function currencyCode(value) {
return typeof value === 'string' && /^[A-Z]{3}$/.test(value.trim().toUpperCase()) ? value.trim().toUpperCase() : null;
}
function displayPrice(value, currency) {
if (value === null) return 'দাম পাওয়া যায়নি';
try {
return new Intl.NumberFormat('bn-BD', {
...(currency ? { style: 'currency', currency } : {}), maximumFractionDigits: 6
}).format(value);
} catch { return [currency, String(value)].filter(Boolean).join(' '); }
}
function publicLink(value, base) {
if (typeof value !== 'string' || !value.trim()) return '';
try {
const url = new URL(value, base);
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return '';
return url.href;
} catch { return ''; }
}
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 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'),
sourceId, sku: typeof record.sku === 'string' ? record.sku : '',
title: String(record.title || '').trim(),
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, base), link,
storeName: context.name, storeId: context.id, category: context.category,
...(typeof record.inStock === 'boolean' ? { inStock: record.inStock } : {})
};
}
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 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 + (typeof variant.title === 'string' && variant.title && variant.title !== 'Default Title' ? ' — ' + variant.title : ''),
brand: item.vendor, price: variant.price, regular: variant.compare_at_price,
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));
});
}
function wooProducts(payload, context) {
if (!Array.isArray(payload)) return [];
return payload.filter(item => item && typeof item.name === 'string' && item.name.trim()).map(item => {
const units = item.prices?.currency_minor_unit;
const validUnits = typeof units === 'number' && Number.isInteger(units) && units >= 0 && units <= 6;
function minor(value) {
const parsed = amount(value);
return validUnits && parsed !== null ? parsed / (10 ** units) : null;
}
const range = item.prices?.price_range;
const isParent = item.type === 'variable' || (range && typeof range === 'object');
const mapped = product({
sourceId: item.id ?? item.permalink, sku: item.sku, title: item.name,
price: isParent ? null : minor(item.prices?.price), regular: isParent ? null : minor(item.prices?.regular_price),
currency: item.prices?.currency_code, image: item.images?.[0]?.src,
link: item.permalink, inStock: item.is_in_stock
}, context);
if (isParent) {
mapped.requiresVariantSelection = true;
const minimum = minor(range?.min_amount), maximum = minor(range?.max_amount);
if (minimum !== null && maximum !== null) {
mapped.priceRange = { minimum, maximum };
mapped.price = displayPrice(minimum, mapped.currency) + ' – ' + displayPrice(maximum, mapped.currency);
}
}
return mapped;
});
}
function schemaProducts(payload, context) {
const products = [], seen = new Set();
function visit(node, depth = 0) {
if (!node || typeof node !== 'object' || depth > 20 || seen.has(node)) return;
seen.add(node);
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 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';
products.push(product({
sourceId: String(node['@id'] || node.sku || node.url || node.name) + ':' + String(offer['@id'] || offer.sku || offer.url || offer.name || offerIndex),
sku: offer.sku || node.sku, title: node.name + (offers.length > 1 && offer.name ? ' — ' + offer.name : ''),
brand: typeof node.brand === 'string' ? node.brand : node.brand?.name,
price: offer.price ?? (isRegularSpecification ? undefined : offer.priceSpecification?.price),
regular: isRegularSpecification ? offer.priceSpecification?.price : undefined,
currency: offer.priceCurrency || offer.priceSpecification?.priceCurrency,
image: typeof image === 'string' ? image : image?.url,
link: offer.url || node.url
}, context));
}
}
for (const value of Object.values(node)) if (value && typeof value === 'object') visit(value, depth + 1);
}
visit(payload);
return products;
}
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 };
+68
View File
@@ -0,0 +1,68 @@
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', 'workspace.js', 'style.css', 'sw.js', 'manifest.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()];
if (!ROOT_FILES.has(relative) && !asset) {
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 };
+84
View File
@@ -0,0 +1,84 @@
const fs = require('node:fs/promises');
const path = require('node:path');
const { randomUUID } = require('node:crypto');
function createStore(rootDirectory) {
if (!rootDirectory || !path.isAbsolute(rootDirectory)) throw new Error('An absolute private data directory is required');
const root = path.resolve(rootDirectory);
const queues = new Map();
async function directory(workspace) {
if (!/^[a-f0-9]{64}$/.test(workspace.namespace || '')) throw new Error('Invalid server workspace namespace');
await fs.mkdir(root, { recursive: true, mode: 0o700 });
const dir = path.join(root, workspace.namespace);
await fs.mkdir(dir, { mode: 0o700 }).catch(error => { if (error.code !== 'EEXIST') throw error; });
const stat = await fs.lstat(dir);
if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error('Unsafe workspace directory');
return dir;
}
async function read(workspace, kind = 'stores') {
if (!['stores', 'brand'].includes(kind)) throw new Error('Invalid storage kind');
const dir = await directory(workspace);
let text;
try { text = await fs.readFile(path.join(dir, kind + '.json'), 'utf8'); }
catch (error) { if (error.code === 'ENOENT') return kind === 'stores' ? [] : null; throw error; }
const records = JSON.parse(text);
if (kind === 'stores' ? !Array.isArray(records) : (!records || typeof records !== 'object' || Array.isArray(records))) throw new Error('Invalid saved workspace data');
return records;
}
async function update(workspace, change, kind = 'stores') {
const key = workspace.namespace;
const previous = queues.get(key) || Promise.resolve();
const task = previous.catch(() => {}).then(async () => {
const records = await read(workspace, kind);
const next = change(records);
const dir = await directory(workspace);
const target = path.join(dir, kind + '.json');
const temporary = path.join(dir, '.' + kind + '-' + randomUUID() + '.tmp');
let handle;
try {
handle = await fs.open(temporary, 'wx', 0o600);
await handle.writeFile(JSON.stringify(next));
await handle.sync();
await handle.close();
handle = null;
await fs.rename(temporary, target);
if (process.platform !== 'win32') {
const parent = await fs.open(dir, 'r');
try { await parent.sync(); } finally { await parent.close(); }
}
} finally {
if (handle) await handle.close();
await fs.unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; });
}
return next;
});
queues.set(key, task);
try { return await task; }
finally { if (queues.get(key) === task) queues.delete(key); }
}
return {
read,
readBrand(workspace) { return read(workspace, 'brand'); },
saveBrand(workspace, brand) { return update(workspace, () => brand, 'brand'); },
upsert(workspace, store) {
if (!store || typeof store.id !== 'string' || !store.id || store.id.length > 160 || !Array.isArray(store.products)) {
return Promise.reject(new Error('Invalid imported store'));
}
return update(workspace, records => {
const index = records.findIndex(item => item.id === store.id);
if (index < 0) return [...records, store];
return records.map((item, position) => position === index ? store : item);
});
},
remove(workspace, storeId) {
if (typeof storeId !== 'string' || !storeId || storeId.length > 160) return Promise.reject(new Error('Invalid store ID'));
return update(workspace, records => records.filter(item => item.id !== storeId));
}
};
}
module.exports = { createStore };
+119
View File
@@ -0,0 +1,119 @@
const { createHash } = require('node:crypto');
function fail(status, code, message) {
return Object.assign(new Error(message), { status, code });
}
function cookieValue(header, name) {
const entries = String(header || '').split(';').map(item => item.trim());
const values = entries.filter(item => item.startsWith(name + '='));
if (values.length > 1) throw fail(400, 'AMBIGUOUS_COOKIE', 'একাধিক login cookie পাওয়া গেছে।');
if (!values.length) return '';
try { return decodeURIComponent(values[0].slice(name.length + 1)); }
catch { throw fail(400, 'INVALID_COOKIE', 'Login cookie সঠিক নয়।'); }
}
function configuredUrl(value) {
const url = new URL(value);
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.hash) {
throw new Error('A trusted HTTP(S) service URL is required');
}
return url.href;
}
function createWorkspaceResolver({ authMeUrl, clientMeUrl, clientCatalogUrl, fetchImpl = fetch, timeoutMs = 5000 }) {
const authUrl = configuredUrl(authMeUrl);
const clientUrl = configuredUrl(clientMeUrl);
const catalogUrl = clientCatalogUrl ? configuredUrl(clientCatalogUrl) : null;
async function read(url, headers, maxBytes = 256 * 1024, deadlineMs = timeoutMs) {
let response;
try {
response = await fetchImpl(url, {
method: 'GET', headers, redirect: 'error', signal: AbortSignal.timeout(deadlineMs)
});
} catch {
throw fail(503, 'IDENTITY_SERVICE_UNAVAILABLE', 'Workspace যাচাইয়ের service এখন পাওয়া যাচ্ছে না।');
}
if ([401, 403, 404].includes(response.status)) {
throw fail(401, 'LOGIN_REQUIRED', 'আপনার Aura account-এ আবার login করুন।');
}
if (!response.ok) throw fail(503, 'IDENTITY_SERVICE_UNAVAILABLE', 'Workspace যাচাই করা যায়নি।');
try {
if (Number(response.headers?.get('content-length')) > maxBytes) throw new Error('Response limit');
if (response.body) {
const chunks = []; let size = 0;
for await (const chunk of response.body) { size += chunk.length; if (size > maxBytes) throw new Error('Response limit'); chunks.push(Buffer.from(chunk)); }
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
}
const value = await response.json();
if (Buffer.byteLength(JSON.stringify(value)) > maxBytes) throw new Error('Response limit');
return value;
}
catch { throw fail(503, 'INVALID_IDENTITY_RESPONSE', 'Workspace service সঠিক উত্তর দেয়নি।'); }
}
return async function resolveWorkspace(request) {
const token = cookieValue(request.headers.cookie, 'aura_access');
if (!token || token.length > 8192 || /[\r\n]/.test(token)) {
throw fail(401, 'LOGIN_REQUIRED', 'আপনার Aura account-এ login করুন।');
}
const identity = await read(authUrl, { Authorization: 'Bearer ' + token, Accept: 'application/json' });
const user = identity?.user;
if (!user || typeof user.id !== 'string' || !user.id || typeof user.email !== 'string' || !user.email || user.isActive !== true) {
throw fail(401, 'INACTIVE_ACCOUNT', 'সক্রিয় Aura account প্রয়োজন।');
}
const url = new URL(request.url, 'http://studio.invalid');
const requested = String(request.headers['x-aura-tenant'] || url.searchParams.get('tenant') ||
cookieValue(request.headers.cookie, 'aura_active_tenant') || '').trim();
if (requested.length > 256 || /[\r\n]/.test(requested)) {
throw fail(400, 'INVALID_WORKSPACE', 'Workspace নির্বাচন সঠিক নয়।');
}
const privileged = user.role === 'owner' || user.role === 'admin';
if (privileged && !requested) {
throw fail(409, 'WORKSPACE_REQUIRED', 'এই কাজের জন্য আগে একটি client workspace নির্বাচন করুন।');
}
// 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 (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 ||
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();
const workspace = {
tenant, clientId,
namespace: createHash('sha256').update('client:' + clientId).digest('hex'),
userId: user.id,
role: context.role,
canWriteProducts: context.perms?.products === true,
displayName: typeof context.clientName === 'string' ? context.clientName : ''
};
if (catalogUrl) workspace.readConnectedCatalog = async () => {
let catalog;
try { catalog = await read(catalogUrl, { ...headers, 'x-aura-tenant': tenant }, 16 * 1024 * 1024, 35000); }
catch { throw fail(503, 'CONNECTED_CATALOG_UNAVAILABLE', 'Connected catalog এখন পড়া যায়নি; আগের data মুছে দেওয়া হয়নি।'); }
if (catalog?.success !== true || typeof catalog.clientId !== 'string' || catalog.clientId.toLowerCase() !== clientId || typeof catalog.tenant !== 'string' || catalog.tenant.toLowerCase() !== tenant) {
throw fail(403, 'CATALOG_WORKSPACE_MISMATCH', 'Catalog-এর workspace মেলেনি।');
}
return catalog;
};
return workspace;
};
}
function requireProductWrite(workspace) {
if (workspace.canWriteProducts !== true) {
throw fail(403, 'CATALOG_PERMISSION_REQUIRED', 'এই workspace-এর product পরিবর্তনের অনুমতি প্রয়োজন।');
}
}
module.exports = { createWorkspaceResolver, requireProductWrite, fail };
+185
View File
@@ -0,0 +1,185 @@
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 === '/' ? '<html>Fixture Shop</html>' : 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('workspace branding is shared only by the same verified client and never defaults another business contact', async t => {
const f = await setup(t);
const initial = await f.call('a', '/api/workspace');
assert.deepEqual(initial.body.workspace.brand, { name: 'tenant-a', website: '', phone: '' });
const saved = await f.call('a', '/api/brand', { name: 'Client A', website: 'https://shop.example/', phone: '+44 20 7946 0958', clientId: 'victim', tenant: 'tenant-b' });
assert.equal(saved.status, 200);
assert.deepEqual((await f.call('staff', '/api/workspace')).body.workspace.brand, { name: 'Client A', website: 'https://shop.example', phone: '+442079460958' });
assert.deepEqual((await f.call('b', '/api/workspace')).body.workspace.brand, { name: 'tenant-b', website: '', phone: '' });
assert.equal((await f.call('readonly', '/api/brand', { name: 'Overwrite' })).status, 403);
assert.equal((await f.call('a', '/api/brand', { phone: '01712345678' })).status, 400);
assert.equal((await f.call('a', '/api/brand', { website: 'https://user:secret@shop.example' })).status, 400);
assert.equal((await f.call('a', '/api/brand', { website: 'javascript:alert(1)' })).status, 400);
assert.equal((await f.call('a', '/api/brand', { name: 'Overwrite' }, { Origin: 'https://other.example' })).status, 403);
assert.equal((await f.call(null, '/api/brand', { name: 'Overwrite' })).status, 401);
assert.equal((await f.call('a', '/api/workspace')).body.workspace.brand.name, 'Client A');
});
test('corrupt saved branding is reported instead of silently replaced', async t => {
const f = await setup(t);
await f.call('a', '/api/brand', { name: 'Saved name' });
const directories = await fs.readdir(f.root);
assert.equal(directories.length, 1);
await fs.writeFile(path.join(f.root, directories[0], 'brand.json'), '{broken');
assert.equal((await f.call('a', '/api/workspace')).status, 500);
assert.equal((await f.call('a', '/api/brand', { name: 'Erase' })).status, 500);
assert.equal(await fs.readFile(path.join(f.root, directories[0], 'brand.json'), 'utf8'), '{broken');
});
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/);
});
test('workspace bootstrap returns canonical client identity without reading saved catalogs', async t => {
const f = await setup(t);
const a = await f.call('a', '/api/workspace?clientId=victim&tenant=tenant-b');
assert.equal(a.status, 200);
assert.equal(a.body.workspace.tenant, 'tenant-a');
assert.match(a.body.workspace.clientId, /^[a-f0-9-]{36}$/);
assert.equal(a.body.workspace.canWriteProducts, true);
assert.equal(a.body.stores, undefined);
assert.equal(a.body.workspace.namespace, undefined);
assert.equal((await f.call(null, '/api/workspace')).status, 401);
const owner = await f.call('owner', '/api/workspace');
assert.equal(owner.status, 409);
assert.equal((await f.call('readonly', '/api/workspace')).body.workspace.canWriteProducts, false);
});
test('connected catalog remains read-only and returns same-origin image references', async t => {
const f = await setup(t, { getConnected: async ws => ({ id: 'connected:' + ws.clientId, readOnly: true, products: [{ id: 'connected-product', title: 'Source', rawPrice: 380, image: 'https://images.fixture/a.png' }] }) });
const result = await f.call('a', '/api/get-synced-stores');
assert.equal(result.body.stores[0].readOnly, true);
assert.match(result.body.stores[0].products[0].image, /^\/api\/catalog-image\?/);
assert.doesNotMatch(result.body.stores[0].products[0].image, /https:/);
const removed = await f.call('a', '/api/delete-synced-store', { storeId: result.body.stores[0].id });
assert.equal(removed.status, 403);
assert.equal(removed.body.code, 'CONNECTED_CATALOG_READ_ONLY');
});
+73
View File
@@ -0,0 +1,73 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { createWorkspaceResolver } = require('../server/workspace.cjs');
const { createConnectedCatalog } = require('../server/connected.cjs');
const clientId = '11111111-1111-4111-8111-111111111111';
function workspace(name = 'a', readConnectedCatalog) {
return { clientId: name === 'a' ? clientId : '22222222-2222-4222-8222-222222222222', tenant: name, displayName: 'Fixture ' + name, namespace: name.repeat(64), readConnectedCatalog };
}
function catalog(products = []) { return { source: 'supabase', fetchedAt: '2026-10-19T00:00:00Z', products }; }
test('connected catalog preserves zero/unknown prices, image URLs and source timestamps without persistent writes', async () => {
const get = createConnectedCatalog({ publicClientOrigin: 'https://client.fixture' });
const store = await get(workspace('a', async () => catalog([
{ id: 'one', title: 'Source <SKU>', rawPrice: 0, rawRegularPrice: 270, currency: 'BDT', image: 'https://images.fixture/product.png' },
{ id: 'two', title: 'Missing price', rawPrice: null, currency: null }
])));
assert.equal(store.readOnly, true); assert.equal(store.id, 'connected:' + clientId);
assert.equal(store.products[0].rawPrice, 0); assert.equal(store.products[0].image, 'https://images.fixture/product.png');
assert.equal(store.products[1].rawPrice, null); assert.equal(store.products[1].currency, null);
assert.equal(store.products[1].link, ''); assert.equal(store.fetchedAt, '2026-10-19T00:00:00Z');
});
test('connected cache shares one source read for the same client and separates other workspaces', async () => {
let reads = 0;
const get = createConnectedCatalog({ publicClientOrigin: 'https://client.fixture' });
const read = async () => { reads++; return catalog([{ id: 'one', title: 'Product', rawPrice: 380 }]); };
const same = workspace('a', read);
await Promise.all([get(same), get(same), get(same)]);
assert.equal(reads, 1);
await get(workspace('b', read)); assert.equal(reads, 2);
});
test('failed connected reads never become empty success and can be retried after recovery', async () => {
const get = createConnectedCatalog({ publicClientOrigin: 'https://client.fixture', ttlMs: 0 });
let broken = true;
const same = workspace('a', async () => { if (broken) throw Error('fixture outage'); return catalog(); });
await assert.rejects(get(same), /fixture outage/);
broken = false;
assert.equal((await get(same)).products.length, 0);
});
test('simultaneous cold catalog reads across clients are bounded', async () => {
const get = createConnectedCatalog({ publicClientOrigin: 'https://client.fixture', maxConcurrentReads: 1 });
let release, entered;
const started = new Promise(resolve => { entered = resolve; });
const wait = new Promise(resolve => { release = resolve; });
const first = get(workspace('a', async () => { entered(); await wait; return catalog(); }));
await started;
await assert.rejects(get(workspace('b', async () => catalog())), { code: 'CONNECTED_CATALOG_BUSY' });
release(); await first;
assert.equal((await get(workspace('b', async () => catalog()))).products.length, 0);
});
test('Client catalog read forwards only server identity and rejects another canonical client response', async () => {
const calls = [];
let mismatch = false;
const resolve = createWorkspaceResolver({ authMeUrl: 'https://auth.fixture/me', clientMeUrl: 'https://client.fixture/me', clientCatalogUrl: 'https://client.fixture/studio/catalog',
fetchImpl: async (url, options) => {
calls.push({ url, headers: options.headers });
const actor = { id: 'actor', email: 'actor@example.test', role: 'client' };
if (url.includes('auth.fixture')) return Response.json({ user: { ...actor, isActive: true } });
if (url.endsWith('/studio/catalog')) return Response.json({ success: true, clientId: mismatch ? 'other-client' : clientId, tenant: 'canonical', ...catalog() });
return Response.json({ success: true, clientId, tenant: 'canonical', actor, perms: { products: true } });
}
});
const ws = await resolve({ url: '/api/get-synced-stores?tenant=victim', headers: { cookie: 'aura_access=fixture-token; unrelated=must-not-forward', 'x-client-id': 'victim' } });
await ws.readConnectedCatalog();
assert.equal(calls.at(-1).headers.Cookie, 'aura_access=fixture-token');
assert.equal(calls.at(-1).headers['x-aura-tenant'], 'canonical');
assert.equal(calls.at(-1).headers['x-client-id'], undefined);
mismatch = true;
await assert.rejects(ws.readConnectedCatalog(), { code: 'CATALOG_WORKSPACE_MISMATCH' });
});
+81
View File
@@ -0,0 +1,81 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
const workspaceModule = fs.existsSync(path.join(__dirname, '../workspace.js')) ? '../workspace.js' : '../public/workspace.js';
const { scopedStorage, escapeText, whatsappUrl } = require(workspaceModule);
test('WhatsApp links preserve explicit international country codes without a Bangladesh prefix', () => {
assert.equal(whatsappUrl('+880 1712-426871'), 'https://wa.me/8801712426871');
assert.equal(whatsappUrl('+44 20 7946 0958'), 'https://wa.me/442079460958');
assert.equal(whatsappUrl('01712426871'), '');
assert.equal(whatsappUrl(''), '');
assert.equal(whatsappUrl('javascript:alert(1)'), '');
});
const a = '11111111-1111-4111-8111-111111111111';
const b = '22222222-2222-4222-8222-222222222222';
function memory() {
const values = new Map();
return { getItem: key => values.has(key) ? values.get(key) : null, setItem: (key, value) => values.set(key, String(value)), removeItem: key => values.delete(key), values };
}
test('private browser keys are scoped by verified client, with no automatic legacy migration', () => {
const storage = memory(); storage.setItem('opal_gemini_api_key', 'legacy-test-key');
const first = scopedStorage(storage, a), other = scopedStorage(storage, b), staff = scopedStorage(storage, a.toUpperCase());
assert.equal(first.getItem('opal_gemini_api_key'), null);
first.setItem('opal_gemini_api_key', 'client-a-test-key');
assert.equal(staff.getItem('opal_gemini_api_key'), 'client-a-test-key');
assert.equal(other.getItem('opal_gemini_api_key'), null);
other.removeItem('opal_gemini_api_key');
assert.equal(first.getItem('opal_gemini_api_key'), 'client-a-test-key');
assert.equal(storage.getItem('opal_gemini_api_key'), 'legacy-test-key');
assert.throws(() => scopedStorage(storage, '../tenant'), /Verified/);
});
test('imported markup is text in both quoted attributes and HTML content', () => {
assert.equal(escapeText('<img src=x onerror="alert(1)"> & \'SKU\''), '&lt;img src=x onerror=&quot;alert(1)&quot;&gt; &amp; &#39;SKU&#39;');
});
async function bootstrap(response, config = { loginUrl: 'https://auth.fixture/login' }) {
const nodes = new Map(), requests = [], scripts = [], events = [];
function node() { return { hidden: true, value: '', textContent: '', inert: false, prepend() {} }; }
const get = id => { if (!nodes.has(id)) nodes.set(id, node()); return nodes.get(id); };
let start;
const context = {
URL, URLSearchParams, Event, Object, encodeURIComponent,
location: { href: 'https://studio.fixture/?tenant=chosen', origin: 'https://studio.fixture', search: '?tenant=chosen', reload() {}, assign() {} },
localStorage: memory(), sessionStorage: memory(),
fetch: async url => { requests.push(url); return { ok: url === '/api/studio-config' ? true : response.status === 200, status: response.status, json: async () => url === '/api/studio-config' ? config : response.body }; },
document: {
getElementById: get, querySelectorAll: () => [], querySelector: () => null,
createElement: tag => ({ tag }),
addEventListener: (event, callback) => { if (event === 'DOMContentLoaded') start = callback; },
dispatchEvent: event => events.push(event.type),
body: { appendChild: script => scripts.push(script) }
}
};
context.window = context;
vm.runInNewContext(fs.readFileSync(require.resolve(workspaceModule), 'utf8'), context);
await start();
return { context, nodes, requests, scripts, events };
}
test('login and workspace selection failures do not load app code or expose saved client state', async () => {
const login = await bootstrap({ status: 401, body: { code: 'LOGIN_REQUIRED', error: 'Login first' } });
assert.equal(login.scripts.length, 0); assert.equal(login.context.AuraStudio, undefined);
assert.equal(login.nodes.get('workspaceLogin').hidden, false);
assert.equal(new URL(login.nodes.get('workspaceLogin').href).searchParams.get('next'), login.context.location.href);
const owner = await bootstrap({ status: 409, body: { code: 'WORKSPACE_REQUIRED', error: 'Choose workspace' } });
assert.equal(owner.nodes.get('workspaceForm').hidden, false);
assert.equal(owner.scripts.length, 0);
const invalid = await bootstrap({ status: 200, body: { success: true, workspace: { clientId: 'bad', tenant: 'chosen' } } });
assert.equal(invalid.scripts.length, 0);
});
test('validated workspace loads app once and preserves canonical tenant in API requests', async () => {
const ready = await bootstrap({ status: 200, body: { success: true, workspace: { clientId: a, name: 'Fixture shop', tenant: 'canonical' } } });
assert.equal(ready.scripts.length, 1);
assert.equal(ready.scripts[0].src, '/app.js?v=workspace-1');
assert.equal(ready.context.AuraStudio.apiUrl('/api/sync-store?tenant=attacker'), '/api/sync-store?tenant=canonical');
assert.throws(() => ready.context.AuraStudio.apiUrl('https://attacker.fixture/api/x'));
ready.scripts[0].onload();
assert.deepEqual(ready.events, ['aura-studio-ready']);
assert.equal(ready.nodes.get('studioWorkspaceGate').hidden, true);
});
+92
View File
@@ -0,0 +1,92 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const http = require('node:http');
const { createImageHandler, rasterType } = require('../server/images.cjs');
const { createPublicFetcher } = require('../server/public-fetch.cjs');
const { createApiHandler } = require('../server/api.cjs');
// Public-domain 1x1 transparent PNG, used only as a binary response fixture.
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9p8AAAAASUVORK5CYII=', 'base64');
async function fixture(t, fetchPublic, options = {}) {
const reads = [];
const store = { read: async workspace => {
reads.push(workspace.tenant);
return workspace.tenant === 'a' ? [{ id: 'shop', products: [{ id: 'product', image: 'https://images.fixture/p.png' }] }] : [];
} };
const imageHandler = createImageHandler({ store, fetchPublic, maxConcurrent: 1, ...options });
const api = createApiHandler({ store, imageHandler, publicOrigin: 'https://studio.fixture', scrape: async () => {},
resolveWorkspace: async req => {
if (!req.headers.cookie) throw Object.assign(new Error('Login required'), { status: 401 });
return { tenant: req.headers.cookie === 'a' ? 'a' : 'b' };
}
});
const server = http.createServer(api);
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
t.after(() => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); });
const base = 'http://127.0.0.1:' + server.address().port;
return { base, reads, get: (suffix = '', cookie = 'a') => fetch(base + '/api/catalog-image?storeId=shop&productId=product' + suffix, { headers: cookie ? { cookie } : {} }) };
}
test('catalog image is authenticated and cannot be read from another workspace or arbitrary URL', async t => {
let calls = 0;
const f = await fixture(t, async () => { calls++; return { status: 200, body: png }; });
assert.equal((await f.get('', null)).status, 401);
assert.equal((await f.get('', 'b')).status, 404);
assert.equal((await f.get('&url=http://127.0.0.1')).status, 400);
assert.equal(calls, 0);
const result = await f.get();
assert.equal(result.status, 200);
assert.equal(result.headers.get('content-type'), 'image/png');
assert.match(result.headers.get('cache-control'), /no-store/);
assert.equal(result.headers.get('access-control-allow-origin'), null);
assert.equal(result.headers.get('cross-origin-resource-policy'), 'same-origin');
assert.deepEqual(Buffer.from(await result.arrayBuffer()), png);
assert.equal(calls, 1);
});
test('HTML, SVG, fake MIME and source failures never become browser image responses', async t => {
for (const body of [Buffer.from('<svg onload="alert(1)"></svg>'), Buffer.from('<html>login</html>')]) {
const f = await fixture(t, async () => ({ status: 200, headers: { 'content-type': 'image/png' }, body }));
const result = await f.get();
assert.equal(result.status, 415);
assert.match(result.headers.get('content-type'), /application\/json/);
}
const f = await fixture(t, async () => ({ status: 302, body: png }));
assert.equal((await f.get()).status, 502);
assert.equal(rasterType(Buffer.from('GIF89a')), null);
});
test('saved private image addresses are rejected before any socket is opened', async t => {
const publicFetcher = createPublicFetcher({ lookup: async () => [{ address: '127.0.0.1', family: 4 }] });
const f = await fixture(t, publicFetcher);
const result = await f.get();
assert.equal(result.status, 400);
assert.match((await result.json()).code, /PRIVATE|PUBLIC|SOURCE/);
});
test('concurrent image requests are bounded and capacity returns after completion', async t => {
let release;
const gate = new Promise(resolve => { release = resolve; });
let entered;
const started = new Promise(resolve => { entered = resolve; });
const f = await fixture(t, async () => { entered(); await gate; return { status: 200, body: png }; });
const first = f.get();
await started;
assert.equal((await f.get()).status, 503);
release();
assert.equal((await first).status, 200);
assert.equal((await f.get()).status, 200);
});
test('connected image lookup cannot use another client catalog identifier', async t => {
let sourceCalls = 0;
const f = await fixture(t, async () => { sourceCalls++; return { status: 200, body: png }; }, {
getConnected: async () => ({ id: 'connected:own', products: [{ id: 'p', image: 'https://images.fixture/p.png' }] })
});
const call = storeId => fetch(f.base + '/api/catalog-image?' + new URLSearchParams({ storeId, productId: 'p' }), { headers: { cookie: 'a' } });
assert.equal((await call('connected:other-client')).status, 404);
assert.equal(sourceCalls, 0);
assert.equal((await call('connected:own')).status, 200);
assert.equal(sourceCalls, 1);
});
+91
View File
@@ -0,0 +1,91 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { amount, publicLink, shopifyProducts, wooProducts, schemaProducts } = require('../server/products.cjs');
const context = { url: 'https://fixture-store.example/', name: 'Fixture Store', id: 'fixture-store', category: 'general' };
test('price parsing preserves free and decimal prices without inventing missing values', () => {
assert.equal(amount(0), 0);
assert.equal(amount('১,২৩৪.৫০'), 1234.5);
assert.equal(amount(1e-7), 1e-7);
for (const value of [undefined, null, '', 'Call for price', true, -2, Infinity, '1,2', '12USD']) assert.equal(amount(value), null);
});
test('Shopify preserves each variant and its SKU, actual compare price and currency', () => {
const rows = shopifyProducts({ products: [{ id: 7, title: 'Serum', handle: 'serum', variants: [
{ id: 71, title: '5ml', sku: 'SERUM-5', price: '220.00', compare_at_price: '270.00' },
{ id: 72, title: '30ml', sku: 'SERUM-30', price: '0.00', compare_at_price: null }
] }] }, context, 'BDT');
assert.equal(rows.length, 2);
assert.equal(rows[0].rawPrice, 220);
assert.equal(rows[0].rawRegularPrice, 270);
assert.equal(rows[0].sku, 'SERUM-5');
assert.equal(rows[1].rawPrice, 0);
assert.equal(rows[1].regularPrice, '');
assert.notEqual(rows[0].id, rows[1].id);
});
test('missing Shopify prices remain unknown, and unspecified currency is not guessed as BDT', () => {
const row = shopifyProducts({ products: [{ title: 'Unpriced item', variants: [{}] }] }, context)[0];
assert.equal(row.rawPrice, null);
assert.equal(row.currency, null);
assert.equal(row.price, 'দাম পাওয়া যায়নি');
assert.equal(row.rawRegularPrice, null);
});
test('Woo Store API minor units preserve source prices and reject an unknown scale', () => {
const input = { id: 8, name: 'Item', prices: { price: '12345', regular_price: '15000', currency_minor_unit: 2, currency_code: 'USD' } };
const row = wooProducts([input], context)[0];
assert.equal(row.rawPrice, 123.45);
assert.equal(row.rawRegularPrice, 150);
assert.equal(row.currency, 'USD');
delete input.prices.currency_minor_unit;
assert.equal(wooProducts([input], context)[0].rawPrice, null);
});
test('schema products keep missing price unknown and do not turn aggregate lowPrice into an exact variant price', () => {
const rows = schemaProducts({ '@graph': [
{ '@type': 'Product', name: 'Unknown', sku: 'U' },
{ '@type': 'Product', name: 'From price', sku: 'F', offers: { '@type': 'AggregateOffer', lowPrice: 100, highPrice: 900, priceCurrency: 'BDT' } },
{ '@type': 'Product', name: 'Free sample', sku: 'Z', offers: { price: 0, priceCurrency: 'BDT' } }
] }, context);
assert.deepEqual(rows.map(r => r.rawPrice), [null, null, 0]);
assert.ok(rows.every(r => r.rawRegularPrice === null));
});
test('unsafe image/link schemes are excluded and stable variant identifiers repeat', () => {
for (const value of ['javascript:alert(1)', 'data:text/html,unsafe', 'https://user:pass@example.com/']) assert.equal(publicLink(value, context.url), '');
assert.equal(publicLink('/image.jpg', context.url), 'https://fixture-store.example/image.jpg');
const payload = { products: [{ id: 5, title: 'Product', variants: [{ id: 6, price: '1.25' }] }] };
assert.equal(shopifyProducts(payload, context)[0].id, shopifyProducts(payload, context)[0].id);
});
test('products without platform IDs do not overwrite each other', () => {
const rows = shopifyProducts({ products: [
{ title: 'First', variants: [{ price: '10' }] },
{ title: 'Second', variants: [{ price: '20' }] }
] }, context);
assert.notEqual(rows[0].id, rows[1].id);
});
test('a schema strikethrough amount alone is not represented as the selling price', () => {
const row = schemaProducts({ '@type': 'Product', name: 'Item', offers: {
priceSpecification: { priceType: 'https://schema.org/StrikethroughPrice', price: 270, priceCurrency: 'BDT' }
} }, context)[0];
assert.equal(row.rawPrice, null);
assert.equal(row.rawRegularPrice, 270);
});
test('Woo variable parent range is not treated as an exact selected variant price', () => {
const row = wooProducts([{ id: 9, type: 'variable', name: 'Shirt', prices: {
price: '10000', regular_price: '15000', currency_minor_unit: 2, currency_code: 'BDT',
price_range: { min_amount: '10000', max_amount: '20000' }
} }], context)[0];
assert.equal(row.rawPrice, null);
assert.equal(row.rawRegularPrice, null);
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' });
});
+98
View File
@@ -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);
});
+109
View File
@@ -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/', '<link rel="https://api.w.org/" href="https://www.catalog.fixture/shop/wp-json/">');
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, '<html>Storefront</html>');
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, '<html>Shop</html>');
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 = `<ul><li class="product"><a href="/item"><h2 class="woocommerce-loop-product__title">Own item</h2></a>
<span class="price"><del><span class="amount">৳ 270</span></del><ins><span class="amount">৳ 220</span></ins></span></li>
<li class="product"><h2 class="woocommerce-loop-product__title">Call for price</h2><span class="price">Contact us</span></li></ul>`;
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, `<script type="application/ld+json">${JSON.stringify({ '@type': 'Product', name: second ? 'Second' : 'First', sku: second ? 'B' : 'A', offers: { price: second ? 200 : 100, priceCurrency: 'BDT' } })}</script>${second ? '' : '<a rel="next" href="?page=2">Next</a>'}`);
} });
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, '<html>Shop</html>') : 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, '<h1>Sale!</h1>') : 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, '<html>Shop</html>');
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, '<html>Shop</html>'); } });
setTimeout(() => controller.abort(), 20);
await assert.rejects(scrape({ url: 'https://catalog.fixture/' }, { signal: controller.signal }), { code: 'IMPORT_TIMEOUT' });
assert.equal(requests, 1);
});
+60
View File
@@ -0,0 +1,60 @@
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'), '<!doctype html><h1>Fixture Studio</h1>');
await fs.writeFile(path.join(publicDirectory, 'app.js'), '/* fixture */\n'.repeat(200));
await fs.writeFile(path.join(publicDirectory, 'gt_full_catalog.json'), 'LEGACY-SHARED-CATALOG');
await fs.mkdir(path.join(publicDirectory, 'data'));
await fs.writeFile(path.join(publicDirectory, 'data/synced_stores.json'), 'LEGACY-SHARED-CATALOG');
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 ['/gt_full_catalog.json', '/data/synced_stores.json', '/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/);
const config = await fetch(base + '/api/studio-config');
assert.deepEqual(await config.json(), { loginUrl: null });
assert.match(config.headers.get('cache-control'), /no-store/);
});
+115
View File
@@ -0,0 +1,115 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
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 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', 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 } });
}
});
}
const request = (headers = {}, url = '/api/get-synced-stores') => ({ headers: { cookie: 'aura_access=fixture-token', ...headers }, url });
test('uses canonical server tenant, not client-supplied IDs or requested tenant', async () => {
const captures = [];
const ws = await resolver({ captures })(request({ 'x-aura-tenant': 'another-tenant', 'x-client-id': 'victim' }, '/api/get-synced-stores?clientId=victim'));
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');
});
test('missing, ambiguous and inactive login fails before reading workspace', async () => {
const captures = [], resolve = resolver({ captures });
await assert.rejects(resolve({ headers: {}, url: '/' }), { status: 401 });
await assert.rejects(resolve(request({ cookie: 'aura_access=a; aura_access=b' })), { status: 400 });
assert.equal(captures.length, 0);
const inactiveCalls = [];
await assert.rejects(resolver({ active: false, captures: inactiveCalls })(request()), { status: 401 });
assert.equal(inactiveCalls.length, 1);
});
test('platform owner must select workspace explicitly, without a merchant fallback', async () => {
await assert.rejects(resolver({ role: 'owner' })(request()), { code: 'WORKSPACE_REQUIRED' });
const ws = await resolver({ role: 'owner', tenant: 'selected-store' })(request({}, '/api/get-synced-stores?tenant=selected-store'));
assert.equal(ws.tenant, 'selected-store');
});
test('identity service failures fail closed and catalog permissions come from Client', async () => {
await assert.rejects(resolver({ status: 500 })(request()), { status: 503 });
const ws = await resolver({ products: false })(request());
assert.throws(() => requireProductWrite(ws), { status: 403 });
requireProductWrite({ ...ws, canWriteProducts: true });
});
test('owner and staff resolved to the same tenant share data; other tenant is isolated', async t => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'studio-store-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const stores = createStore(root);
const owner = await resolver({ role: 'owner', tenant: 'shop-a' })(request({ 'x-aura-tenant': 'shop-a' }));
const staff = await resolver({ tenant: 'shop-a' })(request());
const other = await resolver({ tenant: 'shop-b' })(request());
await stores.upsert(owner, { id: 'same-store-id', products: [{ rawPrice: 0 }] });
assert.equal((await stores.read(staff))[0].products[0].rawPrice, 0);
assert.deepEqual(await stores.read(other), []);
await stores.remove(other, 'same-store-id');
assert.equal((await stores.read(owner)).length, 1);
});
test('concurrent imports do not overwrite each other and survive a new store instance', async t => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'studio-store-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const stores = createStore(root), ws = await resolver()(request());
await Promise.all(Array.from({ length: 12 }, (_, i) => stores.upsert(ws, { id: 'store-' + i, products: [] })));
assert.equal((await createStore(root).read(ws)).length, 12);
});
test('corrupt saved data is not silently erased during the next import', async t => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'studio-store-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const stores = createStore(root), ws = await resolver()(request());
await stores.read(ws);
const file = path.join(root, ws.namespace, 'stores.json');
await fs.writeFile(file, '{broken data');
await assert.rejects(stores.upsert(ws, { id: 'next-store', products: [] }));
assert.equal(await fs.readFile(file, 'utf8'), '{broken data');
});
test('untrusted namespaces cannot become file paths', async t => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'studio-store-'));
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' });
});
+115
View File
@@ -0,0 +1,115 @@
(function (root) {
'use strict';
function scopedStorage(storage, clientId) {
if (!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(clientId || '')) throw new Error('Verified client identity required');
const prefix = 'aura-studio:' + clientId.toLowerCase() + ':';
return Object.freeze({
getItem(key) { return storage.getItem(prefix + key); },
setItem(key, value) { storage.setItem(prefix + key, value); },
removeItem(key) { storage.removeItem(prefix + key); }
});
}
function escapeText(value) {
return String(value ?? '').replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[char]));
}
function whatsappUrl(phone) {
const digits = String(phone || '').replace(/[\s().-]/g, '').replace(/^\+/, '');
return /^[1-9]\d{6,14}$/.test(digits) ? 'https://wa.me/' + digits : '';
}
if (typeof module === 'object' && module.exports) { module.exports = { scopedStorage, escapeText, whatsappUrl }; return; }
async function start() {
const gate = document.getElementById('studioWorkspaceGate');
const status = document.getElementById('workspaceStatus');
const form = document.getElementById('workspaceForm');
const tenantInput = document.getElementById('workspaceTenant');
const login = document.getElementById('workspaceLogin');
const retry = document.getElementById('workspaceRetry');
const params = new URLSearchParams(location.search);
const tenant = params.get('tenant') || '';
tenantInput.value = tenant;
document.querySelectorAll('body > :not(#studioWorkspaceGate):not(script)').forEach(el => el.inert = true);
retry.onclick = () => location.reload();
form.onsubmit = event => {
event.preventDefault();
const next = new URL(location.href);
next.searchParams.set('tenant', tenantInput.value.trim());
location.assign(next.href);
};
try {
const response = await fetch('/api/workspace' + (tenant ? '?tenant=' + encodeURIComponent(tenant) : ''), { credentials: 'same-origin', cache: 'no-store' });
const data = await response.json();
if (!response.ok || data.success !== true) {
status.textContent = data.error || 'Workspace যাচাই করা যায়নি।';
if (data.code === 'WORKSPACE_REQUIRED') form.hidden = false;
if (response.status === 401) {
const configResponse = await fetch('/api/studio-config', { cache: 'no-store' });
const config = await configResponse.json();
if (configResponse.ok && config.loginUrl) {
const target = new URL(config.loginUrl);
if (!['https:', 'http:'].includes(target.protocol) || target.username || target.password) throw new Error('Invalid login destination');
target.searchParams.set('next', location.href);
login.href = target.href; login.hidden = false;
}
}
return;
}
const workspace = data.workspace;
const runtime = {
workspace: Object.freeze({ ...workspace }),
local: scopedStorage(localStorage, workspace.clientId),
session: scopedStorage(sessionStorage, workspace.clientId),
escapeText,
whatsappUrl,
apiUrl(path) {
const url = new URL(path, location.origin);
if (url.origin !== location.origin || !url.pathname.startsWith('/api/')) throw new Error('Invalid Studio API URL');
url.searchParams.set('tenant', workspace.tenant);
return url.pathname + url.search;
}
};
Object.defineProperty(window, 'AuraStudio', { value: Object.freeze(runtime), writable: false });
const script = document.createElement('script');
script.src = '/app.js?v=workspace-1';
script.onerror = () => { status.textContent = 'Studio load হয়নি। Refresh করে আবার চেষ্টা করুন।'; };
script.onload = () => {
try {
document.dispatchEvent(new Event('aura-studio-ready'));
document.querySelectorAll('body > :not(#studioWorkspaceGate):not(script)').forEach(el => el.inert = false);
gate.hidden = true;
const brandForm = document.getElementById('workspaceBrandForm');
const brandStatus = document.getElementById('workspaceBrandStatus');
if (brandForm) {
const brand = workspace.brand || { name: workspace.name, website: '', phone: '' };
['name', 'website', 'phone'].forEach(key => { brandForm.elements[key].value = brand[key] || ''; });
brandForm.querySelector('button').disabled = !workspace.canWriteProducts;
brandForm.onsubmit = async event => {
event.preventDefault();
const submit = brandForm.querySelector('button');
submit.disabled = true; brandStatus.textContent = 'সংরক্ষণ হচ্ছে…';
try {
const result = await fetch(runtime.apiUrl('/api/brand'), {
method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.fromEntries(['name', 'website', 'phone'].map(key => [key, brandForm.elements[key].value])))
});
const saved = await result.json();
if (!result.ok || saved.success !== true) throw new Error(saved.error || 'সংরক্ষণ হয়নি।');
location.reload();
} catch (error) { brandStatus.textContent = error.message; submit.disabled = !workspace.canWriteProducts; }
};
}
const button = document.createElement('button');
button.type = 'button'; button.className = 'pill-btn';
button.textContent = workspace.name || workspace.tenant;
button.title = 'Workspace নির্বাচন';
button.onclick = () => { gate.hidden = false; form.hidden = false; status.textContent = 'অন্য workspace নির্বাচন করুন।'; };
document.querySelector('.header-actions')?.prepend(button);
} catch { status.textContent = 'Studio চালু হয়নি। Refresh করে আবার চেষ্টা করুন।'; }
};
document.body.appendChild(script);
} catch {
status.textContent = 'Workspace service-এর উত্তর পাওয়া যায়নি। Refresh করে আবার চেষ্টা করুন।';
}
}
document.addEventListener('DOMContentLoaded', start, { once: true });
})(typeof globalThis === 'object' ? globalThis : this);