Add tenant-scoped Studio backend primitives and static asset allowlist
This commit is contained in:
@@ -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 };
|
||||
Reference in New Issue
Block a user