Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6a46c419f2 | |||
| 7c5bcd9ac7 |
+1
-1
@@ -9,7 +9,7 @@ RUN rm -rf /usr/share/nginx/html/*
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
# Publish web assets only. Backend source, tests and local configuration are not static downloads.
|
||||
COPY index.html app.js workspace.js style.css sw.js manifest.json gt_full_catalog.json /usr/share/nginx/html/
|
||||
COPY index.html app.js workspace.js style.css sw.js manifest.json favicon.svg gt_full_catalog.json /usr/share/nginx/html/
|
||||
COPY assets/ /usr/share/nginx/html/assets/
|
||||
COPY data/ /usr/share/nginx/html/data/
|
||||
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ 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 index.html app.js workspace.js style.css sw.js manifest.json favicon.svg ./public/
|
||||
COPY assets/ ./public/assets/
|
||||
RUN mkdir -p /data/studio && chown -R node:node /app /data/studio
|
||||
USER node
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" fill="none">
|
||||
<defs>
|
||||
<linearGradient id="bgStudio" x1="0" y1="0" x2="128" y2="128" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stop-color="#1d0d38"/>
|
||||
<stop offset="100%" stop-color="#0b0718"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="prismGrad" x1="22" y1="22" x2="106" y2="106" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stop-color="#c084fc"/>
|
||||
<stop offset="50%" stop-color="#ec4899"/>
|
||||
<stop offset="100%" stop-color="#fbbf24"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="128" height="128" rx="28" fill="url(#bgStudio)"/>
|
||||
<rect x="4" y="4" width="120" height="120" rx="24" stroke="#c084fc" stroke-opacity="0.4" stroke-width="2.5"/>
|
||||
<path d="M64 24L98 64L64 104L30 64L64 24Z" fill="url(#prismGrad)" fill-opacity="0.16" stroke="url(#prismGrad)" stroke-width="5" stroke-linejoin="round"/>
|
||||
<path d="M64 40L70.5 57.5L88 64L70.5 70.5L64 88L57.5 70.5L40 64L57.5 57.5L64 40Z" fill="url(#prismGrad)"/>
|
||||
<circle cx="96" cy="32" r="5.5" fill="#fbbf24"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
+252
-921
File diff suppressed because it is too large
Load Diff
+61
-7
@@ -43,7 +43,7 @@ function readJson(request, maxBytes) {
|
||||
});
|
||||
}
|
||||
|
||||
function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getConnected, publicOrigin, maxBodyBytes = 32768, maxConcurrentImports = 1, maxImportsPerMinute = 5 }) {
|
||||
function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getConnected, engineProxy, 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');
|
||||
@@ -79,14 +79,31 @@ function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getCo
|
||||
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'
|
||||
'/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/experts': ['GET', 'POST'],
|
||||
'/api/experts/simulate': ['POST'],
|
||||
'/api/experts/generate-content': ['POST'],
|
||||
'/api/playbooks': ['GET', 'POST'],
|
||||
'/api/playbooks/test': ['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 expertDeleteMatch = !routes[pathname] ? /^\/api\/experts\/([a-zA-Z0-9_-]{1,80})$/.exec(pathname) : null;
|
||||
const allowedMethods = routes[pathname] || (expertDeleteMatch ? ['DELETE'] : null);
|
||||
if (!allowedMethods) return sendJson(response, 404, { success: false, code: 'NOT_FOUND', error: 'API পাওয়া যায়নি।' });
|
||||
if (!allowedMethods.includes(request.method)) return sendJson(response, 405, { success: false, code: 'METHOD_NOT_ALLOWED', error: 'এই method সমর্থিত নয়।' });
|
||||
if (request.method === 'POST' || request.method === 'DELETE') writeOrigin(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,
|
||||
multiExpertEnabled: Boolean(engineProxy && engineProxy.isConfigured())
|
||||
};
|
||||
if (pathname === '/api/workspace') {
|
||||
publicWorkspace.brand = normalizeBrand(await store.readBrand(workspace) || {}, workspace.displayName);
|
||||
return sendJson(response, 200, { success: true, workspace: publicWorkspace });
|
||||
@@ -95,6 +112,43 @@ function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getCo
|
||||
if (!imageHandler) throw fail(503, 'IMAGE_UNAVAILABLE', 'Product image এখন পাওয়া যাচ্ছে না।');
|
||||
return await imageHandler(request, response, workspace);
|
||||
}
|
||||
|
||||
// ── Multi-Tenant Multi-Expert Brain & n8n Playbooks Proxy Routes ───────
|
||||
if (pathname === '/api/experts' || expertDeleteMatch || pathname.startsWith('/api/experts/') || pathname === '/api/playbooks' || pathname.startsWith('/api/playbooks/')) {
|
||||
if (!engineProxy || !engineProxy.isConfigured()) {
|
||||
throw fail(503, 'ENGINE_NOT_CONFIGURED', 'Multi-Expert AI Engine সংযুক্ত নয়।');
|
||||
}
|
||||
if (pathname === '/api/experts' && request.method === 'GET') {
|
||||
return sendJson(response, 200, await engineProxy.listExperts(workspace));
|
||||
}
|
||||
if (pathname === '/api/playbooks' && request.method === 'GET') {
|
||||
return sendJson(response, 200, await engineProxy.listPlaybooks(workspace));
|
||||
}
|
||||
if (expertDeleteMatch && request.method === 'DELETE') {
|
||||
requireProductWrite(workspace);
|
||||
return sendJson(response, 200, await engineProxy.deleteExpert(workspace, expertDeleteMatch[1]));
|
||||
}
|
||||
const body = await readJson(request, maxBodyBytes);
|
||||
if (pathname === '/api/experts' && request.method === 'POST') {
|
||||
requireProductWrite(workspace);
|
||||
return sendJson(response, 200, await engineProxy.saveExpert(workspace, body));
|
||||
}
|
||||
if (pathname === '/api/experts/simulate') {
|
||||
return sendJson(response, 200, await engineProxy.simulate(workspace, body));
|
||||
}
|
||||
if (pathname === '/api/experts/generate-content') {
|
||||
return sendJson(response, 200, await engineProxy.generateContent(workspace, body));
|
||||
}
|
||||
if (pathname === '/api/playbooks' && request.method === 'POST') {
|
||||
requireProductWrite(workspace);
|
||||
return sendJson(response, 200, await engineProxy.savePlaybook(workspace, body));
|
||||
}
|
||||
if (pathname === '/api/playbooks/test') {
|
||||
if (!body.dry_run) requireProductWrite(workspace);
|
||||
return sendJson(response, 200, await engineProxy.testPlaybook(workspace, body));
|
||||
}
|
||||
}
|
||||
|
||||
if (request.method === 'GET') {
|
||||
const records = await store.read(workspace);
|
||||
if (getConnected) records.unshift(await getConnected(workspace));
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
const { fail } = require('./workspace.cjs');
|
||||
|
||||
const SAFE_ID_RE = /^[a-zA-Z0-9_-]{1,80}$/;
|
||||
|
||||
function createEngineProxy({ baseUrl, serviceKey, fetchImpl = fetch, timeoutMs = 35000 } = {}) {
|
||||
const configuredUrl = String(baseUrl || '').trim().replace(/\/+$/, '');
|
||||
const configuredKey = String(serviceKey || '').trim();
|
||||
|
||||
function isConfigured() {
|
||||
return Boolean(configuredUrl && configuredKey);
|
||||
}
|
||||
|
||||
function assertConfigured() {
|
||||
if (!isConfigured()) {
|
||||
throw fail(503, 'ENGINE_NOT_CONFIGURED', 'Multi-Expert AI Engine সংযুক্ত নয়। অনুগ্রহ করে অ্যাডমিনের সাথে যোগাযোগ করুন।');
|
||||
}
|
||||
}
|
||||
|
||||
function cleanBody(body) {
|
||||
if (!body || typeof body !== 'object' || Array.isArray(body)) return {};
|
||||
const out = { ...body };
|
||||
delete out.tenant;
|
||||
delete out.tenant_id;
|
||||
delete out.clientId;
|
||||
delete out.client_id;
|
||||
return out;
|
||||
}
|
||||
|
||||
async function forward(workspace, method, enginePath, body = null) {
|
||||
assertConfigured();
|
||||
if (!workspace || !workspace.tenant || !workspace.clientId) {
|
||||
throw fail(401, 'WORKSPACE_REQUIRED', 'বৈধ workspace প্রয়োজন।');
|
||||
}
|
||||
|
||||
const url = configuredUrl + enginePath;
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
const headers = {
|
||||
Authorization: 'Bearer ' + configuredKey,
|
||||
'x-aura-tenant': workspace.tenant,
|
||||
'x-aura-client-id': workspace.clientId,
|
||||
Accept: 'application/json'
|
||||
};
|
||||
const init = { method, headers, signal: controller.signal };
|
||||
if (body !== null && method !== 'GET' && method !== 'HEAD') {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
init.body = JSON.stringify(cleanBody(body));
|
||||
}
|
||||
|
||||
try {
|
||||
const upstream = await fetchImpl(url, init);
|
||||
const rawText = await upstream.text();
|
||||
let parsed;
|
||||
try { parsed = rawText ? JSON.parse(rawText) : {}; }
|
||||
catch { parsed = { success: false, error: 'Engine returned invalid JSON' }; }
|
||||
if (!upstream.ok) {
|
||||
throw fail(
|
||||
upstream.status >= 400 && upstream.status < 600 ? upstream.status : 502,
|
||||
parsed.code || 'ENGINE_UPSTREAM_ERROR',
|
||||
parsed.error || 'AI Engine অনুরোধটি সম্পন্ন করতে পারেনি।'
|
||||
);
|
||||
}
|
||||
return parsed;
|
||||
} catch (err) {
|
||||
if (err && Number.isInteger(err.status)) throw err;
|
||||
if (err && err.name === 'AbortError') {
|
||||
throw fail(504, 'ENGINE_TIMEOUT', 'AI Engine উত্তর দিতে বেশি সময় নিচ্ছে। একটু পরে আবার চেষ্টা করুন।');
|
||||
}
|
||||
throw fail(502, 'ENGINE_UNREACHABLE', 'Multi-Expert AI Engine-এর সাথে সংযোগ পাওয়া যায়নি।');
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isConfigured,
|
||||
listExperts: workspace => forward(workspace, 'GET', '/api/experts'),
|
||||
saveExpert: (workspace, body) => forward(workspace, 'POST', '/api/experts', body),
|
||||
deleteExpert: (workspace, id) => {
|
||||
if (!SAFE_ID_RE.test(String(id || ''))) {
|
||||
throw fail(400, 'INVALID_EXPERT_ID', 'সঠিক Expert ID দিন।');
|
||||
}
|
||||
return forward(workspace, 'DELETE', '/api/experts/' + encodeURIComponent(id));
|
||||
},
|
||||
simulate: (workspace, body) => forward(workspace, 'POST', '/api/experts/simulate', body),
|
||||
generateContent: (workspace, body) => forward(workspace, 'POST', '/api/experts/generate-content', body),
|
||||
listPlaybooks: workspace => forward(workspace, 'GET', '/api/playbooks'),
|
||||
savePlaybook: (workspace, body) => forward(workspace, 'POST', '/api/playbooks', body),
|
||||
testPlaybook: (workspace, body) => forward(workspace, 'POST', '/api/playbooks/test', body)
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createEngineProxy, SAFE_ID_RE };
|
||||
+6
-2
@@ -5,6 +5,7 @@ const { createStore } = require('./store.cjs');
|
||||
const { createPublicFetcher } = require('./public-fetch.cjs');
|
||||
const { createScraper } = require('./scraper.cjs');
|
||||
const { createApiHandler } = require('./api.cjs');
|
||||
const { createEngineProxy } = require('./engine-proxy.cjs');
|
||||
const { createImageHandler } = require('./images.cjs');
|
||||
const { createConnectedCatalog } = require('./connected.cjs');
|
||||
const { createStaticHandler } = require('./static.cjs');
|
||||
@@ -21,7 +22,8 @@ function createStudioServer(config) {
|
||||
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 engineProxy = createEngineProxy({ baseUrl: config.auraEngineUrl, serviceKey: config.auraEngineServiceKey });
|
||||
const api = createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getConnected, engineProxy, publicOrigin: config.publicOrigin, ...config.apiLimits });
|
||||
const staticFiles = createStaticHandler(config.publicDirectory);
|
||||
const server = http.createServer({ maxHeaderSize: 16384 }, async (req, res) => {
|
||||
try {
|
||||
@@ -41,7 +43,7 @@ function createStudioServer(config) {
|
||||
}
|
||||
});
|
||||
server.headersTimeout = 15000;
|
||||
server.requestTimeout = 20000;
|
||||
server.requestTimeout = 45000;
|
||||
server.keepAliveTimeout = 5000;
|
||||
server.maxHeadersCount = 50;
|
||||
return server;
|
||||
@@ -66,6 +68,8 @@ if (require.main === module) {
|
||||
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'),
|
||||
auraEngineUrl: process.env.AURA_ENGINE_URL || '',
|
||||
auraEngineServiceKey: process.env.AURA_ENGINE_SERVICE_KEY || '',
|
||||
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'),
|
||||
|
||||
+2
-2
@@ -4,7 +4,7 @@ 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']);
|
||||
const ROOT_FILES = new Set(['index.html', 'app.js', 'workspace.js', 'style.css', 'sw.js', 'manifest.json', 'favicon.svg']);
|
||||
|
||||
function createStaticHandler(publicDirectory, { maxCacheBytes = 16 * 1024 * 1024 } = {}) {
|
||||
const root = path.resolve(publicDirectory), cache = new Map();
|
||||
@@ -18,7 +18,7 @@ function createStaticHandler(publicDirectory, { maxCacheBytes = 16 * 1024 * 1024
|
||||
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(/^\/+/, '');
|
||||
let relative = pathname === '/' ? 'index.html' : (pathname === '/favicon.ico' ? 'favicon.svg' : 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';
|
||||
|
||||
@@ -1782,3 +1782,173 @@ body {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/* ── Multi-Expert AI Brain OS Styles (v11) ───────────────────────────────── */
|
||||
.mx-telemetry-strip {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
padding: 10px 20px;
|
||||
background: rgba(14, 20, 31, 0.85);
|
||||
border-bottom: 1px solid var(--card-border);
|
||||
justify-content: center;
|
||||
}
|
||||
.mx-stat-pill {
|
||||
font-size: 12px;
|
||||
padding: 6px 12px;
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
border: 1px solid rgba(255, 255, 255, 0.09);
|
||||
color: var(--text-secondary);
|
||||
display: inline-flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
.mx-stat-pill strong { color: #f8fafc; font-weight: 700; }
|
||||
.mx-stat-live strong { color: #34d399; }
|
||||
|
||||
.mx-main { max-width: 1120px; width: 100%; margin: 0 auto; padding: 18px 16px 32px; }
|
||||
.mx-experts-grid, .mx-playbooks-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(310px, 1fr));
|
||||
gap: 14px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
.mx-expert-card, .mx-playbook-card {
|
||||
background: rgba(12, 18, 30, 0.82);
|
||||
border: 1px solid rgba(139, 92, 246, 0.22);
|
||||
border-radius: 16px;
|
||||
padding: 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
transition: border-color 0.2s, transform 0.2s;
|
||||
}
|
||||
.mx-expert-card.is-paused, .mx-playbook-card.is-paused {
|
||||
opacity: 0.65;
|
||||
border-color: rgba(148, 163, 184, 0.18);
|
||||
}
|
||||
.mx-expert-card:hover, .mx-playbook-card:hover {
|
||||
border-color: rgba(139, 92, 246, 0.55);
|
||||
}
|
||||
.mx-expert-top {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
}
|
||||
.mx-expert-title-row { display: flex; gap: 10px; align-items: flex-start; }
|
||||
.mx-role-icon {
|
||||
font-size: 22px;
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border-radius: 10px;
|
||||
background: rgba(139, 92, 246, 0.16);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.mx-expert-card h3, .mx-playbook-card h3 { font-size: 14.5px; font-weight: 700; color: #f8fafc; margin-bottom: 4px; }
|
||||
.mx-expert-desc { font-size: 12.5px; color: var(--text-secondary); line-height: 1.5; }
|
||||
.mx-meta-pills { display: flex; flex-wrap: wrap; gap: 5px; }
|
||||
.mx-badge {
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
text-transform: uppercase;
|
||||
background: rgba(139, 92, 246, 0.2);
|
||||
color: #c4b5fd;
|
||||
}
|
||||
.mx-badge.role-sales { background: rgba(16, 185, 129, 0.2); color: #6ee7b7; }
|
||||
.mx-badge.role-logistics { background: rgba(59, 130, 246, 0.2); color: #93c5fd; }
|
||||
.mx-badge.role-risk { background: rgba(244, 63, 94, 0.2); color: #fda4af; }
|
||||
.mx-badge.role-booking { background: rgba(245, 158, 11, 0.2); color: #fde68a; }
|
||||
.mx-badge.subtle { background: rgba(255, 255, 255, 0.06); color: #94a3b8; }
|
||||
|
||||
.mx-chips-section { display: flex; flex-wrap: wrap; gap: 5px; align-items: center; }
|
||||
.mx-mini-label { font-size: 11px; color: var(--text-muted); font-weight: 700; margin-right: 2px; }
|
||||
.mx-chip {
|
||||
font-size: 11px;
|
||||
padding: 3px 8px;
|
||||
border-radius: 8px;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: #cbd5e1;
|
||||
}
|
||||
.mx-chip.intent { background: rgba(6, 182, 212, 0.16); color: #67e8f9; }
|
||||
.mx-chip.tool { background: rgba(245, 158, 11, 0.15); color: #fcd34d; font-family: monospace; font-size: 10.5px; }
|
||||
.mx-chip.expert { background: rgba(139, 92, 246, 0.22); color: #ddd6fe; font-weight: 600; }
|
||||
.mx-chip.ok { background: rgba(16, 185, 129, 0.2); color: #6ee7b7; font-weight: 700; }
|
||||
.mx-chip.warn { background: rgba(244, 63, 94, 0.2); color: #fda4af; font-weight: 700; }
|
||||
|
||||
.mx-card-actions { display: flex; gap: 8px; align-items: center; margin-top: auto; padding-top: 6px; flex-wrap: wrap; }
|
||||
.mx-pb-result { font-size: 12px; color: #34d399; font-weight: 600; }
|
||||
|
||||
/* Toggle Switch */
|
||||
.mx-switch { position: relative; display: inline-block; width: 42px; height: 24px; flex-shrink: 0; }
|
||||
.mx-switch input { opacity: 0; width: 0; height: 0; }
|
||||
.mx-slider {
|
||||
position: absolute; cursor: pointer; inset: 0;
|
||||
background: #334155; border-radius: 999px; transition: 0.2s;
|
||||
}
|
||||
.mx-slider:before {
|
||||
position: absolute; content: ""; height: 18px; width: 18px; left: 3px; bottom: 3px;
|
||||
background: #fff; border-radius: 50%; transition: 0.2s;
|
||||
}
|
||||
.mx-switch input:checked + .mx-slider { background: #10b981; }
|
||||
.mx-switch input:checked + .mx-slider:before { transform: translateX(18px); }
|
||||
|
||||
/* Playground Trace */
|
||||
.mx-scenario-chips { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.mx-trace-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 12px; }
|
||||
.mx-trace-box {
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid var(--card-border);
|
||||
border-radius: 12px;
|
||||
padding: 12px;
|
||||
}
|
||||
.mx-trace-box label { display: block; font-size: 11px; font-weight: 700; color: var(--text-secondary); margin-bottom: 8px; }
|
||||
.mx-chip-list { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.mx-tools-log pre, .mx-ugc-output {
|
||||
background: rgba(5, 8, 14, 0.85);
|
||||
border: 1px solid rgba(255, 255, 255, 0.09);
|
||||
border-radius: 12px;
|
||||
padding: 14px;
|
||||
font-size: 12px;
|
||||
color: #e2e8f0;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
max-height: 460px;
|
||||
overflow: auto;
|
||||
user-select: text;
|
||||
}
|
||||
.mx-tools-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 8px; margin-top: 6px; }
|
||||
.mx-tool-opt {
|
||||
display: flex; align-items: center; gap: 8px; font-size: 11.5px;
|
||||
background: rgba(255, 255, 255, 0.04); padding: 7px 10px; border-radius: 8px; cursor: pointer;
|
||||
}
|
||||
.mx-tool-opt input { width: auto; }
|
||||
.mx-alert {
|
||||
background: rgba(244, 63, 94, 0.14); border: 1px solid rgba(244, 63, 94, 0.35);
|
||||
color: #fecdd3; padding: 10px 14px; border-radius: 10px; font-size: 12.5px; margin-top: 10px;
|
||||
}
|
||||
.mx-loading { padding: 28px; text-align: center; color: var(--text-secondary); font-size: 13px; }
|
||||
.mx-picker-list { display: flex; flex-direction: column; gap: 8px; max-height: 380px; overflow: auto; }
|
||||
.mx-picker-item {
|
||||
display: flex; align-items: center; gap: 10px; padding: 8px 10px;
|
||||
background: rgba(255, 255, 255, 0.04); border: 1px solid var(--card-border);
|
||||
border-radius: 10px; color: #f8fafc; cursor: pointer; width: 100%;
|
||||
}
|
||||
.mx-picker-item:hover { border-color: var(--purple-primary); }
|
||||
.mx-picker-item img, .mx-picker-ph {
|
||||
width: 44px; height: 44px; border-radius: 8px; object-fit: cover; flex-shrink: 0;
|
||||
display: flex; align-items: center; justify-content: center; background: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
.mx-stores-list { display: flex; flex-direction: column; gap: 8px; }
|
||||
.mx-store-row {
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
padding: 10px 14px; border-radius: 12px; background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid var(--card-border);
|
||||
}
|
||||
|
||||
@@ -1,22 +1,16 @@
|
||||
const CACHE_NAME = 'aura-studio-v9-cache';
|
||||
const CACHE_NAME = 'aura-studio-v11-multi-expert-cache';
|
||||
|
||||
self.addEventListener('install', (e) => {
|
||||
self.addEventListener('install', () => {
|
||||
self.skipWaiting();
|
||||
});
|
||||
|
||||
self.addEventListener('activate', (e) => {
|
||||
e.waitUntil(
|
||||
caches.keys().then((keys) => {
|
||||
return Promise.all(
|
||||
keys.map((key) => caches.delete(key))
|
||||
);
|
||||
}).then(() => self.clients.claim())
|
||||
caches.keys().then((keys) => Promise.all(keys.map((key) => caches.delete(key)))).then(() => self.clients.claim())
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', (e) => {
|
||||
// Always fetch fresh network first, fallback to cache only if completely offline
|
||||
e.respondWith(
|
||||
fetch(e.request).catch(() => caches.match(e.request))
|
||||
);
|
||||
if (e.request.method !== 'GET' || new URL(e.request.url).pathname.startsWith('/api/')) return;
|
||||
e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
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 { createHash } = require('node:crypto');
|
||||
const { createWorkspaceResolver } = require('../server/workspace.cjs');
|
||||
const { createStore } = require('../server/store.cjs');
|
||||
const { createApiHandler } = require('../server/api.cjs');
|
||||
const { createEngineProxy } = require('../server/engine-proxy.cjs');
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
test('multi-expert proxy enforces verified tenant headers, CSRF origin, and read-only write guard', async t => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'studio-engine-proxy-'));
|
||||
t.after(() => fs.rm(root, { recursive: true, force: true }));
|
||||
|
||||
const identities = {
|
||||
a: { id: 'actor-a', role: 'client', isActive: true, tenant: 'tenant-a', products: true },
|
||||
readonly: { id: 'reader-a', role: 'team_member', isActive: true, tenant: 'tenant-a', products: false }
|
||||
};
|
||||
|
||||
const identityUrl = await serve(t, (req, res) => {
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
if (req.url === '/auth') {
|
||||
const u = identities[req.headers.authorization?.replace('Bearer ', '')];
|
||||
res.writeHead(u ? 200 : 401);
|
||||
return res.end(JSON.stringify({ user: u ? { ...u, email: u.id + '@test' } : undefined }));
|
||||
}
|
||||
const key = /aura_access=([^;]+)/.exec(req.headers.cookie || '')?.[1];
|
||||
const u = identities[key];
|
||||
if (!u) { res.writeHead(401); return res.end('{}'); }
|
||||
const hash = createHash('sha256').update(u.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: u.tenant, clientId, actor: { id: u.id, email: u.id + '@test', role: u.role }, role: u.products ? 'manager' : 'agent', clientName: u.tenant, perms: { products: u.products } }));
|
||||
});
|
||||
|
||||
const engineCalls = [];
|
||||
const engineProxy = createEngineProxy({
|
||||
baseUrl: 'http://aura-engine.internal:3005',
|
||||
serviceKey: 'test-service-secret',
|
||||
fetchImpl: async (url, init) => {
|
||||
engineCalls.push({ url, method: init.method, headers: init.headers, body: init.body ? JSON.parse(init.body) : null });
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
text: async () => JSON.stringify({ success: true, echoedUrl: url, tenant: init.headers['x-aura-tenant'] })
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
const api = createApiHandler({
|
||||
resolveWorkspace: createWorkspaceResolver({ authMeUrl: identityUrl + '/auth', clientMeUrl: identityUrl + '/client' }),
|
||||
store: createStore(root),
|
||||
scrape: async () => { throw new Error('unused'); },
|
||||
engineProxy,
|
||||
publicOrigin: 'https://studio.fixture'
|
||||
});
|
||||
const base = await serve(t, api);
|
||||
|
||||
// 1. Unauthenticated blocked before hitting engine
|
||||
const unauth = await fetch(base + '/api/experts');
|
||||
assert.equal(unauth.status, 401);
|
||||
assert.equal(engineCalls.length, 0);
|
||||
|
||||
// 2. GET /api/experts forwards canonical tenant & Bearer secret
|
||||
const listRes = await fetch(base + '/api/experts?tenant=attacker', { headers: { Cookie: 'aura_access=a' } });
|
||||
assert.equal(listRes.status, 200);
|
||||
assert.equal(engineCalls[0].headers['x-aura-tenant'], 'tenant-a');
|
||||
assert.equal(engineCalls[0].headers.Authorization, 'Bearer test-service-secret');
|
||||
|
||||
// 3. POST /api/experts strips spoofed tenant/client_id from body
|
||||
const saveRes = await fetch(base + '/api/experts', {
|
||||
method: 'POST',
|
||||
headers: { Cookie: 'aura_access=a', Origin: 'https://studio.fixture', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'Custom Closer', tenant: 'victim', client_id: '00000000-0000-0000-0000-000000000000' })
|
||||
});
|
||||
assert.equal(saveRes.status, 200);
|
||||
assert.equal(engineCalls[1].headers['x-aura-tenant'], 'tenant-a');
|
||||
assert.equal(engineCalls[1].body.tenant, undefined);
|
||||
assert.equal(engineCalls[1].body.client_id, undefined);
|
||||
|
||||
// 4. Cross-origin POST/DELETE rejected with 403
|
||||
const csrfRes = await fetch(base + '/api/experts/custom-1', {
|
||||
method: 'DELETE',
|
||||
headers: { Cookie: 'aura_access=a', Origin: 'https://evil.example' }
|
||||
});
|
||||
assert.equal(csrfRes.status, 403);
|
||||
|
||||
// 5. Read-only member cannot mutate experts or playbooks, but CAN run safe simulate
|
||||
const roSave = await fetch(base + '/api/playbooks', {
|
||||
method: 'POST',
|
||||
headers: { Cookie: 'aura_access=readonly', Origin: 'https://studio.fixture', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ playbook_key: 'ndr_auto_rescue', is_enabled: true })
|
||||
});
|
||||
assert.equal(roSave.status, 403);
|
||||
|
||||
const roSim = await fetch(base + '/api/experts/simulate', {
|
||||
method: 'POST',
|
||||
headers: { Cookie: 'aura_access=readonly', Origin: 'https://studio.fixture', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message: 'দাম কত?' })
|
||||
});
|
||||
assert.equal(roSim.status, 200);
|
||||
});
|
||||
Reference in New Issue
Block a user