const FB_SOURCE = 'files'; function normalizePath(path) { const raw = String(path || '/').trim(); const parts = raw.split('/').filter(Boolean); const clean = []; for (const part of parts) { if (part === '.') continue; if (part === '..') throw new Error('Invalid path'); clean.push(part); } return `/${clean.join('/')}`; } function joinPath(...parts) { return normalizePath(parts.join('/')); } function parentDir(path) { const parts = normalizePath(path).split('/').filter(Boolean); parts.pop(); return `/${parts.join('/')}`; } function safeName(value) { return String(value || '') .trim() .replace(/[\\/:*?"<>|#%{}^~[\]`]+/g, '-') .replace(/\s+/g, ' ') .replace(/^-+|-+$/g, ''); } function getConfig() { const url = String(process.env.FILEBROWSER_URL || '').trim().replace(/\/+$/, ''); return { url, token: process.env.FILEBROWSER_TOKEN || '', clientRoot: normalizePath(process.env.FILEBROWSER_CLIENT_ROOT || '/fourgebranding/Clients'), configured: Boolean(url), }; } async function fbFetch(config, method, endpoint, { params = {}, headers = {}, body } = {}) { const qs = new URLSearchParams({ source: FB_SOURCE, ...params }).toString(); const res = await fetch(`${config.url}${endpoint}?${qs}`, { method, headers: { Authorization: `Bearer ${config.token}`, ...headers }, body, }); if (!res.ok) { const text = await res.text(); const err = new Error(text || `FileBrowser ${res.status}`); err.status = res.status; throw err; } } async function mkdir(config, parentPath, name) { const folderPath = joinPath(parentPath, safeName(name)); await fbFetch(config, 'POST', '/api/resources', { params: { path: folderPath, isDir: 'true' }, }).catch(() => {}); } async function renameFolder(config, oldName, newName) { const oldSafe = safeName(oldName); const newSafe = safeName(newName); if (!oldSafe || !newSafe || oldSafe === newSafe) return; const fromPath = joinPath(config.clientRoot, oldSafe); const toPath = joinPath(config.clientRoot, newSafe); await fbFetch(config, 'PATCH', '/api/resources', { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'rename', items: [{ fromSource: FB_SOURCE, fromPath, toSource: FB_SOURCE, toPath }], overwrite: false, }), }).catch(() => {}); } export default async function handler(req, res) { if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' }); const secret = process.env.SUPABASE_WEBHOOK_SECRET; if (secret) { const incoming = req.headers['x-webhook-secret'] || req.headers['x-supabase-webhook-secret'] || ''; if (incoming.trim() !== secret.trim()) return res.status(401).json({ error: 'Unauthorized' }); } const { type, record, old_record } = req.body || {}; if (!record?.name) return res.status(200).json({ ok: true, skipped: true }); const config = getConfig(); if (!config.configured || !config.token) return res.status(200).json({ ok: true, skipped: 'not configured' }); const clientRoot = config.clientRoot; const clientsParent = parentDir(clientRoot); const clientsDirName = clientRoot.split('/').filter(Boolean).pop(); // Ensure parent Clients dir exists await mkdir(config, clientsParent, clientsDirName); if (type === 'UPDATE' && old_record?.name && old_record.name !== record.name) { await renameFolder(config, old_record.name, record.name); } // Always ensure folder for current name exists (idempotent) await mkdir(config, clientRoot, record.name); res.status(200).json({ ok: true, type, name: record.name }); }