Initial import: Galena — a self-hosted, git-backed cloud drive

FastAPI + SQLAlchemy 2 + PostgreSQL + GitPython backend, a single static
vanilla-JS console with a committed Slate editor bundle, Argon2id auth +
cookie sessions, optional AES-256-GCM encryption, and in-app DOCX/ODT editing
(with a download→edit→re-upload handoff for RTF/DOC). Apache-2.0; permissive
core with copyleft features as optional plugins.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-16 09:37:29 +02:00
co-authored by Claude Opus 4.8
commit 3a11c89acc
100 changed files with 10958 additions and 0 deletions
+58
View File
@@ -0,0 +1,58 @@
# Copy to .env and replace every change_me_* value before starting. .env is git-ignored.
# ── Postgres ──
POSTGRES_DB=galena
POSTGRES_PASSWORD=change_me_super
DB_APP_PASSWORD=change_me_app
DB_MIGRATOR_PASSWORD=change_me_migrator
# Runtime (app role, DML-only) and migrations (migrator role, DDL). Embed the matching passwords
# above — they are duplicated here, not auto-substituted. Host stays `postgres` for Docker.
DATABASE_URL=postgresql+pg8000://app:change_me_app@postgres:5432/galena
MIGRATION_DATABASE_URL=postgresql+pg8000://migrator:change_me_migrator@postgres:5432/galena
# ── App ──
APP_ENV=production
APP_BASE_URL=http://localhost
DATA_DIR=/data
# Optional frontend plugins root (folder of plugin subfolders). Empty = none. Plugins are
# frontend-only (the backend never runs plugin code) and may carry their own license — e.g. the
# GPL-2.0 DjVu Viewer plugin, kept out of the permissive core. Docker: mount a volume here.
PLUGINS_DIR=
SESSION_TTL_HOURS=12
# Secure session cookie. Leave UNSET (recommended) to auto-detect per request scheme: Secure over
# HTTPS, not over plain HTTP — so login persists on a LAN/HTTP host without manual tweaking. Behind
# Caddy with a domain you get HTTPS (hence Secure) automatically. Uncomment to force true/false.
# SESSION_COOKIE_SECURE=true
# Comma-separated origins for a separately-served console in dev (empty = same-origin only).
CORS_ALLOW_ORIGINS=
# First admin account (created idempotently by the seed).
BOOTSTRAP_ADMIN_EMAIL=admin@example.com
BOOTSTRAP_ADMIN_PASSWORD=change_me_admin
# ── Encryption (optional) ──
# Base64 of 32 random bytes — wraps per-item data keys (server-managed mode). Empty disables
# encryption features. Generate one with:
# python -c "import os,base64;print(base64.b64encode(os.urandom(32)).decode())"
ENCRYPTION_MASTER_KEY=
# ── Web push (optional) ── generate VAPID keys (e.g. `npx web-push generate-vapid-keys`).
VAPID_PUBLIC_KEY=
VAPID_PRIVATE_KEY=
VAPID_SUBJECT=mailto:admin@example.com
# ── Email (optional) ── SMTP for email notifications. Empty host disables the email channel.
SMTP_HOST=
SMTP_PORT=587
SMTP_USER=
SMTP_PASSWORD=
SMTP_FROM=galena@example.com
SMTP_STARTTLS=true
# ── TLS / proxy ── set to your domain for automatic HTTPS, e.g. CADDY_SITE_ADDRESS=galena.example.com
CADDY_SITE_ADDRESS=
# ── Observability (opt-in) ──
OTEL_ENABLED=false
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
+5
View File
@@ -0,0 +1,5 @@
* text=auto eol=lf
*.png binary
*.jpg binary
*.gif binary
*.ico binary
+60
View File
@@ -0,0 +1,60 @@
name: CI
on: [push, pull_request]
jobs:
backend:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_DB: galena
POSTGRES_PASSWORD: superpw
ports: ["5432:5432"]
options: >-
--health-cmd "pg_isready -U postgres" --health-interval 5s
--health-timeout 5s --health-retries 20
env:
DATABASE_URL: postgresql+pg8000://app:apppw@localhost:5432/galena
MIGRATION_DATABASE_URL: postgresql+pg8000://migrator:migpw@localhost:5432/galena
DATA_DIR: ${{ runner.temp }}/galena-data
BOOTSTRAP_ADMIN_EMAIL: admin@example.com
BOOTSTRAP_ADMIN_PASSWORD: adminpass1
GALENA_RUN_INTEGRATION: "1"
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with: { python-version: "3.12" }
- name: Create least-privilege roles
run: |
PGPASSWORD=superpw psql -h localhost -U postgres -d galena -v ON_ERROR_STOP=1 <<'SQL'
CREATE ROLE migrator LOGIN PASSWORD 'migpw';
CREATE ROLE app LOGIN PASSWORD 'apppw';
GRANT CONNECT ON DATABASE galena TO migrator, app;
ALTER SCHEMA public OWNER TO migrator;
GRANT USAGE ON SCHEMA public TO app;
SQL
- name: Install deps
working-directory: backend
run: pip install -r requirements-dev.txt
- name: Migrate + seed
working-directory: backend
run: alembic upgrade head && python -m app.seed
- name: Tests
working-directory: backend
run: pytest -q --cov=app --cov-report=term-missing
- name: License gate (Python)
working-directory: backend
run: python scripts/license_gate.py
editor-license:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: "20" }
- name: Install + JS license gate
working-directory: frontend/editor
run: |
npm install --no-audit --no-fund
npx license-checker --production --onlyAllow "MIT;ISC;BSD-2-Clause;BSD-3-Clause;Apache-2.0;0BSD;CC0-1.0;Unlicense;MPL-2.0" --summary
+24
View File
@@ -0,0 +1,24 @@
# Secrets / config
.env
.env.*
!.env.example
# Local editor / agent config + scratch
.claude/
*.log
# Python
__pycache__/
*.py[cod]
.venv/
*.egg-info/
.pytest_cache/
.coverage
# Node (editor island) — the BUILT bundle in frontend/static/editor.js IS committed
frontend/editor/node_modules/
frontend/editor/.vite/
# Local data (git project repos live here at runtime)
/data/
backend/data/
+119
View File
@@ -0,0 +1,119 @@
# CLAUDE.md
Guidance for Claude Code when working in this repository.
## What this is
**Galena** — a self-hosted, **git-backed cloud drive**. An ordinary cloud-storage UX on top of real
git repositories, de-jargoned for non-git users. Stack: **FastAPI + SQLAlchemy 2 + Alembic +
PostgreSQL 16**, **GitPython** (wraps the system `git` binary), Argon2id auth + server-side cookie
sessions, **cryptography** (AES-256-GCM) for optional encryption, **Pillow** thumbnails, a single
static console (vanilla JS, no build), and a pre-built **Slate** editor bundle. License **Apache-2.0**;
every dependency is permissive (no copyleft). See [`README.md`](README.md) + [`CREDITS.md`](CREDITS.md).
## Where things live
```
backend/app/
main.py config.py db.py deps.py errors.py security.py observability.py enums.py schemas.py seed.py
models/ identity · node (workspace/group/folder/project + grants + favorite) · draft (+messages)
· notification (+push_subscription, prefs) · filecrypto
services/ auth · authz (effective-role resolver) · nodes (tree CRUD + scopes) · git_facade (GitPython)
· changes (the single write chokepoint) · crypto · notify · stats · search · audit · plugins
· office (DOCX/ODT ↔ Markdown round-trip — python-docx + odfdo, permissive)
storage/ base (StorageBackend protocol) · local (LocalStorage; S3 is a seam)
notify/ webpush (VAPID, optional) · email (smtplib)
routers/ auth · users · admin · nodes · permissions · files · history · drafts · dashboard · notifications · search · plugins · health
alembic/ env + 0001_initial (pgcrypto, enums, create_all from metadata, least-privilege grants)
+ 0002_message_threads (idempotent ADD COLUMN for review-comment threading)
frontend/ index.html · app.css · app.js (the console) · sw.js · static/editor.js (built)
editor/ React + Slate source, built by Vite to ../static/editor.js
db/init/ 01-roles.sh (creates the app + migrator roles)
docker-compose.yml · Caddyfile · .env.example · .github/workflows/ci.yml
```
## Commands
```bash
docker compose up -d --build # full stack: postgres -> migrate(+seed) -> backend -> caddy
cd backend && pytest # DB-free unit tests; integration auto-skips
GALENA_RUN_INTEGRATION=1 pytest # full API loop (needs a migrated+seeded Postgres)
python scripts/license_gate.py # CI license gate locally
cd frontend/editor && npm run build # rebuild the editor bundle (commit ../static/editor.js)
```
## Invariants — preserve these
- **De-jargoned UI, technical internals.** UI says Workspace/Group/Folder/Project, main version,
redaction, version, draft, publish, combine versions, resolve discrepancies, authorship, changes.
Code/routes keep git terms. Keep the [terminology mapping] consistent across console + README.
- **Strict layering:** routers → services → models. Routers never build SQL; services own domain logic
(enforced — don't inline `select(...)`/`db.add`/`db.execute` in a router). Grant CRUD lives in
`authz`; node/project/favorite reads in `nodes` (incl. `get_project`, the one "is-a-project" check);
draft lists/messages/withdraw in `changes`; notification reads/writes in `notify`; user list/create in
`auth`. A lone `db.get(Model, id)` by primary key in a router is acceptable.
- **Single write chokepoint:** all file writes go through `services/changes.apply_change` (policy +
encryption). `git_facade` serializes per-repo writes with an **in-process lock**; reads don't touch
the working tree. Reads use a **cached pure-Python-ODB repo** (`_read_repo`, `odbt=GitDB`) — no
`git cat-file` subprocess, no per-`close()` `gc.collect()` (≈100× faster scans). Every write calls
`_invalidate_read(project_id)` so reads reflect the latest redaction. Multi-instance scale-out needs
a distributed lock (see README roadmap).
- **Permissions:** `services/authz` is the only authority; routers call `assert_can_read` /
`assert_role(node, min)` before any read/write. Effective role = highest ancestor-or-self grant.
- **Append-only audit:** the `app` DB role has no UPDATE/DELETE on `audit_log` (enforced in the
migration). `migrator` owns DDL; `app` is DML-only.
- **Encryption:** each git blob is **self-describing** — it embeds its own mode/salt/nonces/wrapped
DEK (`MAGIC|...|ciphertext`, see `services/crypto.py`), so every ref/branch/re-encryption decrypts
independently. `file_crypto` is only a UI marker (NOT the key source — do not "fix" decryption to
read keys from the row; that reintroduces the history-corruption bug). Git stores ciphertext;
passphrase mode is zero-knowledge. `decrypt()` detects encryption from the blob header itself.
- **Console security:** `esc()` every dynamic value; bearer token in memory only; cookie session is primary.
Untrusted file bytes never execute in-origin: `/raw` forces non-allowlisted media to
`octet-stream` + sandbox CSP; every git write path goes through `git_facade.safe_path`.
- **Accent = monochrome** (near-black light / near-white dark). Open Color **violet8** (#5f3dc4) is
used **only** on the brand app icon (rounded square + Tabler `square-asterisk` in violet0).
- **Editor is a committed build artifact** (`frontend/static/editor.js`); runtime stays no-build, and
the console falls back to a plain textarea if the bundle is absent.
- **Office editing = lossy Markdown round-trip via permissive libs (`services/office.py`).** DOCX
(python-docx, MIT) and ODT (odfdo, Apache-2.0) extract to the editor's Markdown subset on read and
regenerate on save through a binary-capable route (`POST /projects/{id}/office-file`) that still
funnels through `changes.apply_change` (policy + encryption + audit + redaction/draft) — the JSON
`POST .../file` is UTF-8-text-only and must not carry office bytes. It is **body-level and lossy by
design** (tables/images/styles/comments dropped) — keep the "formatting simplified" banner. **RTF**
has no permissive writer and legacy **DOC** no permissive reader, and passphrase-encrypted files
can't be parsed server-side → all three fall back to the **download→edit→re-upload handoff**
(`replaceByUpload` → `/upload` with `dest=<path>`, overwriting in place). Don't add a copyleft/heavy
office engine (LibreOffice/Collabora/ONLYOFFICE) to core — those are optional sidecars (see
[`OPTIONS.md`](OPTIONS.md)). Changes-diff/Authorship stay text-only, so they remain unavailable for
the binary office blobs (documented).
- **Core stays permissive; copyleft/optional features are plugins.** Frontend plugins live under
`PLUGINS_DIR` (folder + `plugin.json` + `frontend/` entry); backend only serves their assets +
lists manifests (`services/plugins.py`, `GET /plugins`) and **never executes plugin code**; the
console lazy-loads them post-login and they register previews via `window.Galena.registerPreview`.
**DjVu is the GPL-2.0 `GalenaPlugins/DjVuViewer` plugin, NOT core** — don't reintroduce djvu.js into
`frontend/static`. Binary files with no preview handler show a download card (never an editor).
Admins enable/disable installed plugins under **Administration → Plugins** (`GET/PUT /admin/plugins`,
state in the `disabled_plugins` setting); the console's `/plugins` list returns only enabled ones.
- **Session cookie `Secure` is auto-detected from the request scheme** (`routers/auth._cookie_secure`):
Secure over HTTPS, omitted over plain HTTP — never key it off `APP_ENV` again, or login silently
breaks over HTTP (the browser drops a Secure cookie → bounced on reload). `SESSION_COOKIE_SECURE`
forces it; an empty value is coerced to auto so it can't crash startup.
- **i18n covers `title`/`placeholder` attributes, not just text nodes** (`localize`/`_trAttr`). Every
standalone static UI string must be an `I18N.pl` key or it stays English; the editor content area
is `data-no-i18n` so typed text isn't translated. Keep PL coverage when adding UI.
## Gotchas
- **GitPython needs the `git` binary** (in the Dockerfile; verify locally with `git --version`).
- On Windows, write `.env` without a BOM (PowerShell `Out-File -Encoding utf8` adds one) — use
`[System.IO.File]::WriteAllText`.
- The migration creates enum types explicitly, then runs `Base.metadata.create_all` (enums use
`create_type=False`), then applies grants in a role-guarded DO block. If you add a model, the table
is picked up automatically; only add a new enum to the migration's `ENUMS` map.
## Status
Initial build (June 2026). Verified: backend import + ORM mappers, full GitPython round-trip
(commit/changes/publish/blame/clone), 51 API routes register, static console boots with no JS errors,
the Slate editor mounts and parses Markdown. Integration tests are written and gated on a Postgres
(`GALENA_RUN_INTEGRATION=1`); full end-to-end is exercised by `docker compose` / CI.
+68
View File
@@ -0,0 +1,68 @@
# Credits & licenses
Galena is **Apache-2.0**. Every runtime dependency in **core** is permissive (Apache / MIT / BSD /
HPND / PSF) — no copyleft (not even LGPL) — so it clears a corporate legal/IT license scan. A CI
gate (`backend/scripts/license_gate.py` + a JS `license-checker`) fails the build on GPL/AGPL/SSPL.
**Optional plugins are separate.** Galena supports drop-in frontend plugins (see *Plugins* below)
that an operator installs deliberately, outside the core tree. A plugin may carry its own license —
e.g. the **DjVu Viewer** plugin is **GPL-2.0** because DjVu has no permissive decoder (see below).
Core ships none of that; the copyleft-free guarantee is about what's installed by default.
## Backend (Python)
| Dependency | Purpose | License |
|---|---|---|
| FastAPI | web framework | MIT |
| uvicorn | ASGI server | BSD-3-Clause |
| python-multipart | file uploads | Apache-2.0 |
| pydantic / pydantic-settings | validation & settings | MIT |
| SQLAlchemy | ORM | MIT |
| Alembic | migrations | MIT |
| pg8000 | pure-Python Postgres driver (no libpq) | BSD-3-Clause |
| argon2-cffi | Argon2id password + passphrase KDF | MIT |
| cryptography | AES-256-GCM envelope encryption | Apache-2.0 / BSD-3-Clause |
| GitPython | the git facade (wraps the system `git`) | BSD-3-Clause |
| Pillow | image thumbnails + EXIF | HPND |
| python-docx | DOCX read/write (in-app editing) | MIT |
| odfdo | ODT read/write (in-app editing) | Apache-2.0 |
| striprtf | RTF → text extraction (read-only) | BSD-3-Clause |
| OpenTelemetry SDK/exporters (opt-in) | tracing | Apache-2.0 |
## Frontend
- The **console** (`frontend/index.html` + `app.css` + `app.js`) is hand-written vanilla
JS/CSS — no framework, no build step. Icons are [Tabler Icons](https://tabler.io/icons) (MIT)
outline path data, drawn inline.
- **Document previews:** **PDF.js** (Apache-2.0, lazy-loaded from cdnjs) renders PDFs in core.
Images use Pillow thumbnails + an in-app lightbox. **DjVu is not in core** — it ships as the
optional, GPL-2.0 **DjVu Viewer** plugin (see *Plugins*).
- The **editor island** (`frontend/editor/`) bundles **React** (MIT), **Slate** /
[`ianstormtaylor/slate`](https://github.com/ianstormtaylor/slate) + `slate-react` +
`slate-history` (all MIT), built once by **Vite** (MIT) into `frontend/static/editor.js`.
## Optional extras (not installed by default)
- `pywebpush` (MPL-2.0) — only if you enable browser-push delivery. Kept out of the default set so
the core dependency tree stays fully copyleft-free. Email uses the stdlib `smtplib` (no dep).
## Plugins (installed deliberately, licensed independently)
Frontend plugins live outside core under `PLUGINS_DIR`; the backend serves their static assets and
the console lazy-loads them after sign-in (it never executes plugin code). They are not part of the
permissive core tree and may be copyleft.
- **DjVu Viewer** (`GalenaPlugins/DjVuViewer`, **GPL-2.0**) — inline `.djvu` preview via
[djvu.js](https://djvu.js.org/). The djvu.js *library* is GPL-2.0 (it borrows DjVuLibre / Java-DjVu
code); the *viewer* wrapper is The Unlicense. **There is no permissive DjVu decoder**: DjVuLibre
and every JS port are GPL. The one exception is [`djvu-rs`](https://github.com/matyushkin/djvu-rs)
(MIT, a clean-room Rust codec with WASM bindings) — promising but young and self-attested
clean-room, so a permissive DjVu plugin built on it is a documented future option, not yet shipped.
## Design inspirations (no code or assets used)
- **UI design system** adapted from the sibling **Counsel Scorecard** project (tokens, components,
Open Color neutrals, Tabler icons).
- **Layout** inspired by **Cloudreve**, **ClovaLink**, and **Nextcloud** — visual reference only.
- The **chat-style review** takes visual cues from ShadCN UI / NiceGUI chat examples — reference only.
- The friendly history view was inspired by, but does not use, **git-sim**.
+33
View File
@@ -0,0 +1,33 @@
# Caddy serves the static console and reverse-proxies the API to the backend.
# Default: plain HTTP on :80. For TLS, set CADDY_SITE_ADDRESS to your domain in .env
# (Caddy then provisions a certificate automatically).
{$CADDY_SITE_ADDRESS::80} {
encode gzip
# API + health → backend
@api path /api/v1/* /healthz
handle @api {
reverse_proxy backend:8000
}
# Everything else → the static console (SPA fallback to index.html)
handle {
root * /srv
try_files {path} /index.html
# Revalidate the console assets (ETag) so a rebuilt app.js/app.css/editor.js is picked
# up without a manual hard refresh.
header Cache-Control "no-cache"
# Content-Security-Policy for the console. 'unsafe-inline' covers the theme pre-paint
# inline script + inline style attributes; cdnjs is the lazy-loaded PDF.js source.
# The backend's /raw endpoint sets its own stricter CSP, so this only applies to /srv.
header Content-Security-Policy "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; img-src 'self' data: blob:; font-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; worker-src 'self' blob: https://cdnjs.cloudflare.com; connect-src 'self' https://cdnjs.cloudflare.com"
file_server
}
header {
X-Content-Type-Options nosniff
X-Frame-Options DENY
Referrer-Policy strict-origin-when-cross-origin
Cross-Origin-Opener-Policy same-origin
}
}
+368
View File
@@ -0,0 +1,368 @@
# Galena — Functional Documentation
This document describes **what Galena does and how people use it** — its features, concepts, and
workflows — independent of the implementation. For setup/architecture see [`README.md`](README.md);
for dependency licensing see [`CREDITS.md`](CREDITS.md).
---
## 1. What Galena is
Galena is a **self-hosted, git-backed cloud drive**. To the person using it, it looks and behaves
like an ordinary file-storage app — folders, uploads, a grid of documents, sharing, search. Underneath,
every project's files live in a real **git repository**, so the product gives you full version history,
side-by-side comparison, review-before-publish, authorship per line, and rollback — **without requiring
any knowledge of git**. The interface is deliberately *de-jargoned*: you never see the words "commit",
"branch", or "merge"; you see **redactions**, **versions**, and **publish**.
**Who it's for:** teams that want versioned, reviewable document storage they host themselves.
---
## 2. Key concepts & terminology
Galena renames git's concepts into plain language. The friendly term is what you see in the app.
| You see (friendly) | Means | Notes |
|---|---|---|
| **Workspace** | A top-level space for a team | The outermost container and a permission boundary. |
| **Group** / **Folder** | A container inside a workspace | Organises things; can carry its own access. |
| **Project** | A place where files live with full history | The only container that *is* a versioned repository. |
| **Main version** | The official, current copy everyone sees | The default line of a project. |
| **Version** | A separate working copy | Lets you make changes without touching the main version. |
| **Redaction** | One saved change | A point in history you can return to. |
| **Draft** | Proposed changes sent for review | Submitted from a working version, published by an approver. |
| **Publish** | Bring approved changes into the main version | |
| **Combine versions** | Merge one version's changes into another | (Not necessarily the main version.) |
| **Resolve discrepancies** | Decide what to keep when two edits overlap | The conflict-resolution screen. |
| **Changes** | A before-and-after comparison | Side-by-side or merged/inline. |
| **Authorship** | Who wrote each line, and when | |
| **Clone** | Make your own separate copy of a project, with its history | |
A built-in glossary is also available in the app under **Account → About & help**.
---
## 3. The access model (roles & permissions)
Access is granted to a **person** on any node (a workspace, group, folder, or project). A grant
**cascades downward**: granting someone access on a workspace gives them that access on everything
inside it. The effective access on any item is the **highest** grant they hold on that item or any of
its ancestors.
**Roles, from least to most powerful:**
| Role | Can… |
|---|---|
| **Viewer** | Open and read items; download files; view history, changes, and authorship. |
| **Editor** | Everything a viewer can, plus: create/edit/upload/rename/move/copy/delete files, save redactions, submit drafts, and take part in review threads. |
| **Approver** | Everything an editor can, plus: **approve & publish** or **request changes** on a draft. |
| **Manager** | Everything an approver can, plus: manage members and roles on the item, rename/move/delete the node, and change project settings. |
**Other rules:**
- **Instance administrators** (a per-account flag) implicitly have manager-level access everywhere and can reach the Administration area.
- A node's **owner** (and your personal *My files* workspace) always has manager rights on it.
- **No access → the item is hidden** (you get a "not found", not a "forbidden", so its existence isn't leaked).
- You **cannot approve your own draft** — a different approver must review it.
- A **viewer can read a review but not post in it**; posting requires editor or higher.
The model is **SSO/LDAP-ready**: grants reference an abstract principal and passwords are optional at
the schema level, so external identity providers can be added later.
---
## 4. The console at a glance
- **Left sidebar** — the file scopes: **My files** (your personal workspace), **Favourites**,
**Shared with me**, **Recent**, an expandable **Workspaces** tree, a **Storage** usage indicator,
and **Settings**. The Workspaces tree expands at **every level** — click the twisty next to any
workspace, group, or folder to reveal what's inside it (projects are leaves, opened in the main
area). The sidebar can be hidden; on narrow screens it becomes a drawer.
- **Top bar** — a sidebar toggle, a **breadcrumb trail** of where you are (each segment is clickable;
it wraps to a second line for long paths), then the right-aligned actions: **Dashboard**, **Drafts**,
**Administration** (admins only), **search**, **notifications** (bell with an unread counter),
**theme**, **language**, and your **account** menu.
- **Main area** — a grid/list of folders and files, or the current view (dashboard, a draft, history…).
The brand mark (a violet square with an asterisk) is the only place the brand colour appears; every
other control is monochrome with outline icons.
---
## 5. Workspaces, groups/folders, and projects
- **Create** anything from the **New ▾** menu: a workspace (top level only), a group, a folder, a
project, a document, or an upload.
- **Projects** are where versioned files live; creating one initialises its history automatically.
- Containers can be **renamed**, **moved**, and **deleted** (managers); deleting a container removes
everything inside it.
- A container's page header carries quick actions: **Favourite** (the star **fills in** when the item
is one of your favourites, hollow when not — click to toggle), **Share** (managers), and **Details**
(a panel listing type, path, access, policy, and encryption).
- Each card shows a **status icon** indicating access at a glance:
- *plain* — open / inherited access (nothing special needed);
- *open padlock* — access-controlled and **you have access**;
- *closed padlock* — **you don't have access** → offers **Request access**;
- *people* — shared with others;
- *shield* — the item is **encrypted**.
**Drive views & sorting:** switch between **grid / compact / list**, **filter** by name, and **sort**
by name or size (ascending/descending). Your chosen view, sort field, and direction are **remembered**
across sessions.
---
## 6. Working with files in a project
Inside a project you get the usual file-manager actions (via the **New ▾** menu and a per-item
right-click / kebab menu), subject to your role:
- **Open / Preview** — images open in a lightbox; PDFs render inline; DjVu renders if the plugin is
installed (else it downloads); other files open in the editor or download. Every full-screen
preview has a **✕ close button** in the top-right corner (and also closes on **Esc** or by clicking
the backdrop).
- **Download** the file.
- **Create** a document or **Upload** files (there is a per-file size limit to protect the server).
- **Rename**, **Move** (to a new path within the project), and **Copy** a file.
- **History** and **Authorship** for the file.
- **Encrypt / Re-encrypt** the file.
- **Delete** the file.
### Office documents (Word / OpenDocument)
You can edit **DOCX** and **ODT** files right in the browser: Galena opens the document's text in the
normal editor and saves your changes back as a DOCX/ODT, recorded as a redaction like any other edit.
This editing is **simplified** — it keeps headings, paragraphs, bold/italic, lists and basic tables,
but **drops images, footnotes, comments, custom styles and tracked changes on save**, so a banner
warns you and offers **Download original** to edit with full formatting in your own app.
**RTF** and older **DOC** files (and any office file protected by a passphrase) can't be edited
in-browser; they show a card to **Download**, edit in your desktop app, then **Upload edited version**,
which replaces the file in place as a new redaction. This "edit locally" handoff is also the way to
make a fully-faithful change to a DOCX/ODT when the simplified editor isn't enough.
> A note on history for office files: because Word/OpenDocument files are compressed binaries,
> **Changes (the side-by-side diff) and Authorship aren't available** for them the way they are for
> text — the file still has full version history and rollback, but you compare versions by opening
> them, not line by line.
Every save, upload, move, copy, or delete is recorded as a **redaction** in the project's history.
---
## 7. Document previews
- **Images** — click to open a lightbox; thumbnails appear on grid cards.
- **PDF** — renders inline, page by page.
- **DjVu** — provided by the optional **DjVu Viewer plugin**. With it installed, `.djvu`/`.djv` files
preview inline (with page navigation); without it, they simply download. Files the in-browser
decoder can't render (e.g. multi-file/indirect documents) fall back to a download button.
- Untrusted file types are served safely (as downloads, sandboxed) so they can't run code in the app.
---
## 8. The editor
Opening a text or Markdown document loads a **rich, document-style editor** (bold/italic/underline,
headings, bullet/numbered lists, tables, links, quotes). If the editor can't load, it falls back to a
plain text box so editing always works. Saving routes through the normal save workflow (below), so an
edit becomes a redaction or a draft depending on the project's policy.
---
## 9. Saving, versions, and the review policy
Each **project** has a **review policy**:
- **Save directly** (`open`) — your saves are recorded as redactions straight onto the **main version**.
- **Needs approval** (`review_required`) — your saves land on **your own working version**, and you
submit a **draft** to bring them into the main version. Nothing reaches the main version until an
approver publishes it.
Managers set the policy per project; admins set the default for new projects.
---
## 10. Drafts & review (the review conversation)
A **draft** is a request to bring a working version's redactions into the main version. Opening a draft
shows a **review conversation**:
- **Changed files** — each links to its **Changes** (the diff) and, for participants, a **Comment** button.
- **Comment threads** — the review is organised as resolvable threads:
- **Start a thread** with a top-level comment (optionally **anchored to a file**).
- **Reply** within a thread (replies nest under the thread and inherit its file anchor).
- **Resolve** a thread to close it (it collapses) and **Reopen** it later; expand/collapse with **Show/Hide**.
- **Actions** are role-aware:
- An **approver** (who isn't the author) sees **Approve & publish** and **Request changes** (the
latter opens a box for the reason, which is recorded in the thread).
- The **author** sees **Withdraw** and a note that they're waiting for an approver.
- When a draft is **closed** (published, sent back, or withdrawn) the conversation becomes read-only
and a status banner explains the outcome.
- **Approve & publish** merges the draft into the main version. If the merge overlaps with other edits,
you're taken to **Resolve discrepancies** instead.
Drafts are listed on the **Drafts** screen — those you authored plus open ones you can approve (the
latter flagged "for you").
---
## 11. Resolve discrepancies (conflicts)
When publishing (or combining) would overlap with changes already made elsewhere, Galena detects the
conflict and opens **Resolve discrepancies**: a per-file, side-by-side picker showing **Main version**,
**Your version**, and an editable **Result**. You choose which side to keep (or write a combined
result) and then publish. Plain-language throughout — "two people changed the same lines; choose what
to keep."
---
## 12. Combine versions
From a project's **History** you can **Combine versions** — merge one version's changes into another
(not necessarily the main version). You pick a source and a target version; a clean merge applies
immediately, and an overlapping one reports the discrepancies.
---
## 13. Clone
**Clone** makes an independent copy of a project — **with its full history** — as a new project. Useful
for branching off a separate line of work that won't affect the original.
---
## 14. History & Changes
- **History** of a project is shown as an **interactive version graph**: a lane-packed timeline of every
redaction across all versions, with branch/merge lines and **version-tip badges** (e.g. *main
version*). **Click any redaction** to see its details and exactly which files it changed; each file
links to its **Changes**.
- A single file's **History** is a clickable timeline of its redactions.
- **Changes** is the diff between two points. By default it's a **two-window, side-by-side** compare
(removed lines on the left, added on the right) with a toggle to a **merged/inline** view. The
breadcrumb shows the full path to the file being compared.
- **Authorship** shows who wrote each line of a file and when (not available for binary or encrypted files).
---
## 15. Encryption
Files and folders can be **optionally encrypted** (they show a shield icon). Encryption is **per-file
envelope encryption** with two modes:
- **Server-managed** — the server can decrypt for authorised users, so previews, search, and Changes
keep working transparently.
- **Passphrase (zero-knowledge)** — protected by a passphrase that only the user knows; the server
cannot decrypt without it (you're prompted for the passphrase to open the file, and lost passphrase =
lost data).
In all cases the stored repository holds **ciphertext** — encryption keys are never kept in the
repository. History and older versions remain decryptable because each stored version carries its own
key material, so re-encrypting a file never breaks its past.
---
## 16. Permissions & sharing
From any item, **managers** open **Share & permissions** to:
- See **direct** grants on the item and **inherited** grants (and which ancestor they come from), plus the owner.
- **Add a person** by selecting them and a role (viewer/editor/approver/manager).
- **Change or remove** a grant.
If you land on something you can't access, you can **Request access**, which notifies the item's managers.
---
## 17. Notifications
A **bell** in the top bar shows an **unread count** and opens an in-app panel listing events with
relative timestamps and a **Mark all read** action. Events include: you're asked to **review** a draft,
you're **mentioned** (`@name`), your draft was **published** or **sent back**, a **new review message**,
a **permission was granted**, or someone **requested access**.
Delivery channels (per-user, under **Notification settings**): **in-app** (always on), opt-in **browser
push**, and opt-in **email**. Push and email are only active if the server is configured for them.
---
## 18. Search
The top-bar **search** (also the Ctrl/⌘-K palette) searches **across workspaces, groups, folders, and
projects** by name/path **and inside file content**, returning a short **snippet** for content matches.
Results are scoped to what you're allowed to see. (Encrypted and binary file contents aren't searched.)
---
## 19. Dashboard
A workflow-tuned overview: **stat cards** (workspaces, active users, open drafts, storage used of
quota), a **14-day activity chart** (redactions vs drafts vs publishes), a **file-types** breakdown, a
**storage-by-workspace** chart, an **"Approvals waiting for you"** queue with quick links, and a
**recent-activity** feed — all scoped to what you can see (no global activity leakage).
---
## 20. Administration
Instance administrators get an **Administration** area to:
- **Manage users** — create users, edit name/admin flag, change passwords (which immediately ends that
user's existing sessions), and deactivate accounts.
- **Manage access** — view and change a user's grants across nodes; create workspaces/groups.
- **Git & instance settings** — the default review policy for new projects, the commit author identity,
and read-only info (storage backend, data directory, whether encryption is configured).
- **Plugins** — see installed plugins (name, version, license) and **enable/disable** each one.
---
## 21. Plugins
Galena's core ships only permissively-licensed code. Capabilities that would require copyleft or niche
code are delivered as **optional, separately-licensed frontend plugins** that an operator installs
deliberately. The reference plugin is **DjVu Viewer** (inline DjVu preview). Plugins register their
features with the console after sign-in; with a plugin absent, the related files degrade gracefully
(e.g. DjVu files download). Admins toggle plugins from **Administration → Plugins**.
---
## 22. Account, sessions, theme & language
- **Account menu** — About & help, Settings, and Sign out.
- **Sessions** are server-side and can be revoked instantly (sign out, account deactivation, or a
password change all end existing sessions). Login persists correctly whether you're on HTTPS or a
plain-HTTP LAN host.
- **Theme** — light / dark / **system** (follows your OS), chosen with no flash on load.
- **Language** — full **English / Polish** localization, including the login screen; the interface
auto-detects Polish browsers. (Some proper nouns and technical identifiers stay as-is by design.)
---
## 23. Typical end-to-end flow
1. Sign in → open a **Workspace** (or your **My files**).
2. Create a **Project**; set it to **Needs approval** if changes should be reviewed.
3. **Upload** files or **create a document** and edit it; each save is a **redaction**.
4. Submit a **Draft** for review.
5. An **approver** opens the draft, reads the **Changes**, leaves **comments** in resolvable threads,
then **Approves & publishes** (or **Requests changes**).
6. If edits overlap, **Resolve discrepancies**, then publish.
7. Anyone with access can browse **History**, compare **Changes**, and see **Authorship** — and roll
back by reverting to an earlier redaction.
---
## 24. Glossary (quick reference)
- **Workspace / Group / Folder** — containers (top-level / nested).
- **Project** — a container whose files are versioned.
- **Main version** — the canonical, published copy.
- **Version** — a separate working line of changes.
- **Redaction** — one saved change.
- **Draft** — proposed changes awaiting approval.
- **Publish** — bring approved changes into the main version.
- **Combine versions** — merge one version into another.
- **Resolve discrepancies** — settle overlapping edits.
- **Changes** — a before/after comparison.
- **Authorship** — per-line "who and when".
- **Clone** — an independent copy of a project, with history.
- **Viewer / Editor / Approver / Manager** — the four access roles, least to most powerful.
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or Derivative
Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and do
not modify the License. You may add Your own attribution notices
within Derivative Works that You distribute, alongside or as an
addendum to the NOTICE text from the Work, provided that such
additional attribution notices cannot be construed as modifying
the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 The Galena Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+9
View File
@@ -0,0 +1,9 @@
Galena
Copyright 2026 The Galena Authors
This product includes software developed as part of the Galena project,
licensed under the Apache License, Version 2.0 (see LICENSE).
Galena is a git-backed cloud-storage application. Its user interface design system
is adapted from the sibling Counsel Scorecard project. Layout ideas were inspired by
Cloudreve, ClovaLink, and Nextcloud — no code or assets from those projects were used.
+91
View File
@@ -0,0 +1,91 @@
# Editing office documents (DOC / DOCX / ODT / RTF) — options & decision
This records the deep analysis behind how Galena edits office documents, and the options that were
considered and rejected, so the trade-offs aren't re-litigated from scratch later.
## Decision
- **Primary (shipped, in core): option #2 — in-app editing of DOCX & ODT via the Markdown editor.**
On open, the document body is extracted to Markdown (`python-docx` for DOCX, `odfdo` for ODT) and
opened in the existing Slate editor; on save, it's regenerated from Markdown and funnelled through
the normal write chokepoint (`changes.apply_change`) as a redaction/draft. All deps are permissive
(MIT / Apache-2.0 / BSD-3), so it stays in the permissive core.
- **Fallback (shipped, in core): option #1 — "edit locally" handoff.** Any document that can't be
round-tripped — **RTF**, **legacy DOC**, passphrase-encrypted files, or a DOCX/ODT that fails to
parse — shows a card to **Download**, edit in your own app, and **Upload edited version** (which
overwrites the file in place, again through `apply_change`). This is also offered alongside the
editor for DOCX/ODT when full fidelity matters.
### The honest trade-off
Editing via Markdown is **body-level and lossy**: headings, paragraphs, bold/italic, bullet/number
lists and (DOCX) simple tables survive; **images, footnotes, comments, custom styles, headers/footers
and tracked changes are dropped on save.** The editor therefore shows a "formatting may be simplified"
banner and a one-click Download-the-original. For full fidelity, use the handoff.
> **No option is both permissive-core-eligible *and* high-fidelity** — that combination does not exist.
> Every faithful editor is copyleft (Collabora MPL, ONLYOFFICE/SuperDoc AGPL) or proprietary (Apryse,
> Syncfusion). And keeping the real office binary breaks Galena's git-native UX (a zipped DOCX/ODT
> diffs *wholesale*, so Changes/Authorship/merge/search degrade — see the binary-blob note below).
> The ranking optimizes for Galena's priorities: **permissive core → git-native text UX → low infra.**
## Full ranking (best → worse for Galena)
| # | Option | Formats truly editable | License → placement | Fidelity | Effort | Git fit |
|---|--------|------------------------|---------------------|----------|--------|---------|
| 1 | **Native handoff** (download → edit → re-upload) | DOC·DOCX·ODT·RTF (lossless) | none → **core** | Perfect | Low | binary |
| 2 | **python-docx + odfdo** behind the Slate editor | DOCX·ODT (lossy); RTF/DOC read-only | MIT/Apache → **core** | Low | High | text (extracted) |
| 3 | **Collabora Online** (WOPI sidecar) | DOC·DOCX·ODT·RTF | MPL-2.0 → operator add-on | Highest | Very high | binary |
| 4 | **ONLYOFFICE Docs** (iframe+JWT sidecar) | DOC·DOCX·ODT·RTF | AGPL-3.0 → add-on | High | Very high | binary |
| 5 | **SuperDoc** (client-side, plugin) | DOCX only | AGPL-3.0 → plugin | High | High | binary |
| 6 | **LibreOffice-WASM** (ZetaOffice, plugin) | DOC·DOCX·ODT·RTF | MPL+LGPL → plugin | Highest, but beta | Very high | binary |
| 7 | **Pandoc** (server convert ↔ Markdown) | DOCX·ODT·RTF; no DOC | GPL → out-of-process | Low (double-lossy) | Very high | text |
| 8 | **Apryse WebViewer** (commercial, client WASM) | DOCX only | Proprietary (~$10k+/yr) | High | Very high | binary |
| 9 | **TipTap + DOCX converters** | DOCX only | Paid+cloud *or* AGPL | High | Very high | binary |
| 10 | **LibreOffice headless** (`soffice --convert-to`) | all (convert-only, not an editor) | MPL+bundled (L)GPL → sidecar | High convert / lossy edit | Very high | binary |
**Considered and cut:** **Syncfusion Document Editor** (proprietary + needs a second .NET/Java service
— worst stack clash) and **CKEditor 5** (GPL core + paid/cloud converters that egress document bytes,
and it's HTML round-trip, not true DOCX round-trip).
### Why each rank (one line)
1. **Handoff** — already ~95% built (binary download card + multipart upload through `apply_change`); zero deps/infra; lossless for all four formats because the user's own app does the editing.
2. **python-docx + odfdo** — the only path that's both permissive-core-eligible *and* can revive text-native features; reuses the existing editor; lossy and DOCX/ODT-only. **(chosen)**
3. **Collabora** — best fidelity + co-editing; MPL (most permissive heavyweight); but a ~1GB sidecar and a full WOPI host in the backend; the pattern Nextcloud/Seafile/etc. all use.
4. **ONLYOFFICE** — marginally better Microsoft-format fidelity than Collabora, but AGPL-3.0 (network copyleft) and heavier (~4GB).
5. **SuperDoc** — cleanest in-browser true editor (no server), but AGPL and DOCX-only; needs a `registerEditor` plugin seam Galena lacks.
6. **LibreOffice-WASM** — real LibreOffice client-side for all four formats, but beta/unstable, ~1GB runtime, and the export-bytes-out step is unimplemented today. Watch, don't ship.
7. **Pandoc** — cleanest git story *if* Markdown becomes canonical, but GPL (can't even be a plugin), no `.doc`, doubly-lossy; strictly a worse-licensed #2.
8. **Apryse** — genuine client-side WASM DOCX editing, but proprietary (~$10k+/yr) and DOCX-only.
9. **TipTap + converters** — MIT editor, but converters are paid+cloud or AGPL; effectively DOCX-only and needs a full editor-bundle swap. Dominated by #5.
10. **LibreOffice headless** — reference converter, not an editor; heavy, copyleft-bundling, server attack surface. Its real value is office→PDF **preview**, not editing.
## Cross-cutting constraints (why the ranking is what it is)
- **License is the dominant axis.** Core ships only permissive deps and must pass
`backend/scripts/license_gate.py` (denies AGPL/SSPL always, GPL-without-LGPL). Only zero-dependency
patterns (the handoff) and genuinely permissive libs (`python-docx` MIT, `odfdo` Apache-2.0,
`striprtf` BSD-3) can touch core. Everything high-fidelity is copyleft or proprietary → operator-
installed plugin/sidecar only (the GPL-2.0 DjVu Viewer is the precedent). *(Trap: avoid `odfpy` —
its tri-license string slips the gate via the "LGPL" substring but embeds GPL; use `odfdo`.)*
- **Git-model fit splits the field.** Storing the real office binary is `binary-blob`: a zipped
DOCX/ODT decodes as non-UTF-8, so Changes returns "binary" (re-zipping diffs wholesale), Authorship
is unavailable, the textarea-based Resolve-discrepancies is meaningless, `git merge` conflicts
wholesale, and search skips it. Only *convert-to-text* strategies make those features meaningful —
and only by tracking text. Galena keeps the original DOCX/ODT as the blob (so these features stay
limited for office files, as documented) and gives editing via extraction.
- **Infra fit.** Galena is single-instance FastAPI + Postgres + Caddy, no runtime build, one committed
editor bundle. Anything adding a container or foreign runtime (Collabora ~1GB, ONLYOFFICE ~4GB,
Syncfusion .NET, …) is operator-add-on-only. Option #2 runs in-process with permissive Python libs.
- **Write chokepoint.** The JSON save route is UTF-8-text-only; office saves use a binary-capable route
(`POST /projects/{id}/office-file`, and the multipart `/upload` for the handoff) that still funnels
through `changes.apply_change` — preserving review policy, encryption, audit, and redaction/draft.
- **Encryption wall.** Passphrase-mode blobs can't be decrypted server-side, so they can't be extracted
for editing — they fall back to the handoff (the user supplies the passphrase to their own app).
## If higher fidelity is ever needed
Add **Collabora Online over WOPI** as an *optional, operator-installed* sidecar (rank 3) — the same
two-tier split (Markdown editor in core, office suite as an external WOPI server) that the whole
self-hosted-drive market uses. This is a deliberate, documented future step, not core.
+366
View File
@@ -0,0 +1,366 @@
# Galena
![Galena — a self-hosted, git-backed cloud drive](docs/social-preview.png)
> 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.
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`](CREDITS.md)).
📖 For a feature-by-feature description of what Galena does and how people use it, see
**[`FUNCTIONAL.md`](FUNCTIONAL.md)**.
---
## Quick start
```bash
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())"
docker compose up -d --build # postgres -> migrate(+seed) -> backend -> caddy
```
Open **http://localhost/** and sign in with `BOOTSTRAP_ADMIN_EMAIL` / `BOOTSTRAP_ADMIN_PASSWORD`.
API docs are at **http://localhost/api/v1/docs**. Only Caddy is published to the host; Postgres and
the backend are 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). |
| **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**. |
| **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 **two-window side-by-side compare** with a merged/inline toggle. |
| **Editor** | a **Slate** rich-text editor with a docx-style toolbar, shipped as one pre-built bundle (progressive enhancement over a plain-text fallback). 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** (and passphrase-encrypted files) use the **download → edit → re-upload** handoff. See [supported formats](#supported-file-formats) and [`OPTIONS.md`](OPTIONS.md). |
| **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. |
| **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. |
| **Previews** | images open in a lightbox (grid cards show Pillow thumbnails); **PDF** renders inline via **PDF.js**. **DjVu** is an optional [plugin](#plugins). |
| **Sessions** | server-side **cookie** sessions (instant kill-switch). JWT was considered — see roadmap. |
| **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**, **legacy DOC** | download | ↪ **handoff** | No permissive round-trip — **Download → edit in your app → Upload edited version** (overwrites in place as a new redaction). |
| **Images** (`.png .jpg .jpeg .gif .webp .bmp`) | ✅ lightbox + thumbnails | — | Pillow thumbnails on cards. |
| **PDF** | ✅ inline (PDF.js) | — | Lazy-loaded viewer with a close button. |
| **DjVu** (`.djvu`, `.djv`) | ✅ via optional [plugin](#plugins) | — | GPL-2.0 plugin, not core. |
| **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`](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.
- Errors are **RFC 9457** Problem Details; the audit log is **append-only** (the runtime DB role has
no UPDATE/DELETE on it).
---
## 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
/ instance-admin 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).
---
## Configuration
All via `.env` (see [`.env.example`](.env.example)). Highlights:
| Variable | Purpose |
|---|---|
| `DATABASE_URL` / `MIGRATION_DATABASE_URL` | runtime (`app`, DML) / migrations (`migrator`, DDL) |
| `DATA_DIR` | where project git repos live (LocalStorage) |
| `BOOTSTRAP_ADMIN_EMAIL` / `_PASSWORD` | first admin (created by the seed) |
| `SESSION_TTL_HOURS` | cookie session lifetime (hours) |
| `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) |
| `CADDY_SITE_ADDRESS` | set to your domain for automatic HTTPS |
| `OTEL_ENABLED` | opt-in OpenTelemetry export |
---
## API reference
Base path `/api/v1` (full OpenAPI at `/api/v1/docs`).
```
Auth POST /auth/login · /auth/logout · GET /auth/me
Users (admin) GET/POST /users · PATCH /users/{id} · POST /users/{id}/deactivate
Drive scopes GET /drive/home · /drive/favorites · /drive/shared · /drive/recent
Nodes GET /nodes/{id} · POST /nodes · PATCH /nodes/{id} · POST /nodes/{id}/move
· 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|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
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.
- 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.
**DjVu Viewer** (`GalenaPlugins/DjVuViewer`, **GPL-2.0**) is the reference plugin: 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.
---
## 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 → Caddy; only Caddy is published.
```bash
cp .env.example .env # then edit secrets (DB passwords, ENCRYPTION_MASTER_KEY)
docker compose up -d --build
```
Open **http://localhost** and sign in as the bootstrap admin from your `.env`
(`BOOTSTRAP_ADMIN_EMAIL` / `_PASSWORD`). API docs at `http://localhost/api/v1/docs`. For HTTPS, set
`CADDY_SITE_ADDRESS=your.domain` in `.env` and Caddy provisions a certificate automatically.
### 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** you can reach. The console is no-build, so there's nothing to compile on the frontend.
1. **A database.** Either a full Postgres with the two least-privilege roles (`db/init/01-roles.sh`
creates `app` + `migrator`), or — for quick local work — a single trust-auth instance where one
role plays both. Point both URLs at it:
```bash
export DATABASE_URL=postgresql+pg8000://postgres@localhost:5432/galena
export MIGRATION_DATABASE_URL=$DATABASE_URL
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`. (Behind Caddy/HTTPS it's set
> automatically.) No need to fiddle with `SESSION_COOKIE_SECURE`.
2. **Migrate, seed, run:**
```bash
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
```
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.
### Tests
```bash
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/`)
```bash
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.
- **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`) + two-window changes. *Considered:*
**git-sim** (Manim) to export printable/animated diagrams — heavy (ffmpeg/cairo/LaTeX), deferred.
- **Previews.** Images (Pillow thumbnails + lightbox) and **PDF via PDF.js** (lazy-loaded from cdnjs)
are core. More viewers slot into the same extension→preview switch, now exposed to **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) — see
[supported formats](#supported-file-formats) and [`OPTIONS.md`](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
both the FastAPI middleware and the Caddyfile.
- **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. 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`.
- **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. Postgres + backend are `expose`-only; Caddy 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 same-origin design + cookie scoping
but not by per-request tokens; add `SameSite`/CSRF tokens before exposing to untrusted origins.
- **CSP uses `'unsafe-inline'`** for the console (theme pre-paint script + inline styles). Tightening
to nonces/hashes is a follow-up.
- **`--forwarded-allow-ips *`** is safe only because the backend is `expose`-only behind Caddy. If
you publish the backend port directly, set `FORWARDED_ALLOW_IPS` to the proxy address.
- **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](LICENSE) — chosen for its explicit patent grant and clean corporate review. See also
[`NOTICE`](NOTICE) and [`CREDITS.md`](CREDITS.md).
+54
View File
@@ -0,0 +1,54 @@
# Code review — June 2026 polish session
A record of the adversarial, multi-agent code review run over the changes made in the June 2026
"polish" session, and how each confirmed finding was resolved. Kept in-repo so the review history
travels with the code.
## Changes that were under review
| Area | Change |
|---|---|
| **Search** | Correct substring matching (start/middle/end + file content) **and** a ~100–120× speedup: reads moved to a cached pure-Python-ODB repo (`git_facade._read_repo`, `odbt=GitDB`) — no `git cat-file` subprocess per object, no per-`close()` `gc.collect()`; writes call `_invalidate_read`. Search uses `git_facade.scan_blobs` (one repo open + one tree walk, lazy content). 30 s timeout → <200 ms. |
| **i18n (PL)** | All 31 audit findings fixed (missing keys + mixed text nodes wrapped in their own `<span>`); review-thread system messages localized; dialog titles pre-translated via `_tr()`. |
| **Sidebar** | `navTree` made **recursive** — every container (workspace/group/folder) expands at any depth; projects are aligned leaf nodes. |
| **Drive/details** | Favourite star **fills** when set; the filter box matches the button height (36 px); the Details dialog rows got `.detail-rows .row` flex styling (label ⟷ value) — fixed the glued "Dostępotwarty" / "Szyfrowanienone". |
| **Previews** | A persistent corner **✕** close button on every full-screen preview (PDF, the DjVu plugin via `Galena.docOverlay`, and the image lightbox). |
| **Tests** | 10 new DB-free unit tests (read-repo cache + invalidation, `scan_blobs`, search snippet); benign Windows GC finalizer warning suppressed with a documented `filterwarnings`. |
## Method
A workflow fanned out **5 reviewers** (sidebar recursion, i18n completeness, CSS regressions, the
`git_facade` read-cache, docs accuracy). Each finding was then handed to an **independent verifier**
that re-read the code and tried to refute it. Result: **14 raw findings → 9 confirmed → 9 fixed**;
**5 were refuted** by the verification pass and dropped. (19 agents total.)
## Confirmed findings — all resolved
| # | Severity | Area | Problem | Resolution | Verified |
|---|---|---|---|---|---|
| 1 | **major** | sidebar | The recursive `state.children` cache was never invalidated, so **create / rename / delete / move** left an expanded subtree showing the old child list until manual collapse/re-expand. | Added `refreshExpanded()` (refetches children for every expanded container) and wired it into `createNode`, `renameNode`, `delNode`, the move handler, `cloneProject`, `adminCreateChild`, `createGroupDialog`. | Live: create + delete reflected in the sidebar with no collapse/re-expand. |
| 2 | minor | sidebar | `toggleTree`'s bare `catch {}` left an open chevron with an empty subtree and **no error feedback** if the children fetch failed. | On failure, revert `state.expanded[id]` and `toast(e.message)` — matching the file's convention. | code review |
| 3 | minor | i18n | The review-thread **"requested changes: «reason»"** system message didn't translate in PL (the whole `reason`-bearing string never matched the `requested changes` key). | In `renderThread`, split a `"phrase: detail"` body so the fixed phrase is its own keyable `<span>` and the reason stays verbatim. | `poprosił(a) o zmiany: Fix the typos` |
| 4 | minor | i18n | File extensions that collide with new lowercase keys (`.pages`→`stron`, `.copy`→`kopia`, …) were **mistranslated** in the list-view Type column. | Uppercase the extension for `_type` (`PAGES`, `PDF`) so user data never matches a UI key. | `PAGES`/`COPY` stay verbatim |
| 5 | minor | i18n | `version:` prefix was untranslated in the **Combine-versions dropdown** (a glued `<option>` text node can't be split). | Pre-translate the static prefix at build time in `_versionLabel` via `_tr()`. | `wersja: feature-x` |
| 6 | minor | i18n | The Details dialog **Access / Encryption** enum values (`granted`/`locked`/`shared`/`none`/`server`/`passphrase`) rendered in English in PL. | Added `I18N.pl` keys for the enum values. | `przyznany` / `brak` / `serwer` |
| 7 | minor | css | A long, unbroken **path overflowed and was clipped** in the fixed-width Details dialog. | Value column `min-width:0; overflow-wrap:anywhere; text-align:right`. | wraps to 2 lines, no overflow (1200 px viewport) |
| 8 | nit | css | `.nav-sub` became **dead CSS** after the recursive rewrite (indentation is now inline `padding-left`). | Removed the rule. | 0 elements use it |
| 9 | nit | i18n | The `'Someone'` author fallback in system messages wasn't keyed. | Added `'Someone' → 'Ktoś'` (and wrapped the author in its own span). | `Ktoś` |
## Refuted (no action)
Five raw findings were dropped after the verification pass could not reproduce them in the code —
e.g. claims of a sidebar recursion cycle, a `.tw` vs `.nav-item svg` specificity conflict, and a
filter-box flex-wrap regression were all checked against the actual CSS/JS and found not to hold.
This is the point of the adversarial second pass: only defects that survive an independent attempt to
refute them get acted on.
## Verification
- **Tests:** `cd backend && pytest` → 37 passed, 5 skipped (the 5 are integration tests gated on
`GALENA_RUN_INTEGRATION` + a migrated Postgres). License gate OK (61 packages, no copyleft).
- **Frontend:** `app.js` reloads with no console errors; each fix confirmed against the live DOM
(computed styles, bounding rects, and a real create→delete sidebar cycle) rather than by eyeballing.
- **Note:** during verification the preview pane had collapsed to ~21 px wide, which produced
misleading overflow readings and screenshot timeouts; measurements were re-taken at 1200 px.
+7
View File
@@ -0,0 +1,7 @@
# Keep the build context small + Linux-clean (the venv holds Windows binaries).
.venv/
__pycache__/
*.py[cod]
.pytest_cache/
*.egg-info/
.coverage
+29
View File
@@ -0,0 +1,29 @@
FROM python:3.12-slim
# git is required by GitPython (the facade wraps the system git binary).
RUN apt-get update && apt-get install -y --no-install-recommends git \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN useradd -m app && mkdir -p /data && chown -R app /data /app
ENV DATA_DIR=/data
USER app
# A default identity + main as the default branch keep GitPython operations clean.
RUN git config --global user.email "galena@localhost" \
&& git config --global user.name "Galena" \
&& git config --global init.defaultBranch main \
&& git config --global --add safe.directory '*'
EXPOSE 8000
HEALTHCHECK --interval=15s --timeout=5s --retries=10 \
CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/api/v1/health').status==200 else 1)"
# Trust X-Forwarded-For only from the reverse proxy. The default '*' is safe ONLY because the
# backend is expose-only in docker-compose (never host-published) — Caddy is the sole ingress.
# If you publish this port directly, set FORWARDED_ALLOW_IPS to the proxy's address so client IPs
# in the audit log can't be spoofed.
ENV FORWARDED_ALLOW_IPS=*
CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port 8000 --forwarded-allow-ips \"$FORWARDED_ALLOW_IPS\""]
+38
View File
@@ -0,0 +1,38 @@
[alembic]
script_location = alembic
prepend_sys_path = .
# The URL is overridden in env.py from MIGRATION_DATABASE_URL (the migrator role).
sqlalchemy.url = postgresql+pg8000://migrator:migrator@localhost:5432/galena
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = console
qualname =
[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
+46
View File
@@ -0,0 +1,46 @@
"""Alembic environment — uses MIGRATION_DATABASE_URL (the DDL `migrator` role)."""
from __future__ import annotations
import sys
from logging.config import fileConfig
from pathlib import Path
from alembic import context
from sqlalchemy import engine_from_config, pool
sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # put backend/ on sys.path
from app.config import get_settings # noqa: E402
from app.models import Base # noqa: E402
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
config.set_main_option("sqlalchemy.url", get_settings().migration_database_url)
target_metadata = Base.metadata
def run_migrations_offline() -> None:
context.configure(url=config.get_main_option("sqlalchemy.url"),
target_metadata=target_metadata, literal_binds=True,
dialect_opts={"paramstyle": "named"})
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.", poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+60
View File
@@ -0,0 +1,60 @@
"""Initial schema: pgcrypto, native enums, all tables, and least-privilege grants.
Tables are created from the ORM metadata (after the enum types exist) so the migration stays in
lockstep with the models; enums, the pgcrypto extension, and the append-only audit grant are
explicit DDL the runtime `app` role can never perform.
"""
from __future__ import annotations
from alembic import op
from app.models import Base
revision = "0001"
down_revision = None
branch_labels = None
depends_on = None
ENUMS = {
"node_kind": ["workspace", "group", "folder", "project"],
"node_role": ["viewer", "editor", "approver", "manager"],
"principal_type": ["user", "group"],
"review_policy": ["open", "review_required"],
"draft_status": ["open", "approved", "rejected", "withdrawn", "published"],
"encryption_mode": ["none", "server", "passphrase"],
"notification_kind": [
"review_requested", "mention", "draft_published", "draft_rejected",
"review_message", "permission_granted", "access_requested",
],
"draft_message_kind": ["message", "comment", "system"],
}
_GRANTS = """
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'app') THEN
GRANT USAGE ON SCHEMA public TO app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app;
-- Append-only audit: the runtime role may insert + read, never mutate.
REVOKE UPDATE, DELETE ON audit_log FROM app;
END IF;
END $$;
"""
def upgrade() -> None:
bind = op.get_bind()
op.execute('CREATE EXTENSION IF NOT EXISTS "pgcrypto"')
for name, values in ENUMS.items():
labels = ", ".join(f"'{v}'" for v in values)
op.execute(f"CREATE TYPE {name} AS ENUM ({labels})")
Base.metadata.create_all(bind=bind)
op.execute(_GRANTS)
def downgrade() -> None:
bind = op.get_bind()
Base.metadata.drop_all(bind=bind)
for name in ENUMS:
op.execute(f"DROP TYPE IF EXISTS {name}")
op.execute('DROP EXTENSION IF EXISTS "pgcrypto"')
@@ -0,0 +1,33 @@
"""Review-comment threads: parent_id (reply → thread root) + resolved (thread closed) on
draft_message. Idempotent ADD COLUMN IF NOT EXISTS so it's a no-op on a fresh DB where 0001's
create_all already built the columns from the current model, and an additive ALTER on an existing
DB. Table-level grants already cover the new columns (no extra grant needed).
"""
from __future__ import annotations
from alembic import op
revision = "0002"
down_revision = "0001"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.execute(
"ALTER TABLE draft_message "
"ADD COLUMN IF NOT EXISTS parent_id uuid REFERENCES draft_message(id) ON DELETE CASCADE"
)
op.execute(
"ALTER TABLE draft_message "
"ADD COLUMN IF NOT EXISTS resolved boolean NOT NULL DEFAULT false"
)
op.execute(
"CREATE INDEX IF NOT EXISTS ix_draft_message_parent_id ON draft_message (parent_id)"
)
def downgrade() -> None:
op.execute("DROP INDEX IF EXISTS ix_draft_message_parent_id")
op.execute("ALTER TABLE draft_message DROP COLUMN IF EXISTS resolved")
op.execute("ALTER TABLE draft_message DROP COLUMN IF EXISTS parent_id")
+4
View File
@@ -0,0 +1,4 @@
"""Galena backend — a git-backed cloud drive."""
from __future__ import annotations
__version__ = "0.1.0"
+96
View File
@@ -0,0 +1,96 @@
"""Typed application settings, sourced from environment variables / .env."""
from __future__ import annotations
from functools import lru_cache
from pathlib import Path
from pydantic import field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
# Core — defaults fail-closed (production hides error detail + enables Secure cookies).
# Set APP_ENV=development explicitly for local plain-HTTP work.
app_env: str = "production"
app_base_url: str = "http://localhost"
# Database (runtime = least-privilege "app" role; migrator = DDL)
database_url: str = "postgresql+pg8000://app:app@localhost:5432/galena"
migration_database_url: str = "postgresql+pg8000://migrator:migrator@localhost:5432/galena"
# Where git projects live on disk (LocalStorage backend). S3 backend is a documented seam.
data_dir: str = "data"
# Optional frontend plugins root (parent of plugin folders, each with a plugin.json). Empty →
# no plugins. Plugins are FRONTEND-ONLY (static assets + manifest); the backend never executes
# plugin code. Used e.g. for the separately-licensed (GPL) DjVu viewer, kept out of core.
plugins_dir: str = ""
# Auth / sessions (cookie-based; JWT documented as a considered alternative)
session_ttl_hours: int = 12
login_max_attempts: int = 5
login_lockout_minutes: int = 15
# None → auto-detect per request scheme (Secure over HTTPS only). Set true/false to force.
# An empty env value (SESSION_COOKIE_SECURE=) is treated as None so it never crashes startup.
session_cookie_secure: bool | None = None
@field_validator("session_cookie_secure", mode="before")
@classmethod
def _blank_secure_is_auto(cls, v):
if isinstance(v, str) and v.strip() == "":
return None
return v
# CORS — empty by default (same-origin design). Comma-separated origins to allow a
# separately-served console in dev.
cors_allow_origins: str = ""
# Bootstrap admin (seed)
bootstrap_admin_email: str = "admin@example.com"
bootstrap_admin_password: str = "admin12345"
# Encryption — base64 32-byte master key that wraps per-item data keys (server-managed mode).
# Empty → encryption features are disabled until a key is configured.
encryption_master_key: str = ""
# Web push (opt-in) — VAPID keys. Empty → web-push channel is a no-op.
vapid_public_key: str = ""
vapid_private_key: str = ""
vapid_subject: str = "mailto:admin@example.com"
# Email (opt-in) — SMTP. Empty host → email channel is a no-op.
smtp_host: str = ""
smtp_port: int = 587
smtp_user: str = ""
smtp_password: str = ""
smtp_from: str = "galena@example.com"
smtp_starttls: bool = True
# OpenTelemetry (opt-in)
otel_enabled: bool = False
otel_service_name: str = "galena-backend"
otel_exporter_otlp_endpoint: str = "http://otel-collector:4317"
@property
def is_production(self) -> bool:
return self.app_env.lower() == "production"
@property
def cors_origins_list(self) -> list[str]:
return [o.strip() for o in self.cors_allow_origins.split(",") if o.strip()]
@property
def projects_dir(self) -> Path:
"""Directory holding one git repo per project, as data_dir/projects."""
return Path(self.data_dir) / "projects"
@property
def encryption_enabled(self) -> bool:
return bool(self.encryption_master_key.strip())
@lru_cache
def get_settings() -> Settings:
return Settings()
+39
View File
@@ -0,0 +1,39 @@
"""SQLAlchemy engine + session factory (runtime `app` role, DML only)."""
from __future__ import annotations
from collections.abc import Iterator
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
from .config import get_settings
settings = get_settings()
engine = create_engine(
settings.database_url,
pool_pre_ping=True,
pool_size=5,
max_overflow=10,
future=True,
# Keep bound parameter values out of exception messages and logs so an unexpected DB
# error can't leak row data.
hide_parameters=True,
)
SessionLocal = sessionmaker(
bind=engine,
autoflush=False,
autocommit=False,
expire_on_commit=False,
class_=Session,
)
def get_db() -> Iterator[Session]:
"""FastAPI dependency yielding a request-scoped session."""
db = SessionLocal()
try:
yield db
finally:
db.close()
+51
View File
@@ -0,0 +1,51 @@
"""FastAPI dependencies: DB session, token extraction, current user, admin guard."""
from __future__ import annotations
import ipaddress
from fastapi import Depends, Request
from sqlalchemy.orm import Session
from .db import get_db
from .errors import AuthenticationError, AuthorizationError
from .models import AppUser
from .services import auth as auth_service
SESSION_COOKIE = "galena_session"
def extract_token(request: Request) -> str | None:
"""Authorization: Bearer takes precedence over the session cookie (intentional > ambient)."""
header = request.headers.get("authorization")
if header and header.lower().startswith("bearer "):
token = header[7:].strip()
if token:
return token
return request.cookies.get(SESSION_COOKIE)
def client_ip(request: Request) -> str | None:
host = request.client.host if request.client else None
if not host:
return None
try:
ipaddress.ip_address(host)
except ValueError:
return None
return host
def get_current_user(request: Request, db: Session = Depends(get_db)) -> AppUser:
token = extract_token(request)
if not token:
raise AuthenticationError("Sign in to continue.")
user = auth_service.resolve_session(db, token)
if user is None:
raise AuthenticationError("Your session has expired — please sign in again.")
return user
def require_admin(user: AppUser = Depends(get_current_user)) -> AppUser:
if not user.is_admin:
raise AuthorizationError("This area is for administrators.")
return user
+69
View File
@@ -0,0 +1,69 @@
"""Native PostgreSQL enums, mirrored as Python StrEnums.
The `.value` strings are the canonical DB enum labels. NodeRole is ordered (viewer < editor
< approver < manager) — `rank()` exposes that ordering for the authz resolver.
"""
from __future__ import annotations
from enum import StrEnum
class NodeKind(StrEnum):
"""The organizational tree. Only `project` maps to a git repository on disk."""
workspace = "workspace" # top level — GitLab-group equivalent, permission boundary
group = "group"
folder = "folder"
project = "project" # a git repo: holds versioned files/folders
class NodeRole(StrEnum):
viewer = "viewer" # read files + history
editor = "editor" # create/edit files, create versions/drafts
approver = "approver" # publish drafts (review)
manager = "manager" # manage members + permissions on this node and below
@classmethod
def rank(cls, role: "NodeRole | None") -> int:
order = {cls.viewer: 1, cls.editor: 2, cls.approver: 3, cls.manager: 4}
return order.get(role, 0)
class PrincipalType(StrEnum):
"""Who a permission grant is for. `user` now; group/ldap/oidc are future SSO seams."""
user = "user"
group = "group"
class ReviewPolicy(StrEnum):
open = "open" # save directly to the main version
review_required = "review_required" # edits go to a version + open a draft for approval
class DraftStatus(StrEnum):
open = "open"
approved = "approved"
rejected = "rejected"
withdrawn = "withdrawn"
published = "published"
class EncryptionMode(StrEnum):
none = "none"
server = "server" # master key wraps the data key — server can decrypt
passphrase = "passphrase" # Argon2id(passphrase) wraps the data key — zero-knowledge
class NotificationKind(StrEnum):
review_requested = "review_requested"
mention = "mention"
draft_published = "draft_published"
draft_rejected = "draft_rejected"
review_message = "review_message"
permission_granted = "permission_granted"
access_requested = "access_requested"
class DraftMessageKind(StrEnum):
message = "message"
comment = "comment" # pinned to a file + line
system = "system" # "submitted draft", "added a redaction", etc.
+96
View File
@@ -0,0 +1,96 @@
"""RFC 9457 Problem Details errors + handlers/middleware.
Stack traces are hidden when APP_ENV=production. DB DataError maps to 422 (not 500).
"""
from __future__ import annotations
import logging
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from sqlalchemy.exc import DataError, IntegrityError
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.middleware.base import BaseHTTPMiddleware
from .config import get_settings
log = logging.getLogger("galena.errors")
settings = get_settings()
_PROBLEM = "application/problem+json"
class AppError(Exception):
status_code = 500
title = "Internal Server Error"
def __init__(self, detail: str | None = None):
self.detail = detail or self.title
super().__init__(self.detail)
class AuthenticationError(AppError):
status_code = 401
title = "Unauthorized"
class AuthorizationError(AppError):
status_code = 403
title = "Forbidden"
class NotFoundError(AppError):
status_code = 404
title = "Not Found"
class ConflictError(AppError):
status_code = 409
title = "Conflict"
class ValidationError(AppError):
status_code = 422
title = "Unprocessable Entity"
def _problem(status: int, title: str, detail: str, extra: dict | None = None) -> JSONResponse:
body = {"type": "about:blank", "title": title, "status": status, "detail": detail}
if extra:
body.update(extra)
return JSONResponse(status_code=status, content=body, media_type=_PROBLEM)
def install_error_handlers(app: FastAPI) -> None:
@app.exception_handler(AppError)
async def _app_error(_: Request, exc: AppError):
return _problem(exc.status_code, exc.title, exc.detail)
@app.exception_handler(StarletteHTTPException)
async def _http_error(_: Request, exc: StarletteHTTPException):
return _problem(exc.status_code, str(exc.detail) or "Error", str(exc.detail))
@app.exception_handler(RequestValidationError)
async def _validation_error(_: Request, exc: RequestValidationError):
return _problem(422, "Unprocessable Entity", "Request validation failed.",
{"errors": exc.errors()})
@app.exception_handler(DataError)
async def _data_error(_: Request, __: DataError):
return _problem(422, "Unprocessable Entity", "Invalid data for one or more fields.")
@app.exception_handler(IntegrityError)
async def _integrity_error(_: Request, __: IntegrityError):
return _problem(409, "Conflict", "That conflicts with an existing record.")
class ProblemDetailErrorMiddleware(BaseHTTPMiddleware):
"""Last-resort catch for unhandled exceptions → RFC 9457 500 (added INSIDE CORS)."""
async def dispatch(self, request: Request, call_next):
try:
return await call_next(request)
except Exception as exc: # noqa: BLE001
log.exception("Unhandled error")
detail = "An unexpected error occurred." if settings.is_production else str(exc)
return _problem(500, "Internal Server Error", detail)
+13
View File
@@ -0,0 +1,13 @@
"""Minimal logging configuration."""
from __future__ import annotations
import logging
def configure_logging() -> None:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s — %(message)s",
)
# Quiet noisy libraries.
logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
+123
View File
@@ -0,0 +1,123 @@
"""FastAPI application entrypoint."""
from __future__ import annotations
import os
from pathlib import Path
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from . import __version__
from .config import get_settings
from .db import engine
from .errors import ProblemDetailErrorMiddleware, install_error_handlers
from .logging_config import configure_logging
from .observability import setup_observability
from .routers import (
admin,
auth,
dashboard,
drafts,
files,
health,
history,
nodes,
notifications,
permissions,
plugins,
search,
users,
)
from .services import plugins as plugins_svc
API_PREFIX = "/api/v1"
settings = get_settings()
configure_logging()
app = FastAPI(
title="Galena API",
version=__version__,
description="Backend for Galena — a git-backed cloud drive.",
docs_url=f"{API_PREFIX}/docs",
redoc_url=None,
openapi_url=f"{API_PREFIX}/openapi.json",
)
install_error_handlers(app)
setup_observability(app, engine)
# Added BEFORE CORS so 500s flow back out through CORS and carry the headers a browser needs.
app.add_middleware(ProblemDetailErrorMiddleware)
if settings.cors_origins_list:
if "*" in settings.cors_origins_list:
raise RuntimeError("CORS_ALLOW_ORIGINS='*' is unsafe with credentialed CORS.")
app.add_middleware(
CORSMiddleware, allow_origins=settings.cors_origins_list, allow_credentials=True,
allow_methods=["*"], allow_headers=["*"],
)
# Content-Security-Policy for the console. 'unsafe-inline' is required by the theme pre-paint
# inline <script> and the inline style="" attributes in index.html; cdnjs is the lazy-loaded
# PDF.js source. Tightening this to nonces/hashes is a documented residual hardening step.
_CONSOLE_CSP = (
"default-src 'self'; "
"base-uri 'self'; "
"object-src 'none'; "
"frame-ancestors 'none'; "
"form-action 'self'; "
"img-src 'self' data: blob:; "
"font-src 'self' data:; "
"style-src 'self' 'unsafe-inline'; "
"script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; "
"worker-src 'self' blob: https://cdnjs.cloudflare.com; "
"connect-src 'self' https://cdnjs.cloudflare.com"
)
@app.middleware("http")
async def _security_headers(request, call_next):
"""Revalidate the static console (no-cache → conditional GET, so a rebuilt app.js/app.css is
picked up without a hard refresh) and attach security headers. The console gets a CSP; every
response gets nosniff / no-framing / a tight referrer policy. /raw sets its own stricter CSP
(default-src 'none'; sandbox), so we only setdefault the console CSP — never overriding it."""
resp = await call_next(request)
resp.headers.setdefault("X-Content-Type-Options", "nosniff")
resp.headers.setdefault("X-Frame-Options", "DENY")
resp.headers.setdefault("Referrer-Policy", "same-origin")
resp.headers.setdefault("Cross-Origin-Opener-Policy", "same-origin")
if not request.url.path.startswith(("/api", "/healthz")):
resp.headers.setdefault("Cache-Control", "no-cache")
resp.headers.setdefault("Content-Security-Policy", _CONSOLE_CSP)
return resp
for router in (
health.router, auth.router, users.router, admin.router, nodes.router, permissions.router,
files.router, history.router, drafts.router, dashboard.router, notifications.router,
search.router, plugins.router,
):
app.include_router(router, prefix=API_PREFIX)
@app.get("/healthz")
def healthz() -> dict:
return {"status": "ok"}
# Mount optional frontend plugins' static assets at /plugins/<name>/ (frontend-only — the backend
# never executes plugin code). Before the SPA catch-all so these paths win. Keeps GPL/optional
# components (e.g. the DjVu viewer) out of core while letting the console lazy-load them.
for _plugin in plugins_svc.discover():
app.mount(f"/plugins/{_plugin.name}",
StaticFiles(directory=str(_plugin.frontend_dir)), name=f"plugin-{_plugin.name}")
# Serve the static console (so the app runs without a separate web server in dev). In production
# Caddy can serve it directly. Mount LAST so /api/v1/* and /healthz win.
_FRONTEND = Path(os.environ.get("GALENA_FRONTEND_DIR")
or Path(__file__).resolve().parents[2] / "frontend")
if _FRONTEND.exists():
app.mount("/", StaticFiles(directory=str(_FRONTEND), html=True), name="frontend")
+26
View File
@@ -0,0 +1,26 @@
"""ORM models — import all so Base.metadata is complete for Alembic and create_all."""
from __future__ import annotations
from .base import Base
from .draft import Draft, DraftMessage
from .filecrypto import FileCrypto
from .identity import AppSetting, AppUser, AuditLog, Session
from .node import Favorite, Node, PermissionGrant
from .notification import Notification, NotificationPref, PushSubscription
__all__ = [
"Base",
"AppUser",
"Session",
"AppSetting",
"AuditLog",
"Node",
"PermissionGrant",
"Favorite",
"Draft",
"DraftMessage",
"Notification",
"PushSubscription",
"NotificationPref",
"FileCrypto",
]
+38
View File
@@ -0,0 +1,38 @@
"""Declarative base + shared column mixins."""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import DateTime, MetaData, Uuid, func, text
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
# Predictable constraint/index names → clean Alembic diffs.
NAMING_CONVENTION = {
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s",
}
class Base(DeclarativeBase):
metadata = MetaData(naming_convention=NAMING_CONVENTION)
class UUIDPkMixin:
id: Mapped[uuid.UUID] = mapped_column(
Uuid(as_uuid=True),
primary_key=True,
server_default=text("gen_random_uuid()"),
)
class TimestampMixin:
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
updated_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now()
)
+72
View File
@@ -0,0 +1,72 @@
"""Drafts (review requests) and their review-chat messages."""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, Text, text
from sqlalchemy.orm import Mapped, mapped_column
from ..enums import DraftMessageKind, DraftStatus
from .base import Base, UUIDPkMixin
from .types import pg_enum
class Draft(UUIDPkMixin, Base):
"""A request to bring a working version's redactions into the main version, reviewed in a
chat thread and published by an approver."""
__tablename__ = "draft"
project_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("node.id", ondelete="CASCADE"), nullable=False
)
title: Mapped[str] = mapped_column(Text, nullable=False)
source_version: Mapped[str] = mapped_column(Text, nullable=False) # branch name
target_version: Mapped[str] = mapped_column(Text, nullable=False) # usually the main version
status: Mapped[DraftStatus] = mapped_column(
pg_enum(DraftStatus, "draft_status"), nullable=False, server_default=DraftStatus.open.value
)
author_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("app_user.id"), nullable=False)
approver_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
updated_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
published_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
__table_args__ = (
Index("ix_draft_project_id", "project_id"),
Index("ix_draft_status", "status"),
)
class DraftMessage(UUIDPkMixin, Base):
__tablename__ = "draft_message"
draft_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("draft.id", ondelete="CASCADE"), nullable=False
)
author_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
kind: Mapped[DraftMessageKind] = mapped_column(
pg_enum(DraftMessageKind, "draft_message_kind"), nullable=False,
server_default=DraftMessageKind.message.value,
)
body: Mapped[str] = mapped_column(Text, nullable=False)
file_path: Mapped[str | None] = mapped_column(Text) # for line-pinned comments
line_no: Mapped[int | None] = mapped_column(Integer)
# Threading: a reply points at its thread's root message (NULL = a root / top-level comment).
parent_id: Mapped[uuid.UUID | None] = mapped_column(
ForeignKey("draft_message.id", ondelete="CASCADE")
)
# Whether the thread (set on its root message) is resolved/closed.
resolved: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
__table_args__ = (
Index("ix_draft_message_draft_id", "draft_id"),
Index("ix_draft_message_parent_id", "parent_id"),
)
+44
View File
@@ -0,0 +1,44 @@
"""Per-file encryption metadata. Wrapped data keys + nonces live here in the DB, never in git."""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import DateTime, ForeignKey, Index, LargeBinary, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column
from ..enums import EncryptionMode
from .base import Base, UUIDPkMixin
from .types import pg_enum
class FileCrypto(UUIDPkMixin, Base):
"""One row per encrypted file path within a project.
server mode: `wrapped_dek` = data key wrapped by the instance master key.
passphrase mode: `wrapped_dek` = data key wrapped by an Argon2id(passphrase, salt) key
(zero-knowledge — the server cannot unwrap it without the passphrase). `nonce` is for the
content cipher; `wrap_nonce` for the key-wrap cipher.
"""
__tablename__ = "file_crypto"
project_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("node.id", ondelete="CASCADE"), nullable=False
)
path: Mapped[str] = mapped_column(Text, nullable=False)
mode: Mapped[EncryptionMode] = mapped_column(
pg_enum(EncryptionMode, "encryption_mode"), nullable=False
)
algo: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'AES-256-GCM'"))
wrapped_dek: Mapped[bytes] = mapped_column(LargeBinary, nullable=False)
wrap_nonce: Mapped[bytes] = mapped_column(LargeBinary, nullable=False)
nonce: Mapped[bytes] = mapped_column(LargeBinary, nullable=False)
salt: Mapped[bytes | None] = mapped_column(LargeBinary) # passphrase mode only
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
__table_args__ = (
UniqueConstraint("project_id", "path", name="uq_file_crypto_project_id_path"),
Index("ix_file_crypto_project_id", "project_id"),
)
+87
View File
@@ -0,0 +1,87 @@
"""Identity, sessions, instance settings, audit log."""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, String, Text, Uuid, text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from .base import Base, TimestampMixin, UUIDPkMixin
from .types import SafeInet
class AppUser(UUIDPkMixin, TimestampMixin, Base):
__tablename__ = "app_user"
email: Mapped[str] = mapped_column(Text, nullable=False)
# Nullable so externally-authenticated (SSO/LDAP) accounts can exist without a local password.
password_hash: Mapped[str | None] = mapped_column(Text) # Argon2id
full_name: Mapped[str] = mapped_column(Text, nullable=False)
# Instance administrator: manages users + every workspace, opens the Administration screen.
is_admin: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
failed_login_count: Mapped[int] = mapped_column(
Integer, nullable=False, server_default=text("0")
)
locked_until: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
__table_args__ = (Index("uq_app_user_email_lower", text("lower(email)"), unique=True),)
class Session(UUIDPkMixin, Base):
__tablename__ = "session"
user_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("app_user.id", ondelete="CASCADE"), nullable=False
)
token_hash: Mapped[str] = mapped_column(Text, nullable=False, unique=True)
expires_at: Mapped[dt.datetime] = mapped_column(DateTime(timezone=True), nullable=False)
revoked_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
last_seen_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
created_ip: Mapped[str | None] = mapped_column(SafeInet)
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
__table_args__ = (
Index("ix_session_user_id", "user_id"),
Index("ix_session_expires_at", "expires_at"),
)
class AppSetting(Base):
"""Instance config as auditable key/value."""
__tablename__ = "app_setting"
key: Mapped[str] = mapped_column(Text, primary_key=True)
value: Mapped[str] = mapped_column(Text, nullable=False)
updated_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
updated_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
class AuditLog(UUIDPkMixin, Base):
"""Append-only. The `app` DB role holds INSERT/SELECT only (enforced in migration)."""
__tablename__ = "audit_log"
actor_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
action: Mapped[str] = mapped_column(String(120), nullable=False)
entity_type: Mapped[str] = mapped_column(String(80), nullable=False)
entity_id: Mapped[uuid.UUID | None] = mapped_column(Uuid(as_uuid=True))
detail: Mapped[str | None] = mapped_column(Text)
ip: Mapped[str | None] = mapped_column(SafeInet)
result: Mapped[str | None] = mapped_column(String(20))
request_id: Mapped[str | None] = mapped_column(String(64))
diff: Mapped[dict | None] = mapped_column(JSONB)
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
__table_args__ = (
Index("ix_audit_log_entity", "entity_type", "entity_id"),
Index("ix_audit_log_actor_id", "actor_id"),
Index("ix_audit_log_created_at", "created_at"),
)
+93
View File
@@ -0,0 +1,93 @@
"""The organizational tree: workspaces → groups/folders → projects (git repos),
plus permission grants and favorites."""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import DateTime, ForeignKey, Index, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column
from ..enums import EncryptionMode, NodeKind, NodeRole, PrincipalType, ReviewPolicy
from .base import Base, TimestampMixin, UUIDPkMixin
from .types import pg_enum
class Node(UUIDPkMixin, TimestampMixin, Base):
"""A container (workspace/group/folder) or a project (a git repo).
`path` is a materialized slug path ("/acme/legal/contracts") used by the authz resolver
for ancestor-or-self prefix matching, and is unique. Top-level nodes (parent_id NULL) must
be workspaces. `personal_owner_id` marks a user's personal workspace ("My files").
"""
__tablename__ = "node"
parent_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("node.id", ondelete="CASCADE"))
kind: Mapped[NodeKind] = mapped_column(pg_enum(NodeKind, "node_kind"), nullable=False)
name: Mapped[str] = mapped_column(Text, nullable=False)
slug: Mapped[str] = mapped_column(Text, nullable=False)
path: Mapped[str] = mapped_column(Text, nullable=False, unique=True)
owner_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
personal_owner_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
# Projects only: how edits reach the main version.
review_policy: Mapped[ReviewPolicy] = mapped_column(
pg_enum(ReviewPolicy, "review_policy"), nullable=False,
server_default=ReviewPolicy.open.value,
)
# Inherited encryption policy for files created in this subtree.
encryption_mode: Mapped[EncryptionMode] = mapped_column(
pg_enum(EncryptionMode, "encryption_mode"), nullable=False,
server_default=EncryptionMode.none.value,
)
__table_args__ = (
UniqueConstraint("parent_id", "slug", name="uq_node_parent_id_slug"),
Index("ix_node_parent_id", "parent_id"),
Index("ix_node_kind", "kind"),
Index("ix_node_personal_owner_id", "personal_owner_id"),
)
class PermissionGrant(UUIDPkMixin, Base):
"""A role for a principal on a node. Effective role on any node = the highest grant whose
node is an ancestor-or-self of it (resolved in services/authz.py)."""
__tablename__ = "permission_grant"
node_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("node.id", ondelete="CASCADE"), nullable=False
)
principal_type: Mapped[PrincipalType] = mapped_column(
pg_enum(PrincipalType, "principal_type"), nullable=False,
server_default=PrincipalType.user.value,
)
principal_id: Mapped[uuid.UUID] = mapped_column(nullable=False)
role: Mapped[NodeRole] = mapped_column(pg_enum(NodeRole, "node_role"), nullable=False)
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
created_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
__table_args__ = (
UniqueConstraint(
"node_id", "principal_type", "principal_id",
name="uq_permission_grant_node_id_principal",
),
Index("ix_permission_grant_node_id", "node_id"),
Index("ix_permission_grant_principal", "principal_type", "principal_id"),
)
class Favorite(Base):
__tablename__ = "favorite"
user_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("app_user.id", ondelete="CASCADE"), primary_key=True
)
node_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("node.id", ondelete="CASCADE"), primary_key=True
)
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
+64
View File
@@ -0,0 +1,64 @@
"""In-app notifications, web-push subscriptions, and per-user delivery preferences."""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Text, text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from ..enums import NotificationKind
from .base import Base, UUIDPkMixin
from .types import pg_enum
class Notification(UUIDPkMixin, Base):
__tablename__ = "notification"
recipient_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("app_user.id", ondelete="CASCADE"), nullable=False
)
kind: Mapped[NotificationKind] = mapped_column(
pg_enum(NotificationKind, "notification_kind"), nullable=False
)
title: Mapped[str] = mapped_column(Text, nullable=False)
body: Mapped[str | None] = mapped_column(Text)
link: Mapped[str | None] = mapped_column(Text)
payload: Mapped[dict | None] = mapped_column(JSONB)
read_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
__table_args__ = (
Index("ix_notification_recipient", "recipient_id", "read_at"),
Index("ix_notification_created_at", "created_at"),
)
class PushSubscription(UUIDPkMixin, Base):
__tablename__ = "push_subscription"
user_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("app_user.id", ondelete="CASCADE"), nullable=False
)
endpoint: Mapped[str] = mapped_column(Text, nullable=False, unique=True)
p256dh: Mapped[str] = mapped_column(Text, nullable=False)
auth: Mapped[str] = mapped_column(Text, nullable=False)
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
__table_args__ = (Index("ix_push_subscription_user_id", "user_id"),)
class NotificationPref(Base):
__tablename__ = "notification_pref"
user_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("app_user.id", ondelete="CASCADE"), primary_key=True
)
inapp: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
webpush: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
email: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
+36
View File
@@ -0,0 +1,36 @@
"""Custom SQLAlchemy column types: self-validating INET + native PG enum helper."""
from __future__ import annotations
import ipaddress
from sqlalchemy.dialects.postgresql import ENUM as PGEnum
from sqlalchemy.dialects.postgresql import INET
from sqlalchemy.types import TypeDecorator
class SafeInet(TypeDecorator):
"""An INET column that coerces any non-IP value to NULL on bind, so a bad host
(e.g. Starlette TestClient's literal 'testclient') can never trigger an INET cast error."""
impl = INET
cache_ok = True
def process_bind_param(self, value, dialect):
if value is None:
return None
try:
ipaddress.ip_address(value)
except (ValueError, TypeError):
return None
return value
def pg_enum(py_enum, name: str) -> PGEnum:
# postgresql.ENUM with create_type=False → create_all() never emits CREATE TYPE; the
# Alembic migration's explicit loop is the single source of truth for enum lifecycle.
return PGEnum(
py_enum,
name=name,
create_type=False,
values_callable=lambda enum_cls: [member.value for member in enum_cls],
)
+8
View File
@@ -0,0 +1,8 @@
"""Notification delivery channels. In-app is the DB row itself (always created); web-push and
email are opt-in and best-effort. Import-guarded so the core runs without their config/deps."""
from __future__ import annotations
from . import email as email_channel
from . import webpush as webpush_channel
__all__ = ["email_channel", "webpush_channel"]
+36
View File
@@ -0,0 +1,36 @@
"""Email delivery via SMTP (stdlib smtplib — no extra dependency). No-op unless SMTP_HOST is set."""
from __future__ import annotations
import logging
import smtplib
from email.message import EmailMessage
from ..config import get_settings
log = logging.getLogger("galena.email")
settings = get_settings()
def available() -> bool:
return bool(settings.smtp_host)
def send(to_addr: str, subject: str, body: str) -> bool:
if not available():
return False
msg = EmailMessage()
msg["From"] = settings.smtp_from
msg["To"] = to_addr
msg["Subject"] = subject
msg.set_content(body)
try:
with smtplib.SMTP(settings.smtp_host, settings.smtp_port, timeout=10) as smtp:
if settings.smtp_starttls:
smtp.starttls()
if settings.smtp_user:
smtp.login(settings.smtp_user, settings.smtp_password)
smtp.send_message(msg)
return True
except Exception as exc: # noqa: BLE001 — best-effort
log.warning("email send failed: %s", exc)
return False
+36
View File
@@ -0,0 +1,36 @@
"""Browser push via VAPID. No-op unless VAPID keys are set and `pywebpush` is installed
(an optional, MPL-2.0 extra — kept out of the default copyleft-free dependency set)."""
from __future__ import annotations
import json
import logging
from ..config import get_settings
log = logging.getLogger("galena.webpush")
settings = get_settings()
def available() -> bool:
return bool(settings.vapid_private_key and settings.vapid_public_key)
def send(subscription: dict, title: str, body: str, link: str | None = None) -> bool:
if not available():
return False
try:
from pywebpush import webpush # optional dependency
except ImportError:
log.info("web push enabled but pywebpush is not installed — skipping.")
return False
try:
webpush(
subscription_info=subscription,
data=json.dumps({"title": title, "body": body, "link": link}),
vapid_private_key=settings.vapid_private_key,
vapid_claims={"sub": settings.vapid_subject},
)
return True
except Exception as exc: # noqa: BLE001 — delivery is best-effort
log.warning("web push failed: %s", exc)
return False
+37
View File
@@ -0,0 +1,37 @@
"""Opt-in OpenTelemetry. A no-op unless OTEL_ENABLED and the SDK is importable, so the
backend runs standalone without the observability dependencies installed."""
from __future__ import annotations
import logging
from fastapi import FastAPI
from .config import get_settings
log = logging.getLogger("galena.observability")
settings = get_settings()
def setup_observability(app: FastAPI, engine) -> None:
if not settings.otel_enabled:
return
try:
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
except ImportError:
log.warning("OTEL_ENABLED but opentelemetry packages are not installed — skipping.")
return
provider = TracerProvider(resource=Resource.create({"service.name": settings.otel_service_name}))
provider.add_span_processor(
BatchSpanProcessor(OTLPSpanExporter(endpoint=settings.otel_exporter_otlp_endpoint))
)
trace.set_tracer_provider(provider)
FastAPIInstrumentor.instrument_app(app)
SQLAlchemyInstrumentor().instrument(engine=engine)
log.info("OpenTelemetry enabled → %s", settings.otel_exporter_otlp_endpoint)
+1
View File
@@ -0,0 +1 @@
"""HTTP routers. Validation + auth + permission checks live here; they never build SQL."""
+125
View File
@@ -0,0 +1,125 @@
"""Administration: instance/git settings, node picker, and per-user access (group/permission) mgmt.
All endpoints require an instance administrator."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from sqlalchemy.orm import Session
from ..config import get_settings
from ..db import get_db
from ..deps import require_admin
from ..enums import NodeRole, ReviewPolicy
from ..errors import NotFoundError
from ..models import AppUser
from ..services import authz, git_facade
from ..services import nodes as nodes_svc
from ..services import plugins as plugins_svc
from ..services import settings as settings_svc
from ..storage import backend as storage_backend
router = APIRouter(prefix="/admin", tags=["admin"])
cfg = get_settings()
class SettingsIn(BaseModel):
default_review_policy: ReviewPolicy | None = None
git_author_name: str | None = None
git_author_email: str | None = None
class GrantNodeIn(BaseModel):
node_id: str
role: NodeRole
class PluginToggleIn(BaseModel):
enabled: bool
def _settings_payload(db: Session) -> dict:
return {
"default_review_policy": settings_svc.get(db, "default_review_policy"),
"git_author_name": settings_svc.get(db, "git_author_name"),
"git_author_email": settings_svc.get(db, "git_author_email"),
"storage_backend": type(storage_backend).__name__,
"data_dir": cfg.data_dir,
"encryption_enabled": cfg.encryption_enabled,
}
@router.get("/settings")
def get_settings_ep(db: Session = Depends(get_db), _: AppUser = Depends(require_admin)):
return _settings_payload(db)
@router.put("/settings")
def put_settings(body: SettingsIn, db: Session = Depends(get_db),
admin: AppUser = Depends(require_admin)):
if body.default_review_policy is not None:
settings_svc.set_value(db, "default_review_policy", body.default_review_policy.value, admin.id)
if body.git_author_name is not None:
settings_svc.set_value(db, "git_author_name", body.git_author_name.strip() or "Galena", admin.id)
if body.git_author_email is not None:
settings_svc.set_value(db, "git_author_email", body.git_author_email.strip() or "galena@localhost", admin.id)
db.commit()
git_facade.set_committer(*settings_svc.committer(db))
return _settings_payload(db)
@router.get("/plugins")
def list_plugins(db: Session = Depends(get_db), _: AppUser = Depends(require_admin)):
"""Every installed plugin (under PLUGINS_DIR) with its admin-toggled enabled state."""
off = plugins_svc.disabled_names(db)
return {
"plugins_dir": cfg.plugins_dir,
"plugins": [
{"name": p.name, "title": p.title, "version": p.version, "license": p.license,
"description": p.description, "enabled": p.name not in off}
for p in plugins_svc.discover()
],
}
@router.put("/plugins/{name}")
def toggle_plugin(name: str, body: PluginToggleIn, db: Session = Depends(get_db),
admin: AppUser = Depends(require_admin)):
"""Enable/disable an installed plugin. Disabled plugins are not served to the console."""
if not any(p.name == name for p in plugins_svc.discover()):
raise NotFoundError("Plugin not found.")
plugins_svc.set_enabled(db, name, body.enabled, admin.id)
db.commit()
return {"name": name, "enabled": body.enabled}
@router.get("/nodes")
def all_nodes(db: Session = Depends(get_db), _: AppUser = Depends(require_admin)):
"""Flat list of every node — the picker for granting access."""
return [{"id": str(n.id), "name": n.name, "kind": n.kind.value, "path": n.path}
for n in nodes_svc.all_nodes(db)]
@router.get("/users/{user_id}/grants")
def user_grants(user_id: uuid.UUID, db: Session = Depends(get_db),
_: AppUser = Depends(require_admin)):
return [{"node_id": str(n.id), "name": n.name, "kind": n.kind.value, "path": n.path,
"role": role.value} for n, role in authz.grants_for_user(db, user_id)]
@router.post("/users/{user_id}/grants")
def add_user_grant(user_id: uuid.UUID, body: GrantNodeIn, db: Session = Depends(get_db),
admin: AppUser = Depends(require_admin)):
node = nodes_svc.get_node(db, uuid.UUID(body.node_id))
authz.upsert_user_grant(db, node, user_id, body.role, admin.id) # raises if user unknown
db.commit()
return {"node_id": str(node.id), "role": body.role.value}
@router.delete("/users/{user_id}/grants/{node_id}")
def del_user_grant(user_id: uuid.UUID, node_id: uuid.UUID, db: Session = Depends(get_db),
_: AppUser = Depends(require_admin)):
if authz.remove_user_grant(db, node_id, user_id):
db.commit()
return {"ok": True}
+65
View File
@@ -0,0 +1,65 @@
"""Authentication endpoints — cookie sessions (JWT was a considered alternative, see README)."""
from __future__ import annotations
from fastapi import APIRouter, Depends, Request, Response
from sqlalchemy.orm import Session
from ..config import get_settings
from ..db import get_db
from ..deps import SESSION_COOKIE, client_ip, extract_token, get_current_user
from ..errors import AuthenticationError
from ..models import AppUser
from ..schemas import LoginIn, user_out
from ..services import audit
from ..services import auth as auth_service
router = APIRouter(prefix="/auth", tags=["auth"])
settings = get_settings()
def _cookie_secure(request: Request) -> bool:
"""Whether to set the Secure flag on the session cookie.
Default (SESSION_COOKIE_SECURE unset) is AUTO: Secure only when the request actually arrived
over HTTPS. A Secure cookie sent over plain HTTP is silently dropped by the browser, which logs
the user straight back out on reload — the recurring "login doesn't stick" bug. Keying off the
real scheme (behind a proxy, request.url.scheme reflects X-Forwarded-Proto) makes it correct on
both HTTPS and plain-HTTP/LAN deployments regardless of APP_ENV. Set the env var true/false to
force it."""
if settings.session_cookie_secure is not None:
return settings.session_cookie_secure
return request.url.scheme == "https"
@router.post("/login")
def login(body: LoginIn, request: Request, response: Response, db: Session = Depends(get_db)):
user = auth_service.authenticate(db, body.email, body.password)
if user is None:
audit.record(db, actor_id=None, action="auth.login", entity_type="user",
detail=body.email, result="fail", ip=client_ip(request))
db.commit()
raise AuthenticationError("Invalid email or password.")
_session, token = auth_service.create_session(db, user, ip=client_ip(request))
audit.record(db, actor_id=user.id, action="auth.login", entity_type="user",
entity_id=user.id, ip=client_ip(request))
db.commit()
response.set_cookie(
SESSION_COOKIE, token, httponly=True, samesite="lax", secure=_cookie_secure(request),
max_age=settings.session_ttl_hours * 3600, path="/",
)
return {"token": token, "user": user_out(user)}
@router.post("/logout")
def logout(request: Request, response: Response, db: Session = Depends(get_db)):
token = extract_token(request)
if token:
auth_service.revoke_session(db, token)
db.commit()
response.delete_cookie(SESSION_COOKIE, path="/")
return {"ok": True}
@router.get("/me")
def me(user: AppUser = Depends(get_current_user)):
return user_out(user)
+17
View File
@@ -0,0 +1,17 @@
"""Dashboard statistics (workflow-tuned)."""
from __future__ import annotations
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import get_current_user
from ..models import AppUser
from ..services import stats
router = APIRouter(tags=["dashboard"])
@router.get("/dashboard")
def dashboard(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
return stats.dashboard(db, user)
+180
View File
@@ -0,0 +1,180 @@
"""Versions, drafts (review requests), the review chat, publish, and Resolve discrepancies."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user
from ..enums import NodeRole
from ..errors import ConflictError, NotFoundError
from ..models import AppUser, Draft, Node
from ..schemas import (CombineIn, MessageIn, ResolveIn, SubmitDraft, ThreadResolveIn, draft_out,
message_out)
from ..services import authz, changes, git_facade, nodes
router = APIRouter(tags=["drafts"])
def _project(db: Session, project_id: uuid.UUID) -> Node:
return nodes.get_project(db, project_id)
def _draft(db: Session, draft_id: uuid.UUID) -> tuple[Draft, Node]:
draft = db.get(Draft, draft_id)
if draft is None:
raise NotFoundError("Draft not found.")
return draft, _project(db, draft.project_id)
@router.post("/projects/{project_id}/versions")
def create_version(project_id: uuid.UUID, name: str, from_ref: str = git_facade.MAIN,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
project = _project(db, project_id)
authz.assert_role(db, user, project, NodeRole.editor)
git_facade.create_version(project.id, name, from_ref)
return {"ok": True, "version": name}
@router.post("/projects/{project_id}/combine")
def combine(project_id: uuid.UUID, body: CombineIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""Combine versions: merge one version into another (not necessarily the main version)."""
project = _project(db, project_id)
authz.assert_role(db, user, project, NodeRole.editor)
if body.source == body.target:
raise ConflictError("Pick two different versions to combine.")
versions = git_facade.list_versions(project.id)
if body.source not in versions or body.target not in versions:
raise NotFoundError("Unknown version.")
result = changes.combine_versions(db, user, project, body.source, body.target,
body.message, ip=client_ip(request))
db.commit()
return result
@router.post("/projects/{project_id}/submit-draft")
def submit_draft(project_id: uuid.UUID, body: SubmitDraft, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
project = _project(db, project_id)
authz.assert_role(db, user, project, NodeRole.editor)
draft = changes.submit_draft(db, user, project, body.title, ip=client_ip(request))
db.commit()
return draft_out(draft)
@router.get("/projects/{project_id}/drafts")
def project_drafts(project_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
project = _project(db, project_id)
authz.assert_can_read(db, user, project)
return [draft_out(d) for d in changes.list_project_drafts(db, project)]
@router.get("/drafts")
def my_drafts(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""Drafts I authored, plus open drafts I can approve (the Drafts screen)."""
out = []
for d, project_name, author_name, can_approve in changes.drafts_for_user(db, user):
row = draft_out(d)
row.update({"project": project_name, "author": author_name, "for_me": can_approve})
out.append(row)
return out
@router.get("/drafts/{draft_id}")
def get_draft(draft_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
draft, project = _draft(db, draft_id)
role = authz.assert_can_read(db, user, project)
msgs, names = changes.draft_messages(db, draft)
files = git_facade.changed_files(project.id, draft.target_version, draft.source_version)
author = db.get(AppUser, draft.author_id)
return {
"draft": draft_out(draft),
"project": {"id": str(project.id), "name": project.name},
"author": author.full_name if author else "—",
"messages": [message_out(m, names.get(m.author_id)) for m in msgs],
"files": files,
"can_approve": (NodeRole.rank(role) >= NodeRole.rank(NodeRole.approver)
and draft.author_id != user.id),
"can_post": NodeRole.rank(role) >= NodeRole.rank(NodeRole.editor),
"is_author": draft.author_id == user.id,
}
@router.post("/drafts/{draft_id}/messages")
def post_message(draft_id: uuid.UUID, body: MessageIn, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
draft, project = _draft(db, draft_id)
authz.assert_role(db, user, project, NodeRole.editor) # viewers can read a review, not post in it
parent_id = uuid.UUID(body.parent_id) if body.parent_id else None
msg = changes.post_message(db, user, draft, body.body, body.file_path, body.line_no, parent_id)
db.commit()
return message_out(msg, user.full_name)
@router.post("/drafts/{draft_id}/messages/{message_id}/resolve")
def resolve_thread(draft_id: uuid.UUID, message_id: uuid.UUID, body: ThreadResolveIn,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""Close (resolve) or reopen a comment thread. Any review participant (editor+) may toggle it."""
draft, project = _draft(db, draft_id)
authz.assert_role(db, user, project, NodeRole.editor)
root = changes.set_thread_resolved(db, draft, message_id, body.resolved)
db.commit()
return message_out(root, user.full_name)
@router.post("/drafts/{draft_id}/publish")
def publish(draft_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
draft, project = _draft(db, draft_id)
authz.assert_role(db, user, project, NodeRole.approver)
if draft.author_id == user.id:
raise ConflictError("You can't approve your own draft.")
result = changes.publish_draft(db, user, project, draft, ip=client_ip(request))
db.commit()
return result
@router.get("/drafts/{draft_id}/conflict")
def conflict(draft_id: uuid.UUID, path: str, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
draft, project = _draft(db, draft_id)
authz.assert_role(db, user, project, NodeRole.approver)
return git_facade.conflict_sides(project.id, draft.source_version, path, draft.target_version)
@router.post("/drafts/{draft_id}/resolve")
def resolve(draft_id: uuid.UUID, body: ResolveIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
draft, project = _draft(db, draft_id)
authz.assert_role(db, user, project, NodeRole.approver)
resolutions = {p: c.encode("utf-8") for p, c in body.resolutions.items()}
result = changes.resolve_and_publish(db, user, project, draft, resolutions,
ip=client_ip(request))
db.commit()
return result
@router.post("/drafts/{draft_id}/reject")
def reject(draft_id: uuid.UUID, reason: str = "", db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
draft, project = _draft(db, draft_id)
authz.assert_role(db, user, project, NodeRole.approver)
if draft.author_id == user.id:
raise ConflictError("You can't request changes on your own draft.")
changes.reject_draft(db, user, draft, reason or None)
db.commit()
return draft_out(draft)
@router.post("/drafts/{draft_id}/withdraw")
def withdraw(draft_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
draft, _project_node = _draft(db, draft_id)
changes.withdraw_draft(db, user, draft)
db.commit()
return draft_out(draft)
+234
View File
@@ -0,0 +1,234 @@
"""Files inside a project: list, read, preview/download, write, upload, move, delete, encrypt."""
from __future__ import annotations
import io
import mimetypes
import uuid
from fastapi import APIRouter, Depends, File, Form, Request, Response, UploadFile
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user
from ..enums import EncryptionMode, NodeKind, NodeRole, ReviewPolicy
from ..errors import ConflictError, NotFoundError, ValidationError
from ..models import AppUser, Node
from ..schemas import FileMove, FileWrite
from ..services import audit, authz, changes, crypto, git_facade, nodes, office
from ..services.git_facade import MAIN
router = APIRouter(prefix="/projects", tags=["files"])
# Media types safe to render inline; everything else (text/html, image/svg+xml, *+xml, JS, …)
# is served as an attachment so user-uploaded content can't execute JS in the app origin.
INLINE_MEDIA = {"image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp",
"application/pdf", "text/plain"}
MAX_FILE_BYTES = 64 * 1024 * 1024 # per-file write/upload cap (memory-exhaustion guard)
def _project(db: Session, project_id: uuid.UUID) -> Node:
return nodes.get_project(db, project_id)
def _branch_for(project: Node, user: AppUser) -> str:
return MAIN if ReviewPolicy(project.review_policy) == ReviewPolicy.open \
else changes.working_branch(user)
@router.get("/{project_id}/tree")
def tree(project_id: uuid.UUID, path: str = "", ref: str = MAIN,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
project = _project(db, project_id)
authz.assert_can_read(db, user, project)
entries = git_facade.list_tree(project.id, path, ref)
for e in entries:
if e["type"] == "file":
e["encrypted"] = crypto.get_crypto(db, project.id, e["path"]) is not None
return {"path": path, "ref": ref, "entries": entries,
"versions": git_facade.list_versions(project.id)}
@router.get("/{project_id}/file")
def read_text(project_id: uuid.UUID, path: str, ref: str = MAIN, passphrase: str | None = None,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
project = _project(db, project_id)
authz.assert_can_read(db, user, project)
data = changes.read_decrypted(db, project, path, ref, passphrase)
encrypted = crypto.get_crypto(db, project.id, path) is not None
fmt = office.office_format(path)
if fmt and office.is_editable(path):
# DOCX/ODT: extract the body to Markdown so the existing editor can open it (lossy round-trip).
try:
md = office.extract_markdown(path, data)
return {"path": path, "ref": ref, "binary": False, "content": md, "encrypted": encrypted,
"office": {"format": fmt, "editable": True, "lossy": True}}
except ValidationError:
pass # corrupt/unsupported → fall through to the download handoff
if fmt:
# RTF/DOC (and any office file we can't round-trip): handoff only — never show raw markup in
# the editor, even though RTF is ASCII and would otherwise decode as text.
return {"path": path, "ref": ref, "binary": True, "content": "", "encrypted": encrypted,
"office": {"format": fmt, "editable": False, "lossy": False}}
try:
content = data.decode("utf-8")
binary = False
except UnicodeDecodeError:
content, binary = "", True
return {"path": path, "ref": ref, "binary": binary, "content": content, "encrypted": encrypted}
@router.get("/{project_id}/raw")
def raw(project_id: uuid.UUID, path: str, ref: str = MAIN, passphrase: str | None = None,
download: bool = False, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
project = _project(db, project_id)
authz.assert_can_read(db, user, project)
data = changes.read_decrypted(db, project, path, ref, passphrase)
media = mimetypes.guess_type(path)[0] or "application/octet-stream"
name = path.rsplit("/", 1)[-1].replace('"', "").replace("\r", "").replace("\n", "")
inline = (not download) and media in INLINE_MEDIA
if not inline:
media = "application/octet-stream" # neutralize html/svg/xml/js → no in-origin execution
headers = {
"Content-Disposition": f'{"inline" if inline else "attachment"}; filename="{name}"',
"X-Content-Type-Options": "nosniff",
"Content-Security-Policy": "default-src 'none'; sandbox",
}
return Response(content=data, media_type=media, headers=headers)
@router.get("/{project_id}/thumb")
def thumb(project_id: uuid.UUID, path: str, ref: str = MAIN,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
project = _project(db, project_id)
authz.assert_can_read(db, user, project)
# Passphrase-encrypted images can't be thumbnailed server-side without the passphrase.
if crypto.get_crypto(db, project.id, path) and \
crypto.get_crypto(db, project.id, path).mode == EncryptionMode.passphrase:
raise ConflictError("Encrypted image — open it to preview.")
data = changes.read_decrypted(db, project, path, ref)
try:
from PIL import Image
img = Image.open(io.BytesIO(data))
img.thumbnail((320, 320))
out = io.BytesIO()
img.convert("RGB").save(out, format="PNG")
return Response(content=out.getvalue(), media_type="image/png")
except Exception as exc: # noqa: BLE001
raise ConflictError("Couldn't make a thumbnail for this file.") from exc
@router.post("/{project_id}/file")
def write(project_id: uuid.UUID, body: FileWrite, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
project = _project(db, project_id)
authz.assert_role(db, user, project, NodeRole.editor)
content = body.content.encode("utf-8")
if len(content) > MAX_FILE_BYTES:
raise ValidationError("File is too large.")
result = changes.apply_change(db, user, project, body.path, content,
message=body.message, passphrase=body.passphrase,
ip=client_ip(request))
db.commit()
return result
@router.post("/{project_id}/office-file")
def write_office(project_id: uuid.UUID, body: FileWrite, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""Save an edited DOCX/ODT: regenerate the office bytes from the editor's Markdown, then funnel
them through the same `apply_change` chokepoint (policy + encryption + audit + redaction/draft).
Body-level, lossy — the frontend warns and offers the lossless download→edit→re-upload handoff."""
project = _project(db, project_id)
authz.assert_role(db, user, project, NodeRole.editor)
if not office.is_editable(body.path):
raise ValidationError("This document type can't be edited in the browser.")
content = office.to_office_bytes(body.path, body.content) # Markdown → DOCX/ODT bytes
if len(content) > MAX_FILE_BYTES:
raise ValidationError("File is too large.")
result = changes.apply_change(db, user, project, body.path, content,
message=body.message, passphrase=body.passphrase,
ip=client_ip(request))
db.commit()
return result
@router.post("/{project_id}/upload")
def upload(project_id: uuid.UUID, request: Request, path: str = Form(""), dest: str = Form(""),
file: UploadFile = File(...), db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
project = _project(db, project_id)
authz.assert_role(db, user, project, NodeRole.editor)
# `dest` (explicit full path) overwrites that exact file regardless of the picked filename —
# used by the "edit locally → re-upload" handoff to replace a document in place.
dest = dest.strip() or ((path.rstrip("/") + "/" + file.filename).lstrip("/") if path else file.filename)
data = file.file.read(MAX_FILE_BYTES + 1)
if len(data) > MAX_FILE_BYTES:
raise ValidationError("File is too large.")
result = changes.apply_change(db, user, project, dest, data,
message=f"Upload {file.filename}", ip=client_ip(request))
db.commit()
return {"path": dest, **result}
@router.post("/{project_id}/move-file")
def move_file(project_id: uuid.UUID, body: FileMove, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
project = _project(db, project_id)
authz.assert_role(db, user, project, NodeRole.editor)
branch = _branch_for(project, user)
git_facade.move_file(project.id, body.src, body.dst, branch=branch,
author_name=user.full_name, author_email=user.email,
message=body.message)
row = crypto.get_crypto(db, project.id, body.src)
if row is not None:
row.path = body.dst
db.commit()
return {"ok": True, "branch": branch}
@router.post("/{project_id}/copy-file")
def copy_file(project_id: uuid.UUID, body: FileMove, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""Copy a file to a new path (re-encrypts per the destination policy via the write chokepoint)."""
project = _project(db, project_id)
authz.assert_role(db, user, project, NodeRole.editor)
data = changes.read_decrypted(db, project, body.src, _branch_for(project, user))
if len(data) > MAX_FILE_BYTES:
raise ValidationError("File is too large.")
result = changes.apply_change(db, user, project, body.dst, data,
message=body.message or f"Copy {body.src} to {body.dst}",
ip=client_ip(request))
db.commit()
return {"path": body.dst, **result}
@router.delete("/{project_id}/file")
def delete_file(project_id: uuid.UUID, path: str, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
project = _project(db, project_id)
authz.assert_role(db, user, project, NodeRole.editor)
result = changes.apply_change(db, user, project, path, b"", message=f"Delete {path}",
delete=True, ip=client_ip(request))
db.commit()
return result
@router.post("/{project_id}/encrypt")
def encrypt_file(project_id: uuid.UUID, path: str, mode: EncryptionMode = EncryptionMode.server,
passphrase: str | None = None, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
project = _project(db, project_id)
authz.assert_role(db, user, project, NodeRole.editor)
if mode == EncryptionMode.none:
raise ValidationError("Pick an encryption mode.")
plaintext = changes.read_decrypted(db, project, path, MAIN)
ciphertext = crypto.encrypt(db, project.id, path, plaintext, mode, passphrase)
branch = _branch_for(project, user)
git_facade.commit_file(project.id, path, ciphertext, branch=branch,
author_name=user.full_name, author_email=user.email,
message=f"Encrypt {path}")
audit.record(db, actor_id=user.id, action="file.encrypt", entity_type="project",
entity_id=project.id, detail=path)
db.commit()
return {"ok": True, "encrypted": True, "mode": mode.value}
+13
View File
@@ -0,0 +1,13 @@
"""Liveness/readiness."""
from __future__ import annotations
from fastapi import APIRouter
from .. import __version__
router = APIRouter(tags=["health"])
@router.get("/health")
def health() -> dict:
return {"status": "ok", "version": __version__}
+60
View File
@@ -0,0 +1,60 @@
"""History (redaction timeline), version graph, Changes (two-window/merged), Authorship."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import get_current_user
from ..enums import NodeKind
from ..errors import ConflictError
from ..models import AppUser, Node
from ..services import authz, git_facade, nodes
from ..services.git_facade import MAIN
router = APIRouter(prefix="/projects", tags=["history"])
def _project(db: Session, project_id: uuid.UUID, user: AppUser) -> Node:
node = nodes.get_project(db, project_id)
authz.assert_can_read(db, user, node)
return node
@router.get("/{project_id}/history")
def history(project_id: uuid.UUID, ref: str = MAIN, path: str | None = None, limit: int = 50,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
project = _project(db, project_id, user)
return git_facade.log(project.id, ref, path, limit)
@router.get("/{project_id}/graph")
def graph(project_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
project = _project(db, project_id, user)
return git_facade.version_graph(project.id)
@router.get("/{project_id}/changed")
def changed(project_id: uuid.UUID, b: str, a: str | None = None,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""Files that changed in redaction `b` vs ref `a` (defaults to the empty tree → all files at b).
Powers click-a-node-in-the-graph → see what that redaction touched."""
project = _project(db, project_id, user)
return git_facade.changed_files(project.id, a or git_facade.EMPTY_TREE, b)
@router.get("/{project_id}/changes")
def changes(project_id: uuid.UUID, path: str, a: str = MAIN, b: str = MAIN,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
project = _project(db, project_id, user)
return git_facade.file_changes(project.id, path, a, b)
@router.get("/{project_id}/blame")
def blame(project_id: uuid.UUID, path: str, ref: str = MAIN,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
project = _project(db, project_id, user)
return git_facade.blame(project.id, path, ref)
+179
View File
@@ -0,0 +1,179 @@
"""Workspaces / groups / folders / projects — the organizational tree + drive scopes."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user
from ..enums import EncryptionMode, NodeKind, NodeRole
from ..errors import NotFoundError, ValidationError
from ..models import AppUser, Node
from ..schemas import NodeCreate, NodeMove, NodeRename, PolicyPatch, node_out
from ..services import audit, authz, nodes, settings as settings_svc
router = APIRouter(tags=["nodes"])
def _favorite_ids(db: Session, user: AppUser) -> set:
return nodes.favorite_ids(db, user)
def _annotate(db: Session, user: AppUser, node: Node, favs: set) -> dict:
return node_out(
node,
access=authz.access_state(db, user, node),
favorite=node.id in favs,
encrypted=EncryptionMode(node.encryption_mode) != EncryptionMode.none,
)
@router.get("/drive/home")
def home(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
personal = nodes.personal_workspace(db, user)
db.commit()
favs = _favorite_ids(db, user)
workspaces = [_annotate(db, user, w, favs) for w in nodes.accessible_workspaces(db, user)]
return {"personal_id": str(personal.id), "personal": _annotate(db, user, personal, favs),
"workspaces": workspaces}
@router.get("/drive/favorites")
def favorites(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
favs = _favorite_ids(db, user)
return [_annotate(db, user, n, favs) for n in nodes.favorites(db, user)]
@router.get("/drive/shared")
def shared(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
favs = _favorite_ids(db, user)
return [_annotate(db, user, n, favs) for n in nodes.shared_with_me(db, user)]
@router.get("/drive/recent")
def recent(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
return [{"action": r.action, "detail": r.detail, "at": r.created_at.isoformat(),
"entity_id": str(r.entity_id) if r.entity_id else None}
for r in nodes.recent(db, user)]
@router.get("/nodes/{node_id}")
def get_node(node_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
role = authz.assert_can_read(db, user, node)
favs = _favorite_ids(db, user)
children = [_annotate(db, user, c, favs) for c in nodes.children(db, node)]
crumbs = [{"id": str(n.id), "name": n.name, "kind": n.kind.value}
for n in nodes.breadcrumb(db, node)]
return {
"node": _annotate(db, user, node, favs),
"breadcrumb": crumbs,
"children": children,
"is_project": node.kind == NodeKind.project,
"can_write": NodeRole.rank(role) >= NodeRole.rank(NodeRole.editor),
"can_manage": NodeRole.rank(role) >= NodeRole.rank(NodeRole.manager),
"can_approve": NodeRole.rank(role) >= NodeRole.rank(NodeRole.approver),
}
@router.post("/nodes")
def create_node(body: NodeCreate, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
parent = None
if body.parent_id:
parent = nodes.get_node(db, uuid.UUID(body.parent_id))
authz.assert_role(db, user, parent, NodeRole.editor)
node = nodes.create_node(db, user, parent=parent, kind=body.kind, name=body.name)
if node.kind == NodeKind.project:
node.review_policy = body.review_policy or settings_svc.default_review_policy(db)
audit.record(db, actor_id=user.id, action="node.create", entity_type=node.kind.value,
entity_id=node.id, detail=node.path, ip=client_ip(request))
db.commit()
return node_out(node, access="granted", favorite=False,
encrypted=EncryptionMode(node.encryption_mode) != EncryptionMode.none)
@router.patch("/nodes/{node_id}")
def rename_node(node_id: uuid.UUID, body: NodeRename, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
authz.assert_role(db, user, node, NodeRole.manager)
nodes.rename(db, node, body.name)
db.commit()
return node_out(node)
@router.post("/nodes/{node_id}/move")
def move_node(node_id: uuid.UUID, body: NodeMove, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
authz.assert_role(db, user, node, NodeRole.manager)
parent = None
if body.parent_id:
parent = nodes.get_node(db, uuid.UUID(body.parent_id))
authz.assert_role(db, user, parent, NodeRole.editor)
nodes.move(db, node, parent)
db.commit()
return node_out(node)
@router.put("/nodes/{node_id}/policy")
def set_policy(node_id: uuid.UUID, body: PolicyPatch, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
authz.assert_role(db, user, node, NodeRole.manager)
if body.review_policy is not None:
node.review_policy = body.review_policy
if body.encryption_mode is not None:
node.encryption_mode = body.encryption_mode
db.commit()
return node_out(node)
@router.delete("/nodes/{node_id}")
def delete_node(node_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
authz.assert_role(db, user, node, NodeRole.manager)
if node.personal_owner_id is not None:
raise ValidationError("Your personal workspace can't be deleted.")
audit.record(db, actor_id=user.id, action="node.delete", entity_type=node.kind.value,
entity_id=node.id, detail=node.path, ip=client_ip(request))
nodes.delete(db, node)
db.commit()
return {"ok": True}
@router.post("/nodes/{node_id}/favorite")
def toggle_favorite(node_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
authz.assert_can_read(db, user, node)
fav = nodes.toggle_favorite(db, user, node)
db.commit()
return {"favorite": fav}
@router.post("/nodes/{node_id}/clone")
def clone_project(node_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
src = nodes.get_node(db, node_id)
if src.kind != NodeKind.project:
raise ValidationError("Only projects can be cloned.")
authz.assert_can_read(db, user, src)
parent = db.get(Node, src.parent_id) if src.parent_id else None
if parent is not None:
authz.assert_role(db, user, parent, NodeRole.editor)
from ..services import git_facade
dst = nodes.create_node(db, user, parent=parent, kind=NodeKind.project,
name=f"{src.name} (copy)")
# create_node already git-init'd dst; replace it with a clone of src for full history.
git_facade.remove_project(dst.id)
git_facade.clone_project(src.id, dst.id)
audit.record(db, actor_id=user.id, action="project.clone", entity_type="project",
entity_id=dst.id, detail=f"from {src.path}", ip=client_ip(request))
db.commit()
return node_out(dst, access="granted", favorite=False, encrypted=False)
+79
View File
@@ -0,0 +1,79 @@
"""Notifications: list, mark read, delivery preferences, web-push subscription."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from ..config import get_settings
from ..db import get_db
from ..deps import get_current_user
from ..models import AppUser, NotificationPref
from ..schemas import PrefsIn, PushSub, notification_out
from ..services import notify
router = APIRouter(prefix="/notifications", tags=["notifications"])
settings = get_settings()
@router.get("")
def list_notifications(limit: int = 30, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
return {"items": [notification_out(n) for n in notify.list_for_user(db, user.id, limit)],
"unread": notify.unread_count(db, user.id)}
@router.get("/unread")
def unread(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
return {"unread": notify.unread_count(db, user.id)}
@router.post("/read-all")
def read_all(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
notify.mark_all_read(db, user.id)
db.commit()
return {"ok": True}
@router.post("/{notification_id}/read")
def mark_read(notification_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
notify.mark_read(db, user.id, notification_id)
db.commit()
return {"ok": True}
@router.get("/prefs")
def get_prefs(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
pref = db.get(NotificationPref, user.id)
return {"inapp": pref.inapp if pref else True,
"webpush": pref.webpush if pref else False,
"email": pref.email if pref else False,
"vapid_public_key": settings.vapid_public_key,
"push_available": bool(settings.vapid_public_key)}
@router.put("/prefs")
def set_prefs(body: PrefsIn, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
pref = db.get(NotificationPref, user.id)
if pref is None:
pref = NotificationPref(user_id=user.id)
db.add(pref)
if body.inapp is not None:
pref.inapp = body.inapp
if body.webpush is not None:
pref.webpush = body.webpush
if body.email is not None:
pref.email = body.email
db.commit()
return {"inapp": pref.inapp, "webpush": pref.webpush, "email": pref.email}
@router.post("/subscribe")
def subscribe(body: PushSub, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
notify.subscribe_push(db, user.id, body.endpoint, body.p256dh, body.auth)
db.commit()
return {"ok": True}
+60
View File
@@ -0,0 +1,60 @@
"""Permission grants on a node + request-access (the Share & permissions dialog backend)."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user
from ..enums import NodeRole, NotificationKind
from ..models import AppUser
from ..schemas import GrantIn
from ..services import audit, authz, notify, nodes
router = APIRouter(tags=["permissions"])
@router.get("/nodes/{node_id}/permissions")
def list_permissions(node_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
authz.assert_role(db, user, node, NodeRole.manager)
return authz.list_grants_for_display(db, node)
@router.post("/nodes/{node_id}/permissions")
def set_permission(node_id: uuid.UUID, body: GrantIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
authz.assert_role(db, user, node, NodeRole.manager)
_grant, target = authz.upsert_user_grant(db, node, uuid.UUID(body.user_id), body.role, user.id)
audit.record(db, actor_id=user.id, action="permission.grant", entity_type="node",
entity_id=node.id, detail=f"{target.email}={body.role.value}",
ip=client_ip(request))
notify.notify_permission_granted(db, target.id, node, body.role, actor=user)
db.commit()
return {"user_id": str(target.id), "role": body.role.value}
@router.delete("/nodes/{node_id}/permissions/{target_id}")
def remove_permission(node_id: uuid.UUID, target_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
authz.assert_role(db, user, node, NodeRole.manager)
if authz.remove_user_grant(db, node.id, target_id):
db.commit()
return {"ok": True}
@router.post("/nodes/{node_id}/request-access")
def request_access(node_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)):
node = nodes.get_node(db, node_id)
for uid in authz.users_with_role_at_least(db, node, NodeRole.manager):
notify.create(db, uid, NotificationKind.access_requested,
f"{user.full_name} requested access to {node.name}",
link="#/", actor=user)
db.commit()
return {"ok": True}
+28
View File
@@ -0,0 +1,28 @@
"""Frontend plugin discovery for the console (lists enabled plugins + their entry assets)."""
from __future__ import annotations
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from ..db import get_db
from ..services import plugins as plugins_svc
router = APIRouter(prefix="/plugins", tags=["plugins"])
@router.get("")
def list_plugins(db: Session = Depends(get_db)):
"""The console fetches this after sign-in and lazy-loads each plugin's frontend entry from
/plugins/<name>/. Returns only ENABLED plugins' manifest metadata — no filesystem paths."""
return [
{
"name": p.name,
"title": p.title,
"version": p.version,
"license": p.license,
"description": p.description,
"entry": f"/plugins/{p.name}/{p.frontend_entry}",
"base": f"/plugins/{p.name}/",
}
for p in plugins_svc.enabled(db)
]
+17
View File
@@ -0,0 +1,17 @@
"""Global search (command palette)."""
from __future__ import annotations
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import get_current_user
from ..models import AppUser
from ..services import search as search_service
router = APIRouter(tags=["search"])
@router.get("/search")
def search(q: str = "", db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
return {"hits": search_service.search(db, user, q)}
+59
View File
@@ -0,0 +1,59 @@
"""User administration (instance admins only)."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import require_admin
from ..errors import NotFoundError
from ..models import AppUser
from ..schemas import UserCreate, UserPatch, user_out
from ..security import hash_password
from ..services import auth as auth_service
router = APIRouter(prefix="/users", tags=["users"])
@router.get("")
def list_users(db: Session = Depends(get_db), _: AppUser = Depends(require_admin)):
return [user_out(u) for u in auth_service.list_users(db)]
@router.post("")
def create_user(body: UserCreate, db: Session = Depends(get_db),
_: AppUser = Depends(require_admin)):
user = auth_service.create_user(db, email=body.email, full_name=body.full_name,
password=body.password, is_admin=body.is_admin)
db.commit()
return user_out(user)
@router.patch("/{user_id}")
def patch_user(user_id: uuid.UUID, body: UserPatch, db: Session = Depends(get_db),
_: AppUser = Depends(require_admin)):
user = db.get(AppUser, user_id)
if user is None:
raise NotFoundError("User not found.")
if body.full_name is not None:
user.full_name = body.full_name
if body.is_admin is not None:
user.is_admin = body.is_admin
if body.password:
user.password_hash = hash_password(body.password)
auth_service.revoke_user_sessions(db, user.id) # password change → drop existing sessions
db.commit()
return user_out(user)
@router.post("/{user_id}/deactivate")
def deactivate(user_id: uuid.UUID, db: Session = Depends(get_db),
_: AppUser = Depends(require_admin)):
user = db.get(AppUser, user_id)
if user is None:
raise NotFoundError("User not found.")
user.is_active = False
db.commit()
return user_out(user)
+160
View File
@@ -0,0 +1,160 @@
"""Pydantic request models + lightweight output serializers."""
from __future__ import annotations
import re
from typing import Annotated
from pydantic import AfterValidator, BaseModel, Field
from .enums import EncryptionMode, NodeKind, NodeRole, ReviewPolicy
from .models import AppUser, Draft, DraftMessage, Node, Notification
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
def _valid_email(v: str) -> str:
if not _EMAIL_RE.match(v or ""):
raise ValueError("Enter a valid email address.")
return v.strip()
Email = Annotated[str, AfterValidator(_valid_email)]
# ── auth / users ──
class LoginIn(BaseModel):
email: Email
password: str
class UserCreate(BaseModel):
email: Email
full_name: str = Field(min_length=1)
password: str = Field(min_length=8)
is_admin: bool = False
class UserPatch(BaseModel):
full_name: str | None = None
is_admin: bool | None = None
password: str | None = None
# ── nodes ──
class NodeCreate(BaseModel):
parent_id: str | None = None
kind: NodeKind
name: str = Field(min_length=1)
review_policy: ReviewPolicy | None = None
class NodeRename(BaseModel):
name: str = Field(min_length=1)
class NodeMove(BaseModel):
parent_id: str | None = None
class PolicyPatch(BaseModel):
review_policy: ReviewPolicy | None = None
encryption_mode: EncryptionMode | None = None
# ── permissions ──
class GrantIn(BaseModel):
user_id: str
role: NodeRole
# ── files / changes ──
class FileWrite(BaseModel):
path: str = Field(min_length=1)
content: str
message: str = "Edit"
passphrase: str | None = None
class FileMove(BaseModel):
src: str
dst: str
message: str = "Move"
class SubmitDraft(BaseModel):
title: str = "Draft"
class MessageIn(BaseModel):
body: str = Field(min_length=1)
file_path: str | None = None
line_no: int | None = None
parent_id: str | None = None # reply → the thread root message id
class ThreadResolveIn(BaseModel):
resolved: bool = True
class CombineIn(BaseModel):
source: str
target: str
message: str | None = None
class ResolveIn(BaseModel):
resolutions: dict[str, str]
class PushSub(BaseModel):
endpoint: str
p256dh: str
auth: str
class PrefsIn(BaseModel):
inapp: bool | None = None
webpush: bool | None = None
email: bool | None = None
# ── serializers ──
def user_out(u: AppUser) -> dict:
return {"id": str(u.id), "email": u.email, "full_name": u.full_name,
"is_admin": u.is_admin, "is_active": u.is_active}
def node_out(n: Node, *, access: str | None = None, favorite: bool | None = None,
encrypted: bool | None = None) -> dict:
d = {"id": str(n.id), "parent_id": str(n.parent_id) if n.parent_id else None,
"kind": n.kind.value, "name": n.name, "slug": n.slug, "path": n.path,
"review_policy": n.review_policy.value, "encryption_mode": n.encryption_mode.value}
if access is not None:
d["access"] = access
if favorite is not None:
d["favorite"] = favorite
if encrypted is not None:
d["encrypted"] = encrypted
return d
def draft_out(d: Draft) -> dict:
return {"id": str(d.id), "project_id": str(d.project_id), "title": d.title,
"source_version": d.source_version, "target_version": d.target_version,
"status": d.status.value, "author_id": str(d.author_id),
"approver_id": str(d.approver_id) if d.approver_id else None,
"created_at": d.created_at.isoformat(),
"published_at": d.published_at.isoformat() if d.published_at else None}
def message_out(m: DraftMessage, author_name: str | None = None) -> dict:
return {"id": str(m.id), "draft_id": str(m.draft_id), "kind": m.kind.value, "body": m.body,
"author_id": str(m.author_id) if m.author_id else None, "author": author_name,
"file_path": m.file_path, "line_no": m.line_no,
"parent_id": str(m.parent_id) if m.parent_id else None, "resolved": bool(m.resolved),
"created_at": m.created_at.isoformat()}
def notification_out(n: Notification) -> dict:
return {"id": str(n.id), "kind": n.kind.value, "title": n.title, "body": n.body,
"link": n.link, "read": n.read_at is not None, "created_at": n.created_at.isoformat()}
+48
View File
@@ -0,0 +1,48 @@
"""Password hashing (Argon2id), opaque session tokens, and passphrase key derivation."""
from __future__ import annotations
import hashlib
import secrets
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from argon2.low_level import Type, hash_secret_raw
# Starting parameters (memory-hard).
_hasher = PasswordHasher(memory_cost=65536, time_cost=3, parallelism=2)
def hash_password(password: str) -> str:
return _hasher.hash(password)
def verify_password(password: str, password_hash: str) -> bool:
try:
return _hasher.verify(password_hash, password)
except VerifyMismatchError:
return False
except Exception: # noqa: BLE001 — malformed hash, etc.
return False
def generate_session_token() -> str:
"""Opaque, high-entropy token handed to the client (only its hash is stored)."""
return secrets.token_urlsafe(48)
def hash_token(token: str) -> str:
"""SHA-256 of the session token. Stored server-side; enables an instant kill-switch."""
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def derive_key(passphrase: str, salt: bytes) -> bytes:
"""Derive a 32-byte key from a passphrase via Argon2id (for passphrase-mode encryption)."""
return hash_secret_raw(
secret=passphrase.encode("utf-8"),
salt=salt,
time_cost=3,
memory_cost=65536,
parallelism=2,
hash_len=32,
type=Type.ID,
)
+58
View File
@@ -0,0 +1,58 @@
"""Idempotent seed: bootstrap admin + a small demo workspace/project so the drive isn't empty."""
from __future__ import annotations
import logging
from sqlalchemy import select
from .config import get_settings
from .db import SessionLocal
from .enums import NodeKind, ReviewPolicy
from .models import AppUser, Node
from .security import hash_password
from .services import git_facade, nodes
log = logging.getLogger("galena.seed")
settings = get_settings()
def run() -> None:
db = SessionLocal()
try:
admin = db.scalar(select(AppUser).where(AppUser.email == settings.bootstrap_admin_email))
if admin is None:
admin = AppUser(
email=settings.bootstrap_admin_email,
full_name="Administrator",
password_hash=hash_password(settings.bootstrap_admin_password),
is_admin=True,
)
db.add(admin)
db.commit()
log.info("Created bootstrap admin %s", admin.email)
if db.scalar(select(Node).where(Node.path == "/acme")) is None:
ws = nodes.create_node(db, admin, parent=None, kind=NodeKind.workspace, name="Acme")
legal = nodes.create_node(db, admin, parent=ws, kind=NodeKind.group, name="Legal")
project = nodes.create_node(db, admin, parent=legal, kind=NodeKind.project,
name="Contracts")
project.review_policy = ReviewPolicy.open
db.commit()
git_facade.commit_file(
project.id, "welcome.md",
b"# Welcome to Galena\n\nThis file lives in a git project - every save is a "
b"redaction you can revisit in History.\n",
author_name="Administrator", author_email=admin.email,
message="Add welcome note",
)
log.info("Seeded demo workspace /acme/legal/contracts")
# Ensure the admin has a personal workspace ("My files").
nodes.personal_workspace(db, admin)
db.commit()
finally:
db.close()
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
run()
+2
View File
@@ -0,0 +1,2 @@
"""Domain services. Strict layering: routers → services → models; services never build raw SQL
strings and routers never touch the DB session directly except through these."""
+37
View File
@@ -0,0 +1,37 @@
"""Append-only audit log writer."""
from __future__ import annotations
import uuid
from sqlalchemy.orm import Session as DbSession
from ..models import AuditLog
def record(
db: DbSession,
*,
actor_id: uuid.UUID | None,
action: str,
entity_type: str,
entity_id: uuid.UUID | None = None,
detail: str | None = None,
ip: str | None = None,
result: str | None = "ok",
request_id: str | None = None,
diff: dict | None = None,
) -> None:
"""Insert one audit row. The `app` DB role has INSERT/SELECT only on audit_log."""
db.add(
AuditLog(
actor_id=actor_id,
action=action,
entity_type=entity_type,
entity_id=entity_id,
detail=detail,
ip=ip,
result=result,
request_id=request_id,
diff=diff,
)
)
+121
View File
@@ -0,0 +1,121 @@
"""Authentication: credential check + server-side sessions (instant kill-switch)."""
from __future__ import annotations
import datetime as dt
from sqlalchemy import func, select, update
from sqlalchemy.orm import Session as DbSession
from ..config import get_settings
from ..errors import ConflictError
from ..models import AppUser, Session
from ..security import generate_session_token, hash_password, hash_token, verify_password
settings = get_settings()
# A throwaway hash to equalize login timing on the user-missing / inactive / no-password path,
# so latency can't distinguish "unknown email" from "wrong password".
_DUMMY_HASH = hash_password("timing-pad-not-a-real-password")
def find_user_by_email(db: DbSession, email: str) -> AppUser | None:
"""Exact, case-insensitive, wildcard-free lookup backed by uq_app_user_email_lower."""
return db.scalar(select(AppUser).where(func.lower(AppUser.email) == email.lower()))
def list_users(db: DbSession) -> list[AppUser]:
return list(db.scalars(select(AppUser).order_by(AppUser.email)).all())
def create_user(db: DbSession, *, email: str, full_name: str, password: str,
is_admin: bool = False) -> AppUser:
if find_user_by_email(db, email):
raise ConflictError("A user with that email already exists.")
user = AppUser(email=email, full_name=full_name,
password_hash=hash_password(password), is_admin=is_admin)
db.add(user)
db.flush()
return user
def authenticate(db: DbSession, email: str, password: str) -> AppUser | None:
"""Return the user on valid credentials, else None. Tracks failures + app-level lockout."""
user = find_user_by_email(db, email)
if user is None or not user.is_active or not user.password_hash:
verify_password(password, _DUMMY_HASH) # equalize timing
return None
now = dt.datetime.now(dt.timezone.utc)
if user.locked_until is not None and user.locked_until > now:
verify_password(password, _DUMMY_HASH)
return None
if not verify_password(password, user.password_hash):
new_count = db.execute(
update(AppUser)
.where(AppUser.id == user.id)
.values(failed_login_count=AppUser.failed_login_count + 1)
.returning(AppUser.failed_login_count)
).scalar_one()
if new_count >= settings.login_max_attempts:
db.execute(
update(AppUser)
.where(AppUser.id == user.id)
.values(
locked_until=now + dt.timedelta(minutes=settings.login_lockout_minutes),
failed_login_count=0,
)
)
return None
if user.failed_login_count or user.locked_until is not None:
db.execute(
update(AppUser).where(AppUser.id == user.id)
.values(failed_login_count=0, locked_until=None)
)
return user
def create_session(db: DbSession, user: AppUser, ip: str | None = None) -> tuple[Session, str]:
"""Create a DB-backed session. Returns (session, raw_token). Only the hash is stored."""
raw_token = generate_session_token()
now = dt.datetime.now(dt.timezone.utc)
session = Session(
user_id=user.id,
token_hash=hash_token(raw_token),
expires_at=now + dt.timedelta(hours=settings.session_ttl_hours),
last_seen_at=now,
created_ip=ip,
)
db.add(session)
db.flush()
return session, raw_token
def resolve_session(db: DbSession, raw_token: str) -> AppUser | None:
"""Validate a token → active user. None if invalid/expired/revoked."""
now = dt.datetime.now(dt.timezone.utc)
session = db.scalar(select(Session).where(Session.token_hash == hash_token(raw_token)))
if session is None or session.revoked_at is not None or session.expires_at <= now:
return None
user = db.get(AppUser, session.user_id)
if user is None or not user.is_active:
return None
if session.last_seen_at is None or now - session.last_seen_at > dt.timedelta(minutes=5):
session.last_seen_at = now
db.commit()
return user
def revoke_session(db: DbSession, raw_token: str) -> None:
session = db.scalar(select(Session).where(Session.token_hash == hash_token(raw_token)))
if session is not None and session.revoked_at is None:
session.revoked_at = dt.datetime.now(dt.timezone.utc)
def revoke_user_sessions(db: DbSession, user_id) -> None:
"""Kill every active session for a user (used on password change → containment)."""
db.execute(
update(Session).where(Session.user_id == user_id, Session.revoked_at.is_(None))
.values(revoked_at=dt.datetime.now(dt.timezone.utc))
)
+193
View File
@@ -0,0 +1,193 @@
"""Effective-role resolution with GitLab-style ancestor-or-self inheritance.
A grant on node G applies to every descendant of G. The effective role on a target node is the
highest-ranked grant among the target and all its ancestors (by materialized path), plus owner /
personal-workspace / instance-admin overrides. This module is the single authority for access;
routers call assert_* before any read/write.
"""
from __future__ import annotations
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..enums import NodeRole, PrincipalType
from ..errors import AuthorizationError, NotFoundError
from ..models import AppUser, Node, PermissionGrant
def ancestor_paths(path: str) -> list[str]:
"""All ancestor-or-self paths for '/a/b/c' → ['/a', '/a/b', '/a/b/c']."""
parts = [p for p in path.split("/") if p]
return ["/" + "/".join(parts[: i + 1]) for i in range(len(parts))]
def ancestor_or_self_nodes(db: DbSession, node: Node) -> list[Node]:
paths = ancestor_paths(node.path)
if not paths:
return [node]
return list(db.scalars(select(Node).where(Node.path.in_(paths))).all())
def effective_role(db: DbSession, user: AppUser, node: Node) -> NodeRole | None:
"""Highest role the user holds on `node`, or None if no access."""
if user.is_admin:
return NodeRole.manager
chain = ancestor_or_self_nodes(db, node)
for n in chain:
if n.personal_owner_id == user.id or n.owner_id == user.id:
return NodeRole.manager
chain_ids = [n.id for n in chain]
grants = db.scalars(
select(PermissionGrant).where(
PermissionGrant.node_id.in_(chain_ids),
PermissionGrant.principal_type == PrincipalType.user,
PermissionGrant.principal_id == user.id,
)
).all()
best: NodeRole | None = None
for g in grants:
if NodeRole.rank(g.role) > NodeRole.rank(best):
best = g.role
return best
def assert_can_read(db: DbSession, user: AppUser, node: Node) -> NodeRole:
"""Require any access. No access → 404 (hide existence)."""
role = effective_role(db, user, node)
if role is None:
raise NotFoundError("Not found.")
return role
def assert_role(db: DbSession, user: AppUser, node: Node, minimum: NodeRole) -> NodeRole:
"""Require at least `minimum`. None → 404; insufficient → 403."""
role = effective_role(db, user, node)
if role is None:
raise NotFoundError("Not found.")
if NodeRole.rank(role) < NodeRole.rank(minimum):
raise AuthorizationError(f"This needs the '{minimum.value}' role or higher.")
return role
def users_with_role_at_least(db: DbSession, node: Node, minimum: NodeRole) -> set:
"""User ids holding at least `minimum` on `node` (via grants on it or an ancestor, ownership,
or instance-admin). Used to find who to notify for a review request."""
chain = ancestor_or_self_nodes(db, node)
ids: set = set()
for n in chain:
if n.owner_id:
ids.add(n.owner_id)
if n.personal_owner_id:
ids.add(n.personal_owner_id)
chain_ids = [n.id for n in chain]
grants = db.scalars(
select(PermissionGrant).where(
PermissionGrant.node_id.in_(chain_ids),
PermissionGrant.principal_type == PrincipalType.user,
)
).all()
for g in grants:
if NodeRole.rank(g.role) >= NodeRole.rank(minimum):
ids.add(g.principal_id)
admins = db.scalars(select(AppUser.id).where(AppUser.is_admin.is_(True))).all()
ids.update(admins)
return ids
# ── grant CRUD (the single owner of permission-grant reads + mutations; routers call these) ──
def find_user_grant(db: DbSession, node_id, user_id) -> PermissionGrant | None:
return db.scalar(
select(PermissionGrant).where(
PermissionGrant.node_id == node_id,
PermissionGrant.principal_type == PrincipalType.user,
PermissionGrant.principal_id == user_id,
)
)
def upsert_user_grant(db: DbSession, node: Node, target_id, role: NodeRole, created_by):
"""Create or update a user's grant on a node. Raises NotFoundError if the user is unknown."""
target = db.get(AppUser, target_id)
if target is None:
raise NotFoundError("User not found.")
grant = find_user_grant(db, node.id, target.id)
if grant is None:
grant = PermissionGrant(node_id=node.id, principal_type=PrincipalType.user,
principal_id=target.id, role=role, created_by=created_by)
db.add(grant)
else:
grant.role = role
return grant, target
def remove_user_grant(db: DbSession, node_id, target_id) -> bool:
grant = find_user_grant(db, node_id, target_id)
if grant is not None:
db.delete(grant)
return True
return False
def list_grants_for_display(db: DbSession, node: Node) -> dict:
"""Direct + inherited user grants on a node (for the Share dialog), batched into 3 queries."""
chain = ancestor_or_self_nodes(db, node)
node_by_id = {n.id: n for n in chain}
grants = db.scalars(
select(PermissionGrant).where(
PermissionGrant.node_id.in_([n.id for n in chain]),
PermissionGrant.principal_type == PrincipalType.user,
)
).all()
uids = {g.principal_id for g in grants}
if node.owner_id:
uids.add(node.owner_id)
users = ({u.id: u for u in db.scalars(select(AppUser).where(AppUser.id.in_(uids))).all()}
if uids else {})
def _row(g, from_node):
u = users.get(g.principal_id)
return {"user_id": str(g.principal_id), "name": u.full_name if u else "—",
"email": u.email if u else "", "role": g.role.value,
"from": from_node.name if from_node else None,
"from_id": str(from_node.id) if from_node else None}
direct = [_row(g, None) for g in grants if g.node_id == node.id]
inherited = [_row(g, node_by_id.get(g.node_id)) for g in grants if g.node_id != node.id]
owner = users.get(node.owner_id) if node.owner_id else None
return {"direct": direct, "inherited": inherited,
"owner": {"id": str(owner.id), "name": owner.full_name} if owner else None}
def grants_for_user(db: DbSession, user_id) -> list[tuple[Node, NodeRole]]:
"""Every (node, role) granted directly to a user — for the admin per-user access view."""
grants = db.scalars(
select(PermissionGrant).where(
PermissionGrant.principal_type == PrincipalType.user,
PermissionGrant.principal_id == user_id,
)
).all()
if not grants:
return []
nodes_by_id = {n.id: n for n in
db.scalars(select(Node).where(Node.id.in_([g.node_id for g in grants]))).all()}
return [(nodes_by_id[g.node_id], g.role) for g in grants if g.node_id in nodes_by_id]
def access_state(db: DbSession, user: AppUser, node: Node) -> str:
"""Status for the folder badge: 'locked' | 'granted' | 'shared' | 'open'."""
role = effective_role(db, user, node)
if role is None:
return "locked"
own_grants = db.scalars(
select(PermissionGrant).where(PermissionGrant.node_id == node.id)
).all()
direct_for_user = any(
g.principal_type == PrincipalType.user and g.principal_id == user.id for g in own_grants
)
if direct_for_user:
return "granted"
others = [g for g in own_grants if not (g.principal_type == PrincipalType.user
and g.principal_id == user.id)]
if others and NodeRole.rank(role) >= NodeRole.rank(NodeRole.manager):
return "shared"
return "open"
+272
View File
@@ -0,0 +1,272 @@
"""The single write chokepoint + the draft/review workflow.
`open` policy → a redaction straight onto the main version.
`review_required` → redactions land on the editor's working version; submitting opens a Draft that
an approver publishes. Encryption (if set) is applied transparently here before content hits git.
"""
from __future__ import annotations
import datetime as dt
import uuid
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..enums import (
DraftMessageKind,
DraftStatus,
EncryptionMode,
NodeRole,
NotificationKind,
PrincipalType,
ReviewPolicy,
)
from ..errors import ConflictError, NotFoundError, ValidationError
from ..models import AppUser, Draft, DraftMessage, Node
from . import audit, authz, crypto, git_facade, notify, settings
from .git_facade import MAIN
from .nodes import slugify
def working_branch(user: AppUser) -> str:
return f"version/{slugify(user.email)}"
def _effective_mode(db: DbSession, project: Node, path: str) -> EncryptionMode:
row = crypto.get_crypto(db, project.id, path)
if row is not None:
return EncryptionMode(row.mode)
return EncryptionMode(project.encryption_mode)
def read_decrypted(db: DbSession, project: Node, path: str, ref: str = MAIN,
passphrase: str | None = None) -> bytes:
# Blobs are self-describing: decrypt() detects encryption from the blob header itself, so this
# reads correctly for every ref (history/branches) regardless of the current file_crypto row.
raw = git_facade.read_file(project.id, path, ref)
return crypto.decrypt(raw, passphrase)
def apply_change(db: DbSession, user: AppUser, project: Node, path: str, content: bytes, *,
message: str, passphrase: str | None = None, delete: bool = False,
ip: str | None = None) -> dict:
"""Save a file. Encrypts if policy requires, then routes by review policy."""
git_facade.set_committer(*settings.committer(db))
mode = _effective_mode(db, project, path)
blob = content
if not delete and mode != EncryptionMode.none:
blob = crypto.encrypt(db, project.id, path, content, mode, passphrase)
elif delete:
crypto.clear(db, project.id, path)
if ReviewPolicy(project.review_policy) == ReviewPolicy.open:
sha = git_facade.commit_file(
project.id, path, blob, branch=MAIN, author_name=user.full_name,
author_email=user.email, message=message, delete=delete,
)
audit.record(db, actor_id=user.id, action="redaction", entity_type="project",
entity_id=project.id, detail=f"{path} → main", ip=ip)
return {"mode": "published", "branch": MAIN, "sha": sha}
branch = working_branch(user)
sha = git_facade.commit_file(
project.id, path, blob, branch=branch, author_name=user.full_name,
author_email=user.email, message=message, delete=delete,
)
audit.record(db, actor_id=user.id, action="redaction", entity_type="project",
entity_id=project.id, detail=f"{path} → {branch}", ip=ip)
return {"mode": "working", "branch": branch, "sha": sha}
def _open_draft_for(db: DbSession, project: Node, user: AppUser) -> Draft | None:
return db.scalar(
select(Draft).where(
Draft.project_id == project.id, Draft.author_id == user.id,
Draft.status == DraftStatus.open,
)
)
def submit_draft(db: DbSession, user: AppUser, project: Node, title: str,
ip: str | None = None) -> Draft:
branch = working_branch(user)
if branch not in git_facade.list_versions(project.id):
raise ConflictError("Make some edits before submitting a draft.")
draft = _open_draft_for(db, project, user)
if draft is None:
draft = Draft(project_id=project.id, title=title or "Draft", source_version=branch,
target_version=MAIN, status=DraftStatus.open, author_id=user.id)
db.add(draft)
db.flush()
else:
draft.title = title or draft.title
draft.updated_at = dt.datetime.now(dt.timezone.utc)
db.add(DraftMessage(draft_id=draft.id, author_id=user.id, kind=DraftMessageKind.system,
body="submitted this draft"))
audit.record(db, actor_id=user.id, action="draft.submit", entity_type="draft",
entity_id=draft.id, ip=ip)
notify.notify_approvers(db, project, draft, actor=user)
return draft
def post_message(db: DbSession, user: AppUser, draft: Draft, body: str,
file_path: str | None = None, line_no: int | None = None,
parent_id=None) -> DraftMessage:
body = (body or "").strip()
if not body:
raise ValidationError("Message can't be empty.")
parent = db.get(DraftMessage, parent_id) if parent_id else None
if parent is not None and parent.draft_id != draft.id:
raise ValidationError("That comment isn't part of this review.")
# A reply inherits its thread root's file anchor; replies always hang off the ROOT, never a reply.
if parent is not None:
root = db.get(DraftMessage, parent.parent_id) if parent.parent_id else parent
parent_id, file_path, line_no = root.id, root.file_path, root.line_no
kind = DraftMessageKind.comment if (file_path or parent_id) else DraftMessageKind.message
msg = DraftMessage(draft_id=draft.id, author_id=user.id, kind=kind, body=body,
file_path=file_path, line_no=line_no, parent_id=parent_id)
db.add(msg)
db.flush()
notify.notify_review_message(db, draft, actor=user, body=body)
return msg
def set_thread_resolved(db: DbSession, draft: Draft, root_id, resolved: bool) -> DraftMessage:
"""Mark a thread (its root message) resolved/reopened. Only a root comment can carry state."""
root = db.get(DraftMessage, root_id)
if root is None or root.draft_id != draft.id:
raise NotFoundError("Comment not found.")
if root.parent_id is not None:
raise ValidationError("Resolve the thread from its first comment.")
root.resolved = bool(resolved)
db.flush()
return root
def publish_draft(db: DbSession, approver: AppUser, project: Node, draft: Draft,
ip: str | None = None) -> dict:
if draft.status != DraftStatus.open:
raise ConflictError("This draft is already closed.")
git_facade.set_committer(*settings.committer(db))
result = git_facade.publish(
project.id, draft.source_version, draft.target_version,
author_name=draft.author_id and approver.full_name or approver.full_name,
author_email=approver.email, message=f"Publish draft: {draft.title}",
)
if not result.get("ok"):
return {"ok": False, "conflicts": result.get("conflicts", [])}
draft.status = DraftStatus.published
draft.approver_id = approver.id
draft.published_at = dt.datetime.now(dt.timezone.utc)
db.add(DraftMessage(draft_id=draft.id, author_id=approver.id, kind=DraftMessageKind.system,
body="approved & published this draft"))
audit.record(db, actor_id=approver.id, action="draft.publish", entity_type="draft",
entity_id=draft.id, ip=ip)
notify.notify_author(db, draft, kind=NotificationKind.draft_published, actor=approver,
title="Your draft was published")
return {"ok": True, "sha": result["sha"]}
def resolve_and_publish(db: DbSession, approver: AppUser, project: Node, draft: Draft,
resolutions: dict[str, bytes], ip: str | None = None) -> dict:
git_facade.set_committer(*settings.committer(db))
result = git_facade.resolve_publish(
project.id, draft.source_version, draft.target_version, resolutions,
author_name=approver.full_name, author_email=approver.email,
message=f"Publish draft (resolved): {draft.title}",
)
draft.status = DraftStatus.published
draft.approver_id = approver.id
draft.published_at = dt.datetime.now(dt.timezone.utc)
db.add(DraftMessage(draft_id=draft.id, author_id=approver.id, kind=DraftMessageKind.system,
body="resolved discrepancies and published this draft"))
audit.record(db, actor_id=approver.id, action="draft.publish", entity_type="draft",
entity_id=draft.id, ip=ip)
notify.notify_author(db, draft, kind=NotificationKind.draft_published, actor=approver,
title="Your draft was published")
return {"ok": True, "sha": result["sha"]}
def list_project_drafts(db: DbSession, project: Node) -> list[Draft]:
return list(db.scalars(
select(Draft).where(Draft.project_id == project.id).order_by(Draft.created_at.desc())
).all())
def drafts_for_user(db: DbSession, user: AppUser) -> list[tuple]:
"""Drafts the user authored + open drafts they can approve. Returns (draft, project_name,
author_name, can_approve). Batched: 2 lookups + one role per distinct project."""
drafts = db.scalars(select(Draft).order_by(Draft.created_at.desc())).all()
if not drafts:
return []
projects = {n.id: n for n in db.scalars(
select(Node).where(Node.id.in_({d.project_id for d in drafts}))).all()}
authors = {u.id: u for u in db.scalars(
select(AppUser).where(AppUser.id.in_({d.author_id for d in drafts}))).all()}
rc: dict = {}
def _role(nid):
if nid not in rc:
n = projects.get(nid)
rc[nid] = authz.effective_role(db, user, n) if n else None
return rc[nid]
out = []
for d in drafts:
project = projects.get(d.project_id)
if project is None:
continue
mine = d.author_id == user.id
can_approve = (d.status == DraftStatus.open and not mine
and NodeRole.rank(_role(d.project_id)) >= NodeRole.rank(NodeRole.approver))
if mine or can_approve:
author = authors.get(d.author_id)
out.append((d, project.name, author.full_name if author else "—", can_approve))
return out
def draft_messages(db: DbSession, draft: Draft) -> tuple[list[DraftMessage], dict]:
"""A draft's messages + a {user_id: full_name} map for just the authors that appear."""
msgs = db.scalars(
select(DraftMessage).where(DraftMessage.draft_id == draft.id)
.order_by(DraftMessage.created_at)
).all()
author_ids = {m.author_id for m in msgs if m.author_id}
names = ({u.id: u.full_name for u in
db.scalars(select(AppUser).where(AppUser.id.in_(author_ids))).all()}
if author_ids else {})
return list(msgs), names
def withdraw_draft(db: DbSession, user: AppUser, draft: Draft) -> Draft:
if draft.author_id != user.id:
raise ConflictError("Only the author can withdraw a draft.")
draft.status = DraftStatus.withdrawn
return draft
def combine_versions(db: DbSession, user: AppUser, project: Node, source: str, target: str,
message: str | None = None, ip: str | None = None) -> dict:
"""Merge one version into another (branch→branch, not necessarily main) — 'Combine versions'.
Returns {ok, sha} or {ok: False, conflicts: [...]} just like publish."""
git_facade.set_committer(*settings.committer(db))
result = git_facade.publish(
project.id, source, target, author_name=user.full_name, author_email=user.email,
message=message or f"Combine {source} into {target}",
)
if result.get("ok"):
audit.record(db, actor_id=user.id, action="combine", entity_type="project",
entity_id=project.id, detail=f"{source} → {target}", ip=ip)
return result
def reject_draft(db: DbSession, approver: AppUser, draft: Draft, reason: str | None = None) -> Draft:
if draft.status != DraftStatus.open:
raise ConflictError("This draft is already closed.")
draft.status = DraftStatus.rejected
draft.approver_id = approver.id
db.add(DraftMessage(draft_id=draft.id, author_id=approver.id, kind=DraftMessageKind.system,
body="requested changes" + (f": {reason}" if reason else "")))
notify.notify_author(db, draft, kind=NotificationKind.draft_rejected, actor=approver,
title="Your draft needs changes")
return draft
+141
View File
@@ -0,0 +1,141 @@
"""Optional per-file encryption: AES-256-GCM with envelope-wrapped data keys.
server mode — the data key is wrapped by the instance master key (the server can decrypt for
authorized users, so preview/search/Changes keep working).
passphrase mode — the data key is wrapped by an Argon2id(passphrase, salt) key (zero-knowledge:
the server cannot decrypt without the passphrase supplied in-session).
Wrapped keys + nonces are stored in the `file_crypto` table — never in git. Git holds ciphertext.
"""
from __future__ import annotations
import base64
import os
import uuid
from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..config import get_settings
from ..enums import EncryptionMode
from ..errors import ConflictError, ValidationError
from ..models import FileCrypto
from ..security import derive_key
settings = get_settings()
ALGO = "AES-256-GCM"
# Self-describing encrypted-blob envelope. Every git blob carries its own key material, so each
# ref (history, branches, re-encrypted versions) decrypts independently — there is no single
# mutable key row to corrupt. Fixed-size header:
# MAGIC(8) | mode(1) | salt(16) | wrap_nonce(12) | data_nonce(12) | wrapped_dek(48) | ciphertext
MAGIC = b"GLNAENC\x01"
_WRAPPED_DEK_LEN = 48 # AES-256-GCM of a 32-byte key = 32 + 16-byte tag
HEADER_LEN = len(MAGIC) + 1 + 16 + 12 + 12 + _WRAPPED_DEK_LEN
_MODE_BYTE = {EncryptionMode.server: 1, EncryptionMode.passphrase: 2}
_BYTE_MODE = {v: k for k, v in _MODE_BYTE.items()}
def is_encrypted_blob(blob: bytes) -> bool:
return blob[: len(MAGIC)] == MAGIC
def _master_key() -> bytes:
raw = settings.encryption_master_key.strip()
if not raw:
raise ConflictError("Encryption is not configured (set ENCRYPTION_MASTER_KEY).")
key = base64.b64decode(raw)
if len(key) != 32:
raise ConflictError("ENCRYPTION_MASTER_KEY must be base64 of 32 bytes.")
return key
def get_crypto(db: DbSession, project_id: uuid.UUID, path: str) -> FileCrypto | None:
return db.scalar(
select(FileCrypto).where(FileCrypto.project_id == project_id, FileCrypto.path == path)
)
def _kek(mode: EncryptionMode, salt: bytes | None, passphrase: str | None) -> bytes:
if mode == EncryptionMode.server:
return _master_key()
if mode == EncryptionMode.passphrase:
if not passphrase:
raise ValidationError("A passphrase is required to open this item.")
return derive_key(passphrase, salt)
raise ValidationError("Unknown encryption mode.")
def encrypt(
db: DbSession,
project_id: uuid.UUID,
path: str,
plaintext: bytes,
mode: EncryptionMode,
passphrase: str | None = None,
) -> bytes:
"""Encrypt content into a self-describing blob and upsert the file_crypto marker row.
The returned blob embeds its own salt/nonces/wrapped-DEK, so it decrypts independently of any
DB row. The row is a UI hint (is-this-path-encrypted + mode) — re-encrypting overwrites it
harmlessly, because old git blobs in history/other branches still carry their own key material.
"""
if mode not in (EncryptionMode.server, EncryptionMode.passphrase):
raise ValidationError("Unknown encryption mode.")
dek = AESGCM.generate_key(bit_length=256)
data_nonce = os.urandom(12)
ciphertext = AESGCM(dek).encrypt(data_nonce, plaintext, None)
salt = os.urandom(16) # meaningful for passphrase mode; random filler for server mode
kek = _kek(mode, salt, passphrase)
wrap_nonce = os.urandom(12)
wrapped = AESGCM(kek).encrypt(wrap_nonce, dek, None)
blob = b"".join((MAGIC, bytes([_MODE_BYTE[mode]]), salt, wrap_nonce, data_nonce, wrapped,
ciphertext))
row = get_crypto(db, project_id, path)
if row is None:
row = FileCrypto(project_id=project_id, path=path)
db.add(row)
row.mode, row.algo = mode, ALGO
row.wrapped_dek, row.wrap_nonce, row.nonce, row.salt = wrapped, wrap_nonce, data_nonce, salt
db.flush()
return blob
def decrypt(blob: bytes, passphrase: str | None = None) -> bytes:
"""Decrypt a self-describing blob. Plaintext (no MAGIC) is returned unchanged, so reads work
uniformly across encrypted and unencrypted refs without consulting the DB."""
if not is_encrypted_blob(blob):
return blob
if len(blob) < HEADER_LEN:
raise ValidationError("This file's encrypted data is corrupt.")
o = len(MAGIC)
mode = _BYTE_MODE.get(blob[o])
o += 1
salt, o = blob[o:o + 16], o + 16
wrap_nonce, o = blob[o:o + 12], o + 12
data_nonce, o = blob[o:o + 12], o + 12
wrapped, o = blob[o:o + _WRAPPED_DEK_LEN], o + _WRAPPED_DEK_LEN
ciphertext = blob[o:]
if mode is None:
raise ValidationError("Unsupported encryption format.")
kek = _kek(mode, salt, passphrase)
try:
dek = AESGCM(kek).decrypt(wrap_nonce, wrapped, None)
return AESGCM(dek).decrypt(data_nonce, ciphertext, None)
except InvalidTag as exc:
raise ValidationError("Wrong passphrase, or the content could not be decrypted.") from exc
def clear(db: DbSession, project_id: uuid.UUID, path: str) -> None:
row = get_crypto(db, project_id, path)
if row is not None:
db.delete(row)
def new_master_key_b64() -> str:
"""Helper for setup: a fresh base64 32-byte master key."""
return base64.b64encode(os.urandom(32)).decode("ascii")
+463
View File
@@ -0,0 +1,463 @@
"""GitPython facade — de-jargoned git operations behind a per-repo lock.
User-facing terms (see README): main version = default branch; version = branch; redaction =
commit; publish = merge; combine = branch→branch merge; clone = independent copy; changes = diff;
authorship = blame. Reads navigate the object DB at a ref WITHOUT touching the working tree, so
they're safe to run concurrently; writes take a per-repo in-process lock and use the working tree.
"""
from __future__ import annotations
import difflib
import posixpath
import threading
import uuid
from pathlib import Path
from git import Actor, Repo
from git.exc import GitCommandError
from gitdb.db import GitDB
from ..errors import ConflictError, NotFoundError, ValidationError
from ..storage import backend
MAIN = "main"
# git's canonical empty-tree object — diff a root commit against this to list all its files.
EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
BOT = Actor("Galena", "galena@localhost")
_committer = BOT # instance commit identity; overridable via admin Git settings
def set_committer(name: str | None, email: str | None) -> None:
global _committer
_committer = Actor(name or "Galena", email or "galena@localhost")
def safe_path(path: str) -> str:
"""Validate + normalize a repo-relative file path. Rejects empty, absolute, drive-letter,
`..`/`.` traversal, the `.git` directory, and control chars — the single guard for every
write entrypoint so attacker paths can't escape the working tree or plant git hooks (RCE)."""
p = (path or "").strip().replace("\\", "/")
if not p or p.startswith("/") or (len(p) > 1 and p[1] == ":"):
raise ValidationError("Invalid file path.")
if "\x00" in p or any(ord(c) < 32 for c in p):
raise ValidationError("Invalid file path.")
norm = posixpath.normpath(p)
if norm in (".", "..") or norm.startswith("../") or norm.startswith("/"):
raise ValidationError("Invalid file path.")
if any(seg.strip().lower() == ".git" for seg in norm.split("/")):
raise ValidationError("Invalid file path.")
return norm
def _full_path(working_tree_dir: str, rel: str) -> Path:
"""Resolve a *validated* relative path and confirm it stays inside the working tree."""
root = Path(working_tree_dir).resolve()
full = (root / rel).resolve()
if full != root and root not in full.parents:
raise ValidationError("Path escapes the project.")
return full
_locks: dict[uuid.UUID, threading.RLock] = {}
_locks_guard = threading.Lock()
def _lock(project_id: uuid.UUID) -> threading.RLock:
with _locks_guard:
lock = _locks.get(project_id)
if lock is None:
lock = _locks[project_id] = threading.RLock()
return lock
def _repo(project_id: uuid.UUID) -> Repo:
"""A fresh repo for WRITES (full `git` command + working tree). Reads use `_read_repo`."""
path = backend.repo_path(project_id)
if not path.exists():
raise NotFoundError("Project storage is missing.")
return Repo(path)
# Cached, pure-Python-ODB repos for READS. Opening with GitDB reads objects directly from the loose/
# pack store instead of spawning a `git cat-file` subprocess per object, and caching avoids
# GitPython's per-`close()` `gc.collect()` (called twice on Windows to release tempfile handles) —
# together a ~100x speedup for tree/blob reads (search, browsing, history). Writes call
# `_invalidate_read` so the next read reopens and reflects the latest redaction. Git objects are
# immutable, so a read in flight against the previous snapshot stays consistent. Single-instance
# assumption matches the in-process write lock (see README scale-out roadmap).
_read_repos: dict[uuid.UUID, Repo] = {}
_read_guard = threading.Lock()
def _read_repo(project_id: uuid.UUID) -> Repo:
path = backend.repo_path(project_id)
if not path.exists():
_invalidate_read(project_id)
raise NotFoundError("Project storage is missing.")
with _read_guard:
repo = _read_repos.get(project_id)
if repo is None:
repo = _read_repos[project_id] = Repo(path, odbt=GitDB)
return repo
def _invalidate_read(project_id: uuid.UUID) -> None:
with _read_guard:
repo = _read_repos.pop(project_id, None)
if repo is not None:
try:
repo.close()
except Exception: # noqa: BLE001
pass
def _commit(repo: Repo, ref: str):
try:
return repo.commit(ref)
except Exception as exc: # noqa: BLE001
raise NotFoundError(f"Unknown version '{ref}'.") from exc
def _node_at(repo: Repo, ref: str, path: str):
tree = _commit(repo, ref).tree
if not path:
return tree
try:
return tree / path
except KeyError as exc:
raise NotFoundError("Path not found.") from exc
# ── lifecycle ──────────────────────────────────────────────────────────────────
def init_project(project_id: uuid.UUID) -> Path:
backend.ensure_root()
path = backend.repo_path(project_id)
repo = Repo.init(path, initial_branch=MAIN)
repo.index.commit("Initialize project", author=BOT, committer=BOT)
return path
def remove_project(project_id: uuid.UUID) -> None:
_invalidate_read(project_id)
backend.remove_repo(project_id)
def clone_project(src_id: uuid.UUID, dst_id: uuid.UUID) -> Path:
"""Independent copy of a project, with its history (Clone). The new repo has no remote."""
backend.ensure_root()
src, dst = backend.repo_path(src_id), backend.repo_path(dst_id)
if not src.exists():
raise NotFoundError("Source project is missing.")
repo = Repo.clone_from(str(src), str(dst))
try:
repo.delete_remote("origin")
except Exception: # noqa: BLE001
pass
return dst
# ── reads ────────────────────────────────────────────────────────────────────
def list_tree(project_id: uuid.UUID, path: str = "", ref: str = MAIN) -> list[dict]:
repo = _read_repo(project_id)
node = _node_at(repo, ref, path)
if node.type != "tree":
raise ConflictError("That path is a file, not a folder.")
entries = [
{"name": t.name, "path": t.path, "type": "folder"} for t in node.trees
] + [
{"name": b.name, "path": b.path, "type": "file", "size": b.size} for b in node.blobs
]
entries.sort(key=lambda e: (e["type"] != "folder", e["name"].lower()))
return entries
def read_file(project_id: uuid.UUID, path: str, ref: str = MAIN) -> bytes:
repo = _read_repo(project_id)
obj = _node_at(repo, ref, path)
if obj.type != "blob":
raise ConflictError("That path is a folder, not a file.")
return obj.data_stream.read()
def file_exists(project_id: uuid.UUID, path: str, ref: str = MAIN) -> bool:
try:
obj = _node_at(_read_repo(project_id), ref, path)
return obj.type == "blob"
except NotFoundError:
return False
def list_versions(project_id: uuid.UUID) -> list[str]:
return [h.name for h in _read_repo(project_id).heads]
def create_version(project_id: uuid.UUID, name: str, from_ref: str = MAIN) -> str:
"""Create a new version (branch) from `from_ref`."""
repo = _repo(project_id)
with _lock(project_id):
if name in [h.name for h in repo.heads]:
raise ConflictError("That version already exists.")
repo.create_head(name, _commit(repo, from_ref))
_invalidate_read(project_id)
return name
def _commit_dict(c) -> dict:
return {
"sha": c.hexsha,
"short": c.hexsha[:8],
"message": c.message.strip(),
"author": c.author.name,
"email": c.author.email,
"date": c.authored_datetime.isoformat(),
"parents": [p.hexsha for p in c.parents],
}
def log(project_id: uuid.UUID, ref: str = MAIN, path: str | None = None,
limit: int = 50) -> list[dict]:
repo = _read_repo(project_id)
try:
commits = repo.iter_commits(ref, paths=path or None, max_count=limit)
return [_commit_dict(c) for c in commits]
except GitCommandError as exc:
raise NotFoundError(f"Unknown version '{ref}'.") from exc
def version_graph(project_id: uuid.UUID, limit: int = 200) -> dict:
"""Commits across all versions + which version each tip points at — for the history graph."""
repo = _read_repo(project_id)
commits = [_commit_dict(c) for c in repo.iter_commits(all=True, max_count=limit)]
tips = {h.name: h.commit.hexsha for h in repo.heads}
return {"main": MAIN, "versions": list(tips), "tips": tips, "commits": commits}
def all_files(project_id: uuid.UUID, ref: str = MAIN, limit: int = 2000) -> list[str]:
"""Every file path in the project (recursive) — powers file search."""
repo = _read_repo(project_id)
out: list[str] = []
try:
for item in _commit(repo, ref).tree.traverse():
if item.type == "blob":
out.append(item.path)
if len(out) >= limit:
break
except Exception: # noqa: BLE001
pass
return out
def scan_blobs(project_id: uuid.UUID, ref: str = MAIN, limit: int = 2000):
"""Yield (path, size, read) for each file blob — opening the repo and walking the tree ONCE.
`read()` returns the blob bytes on demand, so a caller can skip content it doesn't need (e.g. a
filename already matched). Far cheaper than all_files + a per-path read_file (which each reopen
the repo and re-traverse the tree). Powers fast file-name + content search."""
repo = _read_repo(project_id)
try:
n = 0
for item in _commit(repo, ref).tree.traverse():
if item.type == "blob":
yield item.path, item.size, (lambda it=item: it.data_stream.read())
n += 1
if n >= limit:
break
except Exception: # noqa: BLE001
return
def changed_files(project_id: uuid.UUID, a: str, b: str) -> list[str]:
"""Paths that differ between versions a and b (for a draft's file list)."""
repo = _read_repo(project_id)
try:
out = repo.git.diff("--name-only", a, b)
except GitCommandError:
return []
return [p for p in out.splitlines() if p.strip()]
def blame(project_id: uuid.UUID, path: str, ref: str = MAIN) -> list[dict]:
repo = _read_repo(project_id)
rows: list[dict] = []
try:
for commit, lines in repo.blame(ref, path):
for ln in lines:
rows.append({
"author": commit.author.name,
"short": commit.hexsha[:8],
"date": commit.authored_datetime.isoformat(),
"text": ln,
})
except GitCommandError as exc:
raise NotFoundError("Authorship is unavailable for this file.") from exc
except (UnicodeDecodeError, ValueError) as exc:
# Binary or encrypted blobs (ciphertext) can't be shown line-by-line.
raise ValidationError("Authorship isn't available for binary or encrypted files.") from exc
return rows
def _text(blob_bytes: bytes) -> list[str] | None:
try:
return blob_bytes.decode("utf-8").splitlines()
except UnicodeDecodeError:
return None
def file_changes(project_id: uuid.UUID, path: str, ref_a: str = MAIN,
ref_b: str = MAIN) -> dict:
"""Two-window + merged change model between two versions of one file (Changes)."""
a = read_file(project_id, path, ref_a) if file_exists(project_id, path, ref_a) else b""
b = read_file(project_id, path, ref_b) if file_exists(project_id, path, ref_b) else b""
la, lb = _text(a), _text(b)
if la is None or lb is None:
return {"binary": True, "rows": [], "merged": [], "added": 0, "removed": 0}
rows: list[dict] = []
merged: list[dict] = []
added = removed = 0
sm = difflib.SequenceMatcher(a=la, b=lb, autojunk=False)
for tag, i1, i2, j1, j2 in sm.get_opcodes():
if tag == "equal":
for k in range(i2 - i1):
rows.append({"op": "equal",
"left": {"n": i1 + k + 1, "text": la[i1 + k]},
"right": {"n": j1 + k + 1, "text": lb[j1 + k]}})
merged.append({"op": "equal", "text": la[i1 + k]})
else:
left = la[i1:i2]
right = lb[j1:j2]
removed += len(left)
added += len(right)
for k in range(max(len(left), len(right))):
lcell = {"n": i1 + k + 1, "text": left[k]} if k < len(left) else None
rcell = {"n": j1 + k + 1, "text": right[k]} if k < len(right) else None
rows.append({"op": tag, "left": lcell, "right": rcell})
for ln in left:
merged.append({"op": "del", "text": ln})
for ln in right:
merged.append({"op": "add", "text": ln})
return {"binary": False, "rows": rows, "merged": merged, "added": added, "removed": removed}
# ── writes (serialized per repo) ───────────────────────────────────────────────
def _ensure_branch(repo: Repo, branch: str) -> None:
if branch not in [h.name for h in repo.heads]:
repo.create_head(branch, _commit(repo, MAIN))
def commit_file(project_id: uuid.UUID, path: str, content: bytes, *, branch: str = MAIN,
author_name: str, author_email: str | None, message: str,
delete: bool = False) -> str:
"""Write (or delete) one file and record a redaction on `branch`. Returns the commit sha."""
repo = _repo(project_id)
path = safe_path(path)
actor = Actor(author_name, author_email or "user@localhost")
with _lock(project_id):
_ensure_branch(repo, branch)
repo.git.checkout(branch)
full = _full_path(repo.working_tree_dir, path)
if delete:
if not full.exists():
raise NotFoundError("File not found.")
repo.index.remove([path], working_tree=True)
else:
full.parent.mkdir(parents=True, exist_ok=True)
full.write_bytes(content)
repo.index.add([path])
sha = repo.index.commit(message, author=actor, committer=_committer).hexsha
_invalidate_read(project_id)
return sha
def move_file(project_id: uuid.UUID, src: str, dst: str, *, branch: str = MAIN,
author_name: str, author_email: str | None, message: str) -> str:
repo = _repo(project_id)
src, dst = safe_path(src), safe_path(dst)
actor = Actor(author_name, author_email or "user@localhost")
with _lock(project_id):
_ensure_branch(repo, branch)
repo.git.checkout(branch)
src_full = _full_path(repo.working_tree_dir, src)
dst_full = _full_path(repo.working_tree_dir, dst)
if not src_full.exists():
raise NotFoundError("File not found.")
dst_full.parent.mkdir(parents=True, exist_ok=True)
data = src_full.read_bytes()
dst_full.write_bytes(data)
repo.index.add([dst])
repo.index.remove([src], working_tree=True)
sha = repo.index.commit(message, author=actor, committer=_committer).hexsha
_invalidate_read(project_id)
return sha
def _conflicted_paths(repo: Repo) -> list[str]:
out = repo.git.diff(name_only=True, diff_filter="U")
return [p for p in out.splitlines() if p.strip()]
def publish(project_id: uuid.UUID, source: str, target: str = MAIN, *,
author_name: str, author_email: str | None, message: str) -> dict:
"""Merge `source` into `target` (publish / combine). Returns {ok, sha} or {ok:False, conflicts}."""
repo = _repo(project_id)
with _lock(project_id):
if source not in [h.name for h in repo.heads]:
raise NotFoundError(f"Unknown version '{source}'.")
repo.git.checkout(target)
with repo.git.custom_environment(
GIT_AUTHOR_NAME=author_name, GIT_AUTHOR_EMAIL=author_email or "user@localhost",
GIT_COMMITTER_NAME=_committer.name, GIT_COMMITTER_EMAIL=_committer.email,
):
try:
repo.git.merge(source, "--no-ff", "-m", message)
except GitCommandError:
conflicts = _conflicted_paths(repo)
repo.git.merge("--abort")
return {"ok": False, "conflicts": conflicts}
_invalidate_read(project_id)
return {"ok": True, "sha": repo.head.commit.hexsha}
def conflict_sides(project_id: uuid.UUID, source: str, path: str, target: str = MAIN) -> dict:
"""The 'main version' (target) and 'your version' (source) contents of a conflicting file —
powers the Resolve discrepancies picker."""
ours = read_file(project_id, path, target) if file_exists(project_id, path, target) else b""
theirs = read_file(project_id, path, source) if file_exists(project_id, path, source) else b""
return {
"path": path,
"main": ours.decode("utf-8", "replace"),
"incoming": theirs.decode("utf-8", "replace"),
}
def resolve_publish(project_id: uuid.UUID, source: str, target: str, resolutions: dict[str, bytes],
*, author_name: str, author_email: str | None, message: str) -> dict:
"""Complete a conflicted merge using the chosen content per path (Resolve discrepancies)."""
repo = _repo(project_id)
with _lock(project_id):
repo.git.checkout(target)
with repo.git.custom_environment(
GIT_AUTHOR_NAME=author_name, GIT_AUTHOR_EMAIL=author_email or "user@localhost",
GIT_COMMITTER_NAME=_committer.name, GIT_COMMITTER_EMAIL=_committer.email,
):
try:
repo.git.merge(source, "--no-commit", "--no-ff")
except GitCommandError:
pass # conflicts expected; we resolve them below
try:
for raw_path, content in resolutions.items():
path = safe_path(raw_path)
full = _full_path(repo.working_tree_dir, path)
full.parent.mkdir(parents=True, exist_ok=True)
full.write_bytes(content)
repo.git.add(path)
if _conflicted_paths(repo):
raise ValidationError("Some discrepancies are still unresolved.")
repo.git.commit("-m", message)
except BaseException:
# never leave the shared working tree mid-merge on failure
try:
repo.git.merge("--abort")
except GitCommandError:
pass
raise
_invalidate_read(project_id)
return {"ok": True, "sha": repo.head.commit.hexsha}
+236
View File
@@ -0,0 +1,236 @@
"""Node-tree CRUD + drive scopes (My files, Favourites, Shared, Recent)."""
from __future__ import annotations
import re
import uuid
from sqlalchemy import or_, select
from sqlalchemy.orm import Session as DbSession
from ..enums import NodeKind, PrincipalType
from ..errors import ConflictError, NotFoundError, ValidationError
from ..models import AppUser, AuditLog, Favorite, Node, PermissionGrant
_SLUG_RE = re.compile(r"[^a-z0-9]+")
def slugify(name: str) -> str:
s = _SLUG_RE.sub("-", name.strip().lower()).strip("-")
return s or "item"
def unique_slug(db: DbSession, parent_id: uuid.UUID | None, base: str) -> str:
slug, i = base, 1
while db.scalar(
select(Node.id).where(Node.parent_id.is_(parent_id) if parent_id is None
else Node.parent_id == parent_id, Node.slug == slug)
):
i += 1
slug = f"{base}-{i}"
return slug
def get_node(db: DbSession, node_id: uuid.UUID) -> Node:
node = db.get(Node, node_id)
if node is None:
raise NotFoundError("Not found.")
return node
def get_project(db: DbSession, project_id: uuid.UUID) -> Node:
"""Fetch a node and assert it's a project (a git repo). The one definition of 'is a project'."""
node = get_node(db, project_id)
if node.kind != NodeKind.project:
raise ConflictError("That isn't a project.")
return node
def all_nodes(db: DbSession) -> list[Node]:
"""Every node, ordered by path — the admin access picker."""
return list(db.scalars(select(Node).order_by(Node.path)).all())
def _child_path(parent: Node | None, slug: str) -> str:
return f"/{slug}" if parent is None else f"{parent.path}/{slug}"
def create_node(
db: DbSession,
user: AppUser,
*,
parent: Node | None,
kind: NodeKind,
name: str,
personal_owner_id: uuid.UUID | None = None,
) -> Node:
"""Create a container or project. Top-level must be a workspace; only a project may be
created inside another project's git tree-? no — projects are leaves of the org tree."""
name = (name or "").strip()
if not name:
raise ValidationError("A name is required.")
if parent is None and kind != NodeKind.workspace:
raise ValidationError("Top-level items must be workspaces.")
if parent is not None and parent.kind == NodeKind.project:
raise ConflictError("Projects can't contain other workspaces/groups/projects.")
slug = unique_slug(db, parent.id if parent else None, slugify(name))
node = Node(
parent_id=parent.id if parent else None,
kind=kind,
name=name,
slug=slug,
path=_child_path(parent, slug),
owner_id=user.id,
personal_owner_id=personal_owner_id,
)
db.add(node)
db.flush()
if kind == NodeKind.project:
from . import git_facade
git_facade.init_project(node.id)
return node
def children(db: DbSession, parent: Node | None) -> list[Node]:
stmt = select(Node).where(
Node.parent_id.is_(None) if parent is None else Node.parent_id == parent.id
).order_by(Node.kind, Node.name)
return list(db.scalars(stmt).all())
def breadcrumb(db: DbSession, node: Node) -> list[Node]:
from .authz import ancestor_paths
paths = ancestor_paths(node.path)
by_path = {n.path: n for n in db.scalars(select(Node).where(Node.path.in_(paths))).all()}
return [by_path[p] for p in paths if p in by_path]
def rename(db: DbSession, node: Node, new_name: str) -> Node:
new_name = (new_name or "").strip()
if not new_name:
raise ValidationError("A name is required.")
new_slug = unique_slug(db, node.parent_id, slugify(new_name))
_reslug(db, node, node.parent_id, new_slug)
node.name = new_name
db.flush()
return node
def move(db: DbSession, node: Node, new_parent: Node | None) -> Node:
if new_parent is not None:
if new_parent.kind == NodeKind.project:
raise ConflictError("Can't move into a project.")
# Prevent moving a node into its own descendant.
if new_parent.path == node.path or new_parent.path.startswith(node.path + "/"):
raise ConflictError("Can't move an item into itself.")
if node.kind == NodeKind.workspace:
raise ConflictError("Workspaces are top-level and can't be moved into another item.")
new_slug = unique_slug(db, new_parent.id if new_parent else None, node.slug)
node.parent_id = new_parent.id if new_parent else None
_reslug(db, node, node.parent_id, new_slug)
db.flush()
return node
def _reslug(db: DbSession, node: Node, parent_id: uuid.UUID | None, new_slug: str) -> None:
"""Set node.slug=new_slug and rewrite the materialized path of node + all descendants."""
parent = db.get(Node, parent_id) if parent_id else None
old_path = node.path
new_path = _child_path(parent, new_slug)
if old_path == new_path and node.slug == new_slug:
return
descendants = list(
db.scalars(select(Node).where(Node.path.like(old_path + "/%"))).all()
)
node.slug = new_slug
node.path = new_path
for d in descendants:
d.path = new_path + d.path[len(old_path):]
def delete(db: DbSession, node: Node) -> None:
if node.kind == NodeKind.project:
from . import git_facade
git_facade.remove_project(node.id)
db.delete(node) # ON DELETE CASCADE removes descendants, grants, drafts, favorites
# ── drive scopes ──────────────────────────────────────────────────────────────
def personal_workspace(db: DbSession, user: AppUser) -> Node:
node = db.scalar(select(Node).where(Node.personal_owner_id == user.id))
if node is None:
node = create_node(db, user, parent=None, kind=NodeKind.workspace,
name="My files", personal_owner_id=user.id)
# personal slug should be stable per user
return node
def favorite_ids(db: DbSession, user: AppUser) -> set:
return set(db.scalars(select(Favorite.node_id).where(Favorite.user_id == user.id)).all())
def toggle_favorite(db: DbSession, user: AppUser, node: Node) -> bool:
"""Add/remove a favourite; returns the new favourited state."""
existing = db.get(Favorite, {"user_id": user.id, "node_id": node.id})
if existing:
db.delete(existing)
return False
db.add(Favorite(user_id=user.id, node_id=node.id))
return True
def accessible_workspaces(db: DbSession, user: AppUser) -> list[Node]:
"""Non-personal workspaces the user can read — the sidebar/home workspace list."""
from . import authz
return [w for w in db.scalars(select(Node).where(Node.kind == NodeKind.workspace)).all()
if w.personal_owner_id is None and authz.effective_role(db, user, w) is not None]
def favorites(db: DbSession, user: AppUser) -> list[Node]:
from . import authz
ids = db.scalars(select(Favorite.node_id).where(Favorite.user_id == user.id)).all()
if not ids:
return []
nodes = db.scalars(select(Node).where(Node.id.in_(ids))).all()
# Drop favorites the user can no longer read (e.g. access was revoked after favouriting).
return [n for n in nodes if authz.effective_role(db, user, n) is not None]
def shared_with_me(db: DbSession, user: AppUser) -> list[Node]:
"""Nodes with a direct grant to the user that aren't in their personal workspace."""
node_ids = db.scalars(
select(PermissionGrant.node_id).where(
PermissionGrant.principal_type == PrincipalType.user,
PermissionGrant.principal_id == user.id,
)
).all()
if not node_ids:
return []
nodes = db.scalars(select(Node).where(Node.id.in_(node_ids))).all()
personal = db.scalar(select(Node).where(Node.personal_owner_id == user.id))
ppath = personal.path if personal else None
return [n for n in nodes if not (ppath and n.path.startswith(ppath))]
def recent(db: DbSession, user: AppUser, limit: int = 20) -> list[AuditLog]:
"""The user's own actions + activity on nodes they can read — never the global audit log.
Batches the entity-node lookups and memoizes readability (was per-row db.get + effective_role)."""
from . import authz
rows = db.scalars(select(AuditLog).order_by(AuditLog.created_at.desc()).limit(300)).all()
node_ids = {r.entity_id for r in rows if r.entity_id and r.actor_id != user.id}
nodes_by_id = ({n.id: n for n in db.scalars(select(Node).where(Node.id.in_(node_ids))).all()}
if node_ids else {})
readable: dict = {}
def _readable(nid):
if nid not in readable:
n = nodes_by_id.get(nid)
readable[nid] = n is not None and authz.effective_role(db, user, n) is not None
return readable[nid]
out: list[AuditLog] = []
for r in rows:
if len(out) >= limit:
break
if r.actor_id == user.id or (r.entity_id and _readable(r.entity_id)):
out.append(r)
return out
+121
View File
@@ -0,0 +1,121 @@
"""Create notifications and fan them out to a user's enabled channels."""
from __future__ import annotations
import datetime as dt
import re
import uuid
from sqlalchemy import func, select, update
from sqlalchemy.orm import Session as DbSession
from ..enums import NodeRole, NotificationKind
from ..models import AppUser, Draft, Node, Notification, NotificationPref, PushSubscription
from ..notify import email_channel, webpush_channel
from . import authz
_MENTION_RE = re.compile(r"@([a-zA-Z0-9._-]+)")
def _prefs(db: DbSession, user_id: uuid.UUID) -> NotificationPref:
pref = db.get(NotificationPref, user_id)
if pref is None:
pref = NotificationPref(user_id=user_id) # defaults: inapp on, push/email off
return pref
def create(db: DbSession, recipient_id: uuid.UUID, kind: NotificationKind, title: str, *,
body: str | None = None, link: str | None = None, payload: dict | None = None,
actor: AppUser | None = None) -> None:
if actor is not None and actor.id == recipient_id:
return # don't notify yourself
db.add(Notification(recipient_id=recipient_id, kind=kind, title=title, body=body,
link=link, payload=payload))
db.flush()
pref = _prefs(db, recipient_id)
if pref.webpush:
for sub in db.scalars(
select(PushSubscription).where(PushSubscription.user_id == recipient_id)
).all():
webpush_channel.send({"endpoint": sub.endpoint,
"keys": {"p256dh": sub.p256dh, "auth": sub.auth}},
title, body or "", link)
if pref.email:
recipient = db.get(AppUser, recipient_id)
if recipient:
email_channel.send(recipient.email, title, f"{body or title}\n\n{link or ''}")
def notify_approvers(db: DbSession, project: Node, draft: Draft, actor: AppUser) -> None:
link = f"#/drafts/{draft.id}"
for uid in authz.users_with_role_at_least(db, project, NodeRole.approver):
create(db, uid, NotificationKind.review_requested,
f"{actor.full_name} asked you to review “{draft.title}”",
body=f"in {project.name}", link=link, actor=actor)
def notify_review_message(db: DbSession, draft: Draft, actor: AppUser, body: str) -> None:
link = f"#/drafts/{draft.id}"
recipients = {draft.author_id, draft.approver_id} - {None, actor.id}
for uid in recipients:
create(db, uid, NotificationKind.review_message,
f"{actor.full_name} commented on “{draft.title}”", body=body[:140], link=link,
actor=actor)
_scan_mentions(db, body, actor, link, draft.title)
def notify_author(db: DbSession, draft: Draft, kind: NotificationKind, actor: AppUser,
title: str) -> None:
create(db, draft.author_id, kind, title, body=f"“{draft.title}”",
link=f"#/drafts/{draft.id}", actor=actor)
def notify_permission_granted(db: DbSession, recipient_id: uuid.UUID, node: Node,
role: NodeRole, actor: AppUser) -> None:
create(db, recipient_id, NotificationKind.permission_granted,
f"You were given {role.value} on {node.name}", link="#/", actor=actor)
def _scan_mentions(db: DbSession, text: str, actor: AppUser, link: str, ctx: str) -> None:
handles = {m.lower() for m in _MENTION_RE.findall(text or "")}
if not handles:
return
for user in db.scalars(select(AppUser).where(AppUser.is_active.is_(True))).all():
local = user.email.split("@", 1)[0].lower()
if local in handles and user.id != actor.id:
create(db, user.id, NotificationKind.mention,
f"{actor.full_name} mentioned you", body=ctx, link=link, actor=actor)
def unread_count(db: DbSession, user_id: uuid.UUID) -> int:
return db.scalar(
select(func.count()).select_from(Notification).where(
Notification.recipient_id == user_id, Notification.read_at.is_(None)
)
) or 0
# ── notification reads/writes (owned by the service, not the router) ──
def list_for_user(db: DbSession, user_id: uuid.UUID, limit: int = 30) -> list[Notification]:
return list(db.scalars(
select(Notification).where(Notification.recipient_id == user_id)
.order_by(Notification.created_at.desc()).limit(limit)
).all())
def mark_all_read(db: DbSession, user_id: uuid.UUID) -> None:
db.execute(
update(Notification).where(Notification.recipient_id == user_id,
Notification.read_at.is_(None))
.values(read_at=dt.datetime.now(dt.timezone.utc))
)
def mark_read(db: DbSession, user_id: uuid.UUID, notification_id: uuid.UUID) -> None:
n = db.get(Notification, notification_id)
if n is not None and n.recipient_id == user_id and n.read_at is None:
n.read_at = dt.datetime.now(dt.timezone.utc)
def subscribe_push(db: DbSession, user_id: uuid.UUID, endpoint: str, p256dh: str, auth: str) -> None:
if db.scalar(select(PushSubscription).where(PushSubscription.endpoint == endpoint)) is None:
db.add(PushSubscription(user_id=user_id, endpoint=endpoint, p256dh=p256dh, auth=auth))
+300
View File
@@ -0,0 +1,300 @@
"""Permissive, in-process office-document support — OPTIONS.md option #2.
DOCX (python-docx, MIT) and ODT (odfdo, Apache-2.0) round-trip through the console's existing
Markdown editor: the document BODY is extracted to Markdown on open and the file is regenerated from
Markdown on save. This is deliberately **body-level and lossy** — headings, paragraphs, bold/italic,
bullet/number lists and (DOCX) simple tables survive; images, footnotes, comments, styles,
headers/footers and tracked changes are dropped on save. The UI therefore warns before editing and
always offers the lossless download→edit→re-upload handoff (option #1).
RTF (striprtf, BSD-3) is read-only here (no maintained permissive writer) and legacy DOC has no
permissive reader — both are handoff-only. Every dependency is permissive (passes `license_gate.py`);
if a library is somehow absent the format simply reports as not-editable and the console falls back to
the download card. Editing always funnels the regenerated bytes back through `changes.apply_change`.
"""
from __future__ import annotations
import io
import re
from ..errors import ValidationError
# Permissive deps, import-guarded so the backend still boots if they're not installed.
try: # DOCX
import docx # python-docx
from docx.oxml.ns import qn
from docx.table import Table as _DocxTable
from docx.text.paragraph import Paragraph as _DocxPara
_HAS_DOCX = True
except Exception: # noqa: BLE001
_HAS_DOCX = False
try: # ODT
from odfdo import Document as _Odf, Header as _OdfHeader, List as _OdfList, \
ListItem as _OdfItem, Paragraph as _OdfPara
_HAS_ODT = True
except Exception: # noqa: BLE001
_HAS_ODT = False
try: # RTF (read-only)
from striprtf.striprtf import rtf_to_text
_HAS_RTF = True
except Exception: # noqa: BLE001
_HAS_RTF = False
_FORMATS = {".docx": "docx", ".odt": "odt", ".rtf": "rtf", ".doc": "doc"}
def _ext(path: str) -> str:
return ("." + path.rsplit(".", 1)[-1].lower()) if "." in path else ""
def office_format(path: str) -> str | None:
"""'docx' | 'odt' | 'rtf' | 'doc' | None."""
return _FORMATS.get(_ext(path))
def is_office(path: str) -> bool:
return office_format(path) is not None
def is_editable(path: str) -> bool:
"""True only for formats we can both extract AND regenerate (round-trip) with permissive libs."""
fmt = office_format(path)
return (fmt == "docx" and _HAS_DOCX) or (fmt == "odt" and _HAS_ODT)
# ── Markdown subset (matches the Slate editor: # ## ###…, **bold**, *italic*, `code`, -/1. lists, > quote) ──
_INLINE = re.compile(r"(\*\*.+?\*\*|\*[^*\n]+?\*|`[^`\n]+?`)")
_HEADING = re.compile(r"^(#{1,6})\s+(.*)$")
_BULLET = re.compile(r"^[-*]\s+(.*)$")
_NUMBER = re.compile(r"^\d+\.\s+(.*)$")
_QUOTE = re.compile(r"^>\s?(.*)$")
_TABLE_ROW = re.compile(r"^\|(.+)\|\s*$")
_TABLE_SEP = re.compile(r"^\|[\s:\-|]+\|\s*$")
def _md_inline_to_runs(paragraph, text: str) -> None:
"""Split a line into python-docx runs honoring **bold**, *italic*, `code`."""
for tok in _INLINE.split(text):
if not tok:
continue
if tok.startswith("**") and tok.endswith("**") and len(tok) > 4:
paragraph.add_run(tok[2:-2]).bold = True
elif tok.startswith("*") and tok.endswith("*") and len(tok) > 2:
paragraph.add_run(tok[1:-1]).italic = True
elif tok.startswith("`") and tok.endswith("`") and len(tok) > 2:
paragraph.add_run(tok[1:-1]).font.name = "Consolas"
else:
paragraph.add_run(tok)
def _docx_runs_to_md(para) -> str:
out = []
for run in para.runs:
t = run.text
if not t:
continue
if run.bold and run.italic:
t = f"***{t}***"
elif run.bold:
t = f"**{t}**"
elif run.italic:
t = f"*{t}*"
out.append(t)
return "".join(out) if out else (para.text or "")
def _join_blocks(blocks: list[tuple[str, str]]) -> str:
"""Join (kind, text) blocks with blank lines, keeping consecutive same-type list items together."""
parts: list[str] = []
prev = None
for kind, text in blocks:
if parts:
same_list = kind in ("bullet", "number") and kind == prev
parts.append("\n" if same_list else "\n\n")
parts.append(text)
prev = kind
return ("".join(parts).strip() + "\n") if parts else ""
# ── DOCX ──────────────────────────────────────────────────────────────────────
def _docx_to_md(data: bytes) -> str:
doc = docx.Document(io.BytesIO(data))
blocks: list[tuple[str, str]] = []
for child in doc.element.body.iterchildren():
if child.tag == qn("w:p"):
para = _DocxPara(child, doc)
style = (para.style.name if para.style else "") or ""
text = _docx_runs_to_md(para).strip()
hm = re.match(r"Heading (\d)", style)
if hm:
lvl = min(int(hm.group(1)), 6)
blocks.append((f"h{lvl}", "#" * lvl + " " + text))
elif "List Bullet" in style:
blocks.append(("bullet", "- " + text))
elif "List Number" in style:
blocks.append(("number", "1. " + text))
elif "Quote" in style:
blocks.append(("quote", "> " + text))
elif text:
blocks.append(("para", text))
elif child.tag == qn("w:tbl"):
tbl = _DocxTable(child, doc)
rows = [[(c.text or "").replace("\n", " ").strip() for c in r.cells] for r in tbl.rows]
if rows:
lines = ["| " + " | ".join(rows[0]) + " |",
"| " + " | ".join(["---"] * len(rows[0])) + " |"]
lines += ["| " + " | ".join(r) + " |" for r in rows[1:]]
blocks.append(("table", "\n".join(lines)))
return _join_blocks(blocks)
def _md_to_docx(md: str) -> bytes:
doc = docx.Document()
styles = {s.name for s in doc.styles}
lines = (md or "").replace("\r\n", "\n").replace("\r", "\n").split("\n")
i = 0
while i < len(lines):
line = lines[i].rstrip()
# markdown table block → real docx table
if _TABLE_ROW.match(line):
rows = []
while i < len(lines) and _TABLE_ROW.match(lines[i].rstrip()):
if not _TABLE_SEP.match(lines[i].rstrip()):
rows.append([c.strip() for c in lines[i].strip().strip("|").split("|")])
i += 1
if rows:
cols = max(len(r) for r in rows)
tbl = doc.add_table(rows=len(rows), cols=cols)
try:
tbl.style = "Table Grid"
except Exception: # noqa: BLE001
pass
for r, cells in enumerate(rows):
for c in range(cols):
tbl.rows[r].cells[c].text = cells[c] if c < len(cells) else ""
continue
if not line.strip():
i += 1
continue
m = _HEADING.match(line)
if m:
doc.add_heading(m.group(2), level=min(len(m.group(1)), 9))
elif _BULLET.match(line):
_md_inline_to_runs(doc.add_paragraph(style="List Bullet"), _BULLET.match(line).group(1))
elif _NUMBER.match(line):
_md_inline_to_runs(doc.add_paragraph(style="List Number"), _NUMBER.match(line).group(1))
elif _QUOTE.match(line):
style = "Quote" if "Quote" in styles else None
_md_inline_to_runs(doc.add_paragraph(style=style), _QUOTE.match(line).group(1))
else:
_md_inline_to_runs(doc.add_paragraph(), line)
i += 1
buf = io.BytesIO()
doc.save(buf)
return buf.getvalue()
# ── ODT ───────────────────────────────────────────────────────────────────────
def _odt_to_md(data: bytes) -> str:
doc = _Odf(io.BytesIO(data))
blocks: list[tuple[str, str]] = []
for el in doc.body.children:
tag = el.tag
if tag == "text:h":
lvl_raw = el.get_attribute("text:outline-level") or 1
try:
lvl = min(int(lvl_raw), 6)
except (TypeError, ValueError):
lvl = 1
txt = (el.inner_text or "").strip()
blocks.append((f"h{lvl}", "#" * lvl + " " + txt))
elif tag == "text:p":
txt = (el.inner_text or "").strip()
if txt:
blocks.append(("para", txt))
elif tag == "text:list":
for li in el.get_elements("text:list-item"):
txt = (li.inner_text or "").strip()
if txt:
blocks.append(("bullet", "- " + txt))
return _join_blocks(blocks)
def _md_to_odt(md: str) -> bytes:
doc = _Odf("text")
body = doc.body
# odfdo seeds a default empty first paragraph + sequence-decls; drop the stray empty paragraph.
for el in list(body.children):
if el.tag == "text:p" and not (el.inner_text or "").strip():
body.delete(el)
pending_list = None
for raw in (md or "").replace("\r\n", "\n").replace("\r", "\n").split("\n"):
line = raw.rstrip()
bullet = _BULLET.match(line) or _NUMBER.match(line)
if bullet:
if pending_list is None:
pending_list = _OdfList()
body.append(pending_list)
pending_list.append(_OdfItem(_strip_inline(bullet.group(1))))
continue
pending_list = None
if not line.strip():
continue
m = _HEADING.match(line)
if m:
body.append(_OdfHeader(min(len(m.group(1)), 6), _strip_inline(m.group(2))))
elif _QUOTE.match(line):
body.append(_OdfPara(_strip_inline(_QUOTE.match(line).group(1))))
else:
body.append(_OdfPara(_strip_inline(line)))
buf = io.BytesIO()
doc.save(buf)
return buf.getvalue()
def _strip_inline(text: str) -> str:
"""ODT generation is plain-text body-level: drop inline markers (lossy, documented)."""
text = re.sub(r"\*\*(.+?)\*\*", r"\1", text)
text = re.sub(r"\*([^*\n]+?)\*", r"\1", text)
text = re.sub(r"`([^`\n]+?)`", r"\1", text)
return text
# ── public API ──────────────────────────────────────────────────────────────
def extract_markdown(path: str, data: bytes) -> str:
"""Office bytes → Markdown for the editor. Raises ValidationError if the format isn't editable."""
fmt = office_format(path)
try:
if fmt == "docx" and _HAS_DOCX:
return _docx_to_md(data)
if fmt == "odt" and _HAS_ODT:
return _odt_to_md(data)
except Exception as exc: # noqa: BLE001 (corrupt/unsupported doc → fall back to handoff)
raise ValidationError("This document couldn't be opened for editing — download it instead.") from exc
raise ValidationError("This document type can't be edited in the browser.")
def to_office_bytes(path: str, markdown: str) -> bytes:
"""Markdown (from the editor) → office bytes for saving. Raises if the format isn't writable."""
fmt = office_format(path)
if fmt == "docx" and _HAS_DOCX:
return _md_to_docx(markdown)
if fmt == "odt" and _HAS_ODT:
return _md_to_odt(markdown)
raise ValidationError("This document type can't be saved from the browser editor.")
def extract_text(path: str, data: bytes) -> str | None:
"""Best-effort plaintext for any office format (docx/odt/rtf) — e.g. for future content search.
Returns None if not extractable (legacy .doc, missing lib, or parse failure)."""
fmt = office_format(path)
try:
if fmt == "docx" and _HAS_DOCX:
return "\n".join(p.text for p in docx.Document(io.BytesIO(data)).paragraphs)
if fmt == "odt" and _HAS_ODT:
return _Odf(io.BytesIO(data)).body.inner_text
if fmt == "rtf" and _HAS_RTF:
return rtf_to_text(data.decode("latin-1", "ignore"))
except Exception: # noqa: BLE001
return None
return None
+103
View File
@@ -0,0 +1,103 @@
"""Optional frontend plugins: discover manifests under PLUGINS_DIR and expose them to the console.
Plugins are **frontend-only** (static JS/CSS assets + a `plugin.json` manifest); the backend never
imports or executes plugin code. This keeps Galena's core dependency tree permissive — e.g. the
GPL-licensed DjVu viewer ships as a plugin, not in core. See README 'Roadmap / extension points'.
"""
from __future__ import annotations
import json
import re
from dataclasses import dataclass
from pathlib import Path
from ..config import get_settings
settings = get_settings()
# Plugin names appear in the /plugins/<name>/ asset URL, so keep them to a safe slug.
_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
@dataclass(frozen=True)
class Plugin:
name: str
title: str
version: str
license: str
description: str
frontend_entry: str
frontend_dir: Path
def _load_one(folder: Path) -> Plugin | None:
manifest = folder / "plugin.json"
if not manifest.is_file():
return None
try:
data = json.loads(manifest.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
name = str(data.get("name", "")).strip().lower()
if not _NAME_RE.match(name):
return None
fe = data.get("frontend") or {}
entry = str(fe.get("entry", "")).strip()
fe_dir = folder / "frontend"
# The entry must be a plain filename inside frontend/ (no traversal) that actually exists.
if not entry or "/" in entry or "\\" in entry or not (fe_dir / entry).is_file():
return None
return Plugin(
name=name,
title=str(data.get("title") or name),
version=str(data.get("version") or "0.0.0"),
license=str(data.get("license") or "UNKNOWN"),
description=str(data.get("description") or ""),
frontend_entry=entry,
frontend_dir=fe_dir,
)
def discover() -> list[Plugin]:
"""Return ALL installed plugins (each folder under PLUGINS_DIR with a valid plugin.json),
regardless of enabled state. Defensive: a malformed manifest is skipped, never fatal. Empty
list when PLUGINS_DIR is unset/missing."""
root = settings.plugins_dir.strip()
if not root:
return []
base = Path(root)
if not base.is_dir():
return []
out: list[Plugin] = []
seen: set[str] = set()
for child in sorted(base.iterdir()):
if not child.is_dir():
continue
plugin = _load_one(child)
if plugin is None or plugin.name in seen:
continue
seen.add(plugin.name)
out.append(plugin)
return out
# ── enabled/disabled state (admin-toggleable, persisted as the `disabled_plugins` setting) ──
def disabled_names(db) -> set[str]:
from . import settings as settings_svc
raw = settings_svc.get(db, "disabled_plugins") or ""
return {n.strip() for n in raw.split(",") if n.strip()}
def enabled(db) -> list[Plugin]:
"""Installed plugins the admin has left enabled — what the console actually loads."""
off = disabled_names(db)
return [p for p in discover() if p.name not in off]
def set_enabled(db, name: str, on: bool, user_id=None) -> None:
from . import settings as settings_svc
off = disabled_names(db)
if on:
off.discard(name)
else:
off.add(name)
settings_svc.set_value(db, "disabled_plugins", ",".join(sorted(off)), user_id)
+79
View File
@@ -0,0 +1,79 @@
"""Search across the node tree (workspaces/groups/folders/projects) AND files inside projects —
matching both file NAMES and their text CONTENT — scoped to what the user may read.
Case-insensitive substring matching; content matching is budgeted (a bounded number of blobs, each
under a size cap, decoded as UTF-8 — binary/encrypted blobs are skipped). A Postgres FTS upgrade
(tsvector + GIN) for ranked, indexed search is noted in the README roadmap.
"""
from __future__ import annotations
from sqlalchemy import or_, select
from sqlalchemy.orm import Session as DbSession
from ..enums import NodeKind
from ..models import AppUser, Node
from . import authz, git_facade
_CONTENT_SCAN_BUDGET = 600 # max blobs read for content matching per query (latency guard)
_MAX_CONTENT_BYTES = 512 * 1024 # skip content match for blobs larger than this
def _snippet(text: str, ql: str) -> str:
i = text.lower().find(ql)
start = max(0, i - 30)
s = text[start:i + len(ql) + 40].replace("\n", " ").replace("\r", " ").strip()
return ("…" if start > 0 else "") + s
def search(db: DbSession, user: AppUser, q: str, limit: int = 30) -> list[dict]:
q = (q or "").strip()
if not q:
return []
like = f"%{q}%"
ql = q.lower()
hits: list[dict] = []
# 1) nodes (workspaces / groups / folders / projects)
for n in db.scalars(
select(Node).where(or_(Node.name.ilike(like), Node.path.ilike(like)))
.order_by(Node.name).limit(limit * 4)
).all():
if authz.effective_role(db, user, n) is None:
continue
hits.append({"type": "node", "id": str(n.id), "name": n.name,
"kind": n.kind.value, "path": n.path})
if len(hits) >= limit:
return hits
# 2) files inside readable projects — match the path/name (substring, anywhere) OR text content.
# One repo open + one tree walk per project; blob bytes are read only when the name didn't match.
budget = _CONTENT_SCAN_BUDGET
for p in db.scalars(select(Node).where(Node.kind == NodeKind.project)).all():
if len(hits) >= limit:
break
if authz.effective_role(db, user, p) is None:
continue
try:
for path, size, read in git_facade.scan_blobs(p.id):
name_match = ql in path.lower()
snippet = None
if not name_match and budget > 0 and 0 < size <= _MAX_CONTENT_BYTES:
budget -= 1
try:
text = read().decode("utf-8") # skips binary/encrypted (UnicodeError)
if ql in text.lower():
snippet = _snippet(text, ql)
except Exception: # noqa: BLE001
pass
if name_match or snippet:
folder = path.rsplit("/", 1)[0] if "/" in path else ""
hit = {"type": "file", "project_id": str(p.id), "project": p.name,
"path": path, "folder": folder, "name": path.rsplit("/", 1)[-1]}
if snippet:
hit["snippet"] = snippet
hits.append(hit)
if len(hits) >= limit:
break
except Exception: # noqa: BLE001
continue
return hits
+40
View File
@@ -0,0 +1,40 @@
"""Instance settings stored as auditable key/value rows (app_setting), incl. git defaults."""
from __future__ import annotations
import uuid
from sqlalchemy.orm import Session as DbSession
from ..enums import ReviewPolicy
from ..models import AppSetting
DEFAULTS = {
"default_review_policy": "open", # policy applied to newly-created projects
"git_author_name": "Galena", # commit identity shown on versions
"git_author_email": "galena@localhost",
}
def get(db: DbSession, key: str) -> str:
row = db.get(AppSetting, key)
return row.value if row else DEFAULTS.get(key, "")
def set_value(db: DbSession, key: str, value: str, user_id: uuid.UUID | None) -> None:
row = db.get(AppSetting, key)
if row is None:
db.add(AppSetting(key=key, value=value, updated_by=user_id))
else:
row.value = value
row.updated_by = user_id
def committer(db: DbSession) -> tuple[str, str]:
return get(db, "git_author_name"), get(db, "git_author_email")
def default_review_policy(db: DbSession) -> ReviewPolicy:
try:
return ReviewPolicy(get(db, "default_review_policy"))
except ValueError:
return ReviewPolicy.open
+165
View File
@@ -0,0 +1,165 @@
"""Dashboard statistics, tuned to the git workflow."""
from __future__ import annotations
import datetime as dt
import os
import uuid
from sqlalchemy import func, select
from sqlalchemy.orm import Session as DbSession
from ..config import get_settings
from ..enums import DraftStatus, NodeKind, NodeRole
from ..models import AppUser, AuditLog, Draft, Node, PermissionGrant
from ..storage import backend
from . import authz
settings = get_settings()
QUOTA_BYTES = 1024 ** 4 # 1 TB display quota
def _scan_project(project_id: uuid.UUID) -> tuple[int, dict]:
"""ONE os.walk per repo → (total_bytes_on_disk, {ext: count}). Size counts the whole repo
(incl. .git, as before); extension counts cover working-tree files only (skip .git)."""
repo = backend.repo_path(project_id)
total = 0
ext: dict = {}
if not repo.exists():
return total, ext
repo_str = str(repo)
for root, _dirs, files in os.walk(repo):
rel = os.path.relpath(root, repo_str)
in_git = rel == ".git" or rel.startswith(".git" + os.sep)
for f in files:
try:
total += os.path.getsize(os.path.join(root, f))
except OSError:
pass
if not in_git:
e = (os.path.splitext(f)[1] or "other").lstrip(".").lower() or "other"
ext[e] = ext.get(e, 0) + 1
return total, ext
def dashboard(db: DbSession, user: AppUser) -> dict:
workspaces = db.scalars(select(Node).where(Node.kind == NodeKind.workspace)).all()
projects = db.scalars(select(Node).where(Node.kind == NodeKind.project)).all()
active_users = db.scalar(
select(func.count()).select_from(AppUser).where(AppUser.is_active.is_(True))
) or 0
# ONE walk per repo → size + extension counts (was three walks per project).
scans = {p.id: _scan_project(p.id) for p in projects}
storage_used = sum(s[0] for s in scans.values())
# 14-day activity, bucketed by category.
today = dt.datetime.now(dt.timezone.utc).date()
days = [today - dt.timedelta(days=i) for i in range(13, -1, -1)]
buckets = {d.isoformat(): {"date": d.isoformat(), "redactions": 0, "drafts": 0, "publishes": 0}
for d in days}
since = dt.datetime.now(dt.timezone.utc) - dt.timedelta(days=14)
for row in db.scalars(select(AuditLog).where(AuditLog.created_at >= since)).all():
key = row.created_at.date().isoformat()
if key not in buckets:
continue
if row.action == "redaction":
buckets[key]["redactions"] += 1
elif row.action == "draft.publish":
buckets[key]["publishes"] += 1
elif (row.action or "").startswith("draft."):
buckets[key]["drafts"] += 1
activity = list(buckets.values())
# File types (top 6) + storage per workspace — both from the single scan above.
ext: dict = {}
ws_size: dict = {str(w.id): {"name": w.name, "bytes": 0} for w in workspaces}
for p in projects:
size, pext = scans[p.id]
for k, v in pext.items():
ext[k] = ext.get(k, 0) + v
ws = next((w for w in workspaces if p.path.startswith(w.path + "/") or p.path == w.path),
None)
if ws is not None:
ws_size[str(ws.id)]["bytes"] += size
file_types = sorted(
[{"ext": k, "count": v} for k, v in ext.items()], key=lambda x: -x["count"]
)[:6]
storage_by_workspace = sorted(ws_size.values(), key=lambda x: -x["bytes"])[:8]
# Per-request role memo so the same project/node isn't re-resolved across the loops below.
_rc: dict = {}
def _role(node):
if node.id not in _rc:
_rc[node.id] = authz.effective_role(db, user, node)
return _rc[node.id]
open_drafts = db.scalars(select(Draft).where(Draft.status == DraftStatus.open)).all()
recent_rows = db.scalars(
select(AuditLog).order_by(AuditLog.created_at.desc()).limit(300)
).all()
# Batch-load the nodes + users referenced by the approvals + recent loops (was per-row db.get).
node_ids = ({d.project_id for d in open_drafts}
| {r.entity_id for r in recent_rows if r.entity_id})
nodes_by_id = ({n.id: n for n in db.scalars(select(Node).where(Node.id.in_(node_ids))).all()}
if node_ids else {})
user_ids = ({d.author_id for d in open_drafts}
| {r.actor_id for r in recent_rows if r.actor_id})
users_by_id = ({u.id: u for u in db.scalars(select(AppUser).where(AppUser.id.in_(user_ids))).all()}
if user_ids else {})
# Approvals waiting for this user.
waiting = []
for d in open_drafts:
project = nodes_by_id.get(d.project_id)
if project is None or d.author_id == user.id:
continue
if NodeRole.rank(_role(project)) >= NodeRole.rank(NodeRole.approver):
author = users_by_id.get(d.author_id)
waiting.append({"draft_id": str(d.id), "title": d.title,
"project": project.name, "project_id": str(project.id),
"author": author.full_name if author else "—",
"created_at": d.created_at.isoformat()})
# Recent activity — the user's own actions + activity on nodes they can read (no global leak).
recent = []
for r in recent_rows:
if len(recent) >= 8:
break
if r.actor_id != user.id:
node = nodes_by_id.get(r.entity_id) if r.entity_id else None
if not (node is not None and _role(node) is not None):
continue
actor = users_by_id.get(r.actor_id) if r.actor_id else None
recent.append({"actor": actor.full_name if actor else "system", "action": r.action,
"detail": r.detail, "at": r.created_at.isoformat()})
open_drafts_count = len(open_drafts)
ws_overview = []
for w in workspaces:
members = db.scalars(
select(func.count(func.distinct(PermissionGrant.principal_id)))
.select_from(PermissionGrant)
.join(Node, Node.id == PermissionGrant.node_id)
.where((Node.path == w.path) | (Node.path.like(w.path + "/%")))
).one()
proj_count = sum(1 for p in projects if p.path.startswith(w.path + "/") or p.path == w.path)
ws_overview.append({"id": str(w.id), "name": w.name, "members": int(members or 0),
"projects": proj_count, "bytes": ws_size[str(w.id)]["bytes"]})
return {
"cards": {
"workspaces": len(workspaces),
"active_users": active_users,
"open_drafts": open_drafts_count,
"storage_used": storage_used,
"storage_quota": QUOTA_BYTES,
"projects": len(projects),
},
"activity": activity,
"file_types": file_types,
"storage_by_workspace": storage_by_workspace,
"approvals_waiting": waiting,
"recent": recent,
"workspaces": ws_overview,
}
+14
View File
@@ -0,0 +1,14 @@
"""Pluggable storage backends for project git repositories.
v1 ships LocalStorage (repos on the local filesystem). An S3Storage backend (object store for
large-blob/attachment offload + backups) is a documented extension point — implement the same
StorageBackend protocol and swap `backend`.
"""
from __future__ import annotations
from .base import StorageBackend
from .local import LocalStorage
backend: StorageBackend = LocalStorage()
__all__ = ["StorageBackend", "LocalStorage", "backend"]
+21
View File
@@ -0,0 +1,21 @@
"""Storage backend protocol — where a project's git repo lives + how it's removed."""
from __future__ import annotations
import uuid
from pathlib import Path
from typing import Protocol, runtime_checkable
@runtime_checkable
class StorageBackend(Protocol):
def ensure_root(self) -> None:
"""Create the storage root if missing."""
...
def repo_path(self, project_id: uuid.UUID) -> Path:
"""Absolute path to the project's git working directory."""
...
def remove_repo(self, project_id: uuid.UUID) -> None:
"""Delete the project's repo on disk (idempotent)."""
...
+23
View File
@@ -0,0 +1,23 @@
"""Local-filesystem storage: one git working directory per project under data/projects/."""
from __future__ import annotations
import shutil
import uuid
from pathlib import Path
from ..config import get_settings
settings = get_settings()
class LocalStorage:
def ensure_root(self) -> None:
settings.projects_dir.mkdir(parents=True, exist_ok=True)
def repo_path(self, project_id: uuid.UUID) -> Path:
return settings.projects_dir / str(project_id)
def remove_repo(self, project_id: uuid.UUID) -> None:
path = self.repo_path(project_id)
if path.exists():
shutil.rmtree(path, ignore_errors=True)
+20
View File
@@ -0,0 +1,20 @@
[project]
name = "galena-backend"
version = "0.1.0"
description = "Galena — a git-backed cloud drive (FastAPI backend)."
requires-python = ">=3.12"
license = { text = "Apache-2.0" }
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q"
filterwarnings = [
# GitPython's GitCmdObjectDB keeps a persistent `git cat-file` subprocess; on Windows its
# Popen.__del__ can poll an already-closed handle during GC (WinError 6). It's a harmless
# finalizer artifact, attributed nondeterministically to whichever test GC runs under.
"ignore:.*Exception ignored in.*Popen.*:pytest.PytestUnraisableExceptionWarning",
]
[tool.ruff]
line-length = 100
target-version = "py312"
+5
View File
@@ -0,0 +1,5 @@
-r requirements.txt
pytest==8.3.4
pytest-cov==6.0.0
httpx==0.28.1 # Starlette TestClient transport (integration tests)
pip-licenses==5.0.0 # CI license gate
+41
View File
@@ -0,0 +1,41 @@
# Web framework
fastapi==0.115.6
uvicorn[standard]==0.34.0
python-multipart==0.0.20 # multipart/form-data file uploads (Apache-2.0)
# Validation / settings
pydantic==2.10.4
pydantic-settings==2.7.1
# email validation is done in-app via a regex validator (schemas.Email) — no email-validator dependency
# DB / ORM / migrations
SQLAlchemy==2.0.50
alembic==1.14.0
pg8000==1.31.2 # pure-Python PostgreSQL driver, BSD-3-Clause (no LGPL, no libpq)
# Auth + encryption
argon2-cffi==23.1.0 # Argon2id password + passphrase KDF (MIT)
cryptography==44.0.0 # AES-256-GCM envelope encryption (Apache-2.0 / BSD)
# Git facade
GitPython==3.1.44 # BSD-3-Clause; wraps the system `git` binary
# Image thumbnails / EXIF
Pillow==11.1.0 # HPND (permissive)
# Office documents — in-app editing of DOCX/ODT via the Markdown editor (body-level, lossy round-trip;
# see OPTIONS.md option #2). All permissive. RTF is read-only (no maintained permissive writer) and
# legacy DOC is download-only (no permissive reader) — both fall back to the download→edit→re-upload
# handoff (option #1).
python-docx==1.1.2 # DOCX read + write (MIT)
odfdo==3.22.8 # ODT read + write (Apache-2.0); 3.22+ needed for lxml 5.x
striprtf==0.0.26 # RTF → text extraction, read-only (BSD-3-Clause)
# OpenTelemetry (OTLP → OTel Collector) — optional, import-guarded in observability.py
opentelemetry-sdk==1.42.1
opentelemetry-exporter-otlp-proto-grpc==1.42.1
opentelemetry-instrumentation-fastapi==0.63b1
opentelemetry-instrumentation-sqlalchemy==0.63b1
# Optional extras (NOT installed by default — keep the core dependency set copyleft-free):
# pywebpush — browser push delivery (MPL-2.0). Install only if you enable web push.
+39
View File
@@ -0,0 +1,39 @@
"""CI license gate: fail the build if any installed dependency is strong copyleft
(GPL / AGPL / SSPL). LGPL is allowed by policy; MPL/Apache/MIT/BSD/HPND/PSF are fine."""
from __future__ import annotations
import json
import subprocess
import sys
DENY = ("AGPL", "SSPL") # always denied
DENY_GPL_EXCEPT_LGPL = "GPL" # deny GPL but allow LGPL
def main() -> int:
out = subprocess.run(
[sys.executable, "-m", "piplicenses", "--format=json"],
capture_output=True, text=True,
)
if out.returncode != 0 or not out.stdout.strip():
# fall back to the console script name (module form may be unavailable)
out = subprocess.run(["pip-licenses", "--format=json"], capture_output=True, text=True)
pkgs = json.loads(out.stdout or "[]")
violations = []
for p in pkgs:
lic = (p.get("License") or "").upper()
if any(tok in lic for tok in DENY):
violations.append((p["Name"], p["License"]))
elif DENY_GPL_EXCEPT_LGPL in lic and "LGPL" not in lic:
violations.append((p["Name"], p["License"]))
if violations:
print("License gate FAILED — disallowed (strong copyleft) dependencies:")
for name, lic in violations:
print(f" - {name}: {lic}")
return 1
print(f"License gate OK — {len(pkgs)} packages, no GPL/AGPL/SSPL.")
return 0
if __name__ == "__main__":
sys.exit(main())
+8
View File
@@ -0,0 +1,8 @@
"""Point DATA_DIR at a throwaway temp dir before any app import, so git_facade tests never
touch a real data directory."""
from __future__ import annotations
import os
import tempfile
os.environ.setdefault("DATA_DIR", tempfile.mkdtemp(prefix="galena-test-"))
+42
View File
@@ -0,0 +1,42 @@
"""DB-free coverage of the encryption primitives + authz pure logic."""
from __future__ import annotations
import base64
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from app.enums import NodeRole
from app.security import derive_key
from app.services.authz import ancestor_paths
from app.services.crypto import new_master_key_b64
def test_aesgcm_envelope_roundtrip():
dek = AESGCM.generate_key(bit_length=256)
nonce = os.urandom(12)
ct = AESGCM(dek).encrypt(nonce, b"top secret contract", None)
assert ct != b"top secret contract"
assert AESGCM(dek).decrypt(nonce, ct, None) == b"top secret contract"
def test_passphrase_kdf_deterministic_and_sized():
salt = os.urandom(16)
assert derive_key("hunter2", salt) == derive_key("hunter2", salt)
assert derive_key("hunter2", salt) != derive_key("other", salt)
assert len(derive_key("hunter2", salt)) == 32
def test_master_key_is_32_bytes():
assert len(base64.b64decode(new_master_key_b64())) == 32
def test_ancestor_paths():
assert ancestor_paths("/acme/legal/contracts") == ["/acme", "/acme/legal", "/acme/legal/contracts"]
assert ancestor_paths("/acme") == ["/acme"]
def test_role_ordering():
assert (NodeRole.rank(NodeRole.manager) > NodeRole.rank(NodeRole.approver)
> NodeRole.rank(NodeRole.editor) > NodeRole.rank(NodeRole.viewer)
> NodeRole.rank(None))
+62
View File
@@ -0,0 +1,62 @@
"""Self-describing encrypted-blob envelope — proves re-encryption never orphans old versions.
The earlier design stored the data key in a single (project, path) row, so re-encrypting a file
overwrote the only key material and made every historical/branch ciphertext undecryptable. Blobs
are now self-describing, so each git ref decrypts from its own embedded header. No DB needed.
"""
from __future__ import annotations
import uuid
import pytest
from app.enums import EncryptionMode
from app.errors import ValidationError
from app.services import crypto
from app.services.crypto import new_master_key_b64
class _FakeDB:
"""Minimal stand-in for the upsert path in crypto.encrypt (no real DB)."""
def __init__(self):
self.row = None
def scalar(self, _stmt):
return self.row
def add(self, obj):
self.row = obj
def flush(self):
pass
def test_reencryption_keeps_old_versions_decryptable(monkeypatch):
monkeypatch.setattr(crypto.settings, "encryption_master_key", new_master_key_b64())
db, pid = _FakeDB(), uuid.uuid4()
v1 = crypto.encrypt(db, pid, "f.txt", b"version one", EncryptionMode.server)
v2 = crypto.encrypt(db, pid, "f.txt", b"version two", EncryptionMode.server) # overwrites row
assert v1 != v2 and crypto.is_encrypted_blob(v1) and crypto.is_encrypted_blob(v2)
# The bug: v1 became undecryptable after v2's row overwrite. Now both still decrypt.
assert crypto.decrypt(v1) == b"version one"
assert crypto.decrypt(v2) == b"version two"
def test_plaintext_passes_through_untouched():
assert crypto.decrypt(b"not encrypted at all") == b"not encrypted at all"
assert crypto.decrypt(b"") == b""
def test_passphrase_blob_is_zero_knowledge(monkeypatch):
monkeypatch.setattr(crypto.settings, "encryption_master_key", new_master_key_b64())
db, pid = _FakeDB(), uuid.uuid4()
blob = crypto.encrypt(db, pid, "s.txt", b"secret", EncryptionMode.passphrase,
passphrase="hunter2")
assert crypto.decrypt(blob, "hunter2") == b"secret"
with pytest.raises(ValidationError):
crypto.decrypt(blob) # no passphrase supplied
with pytest.raises(ValidationError):
crypto.decrypt(blob, "wrong") # wrong passphrase
+158
View File
@@ -0,0 +1,158 @@
"""GitPython facade round-trip — no database needed (uses a temp DATA_DIR + the system git)."""
from __future__ import annotations
import uuid
import pytest
from app.errors import ValidationError
from app.services import git_facade as g
@pytest.fixture
def project():
pid = uuid.uuid4()
g.init_project(pid)
return pid
def _commit(pid, path, text, branch="main", msg="edit"):
return g.commit_file(pid, path, text.encode(), branch=branch,
author_name="Tester", author_email="t@example.com", message=msg)
def test_commit_read_tree(project):
_commit(project, "docs/readme.md", "hello\nworld\n")
assert g.read_file(project, "docs/readme.md").decode() == "hello\nworld\n"
top = g.list_tree(project)
assert any(e["name"] == "docs" and e["type"] == "folder" for e in top)
inside = g.list_tree(project, "docs")
assert any(e["name"] == "readme.md" and e["type"] == "file" for e in inside)
def test_versions_and_log(project):
_commit(project, "a.txt", "one\n")
g.create_version(project, "version/feature")
_commit(project, "a.txt", "one\ntwo\n", branch="version/feature")
assert set(g.list_versions(project)) == {"main", "version/feature"}
assert len(g.log(project, "version/feature")) >= 2
def test_changes_two_window_and_merged(project):
_commit(project, "a.txt", "alpha\nbeta\n")
g.create_version(project, "v2")
_commit(project, "a.txt", "alpha\nGAMMA\nbeta\n", branch="v2")
ch = g.file_changes(project, "a.txt", "main", "v2")
assert ch["binary"] is False
assert ch["added"] == 1 and ch["removed"] == 0
assert any(r["op"] != "equal" for r in ch["rows"]) # two-window has a change row
assert any(r["op"] == "add" for r in ch["merged"]) # merged has an added line
def test_publish_merges(project):
_commit(project, "a.txt", "base\n")
g.create_version(project, "v3")
_commit(project, "b.txt", "new file\n", branch="v3")
res = g.publish(project, "v3", "main", author_name="T", author_email="t@e.com", message="publish")
assert res["ok"] is True
assert g.file_exists(project, "b.txt", "main")
def test_blame_and_clone(project):
_commit(project, "a.txt", "line1\nline2\n")
rows = g.blame(project, "a.txt")
assert len(rows) == 2 and rows[0]["author"] == "Tester"
dst = uuid.uuid4()
g.clone_project(project, dst)
assert g.read_file(dst, "a.txt").decode() == "line1\nline2\n"
def test_changed_files(project):
_commit(project, "a.txt", "x\n")
g.create_version(project, "v4")
_commit(project, "c.txt", "y\n", branch="v4")
assert "c.txt" in g.changed_files(project, "main", "v4")
@pytest.mark.parametrize("bad", [
"../escape.txt", # parent traversal
"a/b/../../../escape.txt", # traversal after descent
"/etc/passwd", # absolute (posix)
"C:/Windows/win.ini", # absolute (windows drive)
"..\\windows.txt", # backslash traversal
".git/hooks/post-commit", # writing into the repo's own .git → RCE
"a/.git/config", # nested .git
"", # empty
"foo\x00.txt", # NUL byte
])
def test_commit_rejects_unsafe_paths(project, bad):
with pytest.raises(ValidationError):
_commit(project, bad, "x")
def test_safe_path_normalizes_benign_paths():
assert g.safe_path("docs/./readme.md") == "docs/readme.md"
assert g.safe_path("a/b/../c.txt") == "a/c.txt"
assert g.safe_path("plain.txt") == "plain.txt"
def test_move_rejects_unsafe_destination(project):
_commit(project, "ok.txt", "data\n")
with pytest.raises(ValidationError):
g.move_file(project, "ok.txt", "../../escape.txt", branch="main",
author_name="T", author_email="t@e.com", message="m")
# ── read-repo cache + write invalidation (the fast-read path) ───────────────────
def test_read_repo_is_cached_then_invalidated_by_a_write(project):
_commit(project, "a.txt", "v1\n") # commit_file ends with _invalidate_read
r1 = g._read_repo(project)
r2 = g._read_repo(project)
assert r1 is r2 # same cached instance — no re-open between reads
assert project in g._read_repos
_commit(project, "a.txt", "v2\n") # any write drops the cached read repo
assert project not in g._read_repos
assert g._read_repo(project) is not r1 # reopened fresh after the write
def test_read_reflects_latest_redaction(project):
"""A read after a write must never serve the pre-write snapshot (cache invalidation works)."""
_commit(project, "a.txt", "first\n")
assert g.read_file(project, "a.txt").decode() == "first\n" # populates the read cache
_commit(project, "a.txt", "second\n") # invalidates it
assert g.read_file(project, "a.txt").decode() == "second\n" # fresh, not stale
def test_create_version_and_publish_invalidate_reads(project):
_commit(project, "a.txt", "base\n")
g.list_versions(project) # cache the read repo
g.create_version(project, "v9") # new ref → must invalidate
assert "v9" in g.list_versions(project)
_commit(project, "only.txt", "x\n", branch="v9")
g.read_file(project, "a.txt") # re-cache
g.publish(project, "v9", "main", author_name="T", author_email="t@e.com", message="pub")
assert g.file_exists(project, "only.txt", "main") # publish reflected without a stale read
def test_remove_project_drops_read_cache(project):
_commit(project, "a.txt", "x\n")
g._read_repo(project)
assert project in g._read_repos
g.remove_project(project)
assert project not in g._read_repos
def test_scan_blobs_yields_paths_sizes_and_lazy_content(project):
_commit(project, "x.md", "hello world\n")
_commit(project, "docs/y.txt", "second file\n")
found = {path: (size, read) for path, size, read in g.scan_blobs(project)}
assert {"x.md", "docs/y.txt"} <= set(found)
size, read = found["x.md"]
assert size == len(b"hello world\n")
assert read().decode() == "hello world\n" # read() lazily returns the blob bytes
def test_scan_blobs_respects_limit(project):
for i in range(5):
_commit(project, f"f{i}.txt", f"{i}\n")
assert len(list(g.scan_blobs(project, limit=3))) == 3
+168
View File
@@ -0,0 +1,168 @@
"""Full API loop against a real Postgres. Auto-skips unless GALENA_RUN_INTEGRATION=1 with a
migrated + seeded database reachable via DATABASE_URL (CI sets this up)."""
from __future__ import annotations
import os
import uuid
import pytest
RUN = os.environ.get("GALENA_RUN_INTEGRATION") == "1"
pytestmark = pytest.mark.skipif(
not RUN, reason="set GALENA_RUN_INTEGRATION=1 with a migrated + seeded Postgres")
if RUN:
from fastapi.testclient import TestClient
from app.config import get_settings
from app.main import app
settings = get_settings()
def _client():
return TestClient(app)
def _login(c, email, password):
r = c.post("/api/v1/auth/login", json={"email": email, "password": password})
assert r.status_code == 200, r.text
return r.json()
def test_core_loop_and_permissions():
admin = _client()
_login(admin, settings.bootstrap_admin_email, settings.bootstrap_admin_password)
# Build a workspace → project, save a file (a redaction on the main version), read it back.
ws = admin.post("/api/v1/nodes", json={"parent_id": None, "kind": "workspace",
"name": f"WS {uuid.uuid4().hex[:6]}"}).json()
proj = admin.post("/api/v1/nodes", json={"parent_id": ws["id"], "kind": "project",
"name": "Proj"}).json()
w = admin.post(f"/api/v1/projects/{proj['id']}/file",
json={"path": "a.md", "content": "# Hello\n", "message": "add"})
assert w.status_code == 200 and w.json()["mode"] == "published"
f = admin.get(f"/api/v1/projects/{proj['id']}/file?path=a.md").json()
assert "Hello" in f["content"]
assert len(admin.get(f"/api/v1/projects/{proj['id']}/history").json()) >= 1
# interactive graph: commits + version tips, and per-redaction changed files
graph = admin.get(f"/api/v1/projects/{proj['id']}/graph").json()
assert graph["commits"] and "main" in graph["versions"]
assert "a.md" in admin.get(f"/api/v1/projects/{proj['id']}/changed?b=main").json()
# A viewer can read the workspace but cannot write to the project.
email = f"viewer-{uuid.uuid4().hex[:6]}@example.com"
admin.post("/api/v1/users", json={"email": email, "full_name": "Vee",
"password": "viewerpass1", "is_admin": False})
users = admin.get("/api/v1/users").json()
vid = next(u["id"] for u in users if u["email"] == email)
admin.post(f"/api/v1/nodes/{ws['id']}/permissions", json={"user_id": vid, "role": "viewer"})
viewer = _client()
_login(viewer, email, "viewerpass1")
assert viewer.get(f"/api/v1/nodes/{proj['id']}").status_code == 200 # inherited read
denied = viewer.post(f"/api/v1/projects/{proj['id']}/file",
json={"path": "a.md", "content": "nope", "message": "x"})
assert denied.status_code == 403 # no write
def test_needs_approval_draft_and_publish():
admin = _client()
_login(admin, settings.bootstrap_admin_email, settings.bootstrap_admin_password)
ws = admin.post("/api/v1/nodes", json={"parent_id": None, "kind": "workspace",
"name": f"WS {uuid.uuid4().hex[:6]}"}).json()
proj = admin.post("/api/v1/nodes", json={"parent_id": ws["id"], "kind": "project",
"name": "Reviewed"}).json()
admin.post(f"/api/v1/projects/{proj['id']}/file",
json={"path": "x.md", "content": "base\n", "message": "base"})
admin.put(f"/api/v1/nodes/{proj['id']}/policy", json={"review_policy": "review_required"})
# An edit now lands on a working version, not main.
r = admin.post(f"/api/v1/projects/{proj['id']}/file",
json={"path": "x.md", "content": "base\nmore\n", "message": "edit"})
assert r.json()["mode"] == "working"
draft = admin.post(f"/api/v1/projects/{proj['id']}/submit-draft",
json={"title": "My change"}).json()
# review chat: post a message, then the draft detail shows it + the changed file
assert admin.post(f"/api/v1/drafts/{draft['id']}/messages",
json={"body": "please review"}).status_code == 200
detail = admin.get(f"/api/v1/drafts/{draft['id']}").json()
assert any(m["body"] == "please review" for m in detail["messages"])
assert "x.md" in detail["files"]
assert detail["can_post"] is True and detail["is_author"] is True # author can comment
# an inline comment anchored to a file → a thread root
fc = admin.post(f"/api/v1/drafts/{draft['id']}/messages",
json={"body": "fix this line", "file_path": "x.md"})
assert fc.status_code == 200 and fc.json()["file_path"] == "x.md"
root = fc.json()
# reply threads under the root and inherits its file anchor
rep = admin.post(f"/api/v1/drafts/{draft['id']}/messages",
json={"body": "done", "parent_id": root["id"]}).json()
assert rep["parent_id"] == root["id"] and rep["file_path"] == "x.md"
# close (resolve) then reopen the thread
assert admin.post(f"/api/v1/drafts/{draft['id']}/messages/{root['id']}/resolve",
json={"resolved": True}).json()["resolved"] is True
assert admin.post(f"/api/v1/drafts/{draft['id']}/messages/{root['id']}/resolve",
json={"resolved": False}).json()["resolved"] is False
# The author cannot approve their own draft — a different approver must publish it.
assert admin.post(f"/api/v1/drafts/{draft['id']}/publish").status_code == 409
reviewer = _client()
rid = f"appr-{uuid.uuid4().hex[:6]}@example.com"
admin.post("/api/v1/users", json={"email": rid, "full_name": "Approver",
"password": "approverpass1", "is_admin": True})
_login(reviewer, rid, "approverpass1")
pub = reviewer.post(f"/api/v1/drafts/{draft['id']}/publish").json()
assert pub["ok"] is True
main = admin.get(f"/api/v1/projects/{proj['id']}/file?path=x.md&ref=main").json()
assert "more" in main["content"]
def test_combine_versions_and_file_ops():
"""Combine versions (branch→branch merge) + file copy/rename via the API."""
admin = _client()
_login(admin, settings.bootstrap_admin_email, settings.bootstrap_admin_password)
ws = admin.post("/api/v1/nodes", json={"parent_id": None, "kind": "workspace",
"name": f"WS {uuid.uuid4().hex[:6]}"}).json()
proj = admin.post("/api/v1/nodes", json={"parent_id": ws["id"], "kind": "project",
"name": "Combine"}).json()
pid = proj["id"]
admin.post(f"/api/v1/projects/{pid}/file", json={"path": "a.md", "content": "one\n", "message": "base"})
admin.post(f"/api/v1/projects/{pid}/versions?name=feature&from_ref=main")
# copy + rename a file
assert admin.post(f"/api/v1/projects/{pid}/copy-file",
json={"src": "a.md", "dst": "b.md", "message": "copy"}).json()["path"] == "b.md"
assert admin.post(f"/api/v1/projects/{pid}/move-file",
json={"src": "b.md", "dst": "c.md", "message": "rename"}).json()["ok"] is True
# combine the feature version into main (clean merge)
r = admin.post(f"/api/v1/projects/{pid}/combine", json={"source": "feature", "target": "main"})
assert r.json()["ok"] is True
# content search finds the body text, not just the name
hits = admin.get("/api/v1/search?q=one").json()["hits"]
assert any(h.get("type") == "file" and h.get("snippet") for h in hits)
def test_console_endpoints_smoke():
"""The endpoints the console hits right after login — guards against post-login walls."""
c = _client()
_login(c, settings.bootstrap_admin_email, settings.bootstrap_admin_password)
home = c.get("/api/v1/drive/home").json()
assert "personal_id" in home and isinstance(home["workspaces"], list)
dash = c.get("/api/v1/dashboard").json()
assert "cards" in dash and len(dash["activity"]) == 14
assert "unread" in c.get("/api/v1/notifications").json()
assert isinstance(c.get("/api/v1/search?q=Acme").json()["hits"], list)
assert "inapp" in c.get("/api/v1/notifications/prefs").json()
assert isinstance(c.get("/api/v1/plugins").json(), list) # console plugin list (enabled only)
def test_admin_plugin_enable_disable():
"""Admin can toggle an installed plugin; disabled plugins drop out of the console list."""
admin = _client()
_login(admin, settings.bootstrap_admin_email, settings.bootstrap_admin_password)
listing = admin.get("/api/v1/admin/plugins").json()
names = [p["name"] for p in listing["plugins"]]
if "djvu-viewer" not in names:
import pytest as _pytest
_pytest.skip("djvu-viewer plugin not installed (set PLUGINS_DIR)")
admin.put("/api/v1/admin/plugins/djvu-viewer", json={"enabled": False})
assert "djvu-viewer" not in [p["name"] for p in admin.get("/api/v1/plugins").json()]
admin.put("/api/v1/admin/plugins/djvu-viewer", json={"enabled": True})
assert "djvu-viewer" in [p["name"] for p in admin.get("/api/v1/plugins").json()]
+71
View File
@@ -0,0 +1,71 @@
"""Office round-trip (OPTIONS.md option #2) — DB-free. DOCX (python-docx) and ODT (odfdo) extract to
Markdown and regenerate; RTF/DOC are handoff-only. All deps permissive."""
from __future__ import annotations
import pytest
from app.errors import ValidationError
from app.services import office
MD = (
"# Title\n\n"
"A paragraph with **bold** and *italic* text.\n\n"
"- first bullet\n"
"- second bullet\n\n"
"## Subheading\n\n"
"Another paragraph.\n"
)
def test_format_detection_and_editability():
assert office.office_format("a.docx") == "docx"
assert office.office_format("a.odt") == "odt"
assert office.office_format("a.rtf") == "rtf"
assert office.office_format("a.doc") == "doc"
assert office.office_format("a.md") is None
assert office.is_office("x.docx") and office.is_office("x.rtf") and office.is_office("x.doc")
# round-trippable
assert office.is_editable("x.docx") is True
assert office.is_editable("x.odt") is True
# read-only / no permissive reader → handoff, never "editable"
assert office.is_editable("x.rtf") is False
assert office.is_editable("x.doc") is False
assert office.is_editable("x.md") is False
@pytest.mark.parametrize("path", ["doc.docx", "doc.odt"])
def test_markdown_round_trip(path):
data = office.to_office_bytes(path, MD)
assert isinstance(data, bytes) and len(data) > 0
back = office.extract_markdown(path, data)
# block structure survives for both formats
assert "# Title" in back
assert "## Subheading" in back
assert "- first bullet" in back and "- second bullet" in back
assert "Another paragraph." in back
def test_docx_preserves_inline_and_table():
md = "# H\n\nplain **b** and *i*\n\n| A | B |\n| --- | --- |\n| 1 | 2 |\n"
back = office.extract_markdown("t.docx", office.to_office_bytes("t.docx", md))
assert "**b**" in back and "*i*" in back # DOCX keeps inline marks
assert "| A | B |" in back and "| 1 | 2 |" in back # and rebuilds the table
def test_non_editable_formats_reject_save_and_open():
for path in ("x.rtf", "x.doc"):
with pytest.raises(ValidationError):
office.to_office_bytes(path, "hi")
with pytest.raises(ValidationError):
office.extract_markdown(path, b"whatever")
def test_rtf_text_extraction_read_only():
rtf = rb"{\rtf1\ansi hello \b world\b0 .}"
text = office.extract_text("note.rtf", rtf)
assert text is not None and "hello" in text and "world" in text
def test_extract_markdown_handles_corrupt_docx_gracefully():
with pytest.raises(ValidationError):
office.extract_markdown("broken.docx", b"not a real zip")
+42
View File
@@ -0,0 +1,42 @@
"""DB-free coverage of frontend-plugin discovery (services/plugins.py)."""
from __future__ import annotations
import json
from app.services import plugins
def _make(root, folder, manifest, *, entry_name="entry.js", write_entry=True):
d = root / folder
(d / "frontend").mkdir(parents=True)
(d / "plugin.json").write_text(json.dumps(manifest), encoding="utf-8")
if write_entry:
(d / "frontend" / entry_name).write_text("// entry", encoding="utf-8")
return d
def test_discovers_valid_and_skips_invalid(tmp_path, monkeypatch):
root = tmp_path / "plugins"
root.mkdir()
_make(root, "GoodPlugin", {"name": "good", "license": "MIT",
"frontend": {"entry": "entry.js"}})
_make(root, "NoName", {"frontend": {"entry": "entry.js"}}) # missing name → skip
_make(root, "BadName", {"name": "Bad Name!", "frontend": {"entry": "entry.js"}}) # bad slug
_make(root, "Missing", {"name": "missing", "frontend": {"entry": "nope.js"}},
write_entry=False) # entry file absent → skip
_make(root, "Traversal", {"name": "trav", "frontend": {"entry": "../x.js"}}) # traversal → skip
(root / "loose-file.txt").write_text("not a plugin", encoding="utf-8")
monkeypatch.setattr(plugins.settings, "plugins_dir", str(root))
found = plugins.discover()
assert [p.name for p in found] == ["good"]
assert found[0].license == "MIT"
assert found[0].frontend_entry == "entry.js"
assert found[0].frontend_dir.is_dir()
def test_empty_when_unset_or_missing(tmp_path, monkeypatch):
monkeypatch.setattr(plugins.settings, "plugins_dir", "")
assert plugins.discover() == []
monkeypatch.setattr(plugins.settings, "plugins_dir", str(tmp_path / "does-not-exist"))
assert plugins.discover() == []
+32
View File
@@ -0,0 +1,32 @@
"""Search snippet helper — pure, no database. The actual scoped search() is exercised by the
integration suite; here we cover the substring-context builder that powers content-match previews
(matches anywhere in the text: start, middle, or end)."""
from __future__ import annotations
from app.services.search import _snippet
def test_snippet_includes_the_match_and_surrounding_context():
text = "lorem ipsum dolor sit amet consectetur adipiscing elit"
snip = _snippet(text, "consectetur") # match in the middle
assert "consectetur" in snip
def test_snippet_is_case_insensitive_and_matches_at_the_end():
text = ("padding " * 12) + "TARGET" # match near the end of a long line
snip = _snippet(text, "target") # query is lower-case; find() lowercases the text
assert "TARGET" in snip
def test_snippet_left_truncates_a_deep_match_with_an_ellipsis():
text = ("padding " * 10) + "needle tail"
snip = _snippet(text, "needle")
assert snip.startswith("…") # leading … when the match is far into the line
assert "needle" in snip
def test_snippet_collapses_newlines_to_spaces():
text = "first line\nsecond needle line\nthird line"
snip = _snippet(text, "needle")
assert "\n" not in snip and "\r" not in snip
assert "needle" in snip
+24
View File
@@ -0,0 +1,24 @@
#!/bin/bash
# Runs once on first Postgres start (as the superuser). Creates the least-privilege roles:
# migrator — owns DDL (Alembic migrations)
# app — runtime, DML only (+ append-only audit, enforced by the migration's grants)
# Passwords come from the compose environment.
set -e
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
DO \$\$
BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'migrator') THEN
CREATE ROLE migrator LOGIN PASSWORD '${DB_MIGRATOR_PASSWORD}';
END IF;
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'app') THEN
CREATE ROLE app LOGIN PASSWORD '${DB_APP_PASSWORD}';
END IF;
END
\$\$;
GRANT CONNECT ON DATABASE ${POSTGRES_DB} TO migrator, app;
-- migrator owns the schema (so create_all in the migration succeeds + objects are owned by it).
ALTER SCHEMA public OWNER TO migrator;
GRANT USAGE ON SCHEMA public TO app;
EOSQL
+68
View File
@@ -0,0 +1,68 @@
# Galena stack: postgres → migrate (+seed) → backend → caddy.
# Only Caddy is published to the host; postgres + backend are expose-only.
services:
postgres:
image: postgres:16
environment:
POSTGRES_DB: ${POSTGRES_DB:-galena}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-change_me_super}
DB_APP_PASSWORD: ${DB_APP_PASSWORD:-change_me_app}
DB_MIGRATOR_PASSWORD: ${DB_MIGRATOR_PASSWORD:-change_me_migrator}
volumes:
- pgdata:/var/lib/postgresql/data
- ./db/init:/docker-entrypoint-initdb.d:ro
expose: ["5432"]
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d ${POSTGRES_DB:-galena}"]
interval: 5s
timeout: 5s
retries: 20
migrate:
build: ./backend
image: galena-backend:local
env_file: .env
command: sh -c "alembic upgrade head && python -m app.seed"
restart: "no"
volumes:
- galena-data:/data
depends_on:
postgres:
condition: service_healthy
backend:
build: ./backend
image: galena-backend:local
env_file: .env
expose: ["8000"]
volumes:
- galena-data:/data
# Optional frontend plugins (e.g. the GPL DjVu Viewer). Mount a host folder of plugins and set
# PLUGINS_DIR=/plugins in .env. Read-only — the backend only serves their static assets.
# - ./plugins:/plugins:ro
depends_on:
migrate:
condition: service_completed_successfully
caddy:
image: caddy:2
depends_on:
backend:
condition: service_healthy
environment:
CADDY_SITE_ADDRESS: ${CADDY_SITE_ADDRESS:-:80}
ports:
- "80:80"
- "443:443"
- "443:443/udp"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- ./frontend:/srv:ro
- caddy_data:/data
- caddy_config:/config
volumes:
pgdata:
galena-data:
caddy_data:
caddy_config:
Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

+269
View File
@@ -0,0 +1,269 @@
/* Galena console design system — adapted from the Counsel Scorecard tokens (Open Color neutrals,
light/dark). Primary accent is monochrome (near-black light / near-white dark); Open Color
violet appears only on the brand mark. No build step. */
:root{
--bg-app:#ffffff; --bg-canvas:#f8f9fa; --surface:#ffffff; --surface-muted:#f1f3f5; --surface-muted-2:#dee2e6;
--surface-subtle:#f8f9fa; --surface-chip:#f1f3f5; --row-hover:#f8f9fa;
--border:#dee2e6; --border-input:#dee2e6; --border-hover:#adb5bd;
--text-primary:#212529; --text-heading:#000000; --text-secondary:#343a40; --text-muted:#868e96; --text-faint:#adb5bd;
--primary:#000000; --primary-hover:#000000; --primary-fg:#ffffff;
--secondary-bg:#f1f3f5; --secondary-fg:#212529; --secondary-hover:#dee2e6;
--accent:#4263eb; --brand:#5f3dc4;
--info-bg:#edf2ff; --info-border:#bac8ff; --info-text:#364fc7; --info-icon:#4263eb;
--warn-bg:#fff9db; --warn-border:#ffec99; --warn-text:#e8590c;
--ok-bg:#ebfbee; --ok-border:#b2f2bb; --ok-text:#2b8a3e;
--danger-bg:#fff5f5; --danger-border:#ffc9c9; --danger:#e03131;
--add-bg:#ebfbee; --add-text:#2b8a3e; --del-bg:#fff5f5; --del-text:#c92a2a;
--font-sans:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Inter",Arial,sans-serif;
--font-mono:ui-monospace,"SFMono-Regular",Menlo,Consolas,monospace;
--shadow-card:0 1px 2px rgba(0,0,0,.04); --shadow-menu:0 4px 12px rgba(0,0,0,.10),0 1px 2px rgba(0,0,0,.04);
--shadow-dialog:0 16px 48px rgba(0,0,0,.18);
--sidebar-w:248px; --topbar-h:60px; --radius:10px;
}
[data-theme="dark"]{
--bg-app:#000; --bg-canvas:#000; --surface:#212529; --surface-muted:#343a40; --surface-muted-2:#495057;
--surface-subtle:#212529; --surface-chip:#343a40; --row-hover:#343a40;
--border:rgba(255,255,255,.10); --border-input:rgba(255,255,255,.15); --border-hover:rgba(255,255,255,.30);
--text-primary:#f8f9fa; --text-heading:#f8f9fa; --text-secondary:#ced4da; --text-muted:#adb5bd; --text-faint:#868e96;
--primary:#ffffff; --primary-hover:#ffffff; --primary-fg:#000000;
--secondary-bg:#343a40; --secondary-fg:#dee2e6; --secondary-hover:#495057;
--accent:#748ffc; --brand:#9775fa;
--info-bg:rgba(76,110,245,.15); --info-border:#364fc7; --info-text:#91a7ff; --info-icon:#5c7cfa;
--warn-bg:rgba(250,176,5,.15); --warn-border:#d9480f; --warn-text:#ffd43b;
--ok-bg:rgba(64,192,87,.15); --ok-border:#2b8a3e; --ok-text:#8ce99a;
--danger-bg:rgba(240,62,62,.14); --danger-border:rgba(240,62,62,.4); --danger:#ff8787;
--add-bg:rgba(64,192,87,.15); --add-text:#8ce99a; --del-bg:rgba(240,62,62,.14); --del-text:#ffa8a8;
--shadow-card:0 1px 2px rgba(0,0,0,.4); --shadow-menu:0 6px 16px rgba(0,0,0,.5); --shadow-dialog:0 18px 50px rgba(0,0,0,.6);
color-scheme:dark;
}
*{box-sizing:border-box;} html,body{margin:0;}
html{font-family:var(--font-sans);font-size:14px;line-height:1.5;color:var(--text-primary);background:var(--bg-app);-webkit-font-smoothing:antialiased;}
a{color:var(--primary);text-decoration:none;} a:hover{text-decoration:underline;}
.hidden{display:none!important;} .muted{color:var(--text-muted);} .faint{color:var(--text-faint);} .mono{font-family:var(--font-mono);}
/* buttons */
.btn{display:inline-flex;align-items:center;gap:8px;height:36px;padding:0 14px;border-radius:8px;border:1px solid transparent;font:500 14px/1 var(--font-sans);cursor:pointer;white-space:nowrap;background:transparent;color:var(--text-secondary);transition:background .12s,border-color .12s;}
.btn svg{width:16px;height:16px;flex:none;}
.btn.primary{background:var(--primary);color:var(--primary-fg);font-weight:600;} .btn.primary:hover{background:var(--primary-hover);}
.btn.ghost{border-color:var(--border);background:var(--surface);color:var(--text-secondary);} .btn.ghost:hover{background:var(--surface-muted);border-color:var(--border-hover);}
.btn.danger{border-color:var(--danger-border);color:var(--danger);background:var(--surface);} .btn.danger:hover{background:var(--danger-bg);}
.btn.sm{height:30px;padding:0 10px;font-size:13px;} .btn:disabled{opacity:.5;cursor:not-allowed;}
.btn.ghost.on{color:var(--text-primary);border-color:var(--border-hover);} /* e.g. an active favourite (filled star) */
.iconbtn{display:inline-flex;width:34px;height:34px;align-items:center;justify-content:center;border-radius:8px;color:var(--text-secondary);cursor:pointer;border:1px solid transparent;background:transparent;position:relative;}
.iconbtn:hover{background:var(--surface-muted);} .iconbtn svg{width:18px;height:18px;}
.iconbtn.txt{width:auto;padding:0 10px;font-weight:600;font-size:12px;}
/* inputs */
label.field{display:flex;flex-direction:column;gap:6px;font:600 13px/1.3 var(--font-sans);color:var(--text-primary);}
input,select,textarea{font:400 14px/1.4 var(--font-sans);color:var(--text-primary);background:var(--surface);border:1px solid var(--border-input);border-radius:8px;padding:8px 12px;height:36px;width:100%;}
textarea{height:auto;min-height:80px;resize:vertical;}
input:focus,select:focus,textarea:focus{outline:none;border-color:var(--border-hover);box-shadow:0 0 0 2px rgba(120,120,120,.25);}
.checkbox{display:inline-flex;align-items:center;gap:8px;font-size:14px;color:var(--text-secondary);cursor:pointer;}
.checkbox input{width:16px;height:16px;accent-color:var(--primary);}
/* chips / badges */
.chip{display:inline-flex;align-items:center;gap:5px;padding:2px 8px;border-radius:999px;background:var(--surface-chip);border:1px solid var(--border);font-size:11.5px;color:var(--text-secondary);}
.chip.ok{background:var(--ok-bg);border-color:var(--ok-border);color:var(--ok-text);}
.chip.warn{background:var(--warn-bg);border-color:var(--warn-border);color:var(--warn-text);}
.chip.info{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text);}
.avatar{width:28px;height:28px;border-radius:50%;background:var(--info-bg);color:var(--info-text);display:inline-flex;align-items:center;justify-content:center;font-size:11px;font-weight:600;flex:none;}
/* shell */
#app{display:flex;min-height:100vh;}
.sidebar{flex:0 0 var(--sidebar-w);position:sticky;top:0;height:100vh;overflow-y:auto;background:var(--surface);border-right:1px solid var(--border);display:flex;flex-direction:column;}
.brand{display:flex;align-items:center;gap:10px;padding:14px 16px;}
.brand .logo{width:30px;height:30px;flex:none;} .brand .nm{font:700 18px/1 var(--font-sans);color:var(--text-heading);}
.nav{padding:6px 10px;flex:1;}
.nav-item{display:flex;align-items:center;gap:10px;padding:8px 9px;border-radius:8px;font-size:13.5px;color:var(--text-secondary);cursor:pointer;margin:1px 0;border-left:2px solid transparent;}
.nav-item svg{width:17px;height:17px;flex:none;color:var(--text-muted);}
.nav-item:hover{background:var(--surface-muted);}
.nav-item.active{background:var(--surface-muted);color:var(--text-primary);font-weight:500;border-left:2px solid var(--primary);border-radius:0 8px 8px 0;}
.nav-item.active svg{color:var(--text-primary);}
/* sidebar twisty: click to expand any container at any depth; leaf nodes (projects) use an invisible spacer to keep icons aligned */
.tw{display:inline-flex;align-items:center;justify-content:center;width:18px;flex:none;border-radius:4px;cursor:pointer;color:var(--text-faint);}
.nav-item .tw svg{width:15px;height:15px;color:inherit;}
.tw:hover{background:var(--surface-muted);color:var(--text-secondary);}
.tw.empty{visibility:hidden;cursor:default;}
.nav-head{font:600 10.5px/1 var(--font-sans);letter-spacing:.06em;color:var(--text-faint);padding:12px 10px 4px;}
.storage{margin:8px 12px;padding:10px 12px;border:1px solid var(--border);border-radius:8px;}
.storage .bar{height:5px;border-radius:3px;background:var(--surface-muted-2);overflow:hidden;margin:5px 0;}
.storage .bar > i{display:block;height:100%;background:var(--primary);}
.main{flex:1;min-width:0;display:flex;flex-direction:column;}
.topbar{min-height:var(--topbar-h);flex:none;display:flex;align-items:center;gap:6px;padding:8px 14px;border-bottom:1px solid var(--border);background:var(--surface);position:sticky;top:0;z-index:30;}
.crumb{display:flex;align-items:center;flex-wrap:wrap;gap:4px 6px;min-width:0;font-size:14px;color:var(--text-muted);}
.crumb b{color:var(--text-primary);font-weight:500;} .crumb .sep{color:var(--text-faint);} .crumb a{color:var(--text-muted);cursor:pointer;}
.vdiv{width:1px;height:22px;background:var(--border);margin:0 4px;}
.cnt{position:absolute;top:-2px;right:-2px;background:var(--danger);color:#fff;font-size:9px;line-height:1;padding:2px 4px;border-radius:8px;}
.content{flex:1;}
.page{padding:20px 24px;max-width:1200px;}
.page-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;margin-bottom:18px;}
.page-head h1{margin:0;font:700 22px/1.2 var(--font-sans);color:var(--text-heading);}
.page-head .sub{color:var(--text-muted);font-size:14px;margin-top:2px;}
.page-actions{display:flex;gap:8px;align-items:center;}
/* drive */
.drive-tools{display:flex;align-items:center;gap:8px;margin-bottom:16px;flex-wrap:wrap;}
.spacer{flex:1;}
.viewtoggle{display:inline-flex;border:1px solid var(--border);border-radius:8px;overflow:hidden;}
.viewtoggle .vt{padding:7px 9px;color:var(--text-muted);cursor:pointer;display:flex;} .viewtoggle .vt.on{background:var(--surface-muted);color:var(--text-primary);}
.sectlabel{font:600 11px/1 var(--font-sans);letter-spacing:.05em;color:var(--text-faint);margin:6px 0 8px;}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:10px;margin-bottom:18px;}
.grid.compact{grid-template-columns:repeat(auto-fill,minmax(120px,1fr));}
.fcard{border:1px solid var(--border);border-radius:var(--radius);padding:12px;cursor:pointer;background:var(--surface);transition:border-color .12s,background .12s;}
.fcard:hover{border-color:var(--border-hover);background:var(--row-hover);}
.fcard.locked{opacity:.55;}
.fcard .ico{position:relative;display:inline-block;}
.fcard .ico > svg{width:34px;height:34px;}
.fcard .thumb{height:60px;border-radius:6px;background:var(--surface-muted);display:flex;align-items:center;justify-content:center;overflow:hidden;}
.fcard .thumb img{width:100%;height:100%;object-fit:cover;}
.fcard .nm{font-size:13px;margin-top:8px;color:var(--text-primary);display:flex;align-items:center;gap:8px;}
.fcard .nm .nm-t{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;}
.fcard .nm .chip{flex:none;}
.fcard .meta{font-size:11px;color:var(--text-faint);margin-top:2px;display:flex;align-items:center;gap:4px;}
.fcard .kebab{float:right;color:var(--text-faint);}
.badge-ov{position:absolute;right:-5px;bottom:-3px;width:17px;height:17px;border-radius:50%;background:var(--surface);border:1px solid var(--border);display:flex;align-items:center;justify-content:center;}
.badge-ov svg{width:10px;height:10px;}
table.dt{width:100%;border-collapse:collapse;}
table.dt th{text-align:left;font:500 12.5px/1.3 var(--font-sans);color:var(--text-muted);padding:9px 10px;border-bottom:1px solid var(--border);cursor:pointer;}
table.dt td{padding:9px 10px;border-bottom:1px solid var(--border);font-size:13.5px;}
table.dt tr:hover td{background:var(--row-hover);cursor:pointer;}
.empty{padding:48px 24px;text-align:center;color:var(--text-muted);}
/* cards / widgets */
.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);}
.card-head{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:14px 16px;border-bottom:1px solid var(--border);font-weight:600;}
.card-body{padding:16px;}
.cards4{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin-bottom:14px;}
.metric{background:var(--surface-muted);border-radius:var(--radius);padding:12px 14px;}
.metric .k{font-size:12px;color:var(--text-muted);} .metric .v{font:700 24px/1.1 var(--font-sans);color:var(--text-heading);margin-top:3px;}
.kv{display:flex;justify-content:space-between;padding:7px 0;border-top:1px solid var(--border);font-size:13px;} .kv:first-child{border-top:0;}
.bar-h{display:flex;align-items:center;gap:8px;font-size:12px;color:var(--text-secondary);margin-bottom:7px;}
.bar-h .t{flex:1;height:7px;border-radius:4px;background:var(--surface-muted-2);overflow:hidden;} .bar-h .t > i{display:block;height:100%;background:var(--primary);}
/* fields/detail panel */
.detail{position:fixed;top:0;right:0;height:100vh;width:340px;max-width:92vw;background:var(--surface);border-left:1px solid var(--border);box-shadow:var(--shadow-dialog);z-index:60;display:flex;flex-direction:column;}
.detail .dh{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;border-bottom:1px solid var(--border);font-weight:600;}
.detail .db{padding:16px;overflow:auto;flex:1;}
.detail .row{display:flex;justify-content:space-between;gap:10px;padding:7px 0;border-top:1px solid var(--border);font-size:13px;} .detail .row:first-child{border-top:0;}
.detail .row .k{color:var(--text-muted);}
/* Details dialog rows (kv pairs) — label left, value right, with a gap so they never glue together */
.detail-rows .row{display:flex;justify-content:space-between;gap:16px;padding:7px 0;border-top:1px solid var(--border);font-size:13px;} .detail-rows .row:first-child{border-top:0;}
.detail-rows .row .k{color:var(--text-muted);flex:none;}
/* let the value column shrink and wrap so a long (unbroken) path can't overflow the fixed-width dialog */
.detail-rows .row > span:last-child{min-width:0;text-align:right;overflow-wrap:anywhere;}
/* menus / dialogs */
.menu{position:fixed;z-index:80;min-width:190px;background:var(--surface);border:1px solid var(--border);border-radius:8px;box-shadow:var(--shadow-menu);padding:5px;}
.menu button{display:flex;width:100%;align-items:center;gap:10px;padding:8px 10px;border:0;background:transparent;border-radius:6px;font:400 13px/1 var(--font-sans);color:var(--text-secondary);cursor:pointer;text-align:left;}
.menu button:hover{background:var(--surface-muted);color:var(--text-primary);} .menu button svg{width:16px;height:16px;color:var(--text-muted);}
.menu button.danger{color:var(--danger);} .menu .mdiv{height:0;border-top:1px solid var(--border);margin:5px 4px;}
.menu .mhint{margin-left:auto;font-size:10px;color:var(--text-faint);}
.overlay{position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:70;display:flex;align-items:flex-start;justify-content:center;padding-top:10vh;}
/* persistent close button for full-screen document/image previews (PDF, DjVu plugin, image lightbox) */
.doc-close{position:fixed;top:14px;right:16px;z-index:90;width:42px;height:42px;display:inline-flex;align-items:center;justify-content:center;border-radius:9px;background:rgba(20,20,20,.62);color:#fff;border:1px solid rgba(255,255,255,.28);cursor:pointer;backdrop-filter:blur(2px);}
.doc-close:hover{background:rgba(0,0,0,.85);border-color:rgba(255,255,255,.5);}
.doc-close svg{width:22px;height:22px;}
.dialog{width:460px;max-width:94vw;background:var(--surface);border:1px solid var(--border);border-radius:12px;box-shadow:var(--shadow-dialog);overflow:hidden;}
.dialog .dh{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;border-bottom:1px solid var(--border);font-weight:600;}
.dialog .db{padding:16px;} .dialog .df{display:flex;justify-content:flex-end;gap:8px;padding:14px 16px;border-top:1px solid var(--border);}
.pm{display:flex;align-items:center;gap:10px;padding:8px 0;border-top:1px solid var(--border);} .pm:first-child{border-top:0;}
.role-badge{font-size:11px;color:var(--text-secondary);border:1px solid var(--border);border-radius:999px;padding:2px 9px;}
/* palette */
.palette{width:560px;max-width:92vw;background:var(--surface);border:1px solid var(--border);border-radius:10px;box-shadow:var(--shadow-dialog);overflow:hidden;}
.palette .pinp{display:flex;align-items:center;gap:10px;padding:14px 16px;border-bottom:1px solid var(--border);} .palette .pinp svg{width:18px;height:18px;color:var(--text-muted);}
.palette .pinp input{border:0;padding:0;height:auto;font-size:16px;} .palette .pinp input:focus{box-shadow:none;}
.presults{max-height:50vh;overflow:auto;padding:8px;}
.presult{display:flex;align-items:center;gap:10px;padding:9px 10px;border-radius:6px;cursor:pointer;} .presult:hover{background:var(--surface-muted);}
/* notifications panel */
.notif{position:fixed;top:56px;right:14px;width:380px;max-width:94vw;background:var(--surface);border:1px solid var(--border);border-radius:12px;box-shadow:var(--shadow-dialog);z-index:75;overflow:hidden;}
.notif .nh{display:flex;align-items:center;justify-content:space-between;padding:11px 14px;border-bottom:1px solid var(--border);font-weight:600;}
.nt{display:flex;gap:10px;padding:11px 14px;border-top:1px solid var(--border);} .nt.unread{background:var(--surface-muted);}
.nt .ni{width:30px;height:30px;border-radius:50%;background:var(--surface-chip);display:flex;align-items:center;justify-content:center;flex:none;color:var(--text-secondary);}
.nt .ni svg{width:15px;height:15px;} .nt .udot{width:8px;height:8px;border-radius:50%;background:var(--primary);flex:none;align-self:center;}
.nt .ntx{font-size:13px;color:var(--text-primary);line-height:1.4;} .nt .ntm{font-size:11px;color:var(--text-faint);margin-top:2px;}
.tg{font-size:11px;padding:4px 10px;border-radius:999px;border:1px solid var(--border);color:var(--text-secondary);cursor:pointer;} .tg.on{background:var(--primary);color:var(--primary-fg);border-color:var(--primary);}
/* changes (two-window + merged) */
.chg-cols{display:grid;grid-template-columns:1fr 1fr;gap:10px;}
.dl{font:12px/1.5 var(--font-mono);padding:2px 8px;border-radius:4px;margin-bottom:2px;white-space:pre-wrap;word-break:break-word;background:var(--surface-muted);color:var(--text-secondary);}
.dl.add{background:var(--add-bg);color:var(--add-text);} .dl.del{background:var(--del-bg);color:var(--del-text);} .dl.eq{background:transparent;}
.dl.blank{background:transparent;}
.colhead{font-size:11px;color:var(--text-faint);margin-bottom:6px;}
/* history timeline */
.hv{display:flex;gap:12px;padding-bottom:16px;position:relative;}
.hv::before{content:"";position:absolute;left:6px;top:16px;bottom:0;width:2px;background:var(--border);} .hv.last::before{display:none;}
.hd{width:13px;height:13px;border-radius:50%;background:var(--surface-muted-2);flex:none;margin-top:3px;z-index:1;}
.hd.pub{background:var(--primary);} .hd.draft{background:var(--warn-text);}
.hm{font-size:13.5px;color:var(--text-primary);} .hs{font-size:11.5px;color:var(--text-faint);margin-top:1px;}
/* interactive version graph */
.graph{position:relative;}
.graph-row{display:flex;align-items:center;border-radius:8px;cursor:pointer;transition:background .08s;}
.graph-row:hover{background:var(--surface-muted);}
.graph-row.sel{background:var(--surface-muted-2);}
.graph-msg{font-size:13.5px;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:flex;align-items:center;gap:6px;}
.graph-meta{font-size:11.5px;color:var(--text-faint);margin-top:1px;}
.graph-svg circle{cursor:pointer;transition:fill .1s;}
.tipchip{font-size:10px;padding:1px 7px;border-radius:999px;background:var(--surface-muted-2);color:var(--text-secondary);border:1px solid var(--border);flex:none;}
.tipchip.main{background:var(--primary);color:var(--primary-fg);border-color:var(--primary);}
/* review chat */
.sysp{text-align:center;font-size:11.5px;color:var(--text-faint);background:var(--surface-muted);border-radius:999px;padding:4px 12px;width:fit-content;margin:8px auto 12px;}
.msg-anchor{display:inline-flex;align-items:center;gap:3px;color:var(--text-secondary);background:var(--surface-muted-2);border-radius:6px;padding:0 6px;font-size:10.5px;}
.composer-ctx{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--text-secondary);background:var(--surface-muted);border-left:3px solid var(--primary);border-radius:6px;padding:7px 10px;margin-top:12px;}
.composer-ctx .cx{margin-left:auto;cursor:pointer;color:var(--text-faint);display:flex;}
.composer{display:flex;gap:8px;margin-top:12px;}
/* comment threads (resolvable) */
.thread{border:1px solid var(--border);border-radius:10px;padding:10px 12px;margin-bottom:12px;background:var(--surface);}
.thread.resolved{opacity:.7;background:var(--surface-muted);}
.thread-top{display:flex;align-items:center;gap:8px;margin-bottom:8px;}
.thread-actions{margin-left:auto;display:flex;gap:12px;}
.tlink{font-size:11.5px;color:var(--text-muted);cursor:pointer;} .tlink:hover{color:var(--primary);text-decoration:underline;}
.msg-anchor.plain{background:none;color:var(--text-faint);padding:0;}
.tmsg{display:flex;gap:8px;margin-bottom:8px;align-items:flex-start;}
.avatar.sm{width:22px;height:22px;font-size:10px;flex:none;}
.tbub{background:var(--surface-muted);border-radius:8px;padding:7px 11px;font-size:13px;color:var(--text-primary);line-height:1.5;flex:1;}
.thread.resolved .tbub{background:var(--surface);}
.tbub .mh{font-size:11px;color:var(--text-muted);margin-bottom:2px;}
.thread-reply{display:flex;gap:6px;margin-top:8px;padding-left:30px;}
.thread-reply input{flex:1;}
.thread-collapsed{font-size:12px;color:var(--text-faint);padding:2px 0;}
/* editor */
.ed-toolbar{display:flex;gap:2px;padding:8px 12px;border-bottom:1px solid var(--border);flex-wrap:wrap;color:var(--text-secondary);}
.ed-toolbar .tb{width:30px;height:30px;display:flex;align-items:center;justify-content:center;border-radius:6px;cursor:pointer;} .ed-toolbar .tb:hover{background:var(--surface-muted);} .ed-toolbar .tb svg{width:17px;height:17px;}
.ed-toolbar .sep{width:1px;background:var(--border);margin:2px 5px;}
.ed-page{max-width:760px;margin:0 auto;padding:20px;}
.ed-area{min-height:50vh;border:1px solid var(--border);border-radius:8px;padding:16px;background:var(--surface);font:14px/1.7 var(--font-sans);}
.ed-area.code{font-family:var(--font-mono);white-space:pre-wrap;}
/* login */
#login{min-height:100vh;display:flex;align-items:center;justify-content:center;background:var(--bg-canvas);padding:24px;}
.login-card{width:380px;max-width:100%;background:var(--surface);border:1px solid var(--border);border-radius:14px;box-shadow:var(--shadow-dialog);padding:32px;}
.login-card .logo{width:56px;height:56px;margin:0 auto 14px;display:block;}
.login-card h1{margin:0 0 4px;text-align:center;font:700 22px/1.2 var(--font-sans);}
.login-card .lsub{text-align:center;color:var(--text-muted);font-size:14px;margin-bottom:20px;}
.login-card .field{margin-bottom:14px;} .login-card .btn.primary{width:100%;height:44px;justify-content:center;}
/* banners + toast */
.banner{display:flex;gap:10px;align-items:flex-start;padding:11px 14px;border-radius:8px;border:1px solid var(--info-border);background:var(--info-bg);color:var(--info-text);font-size:13px;}
.banner svg{width:16px;height:16px;flex:none;margin-top:1px;} .banner.err{background:var(--danger-bg);border-color:var(--danger-border);color:var(--danger);}
.banner.warn{background:var(--warn-bg);border-color:var(--warn-border);color:var(--warn-text);}
.banner.ok{background:var(--ok-bg,var(--info-bg));border-color:var(--ok-border,var(--info-border));color:var(--ok-text,var(--info-text));}
.page > .banner{margin-bottom:14px;} /* gap between a page-level banner and the content below it */
#toast{position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:90;}
.toast{background:var(--primary);color:var(--primary-fg);padding:10px 16px;border-radius:8px;box-shadow:var(--shadow-menu);font-size:13px;}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:14px;} .grid2 .full{grid-column:1/-1;}
/* desktop: the toggle fully hides the sidebar (mobile uses the .open drawer below) */
@media(min-width:881px){ #app.nav-hidden .sidebar{display:none;} }
@media(max-width:880px){
.sidebar{position:fixed;left:0;top:0;z-index:50;transform:translateX(-100%);transition:transform .2s;}
.sidebar.open{transform:none;box-shadow:var(--shadow-dialog);}
.chg-cols,.grid2{grid-template-columns:1fr;}
.page{padding:14px;}
}
+1236
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
node_modules/
.vite/
+11
View File
@@ -0,0 +1,11 @@
<!doctype html>
<html>
<head><meta charset="utf-8" /><title>Galena editor — dev</title></head>
<body style="font-family:system-ui;padding:24px;max-width:760px;margin:0 auto">
<div id="root"></div>
<script type="module">
import { mount } from './src/main.jsx';
mount(document.getElementById('root'), '# Heading\n\nThis is **Galena** with *Slate*.\n\n- one\n- two\n', (md) => console.log(md));
</script>
</body>
</html>
+1842
View File
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "galena-editor",
"private": true,
"version": "0.1.0",
"description": "Galena rich-text editor island — Slate with a docx-style toolbar. Built once to ../static/editor.js so the console stays no-build at runtime.",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
"slate": "^0.103.0",
"slate-history": "^0.100.0",
"slate-react": "^0.110.3"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.3.4",
"vite": "^5.4.11"
}
}
+160
View File
@@ -0,0 +1,160 @@
/* Galena editor island — Slate (ianstormtaylor/slate) with a docx-style toolbar (Plate-inspired).
Bundled by Vite into ../static/editor.js exposing window.GalenaEditor.mount. The console mounts
this for Markdown/text files; if the bundle is absent it falls back to a plain textarea. */
import React, { useCallback, useMemo, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { createEditor, Editor, Element as SlateElement, Transforms } from 'slate';
import { withHistory } from 'slate-history';
import { Editable, Slate, useSlate, withReact } from 'slate-react';
const LIST_TYPES = ['bulleted-list', 'numbered-list'];
/* ── markdown ↔ slate (a practical subset) ── */
function inlineToNodes(text) {
const res = []; const re = /(\*\*([^*]+)\*\*|`([^`]+)`|\*([^*]+)\*|_([^_]+)_)/g;
let last = 0, m;
const push = (t, marks) => { if (t) res.push({ text: t, ...marks }); };
while ((m = re.exec(text))) {
if (m.index > last) push(text.slice(last, m.index), {});
if (m[2] != null) push(m[2], { bold: true });
else if (m[3] != null) push(m[3], { code: true });
else if (m[4] != null) push(m[4], { italic: true });
else if (m[5] != null) push(m[5], { italic: true });
last = re.lastIndex;
}
if (last < text.length) push(text.slice(last), {});
return res.length ? res : [{ text: '' }];
}
function deserialize(md) {
const lines = (md || '').replace(/\r\n/g, '\n').split('\n');
const nodes = []; let list = null;
const flush = () => { if (list) { nodes.push(list); list = null; } };
for (const line of lines) {
let m;
if ((m = line.match(/^(#{1,3})\s+(.*)$/))) { flush(); const lvl = m[1].length; nodes.push({ type: lvl === 1 ? 'heading-one' : lvl === 2 ? 'heading-two' : 'heading-three', children: inlineToNodes(m[2]) }); }
else if ((m = line.match(/^>\s?(.*)$/))) { flush(); nodes.push({ type: 'block-quote', children: inlineToNodes(m[1]) }); }
else if ((m = line.match(/^[-*]\s+(.*)$/))) { if (!list || list.type !== 'bulleted-list') { flush(); list = { type: 'bulleted-list', children: [] }; } list.children.push({ type: 'list-item', children: inlineToNodes(m[1]) }); }
else if ((m = line.match(/^\d+\.\s+(.*)$/))) { if (!list || list.type !== 'numbered-list') { flush(); list = { type: 'numbered-list', children: [] }; } list.children.push({ type: 'list-item', children: inlineToNodes(m[1]) }); }
else if (line.trim() === '') { flush(); }
else { flush(); nodes.push({ type: 'paragraph', children: inlineToNodes(line) }); }
}
flush();
return nodes.length ? nodes : [{ type: 'paragraph', children: [{ text: '' }] }];
}
function serInline(children) {
return (children || []).map((c) => {
if (c.text == null) return serInline(c.children);
let t = c.text; if (c.code) t = '`' + t + '`'; if (c.italic) t = '*' + t + '*'; if (c.bold) t = '**' + t + '**'; return t;
}).join('');
}
function serialize(nodes) {
const block = (n) => {
switch (n.type) {
case 'heading-one': return '# ' + serInline(n.children);
case 'heading-two': return '## ' + serInline(n.children);
case 'heading-three': return '### ' + serInline(n.children);
case 'block-quote': return '> ' + serInline(n.children);
case 'bulleted-list': return n.children.map((li) => '- ' + serInline(li.children)).join('\n');
case 'numbered-list': return n.children.map((li, i) => (i + 1) + '. ' + serInline(li.children)).join('\n');
default: return serInline(n.children);
}
};
return nodes.map(block).join('\n\n').replace(/\n{3,}/g, '\n\n').trim() + '\n';
}
/* ── formatting helpers ── */
const isMarkActive = (editor, f) => { const m = Editor.marks(editor); return m ? m[f] === true : false; };
const toggleMark = (editor, f) => { isMarkActive(editor, f) ? Editor.removeMark(editor, f) : Editor.addMark(editor, f, true); };
const isBlockActive = (editor, f) => {
const { selection } = editor; if (!selection) return false;
const [match] = Array.from(Editor.nodes(editor, { at: Editor.unhangRange(editor, selection), match: (n) => !Editor.isEditor(n) && SlateElement.isElement(n) && n.type === f }));
return !!match;
};
const toggleBlock = (editor, f) => {
const isList = LIST_TYPES.includes(f);
const active = isBlockActive(editor, f);
Transforms.unwrapNodes(editor, { match: (n) => !Editor.isEditor(n) && SlateElement.isElement(n) && LIST_TYPES.includes(n.type), split: true });
Transforms.setNodes(editor, { type: active ? 'paragraph' : isList ? 'list-item' : f });
if (!active && isList) Transforms.wrapNodes(editor, { type: f, children: [] });
};
const Element = ({ attributes, children, element }) => {
switch (element.type) {
case 'heading-one': return <h1 {...attributes}>{children}</h1>;
case 'heading-two': return <h2 {...attributes}>{children}</h2>;
case 'heading-three': return <h3 {...attributes}>{children}</h3>;
case 'block-quote': return <blockquote {...attributes}>{children}</blockquote>;
case 'bulleted-list': return <ul {...attributes}>{children}</ul>;
case 'numbered-list': return <ol {...attributes}>{children}</ol>;
case 'list-item': return <li {...attributes}>{children}</li>;
default: return <p {...attributes}>{children}</p>;
}
};
const Leaf = ({ attributes, children, leaf }) => {
if (leaf.bold) children = <strong>{children}</strong>;
if (leaf.italic) children = <em>{children}</em>;
if (leaf.underline) children = <u>{children}</u>;
if (leaf.code) children = <code className="g-code">{children}</code>;
return <span {...attributes}>{children}</span>;
};
const MBtn = ({ format, label, title }) => {
const editor = useSlate();
return <button className={'g-tb' + (isMarkActive(editor, format) ? ' on' : '')} title={title}
onMouseDown={(e) => { e.preventDefault(); toggleMark(editor, format); }}>{label}</button>;
};
const BBtn = ({ format, label, title }) => {
const editor = useSlate();
return <button className={'g-tb' + (isBlockActive(editor, format) ? ' on' : '')} title={title}
onMouseDown={(e) => { e.preventDefault(); toggleBlock(editor, format); }}>{label}</button>;
};
const Toolbar = () => (
<div className="g-toolbar">
<MBtn format="bold" label="B" title="Bold" />
<MBtn format="italic" label={<em>I</em>} title="Italic" />
<MBtn format="underline" label={<u>U</u>} title="Underline" />
<MBtn format="code" label="<>" title="Code" />
<span className="g-sep" />
<BBtn format="heading-one" label="H1" title="Heading 1" />
<BBtn format="heading-two" label="H2" title="Heading 2" />
<BBtn format="heading-three" label="H3" title="Heading 3" />
<span className="g-sep" />
<BBtn format="bulleted-list" label="• List" title="Bulleted list" />
<BBtn format="numbered-list" label="1. List" title="Numbered list" />
<BBtn format="block-quote" label="❝" title="Quote" />
</div>
);
function App({ initial, onChange }) {
const editor = useMemo(() => withHistory(withReact(createEditor())), []);
const [value] = useState(() => deserialize(initial));
const renderElement = useCallback((p) => <Element {...p} />, []);
const renderLeaf = useCallback((p) => <Leaf {...p} />, []);
return (
<div className="galena-ed">
<Slate editor={editor} initialValue={value} onChange={() => onChange && onChange(serialize(editor.children))}>
<Toolbar />
<div className="galena-ed-area"><Editable renderElement={renderElement} renderLeaf={renderLeaf} placeholder="Write…" spellCheck /></div>
</Slate>
</div>
);
}
const STYLE = `
.galena-ed .g-toolbar{display:flex;gap:2px;flex-wrap:wrap;padding:8px 4px;border-bottom:1px solid var(--border,#dee2e6);margin-bottom:12px}
.galena-ed .g-tb{min-width:30px;height:30px;padding:0 8px;border:1px solid transparent;background:transparent;border-radius:6px;cursor:pointer;font:600 13px var(--font-sans,system-ui);color:var(--text-secondary,#343a40)}
.galena-ed .g-tb:hover{background:var(--surface-muted,#f1f3f5)} .galena-ed .g-tb.on{background:var(--surface-muted,#f1f3f5);color:var(--text-primary,#212529)}
.galena-ed .g-sep{width:1px;background:var(--border,#dee2e6);margin:3px 6px}
.galena-ed [data-slate-editor]{min-height:50vh;font:15px/1.7 var(--font-sans,system-ui);color:var(--text-primary,#212529);outline:none}
.galena-ed h1{font-size:24px} .galena-ed h2{font-size:20px} .galena-ed h3{font-size:17px}
.galena-ed blockquote{border-left:3px solid var(--border,#dee2e6);margin:8px 0;padding:2px 12px;color:var(--text-secondary,#343a40)}
.galena-ed .g-code{font-family:var(--font-mono,monospace);background:var(--surface-muted,#f1f3f5);padding:1px 5px;border-radius:4px}
`;
let _styled = false;
export function mount(el, markdown, onChange) {
if (!_styled) { const s = document.createElement('style'); s.textContent = STYLE; document.head.appendChild(s); _styled = true; }
const root = createRoot(el);
root.render(<App initial={markdown || ''} onChange={onChange} />);
return { unmount: () => root.unmount() };
}
export default { mount, serialize, deserialize };
+20
View File
@@ -0,0 +1,20 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// Build a single self-contained IIFE bundle that exposes window.GalenaEditor = { mount }.
// React + Slate are bundled in (not external) so the console can load one committed artifact.
export default defineConfig({
plugins: [react()],
define: { 'process.env.NODE_ENV': '"production"' },
build: {
outDir: '../static',
emptyOutDir: false,
cssCodeSplit: false,
lib: {
entry: 'src/main.jsx',
name: 'GalenaEditor',
formats: ['iife'],
fileName: () => 'editor.js',
},
},
});
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect x="2" y="2" width="20" height="20" rx="5" fill="#5f3dc4"/><g stroke="#f3f0ff" stroke-width="2" stroke-linecap="round" fill="none"><path d="M12 7.5v9"/><path d="M8.1 9.75l7.8 4.5"/><path d="M15.9 9.75l-7.8 4.5"/></g></svg>

After

Width:  |  Height:  |  Size: 288 B

+70
View File
@@ -0,0 +1,70 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Galena</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Crect x='2' y='2' width='20' height='20' rx='5' fill='%235f3dc4'/%3E%3Cg stroke='%23f3f0ff' stroke-width='2' stroke-linecap='round'%3E%3Cpath d='M12 7.5v9'/%3E%3Cpath d='M8.1 9.75l7.8 4.5'/%3E%3Cpath d='M15.9 9.75l-7.8 4.5'/%3E%3C/g%3E%3C/svg%3E" />
<script>/* set theme before first paint to avoid a flash */
(function(){try{var m=localStorage.getItem('galena_theme')||'system';
var dark=m==='dark'||(m==='system'&&window.matchMedia&&matchMedia('(prefers-color-scheme:dark)').matches);
document.documentElement.dataset.theme=dark?'dark':'light';}catch(e){}})();</script>
<link rel="stylesheet" href="app.css" />
</head>
<body>
<div id="login">
<div style="position:fixed;top:16px;right:16px;display:flex;gap:8px;z-index:5">
<button class="iconbtn txt" id="btnLangLogin" title="Language" data-no-i18n style="background:var(--surface);border:1px solid var(--border-input)">EN</button>
<button class="iconbtn js-theme" id="btnThemeLogin" title="Theme" style="background:var(--surface);border:1px solid var(--border-input)"></button>
</div>
<form class="login-card" id="loginForm">
<svg class="logo" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect x="2" y="2" width="20" height="20" rx="5" fill="#5f3dc4"/><g stroke="#f3f0ff" stroke-width="2" stroke-linecap="round"><path d="M12 7.5v9"/><path d="M8.1 9.75l7.8 4.5"/><path d="M15.9 9.75l-7.8 4.5"/></g></svg>
<h1>Galena</h1>
<div class="lsub">Text versioning system</div>
<label class="field">Email <input id="email" type="email" value="admin@example.com" autocomplete="username" /></label>
<label class="field" style="margin-top:12px">Password <input id="password" type="password" placeholder="password" autocomplete="current-password" /></label>
<div id="loginErr" class="banner err hidden" style="margin:14px 0"></div>
<button class="btn primary" id="btnLogin" type="submit" style="margin-top:16px">Sign in</button>
</form>
</div>
<div id="app" class="hidden">
<aside class="sidebar" id="sidebar">
<div class="brand">
<svg class="logo" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect x="2" y="2" width="20" height="20" rx="5" fill="#5f3dc4"/><g stroke="#f3f0ff" stroke-width="2" stroke-linecap="round"><path d="M12 7.5v9"/><path d="M8.1 9.75l7.8 4.5"/><path d="M15.9 9.75l-7.8 4.5"/></g></svg>
<span class="nm">Galena</span>
</div>
<nav class="nav" id="nav"></nav>
<div class="storage" id="storage"></div>
<div class="nav" style="flex:none;padding-bottom:10px"><div class="nav-item" id="navSettings"></div></div>
</aside>
<div id="navScrim"></div>
<div class="main">
<header class="topbar">
<button class="iconbtn" id="navToggle" title="Menu"></button>
<svg class="topbar-mark" viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex:none;color:var(--text-secondary)" aria-hidden="true"><path d="M7 10h14l-4 -4"/><path d="M17 14h-14l4 4"/></svg>
<div class="crumb" id="crumb"></div>
<div class="spacer"></div>
<button class="iconbtn" id="aDashboard" title="Dashboard"></button>
<button class="iconbtn" id="aDrafts" title="Drafts"></button>
<button class="iconbtn" id="aAdmin" title="Administration"></button>
<span class="vdiv"></span>
<button class="iconbtn" id="aSearch" title="Search (Ctrl/⌘K)"></button>
<button class="iconbtn" id="aBell" title="Notifications"></button>
<button class="iconbtn js-theme" id="aTheme" title="Theme"></button>
<button class="iconbtn txt" id="aLang" title="Language" data-no-i18n>EN</button>
<span class="avatar" id="aUser" title="Account">?</span>
</header>
<main class="content" id="content"></main>
</div>
</div>
<div id="modalRoot"></div>
<div id="panelRoot"></div>
<div id="toast"></div>
<script defer src="static/editor.js"></script>
<script src="app.js"></script>
</body>
</html>
File diff suppressed because one or more lines are too long
+21
View File
@@ -0,0 +1,21 @@
/* Galena service worker — receives web-push notifications and focuses the app on click. */
self.addEventListener('push', (event) => {
let data = {};
try { data = event.data ? event.data.json() : {}; } catch (e) {}
const title = data.title || 'Galena';
event.waitUntil(self.registration.showNotification(title, {
body: data.body || '',
data: { link: data.link || '/' },
icon: '/favicon.svg',
badge: '/favicon.svg',
}));
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
const link = (event.notification.data && event.notification.data.link) || '/';
event.waitUntil(clients.matchAll({ type: 'window', includeUncontrolled: true }).then((wins) => {
for (const w of wins) { if ('focus' in w) { w.focus(); if (link && 'navigate' in w) w.navigate(link); return; } }
if (clients.openWindow) return clients.openWindow(link);
}));
});