Files
adminandClaude Opus 5.5 3802cc9114 Be our own edge: headers, Open Graph and the console from the backend, no Caddy
The platform is dropping Caddy (Atrium's backend becomes the front door and
forwards /galena/* with the prefix stripped), and the standalone stack drops
it too, so the backend now answers for everything Caddy added.

- app/edge.py: SecurityHeaders, pure ASGI and outermost, stamps every
  response (errors included): the console CSP character for character as
  Caddy sent it, with frame-ancestors from FRAME_ANCESTORS; X-Frame-Options
  DENY or SAMEORIGIN to match; nosniff, Referrer-Policy same-origin, COOP,
  no-cache on the console. The ReaderJS viewer keeps _READER_CSP and
  SAMEORIGIN regardless of the setting. /raw keeps its own sandbox CSP.
- FRAME_ANCESTORS is 'none' (default) or 'self'; anything else refuses to
  start. GALENA_FRAME_ANCESTORS now refuses to start and names the new knob,
  so there is one switch.
- ConsoleFiles: the try_files fallback, plus the Open Graph tags Caddy's
  `templates` rendered, now from GALENA_PUBLIC_URL or scheme://Host +
  root_path (so the /galena prefix is right), HTML-escaped, ETag/304.
- CompressibleGZip skips /raw downloads and images; BodySizeLimit caps a
  request at 100 MB (MAX_FILE_BYTES stays the stricter content limit).
- ProblemDetailErrorMiddleware is pure ASGI, so small answers stay small.
- Dockerfile: frontend as a named build context; uvicorn with
  --proxy-headers, --forwarded-allow-ips and --no-server-header.
- Standalone compose publishes the backend on :80; Caddyfile deleted;
  compose-smoke asserts the new headers and a rendered og:url.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 16:06:40 +02:00

395 lines
34 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* Galena DEMO mock — makes the static console fully clickable with NO backend.
*
* This script is loaded ONLY on the demo deployment (the Netlify build injects it before app.js when
* GALENA_DEMO=1; see netlify/prepare.sh). It patches window.fetch to intercept every /api/v1/* call
* and answer from a seeded in-memory dataset persisted to localStorage, so login, browsing, editing,
* dashboard, drafts, search and notifications all work in the browser. It is a SIMULATION: history is
* canned, data is per-browser, and "Reset demo" wipes it. It never ships in a real deployment (the
* Docker build serves index.html without this <script>), so it can't weaken a real backend.
*/
(function () {
'use strict';
if (window.__galenaDemo) return; window.__galenaDemo = true;
// Same derivation as app.js: the interceptor below matches on this prefix, so it has to agree with
// the base the console actually calls. /api/v1 on the demo site (served at its root), /galena/api/v1
// if the console is ever served under a path prefix.
var API = new URL('api/v1', document.baseURI).pathname;
var LS = 'galena_demo_db_v1', SESS = 'galena_demo_session';
// ── seed dataset ────────────────────────────────────────────────────────────
// A real, valid 2-page PDF (base64) so the demo shows PDF preview working out of the box —
// stored exactly like a binary upload (data URL) and decoded by /raw → rendered by PDF.js.
var SAMPLE_PDF = 'data:application/pdf;base64,JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFszIDAgUiA2IDAgUl0gL0NvdW50IDIgPj4KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCAyIDAgUiAvTWVkaWFCb3ggWzAgMCA0MjAgNTk1XSAvUmVzb3VyY2VzIDw8IC9Gb250IDw8IC9GMSA1IDAgUiA+PiA+PiAvQ29udGVudHMgNCAwIFIgPj4KZW5kb2JqCjQgMCBvYmoKPDwgL0xlbmd0aCA4NiA+PgpzdHJlYW0KQlQgL0YxIDIyIFRmIDYwIDUyMCBUZCAoR2FsZW5hIC0gc2FtcGxlIFBERikgVGogMCAtMzQgVGQgL0YxIDE0IFRmIChQYWdlIDEgb2YgMikgVGogRVQKZW5kc3RyZWFtCmVuZG9iago1IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UeXBlMSAvQmFzZUZvbnQgL0hlbHZldGljYSA+PgplbmRvYmoKNiAwIG9iago8PCAvVHlwZSAvUGFnZSAvUGFyZW50IDIgMCBSIC9NZWRpYUJveCBbMCAwIDQyMCA1OTVdIC9SZXNvdXJjZXMgPDwgL0ZvbnQgPDwgL0YxIDUgMCBSID4+ID4+IC9Db250ZW50cyA3IDAgUiA+PgplbmRvYmoKNyAwIG9iago8PCAvTGVuZ3RoIDEwMCA+PgpzdHJlYW0KQlQgL0YxIDIyIFRmIDYwIDUyMCBUZCAoUmVuZGVyZWQgYnkgUERGLmpzIGluIHRoZSBicm93c2VyKSBUaiAwIC0zNCBUZCAvRjEgMTQgVGYgKFBhZ2UgMiBvZiAyKSBUaiBFVAplbmRzdHJlYW0KZW5kb2JqCnhyZWYKMCA4CjAwMDAwMDAwMDAgNjU1MzUgZiAKMDAwMDAwMDAwOSAwMDAwMCBuIAowMDAwMDAwMDU4IDAwMDAwIG4gCjAwMDAwMDAxMjEgMDAwMDAgbiAKMDAwMDAwMDI0NyAwMDAwMCBuIAowMDAwMDAwMzgzIDAwMDAwIG4gCjAwMDAwMDA0NTMgMDAwMDAgbiAKMDAwMDAwMDU3OSAwMDAwMCBuIAp0cmFpbGVyCjw8IC9TaXplIDggL1Jvb3QgMSAwIFIgPj4Kc3RhcnR4cmVmCjczMAolJUVPRg==';
// nda.md (Contracts) ships two versions so the Changes (ReaderJS compare) view shows a real diff.
// Defined once here: NDA_NEW is the file's current content AND the newest version; NDA_OLD is served
// for the older ref. Editing the NDA text in one place keeps raw/blame/changes/history consistent.
var NDA_OLD = '# Mutual NDA\n\n## 1. Purpose\n\nThe parties wish to explore a business relationship.\n\n## 2. Confidentiality\n\nEach party agrees to keep the other’s information secret.\n';
var NDA_NEW = '# Mutual NDA\n\n## 1. Purpose\n\nThe parties wish to explore a potential business relationship.\n\n## 2. Confidentiality\n\nEach party agrees to keep the other’s information confidential and not to disclose it to any third party.\n\n## 3. Term\n\nThis agreement remains in effect for two years.\n';
function seed() {
var users = [
{ id: 'u-admin', email: 'admin@example.com', full_name: 'Demo Admin', is_admin: true, is_active: true },
{ id: 'u-jane', email: 'jane@acme.test', full_name: 'Jane Approver', is_admin: false, is_active: true },
{ id: 'u-bob', email: 'bob@acme.test', full_name: 'Bob Viewer', is_admin: false, is_active: true }
];
// node tree (flat map; children derived via parent_id)
var nodes = {};
function N(id, name, kind, parent, opts) {
nodes[id] = Object.assign({ id: id, name: name, kind: kind, parent_id: parent || null,
access: 'open', encrypted: false, favorite: false, review_policy: 'open', encryption_mode: 'none' }, opts || {});
}
N('n-personal', 'My files', 'workspace', null);
N('n-personal-notes', 'My Notes', 'project', 'n-personal');
N('n-acme', 'Acme', 'workspace', null);
N('n-legal', 'Legal', 'group', 'n-acme');
N('n-contracts', 'Contracts', 'project', 'n-legal', { review_policy: 'review_required' });
N('n-brand', 'Brand Assets', 'project', 'n-acme');
N('n-eng', 'Engineering', 'workspace', null);
N('n-docs', 'Docs', 'project', 'n-eng');
// files per project
var files = {
'n-personal-notes': [
{ path: 'welcome.md', content: '# Welcome to Galena\n\nThis is a **demo**. Everything you see runs in your browser — no backend.\n\n- Browse the workspaces on the left\n- Open and edit a file\n- Try the Dashboard, Drafts and search\n' },
{ path: 'todo.txt', content: 'Demo to-do:\n- explore the version graph\n- open the .docx file\n- check the review thread\n' },
{ path: 'budget.csv', content: 'Item,Q1,Q2,Q3\nRevenue,120,135,150\nCosts,80,90,95\nProfit,40,45,55\n' },
{ path: 'settings.json', content: '{\n "theme": "system",\n "autosave": true,\n "tabSize": 2,\n "plugins": ["search", "ocr"],\n "limits": { "uploadMb": 50, "retries": 3 }\n}\n' },
{ path: 'sample.pdf', content: SAMPLE_PDF }
],
'n-contracts': [
{ path: 'nda.md', content: NDA_NEW },
// `content` = the extracted Markdown the office editor edits; `raw` = a real .docx (ZIP) the
// ReaderJS viewer renders via /raw (serving the Markdown as a .docx makes JSZip fail to unzip).
{ path: 'q1-report.docx', office: 'docx', content: '# Q1 Report\n\nRevenue is **up 18%** quarter over quarter.\n\n- New customers: 42\n- Churn: 1.2%\n\n## Outlook\n\nWe expect continued growth in Q2.\n',
raw: 'data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,UEsDBBQAAAAIADCj2lzJTxqw6wAAAK4BAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbH1QvU7DMBDeeQrLK4odGBBCSTrwMwJDeYCTfUks7LPlc0v79jht6YAK4933q69b7YIXW8zsIvXyRrVSIJloHU29/Fi/NPdScAGy4CNhL/fIcjVcdet9QhZVTNzLuZT0oDWbGQOwigmpImPMAUo986QTmE+YUN+27Z02kQpSacriIYfuCUfY+CKed/V9LJLRsxSPR+KS1UtIyTsDpeJ6S/ZXSnNKUFV54PDsEl9XgtQXExbk74CT7q0uk51F8Q65vEKoLP0Vs9U2mk2oSvW/zYWecRydwbN+cUs5GmSukwevzkgARz/99WHu4RtQSwMEFAAAAAgAMKPaXLmBRHGwAAAAKgEAAAsAAABfcmVscy8ucmVsc43POw7CMAwG4J1TRN5pWgaEUJMuCKkrKgeIEjeNaB5KwqO3JwMDIAZG278/y233sDO5YUzGOwZNVQNBJ70yTjM4D8f1DkjKwikxe4cMFkzQ8VV7wlnkspMmExIpiEsMppzDntIkJ7QiVT6gK5PRRytyKaOmQciL0Eg3db2l8d0A/mGSXjGIvWqADEvAf2w/jkbiwcurRZd/nPhKFFlEjZnB3UdF1atdFRYob+nHi/wJUEsDBBQAAAAIADCj2lx2p6RRJAEAAJwCAAARAAAAd29yZC9kb2N1bWVudC54bWytUk1PwzAMvfMrrEg70qwFoSlauwMSR9gmEOcsNWtFE4d8tBu/nrQTcJm0yy7Psh2/92RnuTroDnp0viVTsjybM0CjqG7NvmRvr0+3CwY+SFPLjgyW7Iieraqb5SBqUlGjCZAYjBdDyZoQrODcqwa19BlZNKn3QU7LkFK35wO52jpS6H0S0B0v5vMHrmVrWJUod1Qfx2hHcBOsp7DjI/pvGEQvu5LdFSxV+F9/MiG8lSpZtA49uh5Ztclhi5ZcGJ+G08CE9ozKRbYt9mgiQushWsgXM/iK0gV0QGmBv0l2Fa1nHEBFH0in0wi4LzJ4bKIzAvKsmF1H4yWGjujzKlzvCHiwqAIoMqFNa6ph72gIDbQGNsV5xz4NrN3pkqfb8/9/Vf0AUEsBAhQAFAAAAAgAMKPaXMlPGrDrAAAArgEAABMAAAAAAAAAAAAAAIABAAAAAFtDb250ZW50X1R5cGVzXS54bWxQSwECFAAUAAAACAAwo9pcuYFEcbAAAAAqAQAACwAAAAAAAAAAAAAAgAEcAQAAX3JlbHMvLnJlbHNQSwECFAAUAAAACAAwo9pcdqekUSQBAACcAgAAEQAAAAAAAAAAAAAAgAH1AQAAd29yZC9kb2N1bWVudC54bWxQSwUGAAAAAAMAAwC5AAAASAMAAAAA' }
],
'n-brand': [
{ path: 'brand-guide.md', content: '# Brand Guide\n\nAccent is monochrome; the only brand colour is the violet app icon.\n' }
],
'n-docs': [
{ path: 'readme.md', content: '# Engineering Docs\n\nStart here.\n' },
{ path: 'architecture.md', content: '# Architecture\n\nFastAPI + PostgreSQL + GitPython, a static console, and a Slate editor bundle.\n' }
]
};
var drafts = [{
id: 'd-1', title: 'Tighten the confidentiality clause', project_id: 'n-contracts', project: 'Contracts',
author: 'Jane Approver', status: 'open', target_version: 'main', source_version: 'version/jane',
files: ['nda.md'], can_approve: true, is_author: false, can_post: true,
messages: [
{ id: 'm0', kind: 'system', author: 'Jane Approver', body: 'submitted this draft', created_at: iso(-3600 * 26) },
{ id: 'm1', kind: 'comment', author: 'Jane Approver', body: 'Reworded section 2 for clarity — please review.', created_at: iso(-3600 * 25), file_path: 'nda.md', resolved: false }
]
}];
var notifications = [
{ id: 'no1', kind: 'review_requested', title: 'Review requested', body: 'Jane asked you to review “Tighten the confidentiality clause”.', created_at: iso(-3600 * 25), read: false, link: '#/drafts/d-1' },
{ id: 'no2', kind: 'draft_published', title: 'Draft published', body: 'Your change to readme.md was published.', created_at: iso(-3600 * 50), read: true, link: '#/n/n-docs' }
];
// App tokens — what the Word/Excel add-in creates so it never has to store a password. Seeded
// so Settings → Connected apps has something to show.
var tokens = [
{ id: 't-laptop', name: 'GalenaConnect on ROMAN-LAPTOP', prefix: 'galena_pat_a1b2c3',
scope: 'read_write', created_at: iso(-86400 * 9), last_used_at: iso(-3600 * 2),
expires_at: iso(86400 * 21), revoked_at: null, idle_days: 30 },
{ id: 't-desktop', name: 'GalenaConnect on OFFICE-PC', prefix: 'galena_pat_9f8e7d',
scope: 'read', created_at: iso(-86400 * 30), last_used_at: iso(-86400 * 4),
expires_at: iso(86400 * 26), revoked_at: null, idle_days: 30 }
];
return { user: users[0], users: users, nodes: nodes, files: files, drafts: drafts, notifications: notifications,
tokens: tokens, personal_id: 'n-personal', workspaces: ['n-acme', 'n-eng'] };
}
function iso(deltaSec) { return new Date(Date.now() + (deltaSec || 0) * 1000).toISOString(); }
// ── persistence ──────────────────────────────────────────────────────────────
var DB;
try { DB = JSON.parse(localStorage.getItem(LS)); } catch (e) {}
if (!DB || !DB.nodes) { DB = seed(); save(); }
function save() { try { localStorage.setItem(LS, JSON.stringify(DB)); } catch (e) {} }
function loggedIn() { try { return localStorage.getItem(SESS) === '1'; } catch (e) { return false; } }
function setSession(v) { try { v ? localStorage.setItem(SESS, '1') : localStorage.removeItem(SESS); } catch (e) {} }
// ── helpers ──────────────────────────────────────────────────────────────────
function J(data, status) { return new Response(JSON.stringify(data === undefined ? {} : data), { status: status || 200, headers: { 'Content-Type': 'application/json' } }); }
function E(status, detail) { return J({ type: 'about:blank', title: 'Error', status: status, detail: detail }, status); }
function children(id) { return Object.keys(DB.nodes).map(function (k) { return DB.nodes[k]; }).filter(function (n) { return n.parent_id === id; }); }
function pub(n) { return { id: n.id, name: n.name, kind: n.kind, path: pathOf(n.id), access: n.access, encrypted: n.encrypted, favorite: n.favorite, review_policy: n.review_policy, encryption_mode: n.encryption_mode }; }
function pathOf(id) { var parts = [], n = DB.nodes[id]; while (n) { parts.unshift(slug(n.name)); n = n.parent_id ? DB.nodes[n.parent_id] : null; } return '/' + parts.join('/'); }
function slug(s) { return String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, ''); }
function crumb(id) { var c = [], n = DB.nodes[id]; while (n) { c.unshift({ id: n.id, name: n.name }); n = n.parent_id ? DB.nodes[n.parent_id] : null; } return c; }
function projFiles(id) { return DB.files[id] || (DB.files[id] = []); }
function isOfficeEditable(p) { return /\.(docx|odt)$/i.test(p); }
function isOffice(p) { return /\.(docx|odt|rtf|doc)$/i.test(p); }
function rid(pre) { return pre + '-' + Math.random().toString(36).slice(2, 8); }
// ── router (async; returns a Response) ────────────────────────────────────────
async function route(method, p, q, body) {
// ---- auth ----
if (p === '/auth/login' && method === 'POST') { setSession(true); return J({ token: 'demo-token', user: DB.user }); }
if (p === '/auth/logout') { setSession(false); return J({}); }
if (p === '/auth/me') { return loggedIn() ? J(DB.user) : E(401, 'Not signed in.'); }
if (p === '/health' || p === '/healthz') return J({ status: 'ok', version: 'demo' });
if (p === '/meta') return J({ product: 'galena', version: 'demo', api_version: 1,
features: ['app_tokens', 'file_info', 'upload_base_sha', 'write_blob_sha', 'locks', 'ref_mine', 'recursive_tree'],
max_file_bytes: 67108864, session_ttl_hours: 12, app_token_idle_days: 30 });
// ---- app tokens (Settings → Connected apps) ----
if (p === '/auth/tokens' && method === 'GET')
return J((DB.tokens || []).filter(function (t) { return !t.revoked_at; }));
if (/^\/auth\/tokens\/[^/]+$/.test(p) && method === 'DELETE') {
var tid = p.split('/')[3];
DB.tokens = (DB.tokens || []).filter(function (t) { return t.id !== tid; });
save();
return J({ ok: true });
}
// ---- drive scopes ----
if (p === '/drive/home') return J({ personal_id: DB.personal_id, personal: pub(DB.nodes[DB.personal_id]), workspaces: DB.workspaces.map(function (id) { return pub(DB.nodes[id]); }) });
if (p === '/drive/favorites') return J(Object.keys(DB.nodes).map(function (k) { return DB.nodes[k]; }).filter(function (n) { return n.favorite; }).map(pub));
if (p === '/drive/shared') return J([]);
if (p === '/drive/recent') return J([{ action: 'redaction', detail: 'nda.md → main', at: iso(-3600 * 5) }, { action: 'auth.login', detail: '', at: iso(-60) }]);
// ---- nodes ----
var mNode = p.match(/^\/nodes\/([^/]+)$/);
if (mNode) {
var id = mNode[1];
if (method === 'GET') {
var n = DB.nodes[id]; if (!n) return E(404, 'Not found.');
var r = { node: pub(n), is_project: n.kind === 'project', breadcrumb: crumb(id), can_write: true, can_manage: true, can_approve: true };
if (n.kind !== 'project') r.children = children(id).map(pub);
return J(r);
}
if (method === 'PATCH') { if (DB.nodes[id] && body && body.name) DB.nodes[id].name = body.name; save(); return J({ ok: true }); }
if (method === 'DELETE') { delChildren(id); delete DB.nodes[id]; save(); return J({ ok: true }); }
}
if (p === '/nodes' && method === 'POST') {
var nid = rid('n'); DB.nodes[nid] = { id: nid, name: body.name, kind: body.kind, parent_id: body.parent_id || null,
access: 'open', encrypted: false, favorite: false, review_policy: 'open', encryption_mode: 'none' };
if (!body.parent_id && body.kind === 'workspace') DB.workspaces.push(nid);
if (body.kind === 'project') DB.files[nid] = [];
save(); return J({ id: nid, ok: true });
}
var mFav = p.match(/^\/nodes\/([^/]+)\/favorite$/);
if (mFav && method === 'POST') { var fn = DB.nodes[mFav[1]]; if (fn) fn.favorite = !fn.favorite; save(); return J({ ok: true }); }
var mPerm = p.match(/^\/nodes\/([^/]+)\/permissions$/);
if (mPerm) { if (method === 'GET') return J({ direct: [{ user_id: 'u-jane', name: 'Jane Approver', email: 'jane@acme.test', role: 'approver' }], inherited: [{ name: 'Demo Admin', from: 'Acme', role: 'manager', email: 'admin@example.com' }] }); return J({ ok: true }); }
if (/^\/nodes\/[^/]+\/(move|clone|request-access)$/.test(p)) return J({ ok: true });
if (/^\/nodes\/[^/]+\/permissions\/[^/]+$/.test(p) && method === 'DELETE') return J({ ok: true });
// ---- project files ----
var mTree = p.match(/^\/projects\/([^/]+)\/tree$/);
if (mTree) {
var entries = projFiles(mTree[1]).map(function (f) { return { name: f.path, path: f.path, type: 'file', size: (f.content || '').length, encrypted: false }; });
return J({ path: q.path || '', ref: q.ref || 'main', entries: entries, versions: projVersions(mTree[1]) });
}
var mVer = p.match(/^\/projects\/([^/]+)\/versions$/);
if (mVer && method === 'POST') { var vs = projVersions(mVer[1]); if (q.name && vs.indexOf(q.name) < 0) { vs.push(q.name); save(); } return J({ ok: true, version: q.name }); }
var mFile = p.match(/^\/projects\/([^/]+)\/file$/);
if (mFile) {
var pid = mFile[1];
if (method === 'GET') {
var f = projFiles(pid).find(function (x) { return x.path === q.path; });
if (!f) return E(404, 'File not found.');
if (isOfficeEditable(q.path)) return J({ path: q.path, ref: q.ref || 'main', binary: false, content: f.content, encrypted: false, office: { format: f.office || 'docx', editable: true, lossy: true } });
if (isOffice(q.path)) return J({ path: q.path, ref: q.ref || 'main', binary: true, content: '', encrypted: false, office: { format: 'rtf', editable: false } });
if (typeof f.content === 'string' && f.content.slice(0, 5) === 'data:') // binary (PDF/image/…) → no inline editor
return J({ path: q.path, ref: q.ref || 'main', binary: true, content: '', encrypted: false });
return J({ path: q.path, ref: q.ref || 'main', binary: false, content: f.content, encrypted: false });
}
if (method === 'POST') { writeFile(pid, body.path, body.content); save(); return J({ mode: DB.nodes[pid] && DB.nodes[pid].review_policy === 'review_required' ? 'working' : 'published', branch: 'main' }); }
if (method === 'DELETE') { DB.files[pid] = projFiles(pid).filter(function (x) { return x.path !== q.path; }); save(); return J({ ok: true }); }
}
var mOffice = p.match(/^\/projects\/([^/]+)\/office-file$/);
if (mOffice && method === 'POST') { var fo = projFiles(mOffice[1]).find(function (x) { return x.path === body.path; }); if (fo) fo.content = body.content; else writeFile(mOffice[1], body.path, body.content, 'docx'); save(); return J({ mode: 'published', branch: 'main' }); }
var mUp = p.match(/^\/projects\/([^/]+)\/upload$/);
if (mUp && method === 'POST' && body && body.get) {
var dest = body.get('dest') || (body.get('file') && body.get('file').name) || 'upload.bin';
var file = body.get('file'); var content = '';
if (file) {
if (_isBinaryName(dest)) { // keep binary intact (reading it as text mangles PDFs/images → blank preview)
content = 'data:' + (file.type || _mimeFromName(dest)) + ';base64,' + _b64FromBuf(await file.arrayBuffer());
} else {
content = file.text ? await file.text() : '';
}
}
writeFile(mUp[1], dest, content); save(); return J({ path: dest, mode: 'published', branch: 'main' });
}
if (/^\/projects\/[^/]+\/(move-file|copy-file|encrypt)$/.test(p)) return J({ ok: true });
if (/^\/projects\/[^/]+\/raw$/.test(p)) {
var rpid = p.split('/')[2];
var rver = versionAt(rpid, q.path, q.ref); // seeded older version → distinct bytes per ref (real diff)
var rf = projFiles(rpid).find(function (x) { return x.path === q.path; });
var c = (rf && rf.raw) ? rf.raw : (rver ? rver.content : (rf ? rf.content : '')); // rf.raw = a real binary (e.g. .docx) for the viewer
if (typeof c === 'string' && c.slice(0, 5) === 'data:') { // decode a stored binary data URL → real bytes
var comma = c.indexOf(','), mime = c.slice(5, comma).split(';')[0] || 'application/octet-stream';
var bs = atob(c.slice(comma + 1)), bytes = new Uint8Array(bs.length);
for (var bi = 0; bi < bs.length; bi++) bytes[bi] = bs.charCodeAt(bi);
return new Response(bytes, { headers: { 'Content-Type': mime } });
}
return new Response(c, { headers: { 'Content-Type': 'application/octet-stream' } });
}
// ---- history / changes (canned) ----
if (/^\/projects\/[^/]+\/graph$/.test(p)) { var gpid = p.split('/')[2]; return J({ main: 'main', versions: projVersions(gpid), tips: { main: 'a1b2c3d4' }, commits: cannedCommits() }); }
if (/^\/projects\/[^/]+\/history$/.test(p)) return J(cannedCommits());
if (/^\/projects\/[^/]+\/changed$/.test(p)) return J(['nda.md']);
if (/^\/projects\/[^/]+\/changes$/.test(p)) { var cc = diffCounts(p.split('/')[2], q.path, q.a, q.b); return J({ binary: false, rows: [], merged: [], added: cc ? cc.added : 0, removed: cc ? cc.removed : 0 }); }
if (/^\/projects\/[^/]+\/blame$/.test(p)) return J(demoBlame(p.split('/')[2], q.path, q.ref));
if (/^\/projects\/[^/]+\/(submit-draft|combine)$/.test(p)) return J({ ok: true });
// ---- drafts ----
if (p === '/drafts' && method === 'GET') return J(DB.drafts.map(function (d) { return { id: d.id, title: d.title, project: d.project, author: d.author, status: d.status, for_me: d.can_approve }; }));
var mDraft = p.match(/^\/drafts\/([^/]+)$/);
if (mDraft && method === 'GET') { var d = DB.drafts.find(function (x) { return x.id === mDraft[1]; }); if (!d) return E(404, 'Draft not found.'); return J({ draft: { title: d.title, status: d.status, target_version: d.target_version, source_version: d.source_version }, project: { id: d.project_id, name: d.project }, author: d.author, files: d.files, messages: d.messages, can_approve: d.can_approve, is_author: d.is_author, can_post: d.can_post }); }
var mDraftAct = p.match(/^\/drafts\/([^/]+)\/(publish|reject|withdraw|resolve|messages)$/);
if (mDraftAct && method === 'POST') {
var dr = DB.drafts.find(function (x) { return x.id === mDraftAct[1]; }); var act = mDraftAct[2];
if (dr && act === 'publish') { dr.status = 'published'; save(); return J({ ok: true }); }
if (dr && act === 'reject') { dr.status = 'rejected'; save(); return J({ ok: true }); }
if (dr && act === 'withdraw') { dr.status = 'withdrawn'; save(); return J({ ok: true }); }
if (dr && act === 'resolve') { dr.status = 'published'; save(); return J({ ok: true }); }
if (dr && act === 'messages') { var msg = { id: rid('m'), kind: 'comment', author: DB.user.full_name, body: (body && body.body) || '', parent_id: (body && body.parent_id) || null, created_at: iso(0) }; dr.messages.push(msg); save(); return J(msg); }
}
if (/^\/drafts\/[^/]+\/messages\/[^/]+\/resolve$/.test(p)) return J({ resolved: !!(body && body.resolved) });
if (/^\/drafts\/[^/]+\/conflict$/.test(p)) return J({ path: q.path, main: '', incoming: '' });
// ---- dashboard / notifications / search / admin ----
if (p === '/dashboard') return J(dashboard());
if (p === '/notifications/unread') return J({ unread: DB.notifications.filter(function (n) { return !n.read; }).length });
if (p === '/notifications' && method === 'GET') return J({ items: DB.notifications });
if (p === '/notifications/read-all') { DB.notifications.forEach(function (n) { n.read = true; }); save(); return J({ ok: true }); }
if (/^\/notifications\/[^/]+\/read$/.test(p)) { var nid2 = p.split('/')[2]; var nt = DB.notifications.find(function (n) { return n.id === nid2; }); if (nt) nt.read = true; save(); return J({ ok: true }); }
if (p === '/notifications/prefs') return J({ inapp: true, webpush: false, email: false, push_available: false });
if (p === '/notifications/subscribe') return J({ ok: true });
if (p === '/search') return J({ hits: search(q.q || '') });
if (p === '/plugins') return J([]); // no plugins on the demo
if (p === '/admin/plugins') return J({ plugins: [], plugins_dir: '(demo — no plugins)' });
if (p === '/admin/backup') return method === 'GET'
? J({ config: { enabled: false, interval: 'daily', storage: 'local', retention: 7 }, storage: { ok: true, location: '(demo — in-browser, not persisted)' }, backups: [] })
: J({ ok: true });
if (p === '/users' && method === 'GET') return J(DB.users);
if (p === '/users' && method === 'POST') { var u = { id: rid('u'), email: body.email, full_name: body.full_name, is_admin: !!body.is_admin, is_active: true }; DB.users.push(u); save(); return J(u); }
if (/^\/users\/[^/]+/.test(p)) return J({ ok: true });
if (p === '/admin/nodes') return J(Object.keys(DB.nodes).map(function (k) { return { id: k, name: DB.nodes[k].name, kind: DB.nodes[k].kind, path: pathOf(k) }; }));
if (p === '/admin/settings') return method === 'GET'
? J({ default_review_policy: 'open', git_author_name: 'Galena', git_author_email: 'galena@localhost', storage_backend: 'demo (in-browser)', data_dir: '(demo)', encryption_enabled: false })
: J({ ok: true });
if (/^\/admin\/users\/[^/]+\/grants/.test(p)) return method === 'GET' ? J([]) : J({ ok: true });
// ---- graceful fallback ----
return method === 'GET' ? J({}) : J({ ok: true });
}
function projVersions(pid) { DB.versions = DB.versions || {}; return DB.versions[pid] || (DB.versions[pid] = ['main']); }
// Binary-file handling: store uploaded PDFs/images as a base64 data URL (reading them as text
// mangles the bytes → a blank PDF/broken image), and decode it back in /raw.
function _isBinaryName(n) { var e = (String(n).split('.').pop() || '').toLowerCase(); return ['pdf', 'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'tif', 'tiff', 'doc', 'docx', 'odt', 'xls', 'xlsx', 'ppt', 'pptx', 'djvu', 'djv', 'zip', 'bin'].indexOf(e) >= 0; }
function _mimeFromName(n) { var e = (String(n).split('.').pop() || '').toLowerCase(); return { pdf: 'application/pdf', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', bmp: 'image/bmp' }[e] || 'application/octet-stream'; }
function _b64FromBuf(buf) { var b = new Uint8Array(buf), s = '', CH = 0x8000; for (var i = 0; i < b.length; i += CH) s += String.fromCharCode.apply(null, b.subarray(i, i + CH)); return btoa(s); }
function writeFile(pid, path, content, office) {
var arr = projFiles(pid); var f = arr.find(function (x) { return x.path === path; });
if (f) { f.content = content; } else { arr.push({ path: path, content: content, office: office || (isOfficeEditable(path) ? 'docx' : undefined) }); }
}
function delChildren(id) { children(id).forEach(function (c) { delChildren(c.id); delete DB.nodes[c.id]; }); }
function cannedCommits() {
return [
{ sha: 'a1b2c3d4ee', short: 'a1b2c3d4', message: 'Reword confidentiality clause', author: 'Jane Approver', email: 'jane@acme.test', date: iso(-3600 * 25), parents: ['00112233'] },
{ sha: '00112233ff', short: '00112233', message: 'Add NDA template', author: 'Demo Admin', email: 'admin@example.com', date: iso(-3600 * 80), parents: [] }
];
}
// Two-version sample(s) so the Changes (ReaderJS compare) view shows a REAL diff with blame. Keyed
// pid→path, ordered oldest→newest; each redaction lines up with a canned-commit short. The newest
// version's content matches the file's current content above. Only seeded files get versions; every
// other file falls back to its single current content (no diff), as before.
var _VER;
function fileVersions(pid, path) {
if (!_VER) _VER = {
'n-contracts': { 'nda.md': [
{ short: '00112233', author: 'Demo Admin', date: iso(-3600 * 80), message: 'Add NDA template', content: NDA_OLD },
{ short: 'a1b2c3d4', author: 'Jane Approver', date: iso(-3600 * 25), message: 'Reword confidentiality clause', content: NDA_NEW }
] }
};
return (_VER[pid] || {})[path] || null;
}
function versionAt(pid, path, ref) { // a seeded version matching ref, else the newest (= main)
var vs = fileVersions(pid, path); if (!vs) return null;
if (ref && ref !== 'main') for (var i = 0; i < vs.length; i++) { var s = vs[i].short; if (s === ref || s.indexOf(ref) === 0 || ref.indexOf(s) === 0) return vs[i]; }
return vs[vs.length - 1];
}
function demoBlame(pid, path, ref) { // per-line authorship of the version at `ref` (new side)
var vs = fileVersions(pid, path); if (!vs) return [];
var target = versionAt(pid, path, ref), visible = vs.slice(0, vs.indexOf(target) + 1);
var sets = visible.map(function (v) { var s = {}; v.content.split('\n').forEach(function (l) { s[l] = 1; }); return s; }); // line-membership per version
return target.content.replace(/\n+$/, '').split('\n').map(function (line) {
var v = target; for (var i = 0; i < visible.length; i++) if (sets[i][line]) { v = visible[i]; break; } // earliest version that has this line
return { author: v.author, short: v.short, date: v.date, text: line };
});
}
function diffCounts(pid, path, a, b) { // crude line-set +/− for the Changes header (demo only)
var va = versionAt(pid, path, a), vb = versionAt(pid, path, b); if (!va && !vb) return null;
var setA = {}, added = 0, removed = 0;
(va ? va.content : '').split('\n').forEach(function (l) { setA[l] = 1; });
var setB = {}; (vb ? vb.content : '').split('\n').forEach(function (l) { setB[l] = 1; if (l && !setA[l]) added++; });
(va ? va.content : '').split('\n').forEach(function (l) { if (l && !setB[l]) removed++; });
return { added: added, removed: removed };
}
function dashboard() {
var act = []; for (var i = 13; i >= 0; i--) act.push({ day: i, redactions: (i % 4), drafts: (i % 3 === 0 ? 1 : 0), publishes: (i % 5 === 0 ? 1 : 0) });
return {
cards: { workspaces: DB.workspaces.length, active_users: DB.users.length, open_drafts: DB.drafts.filter(function (d) { return d.status === 'open'; }).length, storage_used: 2.4 * 1024 * 1024, storage_quota: 1024 * 1024 * 1024 },
activity: act,
file_types: [{ ext: 'md', count: 5 }, { ext: 'docx', count: 1 }, { ext: 'txt', count: 1 }],
approvals_waiting: DB.drafts.filter(function (d) { return d.status === 'open' && d.can_approve; }).map(function (d) { return { author: d.author, project: d.project, created_at: d.messages[0].created_at, draft_id: d.id, title: d.title }; }),
storage_by_workspace: [{ name: 'Acme', bytes: 1.6 * 1024 * 1024 }, { name: 'Engineering', bytes: 0.6 * 1024 * 1024 }, { name: 'My files', bytes: 0.2 * 1024 * 1024 }],
recent: [{ actor: 'Jane Approver', action: 'submitted a draft', detail: 'Contracts', at: iso(-3600 * 25) }, { actor: 'Demo Admin', action: 'published', detail: 'readme.md', at: iso(-3600 * 50) }]
};
}
function search(qstr) {
var s = qstr.toLowerCase(); if (!s) return [];
var hits = [];
Object.keys(DB.nodes).forEach(function (k) { var n = DB.nodes[k]; if (n.name.toLowerCase().indexOf(s) >= 0) hits.push({ type: 'node', id: n.id, name: n.name, kind: n.kind, path: pathOf(n.id) }); });
Object.keys(DB.files).forEach(function (pid) { projFiles(pid).forEach(function (f) { if (f.path.toLowerCase().indexOf(s) >= 0 || (f.content || '').toLowerCase().indexOf(s) >= 0) hits.push({ type: 'file', project_id: pid, project: (DB.nodes[pid] || {}).name || '', path: f.path, folder: '', name: f.path }); }); });
return hits.slice(0, 20);
}
// ── patch fetch ────────────────────────────────────────────────────────────
var realFetch = window.fetch ? window.fetch.bind(window) : null;
window.fetch = function (input, init) {
try {
var url = (typeof input === 'string') ? input : (input && input.url);
var u = new URL(url, location.origin);
if (u.pathname.indexOf(API) === 0) {
var method = ((init && init.method) || (input && input.method) || 'GET').toUpperCase();
var path = u.pathname.slice(API.length);
var qy = {}; u.searchParams.forEach(function (v, k) { qy[k] = v; });
var b = init && init.body;
if (typeof b === 'string') { try { b = JSON.parse(b); } catch (e) {} }
return route(method, path, qy, b).catch(function (e) { return E(500, String(e && e.message || e)); });
}
} catch (e) { /* fall through */ }
return realFetch ? realFetch(input, init) : Promise.reject(new Error('fetch unavailable'));
};
// ── demo banner + reset ──────────────────────────────────────────────────────
function banner() {
if (document.getElementById('galenaDemoBar')) return;
var bar = document.createElement('div'); bar.id = 'galenaDemoBar';
bar.style.cssText = 'position:fixed;bottom:12px;left:50%;transform:translateX(-50%);z-index:9999;' +
'display:flex;align-items:center;gap:10px;padding:7px 12px;border-radius:999px;font:12px/1 system-ui,sans-serif;' +
'background:rgba(20,20,24,.88);color:#f4f4f5;border:1px solid rgba(255,255,255,.18);box-shadow:0 4px 18px rgba(0,0,0,.35)';
bar.innerHTML = '<span>Demo — sample data, no backend.</span>' +
'<button id="galenaDemoReset" style="cursor:pointer;background:#5f3dc4;color:#fff;border:0;border-radius:999px;padding:4px 10px;font:600 12px system-ui">Reset</button>';
document.body.appendChild(bar);
document.getElementById('galenaDemoReset').onclick = function () {
try { localStorage.removeItem(LS); localStorage.removeItem(SESS); } catch (e) {}
location.reload();
};
}
// prefill the login form with the demo credentials (any credentials work anyway)
function prefill() {
var e = document.getElementById('email'), p = document.getElementById('password');
if (e && !e.value) e.value = 'admin@example.com';
if (p && !p.value) p.value = 'admin12345';
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', function () { banner(); prefill(); });
else { banner(); prefill(); }
console.info('[galena-demo] in-browser mock active — no backend. Reset clears localStorage.');
})();