Files
adminandClaude Opus 5.5 1dd6b4a724 No third-party code in Galena's origin, no session token in the console (Atrium#68, R2)
- ReaderJS, tesseract.js (+ WASM core, language models) and PDF.js are served by
  Galena from static/: backend/scripts/fetch_vendor.py fetches them at image build
  (Dockerfile `vendor` stage, Netlify prepare, local dev) - ReaderJS by full commit
  SHA through git, the npm tarballs at exact versions checked against their
  integrity hashes; a mismatch fails the build. tesseract.js was loaded as `@5`.
- The console and reader CSPs name no CDN; READERJS_DEFAULT_BASE is `dist/`, the
  shell-relative own copy (a remote, immutable override still works).
- POST /auth/login returns the raw session token only with `issue_token: true`
  (Galena Connect asks); the console signs in by the httpOnly cookie alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 16:40:25 +01:00

49 KiB
Raw Permalink Blame History

Galena

Galena — a self-hosted, git-backed cloud drive

A self-hosted, git-backed cloud drive. It looks and feels like an ordinary file store — workspaces, folders, drag-and-drop, sharing, a dashboard — but every file lives in a real git repository underneath, so you get full version history, side-by-side comparison, review, and rollback without anyone needing to know git.

License: Apache-2.0 · Stack: FastAPI + SQLAlchemy + PostgreSQL + GitPython, a single static console, and a small Slate editor bundle.

Live demo: galena.netlify.app — a fully clickable in-browser demo: Galena's real console running against a built-in mock, with no backend (sample data lives in your browser and resets on Reset). Sign in with anything — e.g. admin@example.com / admin12345. See Hosting on Netlify for demo mode vs. a real backend.

The UI design system is adapted from the sibling Counsel Scorecard project. Layout ideas were inspired by Cloudreve, ClovaLink, and Nextcloud — no code or assets from them were used (see CREDITS.md).

📖 For a feature-by-feature description of what Galena does and how people use it, see FUNCTIONAL.md.


Quick start

cp .env.example .env          # then replace every change_me_* value
# generate an encryption master key and paste it into ENCRYPTION_MASTER_KEY:
python -c "import os,base64;print(base64.b64encode(os.urandom(32)).decode())"
DREDD_CORE_TOKEN=github_pat_... docker compose up -d --build  # postgres -> migrate(+seed) -> backend

Building the image needs DREDD_CORE_TOKEN (a read-only fine-grained PAT for Alpaq92/dredd-core) in your shell — compose hands it to the build as a BuildKit secret, so it never lands in an image layer. Don't put it in .env: the backend containers (migrate, backend) load that file at runtime. CI's compose-smoke job runs exactly this stack on every push.

Open http://localhost:8021/ and sign in with BOOTSTRAP_ADMIN_EMAIL / BOOTSTRAP_ADMIN_PASSWORD. API docs are at http://localhost:8021/api/v1/docs. Only the backend is published (host port 8021 — the family numbers ports app / db / static per app, Galena 8012 / 8014 / 8021, so sibling stacks run side by side) — it serves the API, the console and its own security headers; Postgres is internal.


What it is

Requirement How it's delivered
Cloud-drive GUI NextCloud/Cloudreve-style left sidebar (My files · Favourites · Shared with me · Recent · a Workspaces tree that expands at every level · Storage) + a top toolbar whose right side holds the app actions (Dashboard · Drafts · Administration). Folders render as a grid of cards (also compact + list views).
Hierarchy Workspace → Group / Folder → Project. A Project is a git repository; everything above it is an organizational, permission-controlled container (GitLab-group style). Drag-and-drop to move items between containers (and documents between folders); turn an empty folder into a project (blocked if it contains a project — projects can't nest).
Git, de-jargoned commit = redaction, branch = version (default = main version), proposal = draft, merge = publish, branch→branch merge = combine versions, conflict resolution = resolve discrepancies, blame = authorship, diff = changes; a pinned commit under multi-stage sign-off = an approval workflow ("obieg akceptacji"), its stage list = a workflow template.
Permissions roles viewer < editor < approver < manager granted on any node, inherited down the tree (highest ancestor-or-self grant wins). Local accounts now; SSO/LDAP-ready (see roadmap).
Review as a chat a draft opens as a conversation of resolvable comment threads — start a thread, reply within it, and Resolve / Reopen (close/open) each one; threads can be anchored to a file; plus Approve & publish / Request changes (with a reason) / Withdraw. Actions are role-aware (approvers approve; the author replies or withdraws); closed reviews are read-only.
Friendly history an interactive version graph — lane-packed nodes across versions with branch/merge edges and version-tip badges; click a redaction to see what it changed (per-file, links to Changes). Per-file history stays a timeline. Changes is a ReaderJS compare view — side-by-side / unified / inline with word-level highlights and blame-aware tooltips, and it diffs documents (PDF, DjVu, Word/DOCX, ODF, e-books) too, not just text. A version switcher in the project header and the editor creates/switches between versions (branches).
Editor a Slate rich-text editor with a docx-style toolbar, shipped as one pre-built bundle (progressive enhancement over a plain-text fallback); it fills the available width and offers a version switcher, Save / Submit draft, and Print (renders the document to a clean printable page). Plugin formats are a seam.
Office documents DOCX & ODT edit in-app via the editor (body-level, lossy round-trip — python-docx + odfdo, both permissive); RTF & legacy DOC edit in-app too (text-level, in-browser, no server dependency — DOC uses JSDoc, a 0BSD pure-JS Word 97–2003 reader/writer); passphrase-encrypted (or unreadable) files use the download → edit → re-upload handoff. See supported formats and OPTIONS.md.
Edit on your computer any file (incl. plain text) has an Open on your computer action — downloads a copy so you edit it in your own desktop app (Word / LibreOffice Writer / FreeOffice TextMaker, via the OS default handler). Drag the saved file from your computer back onto the document (its card or the open editor) and it's saved as the new version — through the same /upload chokepoint, so review policy, encryption and audit all apply.
Encryption optional per-file/folder AES-256-GCM with envelope-wrapped keys (server-managed or zero-knowledge passphrase). Encrypted items show a shield.
Notifications a bell with an unread counter, an in-app panel, and opt-in browser-push + email.
Approval workflows "Obiegi akceptacji" — a multi-stage approval of one pinned version of a document (moved in from the retired Workflow module). A moderator sets up workflow templates: ordered stages, each approved by a role on the document (viewer/editor/approver/manager) or by named people; a stage is a plain approval, a content review (the approver confirms the exact version they read) or the paper signature (always last: approved by uploading the scan of the signed paper, saved into the document's podpisane/ folder through the normal upload chokepoint). An editor starts a workflow on a version; each stage's assignee approves or rejects with a comment; the starter or a manager may cancel. Every step lands on an append-only timeline. Two lists — Waiting for me and In progress — plus a "Czeka na mnie" tile on /stats. An approved workflow moves the contract card to approved (source: the workflow). It does not replace drafts: content edits stay drafts; the workflow approves a version that already exists. Three example templates are seeded.
Dashboard workflow-tuned: stat cards, a 14-day redactions/publishes/drafts chart, file-type donut, storage-by-workspace, and an "approvals waiting for you" queue.
Viewing clicking any document opens it read-only in the built-in ReaderJS viewer (MIT, same-origin iframe; Galena serves its own copy of the viewer, fetched at image build from an immutable ReaderJS commit — no CDN code runs in Galena's origin; documents never leave the box) — PDF, DjVu, DOC/DOCX/PPTX/XLSX, ODF, images, comics (CBZ/CBR), e-books (EPUB/MOBI), code, and more, all client-side. Editing is a separate action (the kebab menu's Edit / the viewer's Edit button → the in-app editors). DjVu is now permissive core (DejaView), not a plugin.
Sessions server-side cookie sessions (instant kill-switch). JWT was considered — see roadmap.
Password generator a top-bar tool to generate strong passwords (length 4–64; toggle upper/lower/numbers/symbols) with a strength estimate, client-side only via the Web Crypto CSPRNG (crypto.getRandomValues, rejection-sampled — never Math.random); plus show/hide on password fields (incl. sign-in).
OCR (text recognition) a top-bar tool to extract text from an image or PDF entirely in the browser (the file never leaves the box), via Tesseract.js (Apache-2.0 WASM, 100+ languages, model downloaded on demand). PDFs reuse PDF.js (each page → canvas → OCR); copy or download the result as .txt. Higher-accuracy server (PaddleOCR/docTR) and cloud engines are documented operator opt-ins — see OCR.md.
Backups optional auto-backup (off by default), configured in Administration: a scheduled (hourly/daily/weekly) .tar.gz of all files and the whole database (a portable, pure-Python dump — no pg_dump), stored on local disk or S3 (optional boto3), with retention pruning. One-click restore rebuilds everything (confirmation required). Restore rewrites every table via the migrator role; the encryption master key is never stored in a backup.
Theme & language light / dark / system (pre-paint) and full EN/PL localization (auto-detected).

Supported file formats

Every file is stored, versioned, downloaded and rolled back regardless of type. What differs is how you view and edit it in the browser:

Type View in browser Edit in browser Notes
Markdown / plain text (.md, .markdown, .txt) ✅ editor ✅ full The native Slate editor.
DOCX (Word) ✅ as editable text ✅ body-level, lossy Extracted to Markdown (python-docx), regenerated on save. Tables/images/styles/comments are simplified — banner warns; Download original for full fidelity.
ODT (OpenDocument) ✅ as editable text ✅ body-level, lossy Same round-trip via odfdo (inline bold/italic flattened).
RTF (.rtf) ✅ as editable text ✅ text-level, lossy Built-in in-browser reader/writer (no server dependency). Text & paragraphs survive; fonts/colours/tables/images simplified on save — Download for full fidelity.
legacy DOC (.doc) ✅ as editable text ✅ text-level, lossy Word 97–2003 binary OLE2, read/written in-browser by JSDoc (0BSD, pure-JS, no server dependency). Text & paragraphs survive; other formatting simplified on save — Download for full fidelity. Older/encrypted/corrupt variants fall back to the download → edit → re-upload handoff.
Images (.png .jpg .gif .webp .bmp .svg .tiff) ✅ ReaderJS (+ EXIF) — Grid cards also show Pillow thumbnails.
PDF ✅ ReaderJS (PDF.js) — Inline viewer with thumbnails, zoom, print.
DjVu (.djvu, .djv) ✅ ReaderJS (DejaView) — Permissive clean-room decoder — now core, not a plugin.
PPTX / XLSX·XLS / ODS·ODP·ODG / comics (CBZ·CBR·CBT) / e-books (EPUB·MOBI·AZW3·FB2) ✅ ReaderJS — View-only via the universal ReaderJS viewer.
Anything else download card ↪ handoff Served as a sandboxed attachment; editable via the download/re-upload handoff.

Office editing is body-level and lossy by design (the permissive, no-extra-infra trade-off) and passphrase-encrypted documents always use the handoff. The full decision and the higher-fidelity alternatives (Collabora/ONLYOFFICE as optional sidecars, etc.) are in OPTIONS.md.


Architecture

Strict one-way layering — each layer depends only on the one below:

routers/   HTTP, validation, auth + permission checks   ·  never builds SQL
services/  authz · nodes · git_facade · changes · crypto · notify · stats · search · audit
models/    ORM entities (identity, node tree, grants, drafts, notifications, file-crypto)
storage/   StorageBackend protocol → LocalStorage (S3 is a seam)
  • services/git_facade.py wraps GitPython. Reads navigate the object DB at a ref without touching the working tree (safe to run concurrently); writes take a per-repo in-process lock and use the working tree. Reads go through a small cached, pure-Python-ODB repo (GitDB) per project — this avoids spawning a git cat-file subprocess per object and skips GitPython's per-close() gc.collect() (≈100× faster tree/blob scans for search, browsing and history). Every write invalidates that project's cached read-repo, so reads always reflect the latest redaction; git objects are immutable, so an in-flight read against the prior snapshot stays consistent. (Single-instance assumption, matching the write lock — see Roadmap.)
  • services/changes.py is the single write chokepoint: open policy commits a redaction to the main version; review_required commits to the editor's working version and opens a draft.
  • services/authz.py resolves the effective role by ancestor-or-self materialized-path matching.
  • services/moderation.py binds the tiers and the entry guard (see below): who may use this module, and who administers it. Galena reads them; only the hub writes them.
  • Errors are RFC 9457 Problem Details — routing's own included: an unbound method on a real API path answers 405 with Allow, never the static console's 404 (the console mount is wrapped by main._ConsoleUnlessApi). The audit log is append-only (the runtime DB role has no UPDATE/DELETE on it).
  • Identity may live elsewhere. models/ maps app_user / session / module_permission either way, but which schema resolves them — and whether this app may write them — is a deployment question. See One platform, one account.

Hierarchy & permissions

Workspace "Acme"            (permission boundary)
└── Group "Legal"           (own grants, inherits Acme's)
    └── Project "Contracts"  → git repo: folders/files, versions, redactions, drafts

A grant on any node applies to that node and everything beneath it. The effective role on a target is the highest-ranked grant among the target and its ancestors, plus owner / personal-workspace / administration overrides. Files inside a project inherit the project's role (per-file grants are a documented seam). The folder badge reflects this: plain (open), open padlock (you have access), closed padlock (locked — "request access"), people (shared), shield (encrypted).

Who may be here at all, and Galena reads every answer rather than granting any of them:

tier scope where it lives
administrator the whole platform — every module, and the hub app_user.is_admin
moderator administers exactly one module — here, galena module_permission.role = moderator
user may use exactly one module — here, galena module_permission.role = user
(nobody) no access to this module at all — the default no row

The fourth line is the important one: no row means no entry. Before it, anybody with a platform account could open /galena; they saw an empty drive, because they had no grants on any node, but nothing had refused them — and "you can see nothing" is the absence of an access decision rather than one. deps.get_current_user asks now, so a signed-in stranger is refused on their first request.

An administrator is a moderator of everything by definition; a moderator is nothing outside their own module. Both resolve as manager on every node here and pass every /admin/* guard, because a module's administration is not all node-scoped (backups, plugins, storage and git defaults are not). user reaches none of that: it answers whether you may open this app, and what you may do inside is the ordinary permission grants above and nothing else.

Standalone all of this collapses, deliberately and with no second code path: there is one app and nothing to be admitted to, so everyone with an account is a user, "moderator" resolves to is_admin, and not a single query is emitted.


One platform, one account

Galena runs in two shapes, from one codebase, and the switch is a single setting.

Standalone (IDENTITY_SCHEMA empty, the default) is everything above: Galena owns app_user, has its own sign-in screen, and an administrator manages people on its Administration screen. Nothing about this deployment changed and nothing about it is deprecated.

As a module of the platform (IDENTITY_SCHEMA=dredd) the family runs at one origin, one module per path — /atrium, /galena, /sygna, /counsel — and a person has one account. They sign in once, at the hub, and every module resolves the same session. Because there is one origin there is no cross-origin handoff to design: no signed assertion, no audience binding, no SameSite dance. One cookie and one session row is the entire mechanism, and a design that invents a token exchange for this topology is over-engineering.

What that means for this app, concretely:

  • Identity is read, never written. app_user, session and module_permission live in a neutral schema the hub owns. galena_app holds a column-restricted SELECT on app_user — seven columns, and nothing at all on password_hash, failed_login_count or locked_until — plus SELECT and a three-column UPDATE on session (last_seen_at, expires_at, revoked_at) and SELECT on module_permission. No INSERT on any of them: a role that can insert a session row can mint a working credential for the administrator. The enforcement is the grant, not a missing screen.
  • Who may use this module is decided in the hub. module_permission carries one row per person per module, and this app holds SELECT on it and nothing else — no INSERT, no UPDATE, no DELETE. A module able to write it could admit anyone, promote anyone and promote itself, and the hub would neither see it nor be able to take it back.
  • There is no password here. POST /auth/login answers 404 with the hub's address, and the console shows a Sign in link instead of a form. Not even as break-glass: a second password is the thing this change exists to delete, and this app could not check one anyway — it cannot read a hash. That link needs no configuration: the hub is a sibling path at the same origin, so the card derives ../atrium/ from its own document, exactly as Sygna's and Counsel's do. IDENTITY_HUB_URL is an override for a hub that really is elsewhere, not a step you can forget.
  • Refused is not signed out, and the console says which. An account with no module_permission row has a perfectly good session, so GET /auth/me answers 403 rather than 401 and the console shows a short you do not have access to Galena card — the hub link and a sign-out, no sign-in form. Telling someone who is already signed in to sign in is the one answer that cannot help: what they are missing is a row only an administrator can write.
  • Signing out still works, and signs you out of the platform. That is what one account means, and the console says so.
  • App tokens are listed and revoked here and minted at the hub, which stamps them galena_pat_ on this module's behalf, so the prefix still says where a leaked credential came from.
  • Account writes answer 409, pointing at the hub — a sentence rather than a permission error dressed up as a 500.
  • Database isolation is unchanged. Galena keeps its own schema, its own least-privilege roles, its own append-only audit log and its own settings, backups and permission grants. Only identity is shared.
  • Backups carry this module and not the platform. The shared tables are excluded from the archive and from a restore's delete sweep — the second half matters most, because a restore that tried to DELETE FROM app_user as a role holding only SELECT would fail, permanently, and you would find out during an incident.

Turning it on is three steps, in this order, and none of them can be skipped or reordered: the platform admin re-renders db/managed/provision.sql with --identity-schema / --identity-owner and runs it (the schema, USAGE, and a search_path of galena, dredd, extensions — a migrator may do none of that); the hub's own migration creates the three tables and grants this app's two roles their tier; then alembic upgrade head here runs revision 0007, which merges this schema's accounts into the shared ones by e-mail address and re-points every foreign key. Read 0007_shared_identity.py before running it on anything you care about — it drops this app's local identity tables, and every Galena session and app token with them, so everybody signs in again and GalenaConnect tokens are re-minted at the hub.

Revision 0008 follows it and needs nothing from an operator, standalone or not: it renames module_moderator to module_permission on a database whose 0001 ran while dredd-core v0.10.x was pinned (every existing row becomes a moderator, because that is what a row there meant), creates the table on one that predates it altogether, and builds nothing at all where identity has just become the hub's.

Once the cutover is done, admit people to this module in the hub — an account with no module_permission row for galena is refused here, which is the point of the table. On the day of the change that includes whoever administered this module before: the account import deliberately clears is_admin, so 0007 names them in its log and an administrator makes them a moderator of Galena in the hub.

Prove it afterwards:

python -m dredd_core.managed check --expect-schema galena --app-role galena_app \
  --migrator-role galena_migrator --identity-schema dredd --identity-tier reader

Configuration

All via .env (see .env.example). Highlights:

Variable Purpose
DATABASE_URL / MIGRATION_DATABASE_URL runtime (app, DML) / migrations (migrator, DDL); a host that is not local must add ?sslmode=verify-full&sslrootcert=<CA> (the family's one TLS rule) or the app refuses to start
DB_LOCAL_HOSTS comma-separated hosts that count as local besides localhost / 127.0.0.1 / ::1 / postgres, so their URLs need no TLS (a private database on a trusted network); the only opt-out
DB_APP_ROLE the runtime role the grants migration targets — must be DATABASE_URL's role (app; galena_app in the family's shared managed database)
DB_POOL_SIZE / DB_MAX_OVERFLOW runtime connection pool per backend process (default 5 / 10)
DATA_DIR where project git repos live (LocalStorage)
BOOTSTRAP_ADMIN_EMAIL / _PASSWORD first admin (created by the seed; on the platform, looked up in the shared store instead — the hub creates accounts)
IDENTITY_SCHEMA empty (default) = standalone: Galena owns its accounts, has its own sign-in and its own Users screen. Set it (dredd) and this becomes a module of the platform: app_user / session / module_permission live in a neutral schema the hub owns and this app only reads — one account for every module, signed in once, and only where the hub admitted them. See One platform, one account
MODULE_SLUG this app's module on the platform (galena) — the module a module_permission row is a permission for; required whenever IDENTITY_SCHEMA is set, and a slug that does not match the hub's means nobody's row resolves and nobody but an administrator may open this app
IDENTITY_HUB_URL override, normally empty: the hub is a sibling path at the same origin, so the sign-in card derives ../atrium/ from its own document. Set it only for a hub that really is elsewhere (another host)
SESSION_COOKIE_NAME the session cookie's name (galena_session; dredd_session across the platform — one account, one cookie). The old name is still read for a while, so a rename does not sign everybody out
SESSION_TTL_HOURS cookie session lifetime (hours)
APP_TOKENS_ENABLED / APP_TOKEN_IDLE_DAYS named, revocable, scoped credentials for desktop clients; the window is an inactivity timeout that slides forward on use (false = feature off)
SESSION_COOKIE_SECURE leave unset to auto-detect (Secure over HTTPS, not over plain HTTP, so login persists on a LAN/HTTP host); true/false forces it
ENCRYPTION_MASTER_KEY base64 32-byte key wrapping per-item data keys (empty = encryption off)
PLUGINS_DIR optional frontend-plugin root (empty = none); e.g. enables the DjVu Viewer plugin
VAPID_* browser-push keys (empty = web-push off)
SMTP_* email-notification settings (empty host = email off)
FRAME_ANCESTORS who may frame the console and API: 'none' (default, X-Frame-Options: DENY) or 'self' (SAMEORIGIN); anything else refuses start-up. The ReaderJS viewer is always 'self'
FORWARDED_ALLOW_IPS the proxy allowed to set X-Forwarded-* (empty = loopback only; set it to your TLS terminator's address)
GALENA_PUBLIC_URL public address baked into the link-preview tags (empty = derived from the request)
OTEL_ENABLED opt-in OpenTelemetry export

Link previews. When you share the deployed app's URL in WhatsApp/Slack/iMessage/etc., it unfurls with a title, description and the og-image banner — via Open Graph / Twitter Card tags in index.html that the backend renders to absolute, HTML-escaped URLs at serve time (from GALENA_PUBLIC_URL if set, else the request's scheme + host + ROOT_PATH). This is separate from this repo's GitHub social image.


API reference

Base path /api/v1 (full OpenAPI at /api/v1/docs).

Meta          GET  /meta                       (unauthenticated: version, capability flags,
                                                whether this app has a sign-in of its own)
Auth          POST /auth/login · /auth/logout · GET /auth/me
              (login is absent — 404 — on the platform: you sign in at the hub)
App tokens    POST/GET /auth/tokens · DELETE /auth/tokens/{id}
              (minting moves to the hub on the platform; list + revoke stay)
Users (admin) GET/POST /users · PATCH /users/{id} · POST /users/{id}/deactivate
              (the three writes answer 409 on the platform: accounts are the hub's)
Drive scopes  GET /drive/home · /drive/favorites · /drive/shared · /drive/recent
Nodes         GET /nodes/{id} · POST /nodes · PATCH /nodes/{id} · POST /nodes/{id}/move
              · POST /nodes/{id}/convert-to-project · PUT /nodes/{id}/policy · DELETE /nodes/{id}
              · POST /nodes/{id}/favorite · /clone
Permissions   GET/POST /nodes/{id}/permissions · DELETE …/{user} · POST /nodes/{id}/request-access
Files         GET /projects/{id}/tree|file|file-info|raw|thumb · POST …/file|upload|move-file|copy-file|encrypt · DELETE …/file
Versions/Drafts POST /projects/{id}/versions · /combine · /submit-draft · GET /drafts · /drafts/{id}
              · POST /drafts/{id}/messages[/{mid}/resolve]|publish|resolve|reject|withdraw · GET /drafts/{id}/conflict
History       GET /projects/{id}/history|graph|changed|changes|blame
Workflows     GET /workflow-templates · GET/POST /admin/workflow-templates · PATCH …/{id} (moderator)
              · GET/POST /projects/{id}/workflows · POST /workflows/{id}/actions (approve|reject|cancel)
              · POST /workflows/{id}/scan (paper signature) · GET /workflows?view=waiting|active
Stats         GET /stats          (dredd-core stats contract: contracts · drafts · waiting for me)
Dashboard     GET /dashboard      Search GET /search?q=
Notifications GET /notifications · /unread · POST /read-all · /{id}/read · GET/PUT /prefs · POST /subscribe
Plugins       GET /plugins        (enabled only; assets at /plugins/<name>/)
Admin         GET/PUT /admin/settings · GET /admin/nodes · GET/PUT /admin/plugins/{name} · …/users/{id}/grants

Plugins

Galena core ships only permissive dependencies. Features that would pull in copyleft or niche code live as optional frontend plugins, kept out of core and installed deliberately. Ready-made plugins live in the companion repo Alpaq92/GalenaPlugins.

  • Set PLUGINS_DIR to a folder of plugins (Docker: mount a volume). Each plugin is a subfolder with:
    <plugin>/
      plugin.json          # { name, title, version, license, frontend: { entry }, provides }
      frontend/<entry>.js   # registers handlers via window.Galena.registerPreview({extensions, handler})
      frontend/<assets…>    # any libraries the plugin needs (served at /plugins/<name>/)
    
  • The backend serves plugin static assets and lists manifests only — it never executes plugin code. The console fetches GET /api/v1/plugins after sign-in and lazy-loads each entry script.
  • Manage from Administration. Admins see installed plugins (name, version, license) under Administration → Plugins and can enable/disable each one. Disabled plugins aren't served to the console; the state persists server-side. Changes apply on the next sign-in/reload.
  • Trust model: plugins run JavaScript in the console origin (like a browser extension) — install only plugins you trust. Assets are same-origin, so the console CSP applies unchanged.

The reference plugin in GalenaPlugins is:

  • DjVu Viewer (DjVuViewer/, GPL-2.0) — inline .djvu preview via djvu.js. It's GPL because no permissive DjVu decoder exists (DjVuLibre and every JS port are GPL; the lone MIT option, djvu-rs, is a young clean-room Rust→WASM codec, deferred). With the plugin absent, .djvu files simply download — no errors.

The RTF editor started life there as a separate 0BSD plugin, then — being permissive and dependency-free — graduated into core as the built-in .rtf editor (above). It's the worked example of the permissive-plugin → core path, the inverse of DjVu (which stays a plugin because it's GPL and can't go into the permissive core).


Run it locally

Two ways: the whole stack via Docker (simplest), or a bare-metal dev loop (fast reloads, no Docker).

Option A — Docker (full stack)

Needs Docker + Docker Compose. Brings up Postgres → migrate(+seed) → backend; only the backend is published (port 8021).

cp .env.example .env            # then edit secrets (DB passwords, ENCRYPTION_MASTER_KEY)
DREDD_CORE_TOKEN=github_pat_... docker compose up -d --build   # token: see Quick start

Open http://localhost:8021 and sign in as the bootstrap admin from your .env (BOOTSTRAP_ADMIN_EMAIL / _PASSWORD). API docs at http://localhost:8021/api/v1/docs. There is no reverse proxy in this stack: for HTTPS put your own TLS terminator in front of port 8021 and set FORWARDED_ALLOW_IPS to its address (or run Galena as a module of the platform, where Atrium is the front door).

Option B — bare metal (dev loop, no Docker)

Needs Python 3.12, the git binary (GitPython shells out to it — check git --version), and a PostgreSQL 16 or 17 you can reach. The console is no-build, so there's nothing to compile on the frontend.

  1. A database with the two least-privilege roles. Migrations refuse to run as a superuser (a trust-auth postgres included) and grant the runtime role its privileges, so create migrator (owns the schema) and app (runtime, DML only) once, as the superuser — the same setup db/init/01-roles.sh does for Docker (local passwords; never reuse them anywhere else):

    psql -U postgres -v ON_ERROR_STOP=1 <<'SQL'
    CREATE ROLE migrator LOGIN PASSWORD 'migrator';
    CREATE ROLE app LOGIN PASSWORD 'app';
    CREATE DATABASE galena;
    \connect galena
    ALTER SCHEMA public OWNER TO migrator;
    GRANT USAGE ON SCHEMA public TO app;
    CREATE EXTENSION IF NOT EXISTS pgcrypto;
    SQL
    

    Then point the runtime URL at app and the migration URL at migrator:

    export DATABASE_URL=postgresql+pg8000://app:app@localhost:5432/galena
    export MIGRATION_DATABASE_URL=postgresql+pg8000://migrator:migrator@localhost:5432/galena
    export APP_ENV=development                 # show error detail; cookie isn't forced Secure
    export ENCRYPTION_MASTER_KEY=$(python -c "import os,base64;print(base64.b64encode(os.urandom(32)).decode())")
    export DATA_DIR=./data                     # where project git repos live
    export PLUGINS_DIR=../GalenaPlugins        # optional: enables the DjVu Viewer plugin
    # On Windows PowerShell: $env:DATABASE_URL="..."   etc.
    

    Login over plain HTTP works: the session cookie's Secure flag is auto-detected from the request scheme, so it isn't dropped on http://localhost:8021. (Behind an HTTPS terminator it's set automatically.) No need to fiddle with SESSION_COOKIE_SECURE.

  2. Migrate, seed, run:

    cd backend
    python -m venv .venv && source .venv/bin/activate     # Windows: .venv\Scripts\Activate.ps1
    pip install -r requirements-dev.txt
    alembic upgrade head && python -m app.seed            # creates the schema + bootstrap admin + demo data
    uvicorn app.main:app --reload --port 8000             # console at / , API at /api/v1
    

    pip install fetches the private Alpaq92/dredd-core from GitHub (pinned in requirements.txt), so this machine's git needs read access to that repo — e.g. gh auth login or another git credential helper. Keep the token in the helper, not in a git URL or .env. Co-developing core? pip install -e ../dredd-core afterwards shadows the pin.

    Open http://localhost:8000 and sign in (default admin@example.com / admin12345, or your BOOTSTRAP_ADMIN_*). The same uvicorn process serves the static console and the API.

Hosting the console on Netlify (front-end only)

Galena's backend cannot run on Netlify — it needs a persistent process, a writable disk for the git repositories, an in-process per-repo write lock, and a PostgreSQL server, none of which fit Netlify's static + serverless model. Netlify can host the static console; there are two ways to make it usable, via env vars on the Netlify site (the repo ships netlify.toml + netlify/prepare.sh, which publish frontend/):

A. Demo mode — a clickable demo with no backend (the default). If no GALENA_BACKEND_URL is set, the build injects frontend/demo.js, an in-browser mock that intercepts /api/v1/* and serves a seeded dataset from localStorage, so login, browsing, editing, dashboard, drafts and search all work client-side. It's a simulation (data is per-browser and resets via the Reset button). This is what powers the live demo — a backend-less Netlify deploy is a demo out of the box. Set GALENA_DEMO=0 to opt out (publish the bare console with no mock), and note the mock is never injected once a backend is wired (option B) or in a real Docker deploy.

B. Real backend — Netlify as a front-door proxy. Run the backend somewhere that fits it (see below) and set GALENA_BACKEND_URL to its public HTTPS URL; the build proxies /api/v1/* and /healthz there (a same-origin 200-rewrite). On the backend, set CORS_ALLOW_ORIGINS=https://<your-netlify-site>: the proxy hands the backend its own Host, so the browser's Origin names another host and the cross-site write guard refuses sign-in and every cookie-authenticated write unless that origin is listed. Optionally set GALENA_PUBLIC_URL for the link-preview base. For refresh-persistence the backend's TLS terminator must forward X-Forwarded-Proto=https (or set SESSION_COOKIE_SECURE=true).

Where to run the real backend: the most faithful target is a small always-on VM running the repo's own docker compose (e.g. Hetzner ~€4.49/mo, or an Oracle Cloud Always-Free Arm VM for $0) — there the backend already serves the console and the API on one domain, so you don't even need Netlify. Among PaaS, Northflank's free tier fits (always-on + persistent volume + managed PG16); Fly.io / Railway / Render (paid) also work with a persistent volume. Avoid serverless/scale-to-zero hosts (Cloud Run, Lambda, App Runner, Vercel/Netlify Functions, Heroku) for the backend — their ephemeral filesystems destroy the on-disk git repos and multi-instance autoscaling corrupts the per-repo lock.

Deploying on a managed PostgreSQL provider

The family's apps (Atrium, Galena, Sygna, Counsel Scorecard) can share one managed PostgreSQL database. The provider hosts only Postgres, so Galena's backend still runs on a container host. In the shared database Galena gets its own schema galena (never public) and two roles: galena_migrator owns the schema and galena_app is the runtime role. No other app's roles can reach that schema, and a provider's auto-generated API roles get nothing in it.

  1. Set up the database itself (region, the provider's root CA, any auto-generated API off, TLS enforcement, network restrictions, connection budget, backups) once for all four apps, with the checklist in step 0 of db/managed/README.md.
  2. Provision Galena and run it with docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build, following db/managed/README.md. It covers the provisioning command (or provision.sql for the provider's SQL editor), the .env values (a pooler's session mode, <role>.<tenant> user names where the pooler wants them, verify-full TLS, DB_APP_ROLE=galena_app, pool size), migrating, the python -m dredd_core.managed check preflight and restores.

Tests

cd backend
pytest                                                  # DB-free unit tests (git facade, crypto, authz, plugins)
GALENA_RUN_INTEGRATION=1 pytest                         # full API loop — needs a migrated+seeded Postgres
python scripts/license_gate.py                          # fail-on-copyleft dependency gate (CI runs this too)

Rebuilding the editor bundle (only when you change frontend/editor/)

cd frontend/editor && npm install && npm run build      # emits ../static/editor.js (commit the artifact)

Roadmap / extension points

Each item notes the seam to extend and the alternative considered but deferred.

  • Auth backends (SSO/OIDC, LDAP). Grants reference an abstract principal (id + type) and app_user.password_hash is nullable, so externally-authenticated accounts slot in without a local password. Considered: mapping IdP groups directly to principal_type=group grants.
  • Storage (S3 / object store). storage/StorageBackend is a protocol; v1 is LocalStorage. An S3Storage backend can offload large blobs/attachments and backups. Considered: git-LFS-style pointers for big binaries.
  • Cloud / horizontal scale-out. Self-hosted single-instance needs nothing extra. To run multiple instances, replace the per-repo in-process write lock with a distributed lock (Postgres advisory lock / Redis) and put repos on shared storage (network volume or S3-backed). The app tier is already stateless (DB-backed sessions). Considered: a single writer service fronting the repos.
  • Backups. Auto-backup (off by default) writes a .tar.gz of DATA_DIR + a pure-Python DB dump to a BackupTarget — LocalBackupTarget (default) or S3BackupTarget (optional boto3). The scheduler is an in-process asyncio task (single-instance, like the write lock — run it on one instance only in a multi-instance deploy). Restore rewrites every table and so uses MIGRATION_DATABASE_URL (the migrator role) — from Administration, or as the one-shot python -m app.restore <name> --yes where the backend holds no migrator credentials (the managed-database deploy's default); it assumes the same schema version (alembic_version is untouched) and does not include the encryption master key — server-mode encrypted blobs need the same ENCRYPTION_MASTER_KEY after a restore. Considered: pg_dump/pg_restore (more robust for large/edge-case data, but needs the postgresql-client binary) and infra-level snapshots.
  • Database. Postgres now (FTS-ready, concurrency, least-privilege roles). Considered: SQLite (single-file, zero-server) behind the same SQLAlchemy layer for the simplest self-host.
  • Sessions. Server-side cookie sessions (instant revoke). Considered: stateless JWT — faster to scale but no instant kill-switch; rejected for now.
  • Search. Case-insensitive substring match over node names/paths and file content (with a per-query scan budget; binary/encrypted blobs skipped), returning a snippet for content hits. Considered: Postgres FTS (tsvector + GIN + pg_trgm) for ranked, indexed full-text search.
  • History visualization. An interactive lane-packed version graph (clickable nodes → per-redaction file changes via GET /projects/{id}/changed) + Changes rendered by the ReaderJS compare view (side-by-side / unified / inline, word-level, blame-aware). Considered: git-sim (Manim) to export printable/animated diagrams — heavy (ffmpeg/cairo/LaTeX), deferred.
  • Previews. Documents (PDF, DjVu, Office, e-books, images, comics) render client-side in the ReaderJS viewer; grid cards use Pillow thumbnails. Extra viewers slot in via plugins (below). Image/preview breadth. Pillow (HPND) covers common raster formats + EXIF + thumbnails. Considered: Wand/ImageMagick for PDF/PSD/RAW previews — adds a system library; revisit if needed. Rejected: Pymaging (unmaintained).
  • Plugins. Optional frontend plugins live under PLUGINS_DIR (each a folder with a plugin.json + a frontend/ entry script); the backend serves their static assets at /plugins/<name>/ and lists them at GET /api/v1/plugins, and the console lazy-loads them after sign-in, registering preview handlers via the window.Galena API. The backend never executes plugin code, so core stays permissive — copyleft/optional features ship as plugins. DjVu is the first one (GalenaPlugins/DjVuViewer, GPL-2.0, via djvu.js): without it, .djvu files just download. Considered permissive alternative: djvu-rs (MIT clean-room Rust→WASM codec) — the only non-GPL DjVu decoder, but young/self-attested, so deferred. Seam: server-side plugins.
  • Editor formats. Slate with a docx-style toolbar; edits plain text + Markdown, and DOCX/ODT via a body-level Markdown round-trip (python-docx + odfdo, both permissive). RTF has a separate built-in text-level editor (rtfEditor in app.js, client-side, no server dep) — see supported formats and OPTIONS.md. Next (optional, not core): a Collabora/ONLYOFFICE WOPI sidecar for full-fidelity office editing + co-editing.
  • Per-file permissions. Files inherit their project's role today; a per-path grant table is the seam.
  • Encryption. AES-256-GCM envelope via pyca/cryptography (native, no external binary). Modes: server-managed (search/preview keep working) and zero-knowledge passphrase. Considered (native): PyNaCl/libsodium, pyrage (age). Not used: VeraCrypt (external desktop volume tool — for whole-disk at-rest use OS-native LUKS or a cloud-KMS disk instead); M2Crypto (maintenance-mode). Future: a KMS for the master key.
  • Notifications. In-app is core; browser-push (VAPID) and email (SMTP) are opt-in channels. Seam: add channels under notify/ (e.g. Slack/webhook).

Security

What the design enforces:

  • Path safety. Every git write path is normalized + validated (git_facade.safe_path): absolute paths, drive letters, .. traversal, control/NUL bytes, and any .git segment are rejected, and the resolved target is confirmed to stay inside the project working tree — so a crafted filename can't escape the repo or plant a git hook (RCE).
  • Untrusted file serving. /raw serves only an allowlist of media (images, PDF, plain text) inline; everything else (HTML, SVG, XML, JS, …) is forced to application/octet-stream as an attachment, with X-Content-Type-Options: nosniff and Content-Security-Policy: default-src 'none'; sandbox, so user-uploaded content can't execute script in the app origin.
  • Content-Security-Policy + headers on the console (and a stricter one on /raw), plus X-Frame-Options: DENY, Referrer-Policy, nosniff, and Cross-Origin-Opener-Policy — set by the backend on every response, errors included (app/edge.py); FRAME_ANCESTORS='self' relaxes framing to the same origin. Responses are gzip-compressed (text types only) and request bodies are capped at 100 MB (per-file writes stay capped at 64 MB).
  • Tenant isolation in feeds. "Recent activity" (drive + dashboard) and favourites are scoped to the caller's own actions + nodes they can currently read — the global audit log is never exposed, and revoked access drops items from listings.
  • Authn/z. Argon2id password + passphrase hashing; server-side sessions (logout/deactivate, and password change, revoke access instantly); app-level login lockout. App tokens for non-browser clients share that machinery — only a hash is stored, each is named and revocable on its own, a read token is refused every unsafe method at a single chokepoint, and a password change revokes them too. Zero-knowledge passphrases are sent in the X-Galena-Passphrase header; the ?passphrase= query parameter still works but is deprecated and warns, because query strings reach access logs, browser history and Referer. The session cookie is HttpOnly + SameSite=lax, and its Secure flag is auto-detected from the request scheme (set over HTTPS, omitted over plain HTTP) so login persists on a LAN/HTTP host without dropping the cookie. Cascading ancestor-or-self role resolution (viewer < editor < approver < manager); review-chat posting requires editor.
  • Cross-site writes are refused. A state-changing request that rides on the session cookie must come from this site — SameSite=lax alone still lets a same-site sibling (another app under the same parent domain) post with it. One app-wide dependency (deps.refuse_cross_site_write) refuses a Sec-Fetch-Site other than same-origin and, where browsers omit it, an Origin that is null (an opaque origin: a sandboxed iframe, a data: or file: page) or names another host. Bearer-token clients and origins listed in CORS_ALLOW_ORIGINS are trusted. Deployed as a module of the platform (one origin, one module per path) this guard separates the platform from foreign sites only, never one module from another — a page at /sygna is same-origin with /galena.
  • Encryption. AES-256-GCM envelope encryption; each git blob is self-describing (embeds its own salt/nonces/wrapped DEK), so history, branches, and re-encryption all decrypt independently — re-encrypting a file never orphans older versions. Git stores ciphertext; passphrase-mode is zero-knowledge. Per-file size cap on writes/uploads guards against memory exhaustion.
  • Least-privilege DB roles: app is DML-only and append-only on audit_log; DDL belongs to the migrator role. The runtime-grants migration fails loudly (a missing runtime role, migrating as a superuser or postgres, a grant that did not take) instead of skipping, and on a managed Postgres every connection verifies TLS (sslmode=verify-full). Postgres is expose-only; the backend is the only published service. APP_ENV defaults to production (fail-closed: error detail is hidden).

Residual caveats / operator responsibilities (see also Roadmap):

  • Secrets management. .env holds the DB passwords + encryption master key in plaintext. Keep it off shared hosts, restrict file permissions, and rotate anything that has been committed or shared. A real KMS for the master key is a documented seam, not yet implemented.
  • No CSRF tokens. Cross-site request forgery is mitigated by SameSite=lax plus the Sec-Fetch-Site/Origin check above, not by per-request tokens.
  • CSP uses 'unsafe-inline' for the console (theme pre-paint script + inline styles). Tightening to nonces/hashes is a follow-up.
  • FORWARDED_ALLOW_IPS defaults to loopback only, because the backend is published directly. If you put a TLS terminator in front, set it to that proxy's address — never *.
  • Instance admins are super-readers (the Administration role can reach any node); there is no end-to-end encryption from admins in server-managed mode — use passphrase mode for that.
  • Default bootstrap credentials must be changed on first run; sessions have a fixed TTL with no idle timeout.

License

Apache-2.0 — chosen for its explicit patent grant and clean corporate review. See also CREDITS.md for dependency licenses and attributions.