Keep Studio business branding in verified client storage

This commit is contained in:
khondokartowsif171
2026-10-19 11:54:13 +06:00
parent 165320cc9f
commit 54091f4578
11 changed files with 151 additions and 38 deletions
+1 -2
View File
@@ -5,9 +5,8 @@ ENV NODE_ENV=production PORT=3000 STUDIO_DATA_DIR=/data/studio
COPY package.json package-lock.json ./ COPY package.json package-lock.json ./
RUN npm ci --omit=dev --ignore-scripts --no-fund --no-audit RUN npm ci --omit=dev --ignore-scripts --no-fund --no-audit
COPY server/ ./server/ COPY server/ ./server/
COPY index.html app.js workspace.js style.css sw.js manifest.json gt_full_catalog.json ./public/ COPY index.html app.js workspace.js style.css sw.js manifest.json ./public/
COPY assets/ ./public/assets/ COPY assets/ ./public/assets/
COPY data/ ./public/data/
RUN mkdir -p /data/studio && chown -R node:node /app /data/studio RUN mkdir -p /data/studio && chown -R node:node /app /data/studio
USER node USER node
EXPOSE 3000 EXPOSE 3000
+25 -20
View File
@@ -746,7 +746,7 @@ Details & Offer: {{field2}}
Write 3 distinct ready-to-send Bengali fashion customer responses: Write 3 distinct ready-to-send Bengali fashion customer responses:
1. Aesthetic luxury product appreciation highlighting fabric softness, elegant drape, and premium feel. 1. Aesthetic luxury product appreciation highlighting fabric softness, elegant drape, and premium feel.
2. Complete size guidance and direct order closure asking for delivery address and phone number. 2. Complete size guidance and direct order closure asking for delivery address and phone number.
3. 1-Click WhatsApp booking link: https://wa.me/8801712426871 with cash-on-delivery trial assurance.` 3. 1-Click WhatsApp booking link: {{wa_link}} with cash-on-delivery trial assurance.`
}, },
{ {
id: 'panjabi_closer', id: 'panjabi_closer',
@@ -769,7 +769,7 @@ Details & Offer: {{field2}}
Write 3 distinct high-converting, courteous Bengali responses: Write 3 distinct high-converting, courteous Bengali responses:
1. Royal aesthetic appreciation highlighting fine thread embroidery, pre-shrunk premium cotton/silk comfort, and festive elegance. 1. Royal aesthetic appreciation highlighting fine thread embroidery, pre-shrunk premium cotton/silk comfort, and festive elegance.
2. Accurate size guidance (chest & length fit) with doorstep size trial assurance. 2. Accurate size guidance (chest & length fit) with doorstep size trial assurance.
3. 1-Click WhatsApp booking link: https://wa.me/8801712426871 with cash on delivery across Bangladesh.` 3. 1-Click WhatsApp booking link: {{wa_link}} with cash on delivery across Bangladesh.`
}, },
{ {
id: 'gadget_explainer', id: 'gadget_explainer',
@@ -792,7 +792,7 @@ Specs & Offer: {{field2}}
Generate 3 high-trust Bengali customer responses: Generate 3 high-trust Bengali customer responses:
1. Power-packed feature breakdown (battery, AMOLED screen, sound quality, water resistance). 1. Power-packed feature breakdown (battery, AMOLED screen, sound quality, water resistance).
2. Official warranty guarantee & risk-free Cash on Delivery verification guide. 2. Official warranty guarantee & risk-free Cash on Delivery verification guide.
3. Fast 1-Click WhatsApp purchase link: https://wa.me/8801712426871.` 3. Fast 1-Click WhatsApp purchase link: {{wa_link}}.`
}, },
{ {
id: 'organic_honey_lab', id: 'organic_honey_lab',
@@ -861,7 +861,7 @@ Store context: {{field2}}
Write 3 distinct ready-to-copy Bengali replies: Write 3 distinct ready-to-copy Bengali replies:
1. Instant sweet greeting with price & benefits 1. Instant sweet greeting with price & benefits
2. Direct order closing script asking for Name, Address, Phone 2. Direct order closing script asking for Name, Address, Phone
3. 1-Click WhatsApp direct order message with link https://wa.me/8801712426871` 3. 1-Click WhatsApp direct order message with link {{wa_link}}`
}, },
{ {
id: 'veo_prompter', id: 'veo_prompter',
@@ -1216,14 +1216,14 @@ document.addEventListener('aura-studio-ready', () => {
statusMsg.classList.remove('hidden'); statusMsg.classList.remove('hidden');
statusMsg.style.color = '#C084FC'; statusMsg.style.color = '#C084FC';
statusMsg.textContent = '⏳ Processing with Gemini 3.5 AI...'; statusMsg.textContent = '⏳ Processing with Gemini 3.5 AI...';
execBtn.disabled = true;
// Extract form values & dynamic store metadata // Extract form values & dynamic store metadata
const inputs = document.querySelectorAll('.runner-input'); const inputs = document.querySelectorAll('.runner-input');
const selectedBrandKey = document.getElementById('brandWatermarkSelect')?.value || 'glamourstouch'; const selectedBrandKey = document.getElementById('brandWatermarkSelect')?.value || 'glamourstouch';
const activeBrand = getBrandProfile(selectedBrandKey); const activeBrand = getBrandProfile(selectedBrandKey);
const cleanPhone = (activeBrand.footerHotline || '').replace(/\D/g, ''); const dynamicWaLink = window.AuraStudio.whatsappUrl(activeBrand.footerHotline);
const dynamicWaLink = `https://wa.me/88${cleanPhone}`; if (!dynamicWaLink) { alert('Settings-এ country code সহ WhatsApp নম্বর দিন।'); return; }
execBtn.disabled = true;
let prompt = currentRunningApp.promptTemplate || 'Generate helpful response for the user.'; let prompt = currentRunningApp.promptTemplate || 'Generate helpful response for the user.';
@@ -1239,7 +1239,6 @@ document.addEventListener('aura-studio-ready', () => {
prompt = prompt.replace(/{{brand_site}}/g, activeBrand.footerSite); prompt = prompt.replace(/{{brand_site}}/g, activeBrand.footerSite);
prompt = prompt.replace(/{{brand_name}}/g, activeBrand.headerTitle); prompt = prompt.replace(/{{brand_name}}/g, activeBrand.headerTitle);
prompt = prompt.replace(/{{wa_link}}/g, dynamicWaLink); prompt = prompt.replace(/{{wa_link}}/g, dynamicWaLink);
prompt = prompt.replace(/https:\/\/wa\.me\/8801712426871/g, dynamicWaLink);
const apiKey = window.AuraStudio.local.getItem('opal_gemini_api_key') || ''; const apiKey = window.AuraStudio.local.getItem('opal_gemini_api_key') || '';
const model = currentRunningApp.model || window.AuraStudio.local.getItem('opal_selected_model') || 'gemini-2.0-flash'; const model = currentRunningApp.model || window.AuraStudio.local.getItem('opal_selected_model') || 'gemini-2.0-flash';
@@ -1715,10 +1714,11 @@ function initPosterLab() {
shareWhatsAppBtn.addEventListener('click', () => { shareWhatsAppBtn.addEventListener('click', () => {
const selectedBrand = document.getElementById('brandWatermarkSelect')?.value || 'glamourstouch'; const selectedBrand = document.getElementById('brandWatermarkSelect')?.value || 'glamourstouch';
const activeBrand = getBrandProfile(selectedBrand); const activeBrand = getBrandProfile(selectedBrand);
const cleanPhone = (activeBrand.footerHotline || '').replace(/\D/g, ''); const waLink = window.AuraStudio.whatsappUrl(activeBrand.footerHotline);
const pTitle = productInput.value.trim() || 'Authentic Product'; if (!waLink) { alert('Settings-এ country code সহ WhatsApp নম্বর দিন।'); return; }
const pTitle = productInput.value.trim() || 'Product';
const text = encodeURIComponent(`✨ Hello! I want to order: ${pTitle}\nWebsite: https://${activeBrand.footerSite || ''}\nHotline: ${activeBrand.footerHotline}`); const text = encodeURIComponent(`✨ Hello! I want to order: ${pTitle}\nWebsite: https://${activeBrand.footerSite || ''}\nHotline: ${activeBrand.footerHotline}`);
window.open(`https://wa.me/88${cleanPhone}?text=${text}`, '_blank'); window.open(`${waLink}?text=${text}`, '_blank', 'noopener');
}); });
// n8n Auto-Post Webhook // n8n Auto-Post Webhook
@@ -1742,18 +1742,20 @@ function initPosterLab() {
try { try {
const selectedBrand = document.getElementById('brandWatermarkSelect')?.value || 'glamourstouch'; const selectedBrand = document.getElementById('brandWatermarkSelect')?.value || 'glamourstouch';
const activeBrand = getBrandProfile(selectedBrand); const activeBrand = getBrandProfile(selectedBrand);
const cleanPhone = (activeBrand.footerHotline || '').replace(/\D/g, '');
const pTitle = productInput.value.trim() || 'Authentic Product'; const pTitle = productInput.value.trim() || 'Authentic Product';
const pPrice = productPrice.value.trim() || '৳ ১,০৬০'; const pPrice = productPrice.value.trim();
const waLink = window.AuraStudio.whatsappUrl(activeBrand.footerHotline);
const website = window.AuraStudio.workspace.brand?.website || '';
const caption = [`✨ ${pTitle} ✨`, pPrice ? `💰 মূল্য: ${pPrice}` : '', waLink ? `💬 WhatsApp: ${waLink}` : '', website ? `🌐 ${website}` : ''].filter(Boolean).join('\n\n');
const posterDataUrl = posterCanvas.toDataURL('image/jpeg', 0.92); const posterDataUrl = posterCanvas.toDataURL('image/jpeg', 0.92);
const payload = { const payload = {
title: pTitle, title: pTitle,
price: pPrice, price: pPrice,
caption: `✨ ${pTitle} ✨\n\n💰 অফার মূল্য: ${pPrice}\n🛡️ ১০০% অরিজিনাল গ্যারান্টি!\n\n💬 সরাসরি WhatsApp এ অর্ডার করতে ইনবক্স করুন:\n👉 https://wa.me/88${cleanPhone}\n📞 হটলাইন: ${activeBrand.footerHotline}\n🌐 ওয়েবসাইট: https://${activeBrand.footerSite}`, caption,
image_url: posterDataUrl, image_url: posterDataUrl,
store: activeBrand.headerTitle || "Official Store", store: activeBrand.headerTitle || "Official Store",
website: `https://${activeBrand.footerSite}`, website,
whatsapp: activeBrand.footerHotline, whatsapp: activeBrand.footerHotline,
timestamp: new Date().toISOString() timestamp: new Date().toISOString()
}; };
@@ -1802,7 +1804,10 @@ function getDynamicBrandProfiles() {
function getBrandProfile(brandKey) { function getBrandProfile(brandKey) {
const all = getDynamicBrandProfiles(); const all = getDynamicBrandProfiles();
return all[brandKey] || all.workspace; if (brandKey && brandKey !== 'workspace' && all[brandKey]) return all[brandKey];
const brand = window.AuraStudio.workspace.brand || {};
return { ...all.workspace, headerTitle: brand.name || window.AuraStudio.workspace.name,
footerSite: (brand.website || '').replace(/^https?:\/\//, ''), footerHotline: brand.phone || '' };
} }
// Universal Dynamic Product Resolver // Universal Dynamic Product Resolver
@@ -6139,8 +6144,8 @@ async function drawWhatsAppQrOnCanvas(ctx, x, y, size, hotline = '') {
roundRect(ctx, x - 4, y - 4, size + 8, size + 8, 10); roundRect(ctx, x - 4, y - 4, size + 8, size + 8, 10);
ctx.fill(); ctx.fill();
const rawPhone = hotline.replace(/\D/g, ''); const waUrl = window.AuraStudio.whatsappUrl(hotline);
const waUrl = `https://wa.me/88${rawPhone.startsWith('88') ? rawPhone.slice(2) : rawPhone.replace(/^0/, '')}`; if (!waUrl) return;
const qrContainer = document.getElementById('qrcodeHidden'); const qrContainer = document.getElementById('qrcodeHidden');
if (qrContainer && typeof QRCode !== 'undefined') { if (qrContainer && typeof QRCode !== 'undefined') {
@@ -6199,8 +6204,8 @@ function initInboxAI() {
const selectedBrand = document.getElementById('brandWatermarkSelect')?.value || 'glamourstouch'; const selectedBrand = document.getElementById('brandWatermarkSelect')?.value || 'glamourstouch';
const activeBrand = getBrandProfile(selectedBrand); const activeBrand = getBrandProfile(selectedBrand);
const cleanPhone = (activeBrand.footerHotline || '').replace(/\D/g, ''); const dynamicWaLink = window.AuraStudio.whatsappUrl(activeBrand.footerHotline);
const dynamicWaLink = `https://wa.me/88${cleanPhone}`; if (!dynamicWaLink) { alert('Settings-এ country code সহ WhatsApp নম্বর দিন।'); return; }
if (!query) { if (!query) {
alert('Please enter a customer message'); alert('Please enter a customer message');
+9
View File
@@ -818,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>
+11 -2
View File
@@ -1,4 +1,5 @@
const { fail, requireProductWrite } = require('./workspace.cjs'); const { fail, requireProductWrite } = require('./workspace.cjs');
const { normalizeBrand } = require('./brand.cjs');
function sendJson(response, status, value) { function sendJson(response, status, value) {
if (response.destroyed || response.writableEnded) return; if (response.destroyed || response.writableEnded) return;
@@ -78,7 +79,7 @@ function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getCo
try { try {
const pathname = new URL(request.url, origin).pathname; const pathname = new URL(request.url, origin).pathname;
const routes = { const routes = {
'/api/workspace': 'GET', '/api/catalog-image': 'GET', '/api/workspace': 'GET', '/api/brand': 'POST', '/api/catalog-image': 'GET',
'/api/get-synced-stores': 'GET', '/api/sync-store': 'POST', '/api/delete-synced-store': 'POST' '/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 (!routes[pathname]) return sendJson(response, 404, { success: false, code: 'NOT_FOUND', error: 'API পাওয়া যায়নি।' });
@@ -86,7 +87,10 @@ function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getCo
if (request.method === 'POST') writeOrigin(request); if (request.method === 'POST') writeOrigin(request);
const workspace = await resolveWorkspace(request); const workspace = await resolveWorkspace(request);
const publicWorkspace = { clientId: workspace.clientId, name: workspace.displayName, tenant: workspace.tenant, canWriteProducts: workspace.canWriteProducts }; const publicWorkspace = { clientId: workspace.clientId, name: workspace.displayName, tenant: workspace.tenant, canWriteProducts: workspace.canWriteProducts };
if (pathname === '/api/workspace') return sendJson(response, 200, { success: true, workspace: publicWorkspace }); 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 (pathname === '/api/catalog-image') {
if (!imageHandler) throw fail(503, 'IMAGE_UNAVAILABLE', 'Product image এখন পাওয়া যাচ্ছে না।'); if (!imageHandler) throw fail(503, 'IMAGE_UNAVAILABLE', 'Product image এখন পাওয়া যাচ্ছে না।');
return await imageHandler(request, response, workspace); return await imageHandler(request, response, workspace);
@@ -98,6 +102,11 @@ function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getCo
} }
requireProductWrite(workspace); requireProductWrite(workspace);
const body = await readJson(request, maxBodyBytes); 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 (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.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 নির্বাচন করুন।'); if (typeof body.storeId !== 'string' || !body.storeId || body.storeId.length > 160) throw fail(400, 'INVALID_STORE_ID', 'সঠিক store নির্বাচন করুন।');
+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 };
+2 -3
View File
@@ -4,7 +4,7 @@ const { createHash } = require('node:crypto');
const { gzipSync } = require('node:zlib'); 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 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', 'gt_full_catalog.json']); const ROOT_FILES = new Set(['index.html', 'app.js', 'workspace.js', 'style.css', 'sw.js', 'manifest.json']);
function createStaticHandler(publicDirectory, { maxCacheBytes = 16 * 1024 * 1024 } = {}) { function createStaticHandler(publicDirectory, { maxCacheBytes = 16 * 1024 * 1024 } = {}) {
const root = path.resolve(publicDirectory), cache = new Map(); const root = path.resolve(publicDirectory), cache = new Map();
@@ -20,8 +20,7 @@ function createStaticHandler(publicDirectory, { maxCacheBytes = 16 * 1024 * 1024
if (pathname.includes('\\') || pathname.includes('\0') || pathname.split('/').some(p => p.startsWith('.'))) 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(/^\/+/, ''); let relative = pathname === '/' ? 'index.html' : pathname.replace(/^\/+/, '');
const asset = relative.startsWith('assets/') && MIME[path.extname(relative).toLowerCase()]; const asset = relative.startsWith('assets/') && MIME[path.extname(relative).toLowerCase()];
const legacyData = relative === 'data/synced_stores.json'; if (!ROOT_FILES.has(relative) && !asset) {
if (!ROOT_FILES.has(relative) && !asset && !legacyData) {
if (!path.extname(relative) && !/^(?:server|docs|test|data|node_modules)(?:\/|$)/.test(relative) && String(request.headers.accept || '').includes('text/html')) relative = 'index.html'; 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); else return missing(response);
} }
+11 -8
View File
@@ -17,25 +17,26 @@ function createStore(rootDirectory) {
return dir; return dir;
} }
async function read(workspace) { async function read(workspace, kind = 'stores') {
if (!['stores', 'brand'].includes(kind)) throw new Error('Invalid storage kind');
const dir = await directory(workspace); const dir = await directory(workspace);
let text; let text;
try { text = await fs.readFile(path.join(dir, 'stores.json'), 'utf8'); } try { text = await fs.readFile(path.join(dir, kind + '.json'), 'utf8'); }
catch (error) { if (error.code === 'ENOENT') return []; throw error; } catch (error) { if (error.code === 'ENOENT') return kind === 'stores' ? [] : null; throw error; }
const records = JSON.parse(text); const records = JSON.parse(text);
if (!Array.isArray(records)) throw new Error('Invalid saved store data'); if (kind === 'stores' ? !Array.isArray(records) : (!records || typeof records !== 'object' || Array.isArray(records))) throw new Error('Invalid saved workspace data');
return records; return records;
} }
async function update(workspace, change) { async function update(workspace, change, kind = 'stores') {
const key = workspace.namespace; const key = workspace.namespace;
const previous = queues.get(key) || Promise.resolve(); const previous = queues.get(key) || Promise.resolve();
const task = previous.catch(() => {}).then(async () => { const task = previous.catch(() => {}).then(async () => {
const records = await read(workspace); const records = await read(workspace, kind);
const next = change(records); const next = change(records);
const dir = await directory(workspace); const dir = await directory(workspace);
const target = path.join(dir, 'stores.json'); const target = path.join(dir, kind + '.json');
const temporary = path.join(dir, '.stores-' + randomUUID() + '.tmp'); const temporary = path.join(dir, '.' + kind + '-' + randomUUID() + '.tmp');
let handle; let handle;
try { try {
handle = await fs.open(temporary, 'wx', 0o600); handle = await fs.open(temporary, 'wx', 0o600);
@@ -61,6 +62,8 @@ function createStore(rootDirectory) {
return { return {
read, read,
readBrand(workspace) { return read(workspace, 'brand'); },
saveBrand(workspace, brand) { return update(workspace, () => brand, 'brand'); },
upsert(workspace, store) { upsert(workspace, store) {
if (!store || typeof store.id !== 'string' || !store.id || store.id.length > 160 || !Array.isArray(store.products)) { 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 Promise.reject(new Error('Invalid imported store'));
+28
View File
@@ -63,6 +63,34 @@ async function setup(t, settings = {}) {
return { root, counts, call, base, store, resolve }; 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 => { test('HTTP import persists actual source values for owner/staff and isolates another tenant', async t => {
const f = await setup(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' }); 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' });
+9 -1
View File
@@ -4,7 +4,15 @@ const fs = require('node:fs');
const vm = require('node:vm'); const vm = require('node:vm');
const path = require('node:path'); const path = require('node:path');
const workspaceModule = fs.existsSync(path.join(__dirname, '../workspace.js')) ? '../workspace.js' : '../public/workspace.js'; const workspaceModule = fs.existsSync(path.join(__dirname, '../workspace.js')) ? '../workspace.js' : '../public/workspace.js';
const { scopedStorage, escapeText } = require(workspaceModule); 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 a = '11111111-1111-4111-8111-111111111111';
const b = '22222222-2222-4222-8222-222222222222'; const b = '22222222-2222-4222-8222-222222222222';
function memory() { function memory() {
+4 -1
View File
@@ -11,6 +11,9 @@ async function app(t) {
await fs.mkdir(publicDirectory); await fs.mkdir(publicDirectory);
await fs.writeFile(path.join(publicDirectory, 'index.html'), '<!doctype html><h1>Fixture Studio</h1>'); 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, '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'); 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' }); 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)); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
@@ -34,7 +37,7 @@ test('server serves existing static assets, compression and revalidation without
test('backend source, private files and traversal paths are not static downloads', async t => { test('backend source, private files and traversal paths are not static downloads', async t => {
const base = await app(t); const base = await app(t);
for (const route of ['/server/main.cjs', '/.env', '/docs', '/node_modules/x', '/%2e%2e%2fprivate.txt', '/assets/..%5cprivate.txt']) { 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' } }); const result = await fetch(base + route, { headers: { Accept: 'text/html' } });
assert.equal(result.status, 404, route); assert.equal(result.status, 404, route);
assert.doesNotMatch(await result.text(), /PRIVATE-FIXTURE/); assert.doesNotMatch(await result.text(), /PRIVATE-FIXTURE/);
+27 -1
View File
@@ -12,7 +12,11 @@
function escapeText(value) { function escapeText(value) {
return String(value ?? '').replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[char])); return String(value ?? '').replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[char]));
} }
if (typeof module === 'object' && module.exports) { module.exports = { scopedStorage, escapeText }; return; } 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() { async function start() {
const gate = document.getElementById('studioWorkspaceGate'); const gate = document.getElementById('studioWorkspaceGate');
@@ -56,6 +60,7 @@
local: scopedStorage(localStorage, workspace.clientId), local: scopedStorage(localStorage, workspace.clientId),
session: scopedStorage(sessionStorage, workspace.clientId), session: scopedStorage(sessionStorage, workspace.clientId),
escapeText, escapeText,
whatsappUrl,
apiUrl(path) { apiUrl(path) {
const url = new URL(path, location.origin); const url = new URL(path, location.origin);
if (url.origin !== location.origin || !url.pathname.startsWith('/api/')) throw new Error('Invalid Studio API URL'); if (url.origin !== location.origin || !url.pathname.startsWith('/api/')) throw new Error('Invalid Studio API URL');
@@ -72,6 +77,27 @@
document.dispatchEvent(new Event('aura-studio-ready')); document.dispatchEvent(new Event('aura-studio-ready'));
document.querySelectorAll('body > :not(#studioWorkspaceGate):not(script)').forEach(el => el.inert = false); document.querySelectorAll('body > :not(#studioWorkspaceGate):not(script)').forEach(el => el.inert = false);
gate.hidden = true; 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'); const button = document.createElement('button');
button.type = 'button'; button.className = 'pill-btn'; button.type = 'button'; button.className = 'pill-btn';
button.textContent = workspace.name || workspace.tenant; button.textContent = workspace.name || workspace.tenant;