Add tenant-scoped Studio backend primitives and static asset allowlist
This commit is contained in:
@@ -0,0 +1,11 @@
|
|||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
node_modules
|
||||||
|
test
|
||||||
|
docs
|
||||||
|
*.log
|
||||||
|
*.tar
|
||||||
|
*.tar.gz
|
||||||
|
outputs
|
||||||
+6
-4
@@ -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 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
|
||||||
|
|||||||
@@ -7,3 +7,19 @@ The runtime includes substantial poster-renderer changes not represented by main
|
|||||||
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.
|
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.
|
Do not blindly enable serve.js: it uses one shared store file and contains invented price/compare-price fallbacks. A production repair must retain tenant boundaries, real product values and existing client behavior. No Meta 1-Click flow is included in this reconciliation.
|
||||||
|
|
||||||
|
## Backend candidate modules — not yet routed or deployed
|
||||||
|
|
||||||
|
server/workspace.cjs uses the existing Auth active-account endpoint and Client workspace endpoint. Browser client IDs are not accepted as storage identity. An owner must select a workspace explicitly; the Client gate owns the canonical workspace and catalog permission decisions. No database superuser credential or signing key is copied into these modules.
|
||||||
|
|
||||||
|
server/store.cjs persists per-canonical-workspace data using hashed namespace directories, serialized updates, atomic replacement and fsync. It does not load the prototype shared store file into a new tenant. Corrupt saved data fails instead of being silently replaced with an empty list. This store is for a single server process; a multi-replica deployment needs a shared transactional store or cross-process locking before use.
|
||||||
|
|
||||||
|
server/products.cjs maps structured Shopify, Woo Store API and schema.org data without guessed prices, discounts or currencies. It preserves variant/SKU distinctions and zero prices. Missing selling prices remain unknown; an aggregate starting price or strikethrough price alone is not presented as an exact current selling price.
|
||||||
|
|
||||||
|
The Nginx Dockerfile now copies an explicit static asset set instead of publishing all repository files. These candidate modules are not enabled by the static image. HTTP routing, bounded outbound fetching, request protection and frontend integration remain required before claiming that the Studio sync endpoint is repaired.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
const { createHash } = require('node:crypto');
|
||||||
|
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 (!/^(?:\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) {
|
||||||
|
const price = amount(record.price), regular = amount(record.regular);
|
||||||
|
const currency = currencyCode(record.currency);
|
||||||
|
const link = publicLink(record.link, context.url) || 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, context.url), 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 variants = Array.isArray(item.variants) && item.variants.length ? item.variants : [{}];
|
||||||
|
return variants.map((variant, index) => product({
|
||||||
|
sourceId: (item.id ?? item.handle ?? item.title) + ':' + (variant.id ?? (variant.sku || variant.title || index)), sku: variant.sku,
|
||||||
|
title: item.title + (variant.title && variant.title !== 'Default Title' ? ' — ' + variant.title : ''),
|
||||||
|
brand: item.vendor, price: variant.price, regular: variant.compare_at_price,
|
||||||
|
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 offers = Array.isArray(node.offers) && node.offers.length ? 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, publicLink, product, shopifyProducts, wooProducts, schemaProducts };
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
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) {
|
||||||
|
const dir = await directory(workspace);
|
||||||
|
let text;
|
||||||
|
try { text = await fs.readFile(path.join(dir, 'stores.json'), 'utf8'); }
|
||||||
|
catch (error) { if (error.code === 'ENOENT') return []; throw error; }
|
||||||
|
const records = JSON.parse(text);
|
||||||
|
if (!Array.isArray(records)) throw new Error('Invalid saved store data');
|
||||||
|
return records;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function update(workspace, change) {
|
||||||
|
const key = workspace.namespace;
|
||||||
|
const previous = queues.get(key) || Promise.resolve();
|
||||||
|
const task = previous.catch(() => {}).then(async () => {
|
||||||
|
const records = await read(workspace);
|
||||||
|
const next = change(records);
|
||||||
|
const dir = await directory(workspace);
|
||||||
|
const target = path.join(dir, 'stores.json');
|
||||||
|
const temporary = path.join(dir, '.stores-' + 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,
|
||||||
|
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 };
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
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, fetchImpl = fetch, timeoutMs = 5000 }) {
|
||||||
|
const authUrl = configuredUrl(authMeUrl);
|
||||||
|
const clientUrl = configuredUrl(clientMeUrl);
|
||||||
|
|
||||||
|
async function read(url, headers) {
|
||||||
|
let response;
|
||||||
|
try {
|
||||||
|
response = await fetchImpl(url, {
|
||||||
|
method: 'GET', headers, redirect: 'error', signal: AbortSignal.timeout(timeoutMs)
|
||||||
|
});
|
||||||
|
} 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 { return await response.json(); }
|
||||||
|
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 || 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 (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) {
|
||||||
|
throw fail(403, 'WORKSPACE_UNAVAILABLE', 'আপনার workspace প্রস্তুত বা অনুমোদিত নয়।');
|
||||||
|
}
|
||||||
|
const tenant = context.tenant.trim().toLowerCase();
|
||||||
|
return {
|
||||||
|
tenant,
|
||||||
|
namespace: createHash('sha256').update(tenant).digest('hex'),
|
||||||
|
userId: user.id,
|
||||||
|
role: context.role,
|
||||||
|
canWriteProducts: context.perms?.products === true,
|
||||||
|
displayName: typeof context.clientName === 'string' ? context.clientName : ''
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireProductWrite(workspace) {
|
||||||
|
if (workspace.canWriteProducts !== true) {
|
||||||
|
throw fail(403, 'CATALOG_PERMISSION_REQUIRED', 'এই workspace-এর product পরিবর্তনের অনুমতি প্রয়োজন।');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createWorkspaceResolver, requireProductWrite, fail };
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
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 });
|
||||||
|
});
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
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');
|
||||||
|
|
||||||
|
function resolver({ role = 'client', tenant = 'verified-tenant', products = true, active = true, status = 200, captures = [] } = {}) {
|
||||||
|
return createWorkspaceResolver({
|
||||||
|
authMeUrl: 'http://auth.test/api/auth/me', clientMeUrl: 'http://client.test/api/me',
|
||||||
|
fetchImpl: async (url, options) => {
|
||||||
|
captures.push({ url, options });
|
||||||
|
if (url.includes('auth.test')) return new Response(JSON.stringify({ user: { id: 'fixture-user', role, isActive: active } }), { status });
|
||||||
|
return Response.json({ success: true, tenant, role: 'manager', perms: { products } });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
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[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/);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user