120 lines
6.5 KiB
JavaScript
120 lines
6.5 KiB
JavaScript
const { createHash } = require('node:crypto');
|
|
|
|
function fail(status, code, message) {
|
|
return Object.assign(new Error(message), { status, code });
|
|
}
|
|
|
|
function cookieValue(header, name) {
|
|
const entries = String(header || '').split(';').map(item => item.trim());
|
|
const values = entries.filter(item => item.startsWith(name + '='));
|
|
if (values.length > 1) throw fail(400, 'AMBIGUOUS_COOKIE', 'একাধিক login cookie পাওয়া গেছে।');
|
|
if (!values.length) return '';
|
|
try { return decodeURIComponent(values[0].slice(name.length + 1)); }
|
|
catch { throw fail(400, 'INVALID_COOKIE', 'Login cookie সঠিক নয়।'); }
|
|
}
|
|
|
|
function configuredUrl(value) {
|
|
const url = new URL(value);
|
|
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.hash) {
|
|
throw new Error('A trusted HTTP(S) service URL is required');
|
|
}
|
|
return url.href;
|
|
}
|
|
|
|
function createWorkspaceResolver({ authMeUrl, clientMeUrl, clientCatalogUrl, fetchImpl = fetch, timeoutMs = 5000 }) {
|
|
const authUrl = configuredUrl(authMeUrl);
|
|
const clientUrl = configuredUrl(clientMeUrl);
|
|
const catalogUrl = clientCatalogUrl ? configuredUrl(clientCatalogUrl) : null;
|
|
|
|
async function read(url, headers, maxBytes = 256 * 1024, deadlineMs = timeoutMs) {
|
|
let response;
|
|
try {
|
|
response = await fetchImpl(url, {
|
|
method: 'GET', headers, redirect: 'error', signal: AbortSignal.timeout(deadlineMs)
|
|
});
|
|
} catch {
|
|
throw fail(503, 'IDENTITY_SERVICE_UNAVAILABLE', 'Workspace যাচাইয়ের service এখন পাওয়া যাচ্ছে না।');
|
|
}
|
|
if ([401, 403, 404].includes(response.status)) {
|
|
throw fail(401, 'LOGIN_REQUIRED', 'আপনার Aura account-এ আবার login করুন।');
|
|
}
|
|
if (!response.ok) throw fail(503, 'IDENTITY_SERVICE_UNAVAILABLE', 'Workspace যাচাই করা যায়নি।');
|
|
try {
|
|
if (Number(response.headers?.get('content-length')) > maxBytes) throw new Error('Response limit');
|
|
if (response.body) {
|
|
const chunks = []; let size = 0;
|
|
for await (const chunk of response.body) { size += chunk.length; if (size > maxBytes) throw new Error('Response limit'); chunks.push(Buffer.from(chunk)); }
|
|
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
}
|
|
const value = await response.json();
|
|
if (Buffer.byteLength(JSON.stringify(value)) > maxBytes) throw new Error('Response limit');
|
|
return value;
|
|
}
|
|
catch { throw fail(503, 'INVALID_IDENTITY_RESPONSE', 'Workspace service সঠিক উত্তর দেয়নি।'); }
|
|
}
|
|
|
|
return async function resolveWorkspace(request) {
|
|
const token = cookieValue(request.headers.cookie, 'aura_access');
|
|
if (!token || token.length > 8192 || /[\r\n]/.test(token)) {
|
|
throw fail(401, 'LOGIN_REQUIRED', 'আপনার Aura account-এ login করুন।');
|
|
}
|
|
const identity = await read(authUrl, { Authorization: 'Bearer ' + token, Accept: 'application/json' });
|
|
const user = identity?.user;
|
|
if (!user || typeof user.id !== 'string' || !user.id || typeof user.email !== 'string' || !user.email || user.isActive !== true) {
|
|
throw fail(401, 'INACTIVE_ACCOUNT', 'সক্রিয় Aura account প্রয়োজন।');
|
|
}
|
|
|
|
const url = new URL(request.url, 'http://studio.invalid');
|
|
const requested = String(request.headers['x-aura-tenant'] || url.searchParams.get('tenant') ||
|
|
cookieValue(request.headers.cookie, 'aura_active_tenant') || '').trim();
|
|
if (requested.length > 256 || /[\r\n]/.test(requested)) {
|
|
throw fail(400, 'INVALID_WORKSPACE', 'Workspace নির্বাচন সঠিক নয়।');
|
|
}
|
|
const privileged = user.role === 'owner' || user.role === 'admin';
|
|
if (privileged && !requested) {
|
|
throw fail(409, 'WORKSPACE_REQUIRED', 'এই কাজের জন্য আগে একটি client workspace নির্বাচন করুন।');
|
|
}
|
|
|
|
// Client's existing gate owns membership/owner-switch decisions. Never trust a supplied client ID.
|
|
const headers = { Cookie: 'aura_access=' + encodeURIComponent(token), Accept: 'application/json' };
|
|
if (privileged && requested) headers['x-aura-tenant'] = requested;
|
|
const context = await read(clientUrl, headers);
|
|
if (context?.success !== true || typeof context.tenant !== 'string' || !context.tenant.trim() || context.tenant.length > 256 ||
|
|
typeof context.clientId !== 'string' || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(context.clientId)) {
|
|
throw fail(403, 'WORKSPACE_UNAVAILABLE', 'আপনার workspace প্রস্তুত বা অনুমোদিত নয়।');
|
|
}
|
|
if (!context.actor || context.actor.id !== user.id || context.actor.role !== user.role ||
|
|
typeof context.actor.email !== 'string' || context.actor.email.trim().toLowerCase() !== user.email.trim().toLowerCase()) {
|
|
throw fail(401, 'SESSION_CHANGED', 'Account-এর তথ্য বদলেছে; আবার login করুন।');
|
|
}
|
|
const tenant = context.tenant.trim().toLowerCase();
|
|
const clientId = context.clientId.toLowerCase();
|
|
const workspace = {
|
|
tenant, clientId,
|
|
namespace: createHash('sha256').update('client:' + clientId).digest('hex'),
|
|
userId: user.id,
|
|
role: context.role,
|
|
canWriteProducts: context.perms?.products === true,
|
|
displayName: typeof context.clientName === 'string' ? context.clientName : ''
|
|
};
|
|
if (catalogUrl) workspace.readConnectedCatalog = async () => {
|
|
let catalog;
|
|
try { catalog = await read(catalogUrl, { ...headers, 'x-aura-tenant': tenant }, 16 * 1024 * 1024, 35000); }
|
|
catch { throw fail(503, 'CONNECTED_CATALOG_UNAVAILABLE', 'Connected catalog এখন পড়া যায়নি; আগের data মুছে দেওয়া হয়নি।'); }
|
|
if (catalog?.success !== true || typeof catalog.clientId !== 'string' || catalog.clientId.toLowerCase() !== clientId || typeof catalog.tenant !== 'string' || catalog.tenant.toLowerCase() !== tenant) {
|
|
throw fail(403, 'CATALOG_WORKSPACE_MISMATCH', 'Catalog-এর workspace মেলেনি।');
|
|
}
|
|
return catalog;
|
|
};
|
|
return workspace;
|
|
};
|
|
}
|
|
|
|
function requireProductWrite(workspace) {
|
|
if (workspace.canWriteProducts !== true) {
|
|
throw fail(403, 'CATALOG_PERMISSION_REQUIRED', 'এই workspace-এর product পরিবর্তনের অনুমতি প্রয়োজন।');
|
|
}
|
|
}
|
|
|
|
module.exports = { createWorkspaceResolver, requireProductWrite, fail };
|