No third-party code in Galena's origin, no session token in the console (Atrium#68, R2)
- ReaderJS, tesseract.js (+ WASM core, language models) and PDF.js are served by Galena from static/: backend/scripts/fetch_vendor.py fetches them at image build (Dockerfile `vendor` stage, Netlify prepare, local dev) - ReaderJS by full commit SHA through git, the npm tarballs at exact versions checked against their integrity hashes; a mismatch fails the build. tesseract.js was loaded as `@5`. - The console and reader CSPs name no CDN; READERJS_DEFAULT_BASE is `dist/`, the shell-relative own copy (a remote, immutable override still works). - POST /auth/login returns the raw session token only with `issue_token: true` (Galena Connect asks); the console signs in by the httpOnly cookie alone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -25,3 +25,7 @@ backend/data/
|
||||
|
||||
# Generated at deploy time by netlify/prepare.sh
|
||||
frontend/_redirects
|
||||
|
||||
# Third-party browser code, fetched pinned + verified by backend/scripts/fetch_vendor.py (image build / dev)
|
||||
frontend/static/vendor/
|
||||
frontend/static/readerjs/dist/
|
||||
|
||||
@@ -269,10 +269,13 @@ cd frontend/editor && npm run build # rebuild the editor bundle (commit ..
|
||||
`errors.problem_response` the one place that builds the body. `tests/test_api_routing_problems.py`
|
||||
sweeps every parameter-free API path for it, DB-free.
|
||||
- **OCR is in-browser & permissive (`viewOcr` in `app.js`, top-bar tool).** Like RTF, it's a core
|
||||
permissive feature, not a plugin: the engine is **tesseract.js** (Apache-2.0, lazy-loaded from
|
||||
jsDelivr; tessdata Apache-2.0, on demand). **The document never leaves the box** (no upload). This
|
||||
needs `https://cdn.jsdelivr.net` in CSP `script-/worker-/connect-src` **and** `'wasm-unsafe-eval'`
|
||||
in `script-src` (WASM compile; narrower than `'unsafe-eval'`) — keep both. ocrs was evaluated and
|
||||
permissive feature, not a plugin: the engine is **tesseract.js** (Apache-2.0) + its WASM core,
|
||||
the language models and PDF.js, all **served by Galena from `static/vendor/`** — fetched at image
|
||||
build by `backend/scripts/fetch_vendor.py` at exact versions checked against their npm integrity
|
||||
hashes (never committed, `.gitignore`d). **The document never leaves the box** (no upload), and
|
||||
since Atrium#68 (R2) **no CDN code runs in this origin**: the console CSP names no third-party
|
||||
host — never add one back. It needs `'wasm-unsafe-eval'` in `script-src` (WASM compile; narrower
|
||||
than `'unsafe-eval'`) — keep it. Local dev: `python backend/scripts/fetch_vendor.py frontend/static`. ocrs was evaluated and
|
||||
dropped (no stable in-browser build — see [`OCR.md`](OCR.md)); higher-accuracy server (PaddleOCR/docTR)
|
||||
and cloud OCR stay operator opt-ins (privacy) — never a default; cloud must be explicit.
|
||||
- **Accent = monochrome** (near-black light / near-white dark). Open Color **violet8** (#5f3dc4) is
|
||||
@@ -327,11 +330,13 @@ cd frontend/editor && npm run build # rebuild the editor bundle (commit ..
|
||||
**read-only** ReaderJS viewer (`readerView` in `app.js`); editing is a separate action — the kebab
|
||||
menu's **Edit** and the viewer's **Edit** button call `editFile`, which routes to the in-app editors
|
||||
(Slate/text, DOCX/ODT via the editor route, `rtfEditor`, `docEditor`). The viewer is the built
|
||||
`dist-embed/` of [`Alpaq92/ReaderJS`](https://github.com/Alpaq92/ReaderJS), **not vendored**:
|
||||
`frontend/static/readerjs/` holds only the loader `readerjs.js` and a tiny same-origin **shell**
|
||||
`reader.html`, which fetches the build's `reader.html` from **`READERJS_BASE_URL`** (default
|
||||
`config.READERJS_DEFAULT_BASE`, jsDelivr `gh/Alpaq92/ReaderJS@<full SHA>/dist-embed/`; jsDelivr
|
||||
serves .html as text/plain, hence fetch, not frame), injects `<base href=BASE>` and
|
||||
`dist-embed/` of [`Alpaq92/ReaderJS`](https://github.com/Alpaq92/ReaderJS), **not committed**:
|
||||
`frontend/static/readerjs/` holds the loader `readerjs.js` and a tiny same-origin **shell**
|
||||
`reader.html`; the build itself is fetched at image build by `backend/scripts/fetch_vendor.py`
|
||||
(git, by the full commit SHA `READERJS_SHA` — the commit id is the content check) into
|
||||
`static/readerjs/dist/`. The shell fetches the build's `reader.html` from **`READERJS_BASE_URL`**
|
||||
(default `config.READERJS_DEFAULT_BASE` = `dist/`, Galena's own copy, so no CDN code runs in this
|
||||
origin — Atrium#68 R2; a remote override is still allowed, immutable only), injects `<base href=BASE>` and
|
||||
`document.write`s it, and wraps cross-origin Workers in same-origin `blob:` module workers (`import
|
||||
"<url>"`). The backend serves the shell from a route (`readerjs_shell` in `main.py`) with the
|
||||
setting substituted into `<meta name="readerjs-base">`; static hosts serve the file's default, which
|
||||
@@ -339,7 +344,7 @@ cd frontend/editor && npm run build # rebuild the editor bundle (commit ..
|
||||
version — whatever it serves runs in this origin) and the validator refuses anything that could
|
||||
break out of the meta or the CSP. Only code is fetched — documents still arrive over postMessage.
|
||||
`edge.reader_csp(settings.readerjs_base_url)` (main's `_READER_CSP`, handed to `SecurityHeaders`;
|
||||
viewer only, never the console) adds the base's origin to `base-uri`, `script-src`,
|
||||
viewer only, never the console) adds a REMOTE base's origin (none for the default) to `base-uri`, `script-src`,
|
||||
`style-src`, `font-src`, `img-src`, `connect-src`; no `unsafe-eval`. Loader `readerjs.js` exposes `window.ReaderJS.mount(el,{blob,name})` **and
|
||||
`instance.compare(a,b,{mode,blame})`** (also `mount(el,{compare:{a,b,blame,mode}})`); both render inside
|
||||
`reader.html`. The viewer (`readerView`) fetches `/raw` → blob → mount. The **Changes** view
|
||||
|
||||
+5
-4
@@ -42,7 +42,7 @@ Core ships none of that; the copyleft-free guarantee is about what's installed b
|
||||
- **Document viewing & version compare:** the universal viewer is **ReaderJS** ([`Alpaq92/ReaderJS`](https://github.com/Alpaq92/ReaderJS),
|
||||
**MIT**) — a same-origin iframe viewer. Galena does **not** vendor its libraries: it keeps only the
|
||||
~2 KB loader and a tiny shell in `frontend/static/readerjs/`, and the shell loads ReaderJS's built
|
||||
code (`dist-embed/`) from `READERJS_BASE_URL`, pinned to an immutable commit. It renders PDF, DjVu, DOC/DOCX/PPTX/XLSX, ODF, images, comics and
|
||||
code (`dist-embed/`) from Galena's own copy, fetched at image build from an immutable commit. It renders PDF, DjVu, DOC/DOCX/PPTX/XLSX, ODF, images, comics and
|
||||
e-books **entirely client-side** (documents never leave the box), and its **`compare`** mode powers
|
||||
Galena's **Changes** view — a side-by-side/unified/inline, word-level, blame-aware diff of two versions
|
||||
for any extractable-text format (PDF, DjVu, e-books, Office, text). Every bundled engine is permissive —
|
||||
@@ -50,9 +50,10 @@ Core ships none of that; the copyleft-free guarantee is about what's installed b
|
||||
SheetJS (Apache-2.0), **DejaView** (clean-room, permissive DjVu — replaces the old GPL DjVu plugin),
|
||||
**JSDoc** (0BSD) for legacy `.doc`, and **jsdiff** (BSD-3) + **Open-Color** (MIT) behind the compare
|
||||
view; see ReaderJS's own `CREDITS.md`. Grid cards still use Pillow thumbnails.
|
||||
- **OCR (text recognition):** **tesseract.js** (Apache-2.0, lazy-loaded from jsDelivr) runs the
|
||||
Tesseract LSTM engine in the browser; its **tessdata** language models are Apache-2.0 and download
|
||||
on demand (carry an Apache NOTICE/attribution). Permissive and client-side — documents never leave
|
||||
- **OCR (text recognition):** **tesseract.js** + tesseract.js-core (Apache-2.0) run the
|
||||
Tesseract LSTM engine in the browser, with PDF.js (Apache-2.0) for PDFs; its **tessdata** language
|
||||
models are Apache-2.0 (npm packaging `@tesseract.js-data/*`, MIT). All are served by Galena itself,
|
||||
fetched pinned and verified at image build (`backend/scripts/fetch_vendor.py`), and load on demand (carry an Apache NOTICE/attribution). Permissive and client-side — documents never leave
|
||||
the box. Alternatives considered (ocrs; server PaddleOCR/docTR; cloud OCR) are documented operator
|
||||
opt-ins, not core — see [`OCR.md`](OCR.md).
|
||||
- **Code editing:** the in-app code editor (line numbers + syntax highlighting for js/ts/json/yaml/css/
|
||||
|
||||
@@ -61,7 +61,7 @@ serves the API, the console and its own security headers; Postgres is internal.
|
||||
| **Notifications** | a bell with an unread counter, an in-app panel, and opt-in browser-push + email. |
|
||||
| **Approval workflows** | **"Obiegi akceptacji"** — a multi-stage approval of **one pinned version** of a document (moved in from the retired Workflow module). A moderator sets up **workflow templates**: ordered stages, each approved by a **role on the document** (viewer/editor/approver/manager) or by **named people**; a stage is a plain approval, a **content review** (the approver confirms the exact version they read) or the **paper signature** (always last: approved by uploading the **scan of the signed paper**, saved into the document's `podpisane/` folder through the normal upload chokepoint). An editor starts a workflow on a version; each stage's assignee **approves or rejects with a comment**; the starter or a manager may cancel. Every step lands on an **append-only timeline**. Two lists — **Waiting for me** and **In progress** — plus a "Czeka na mnie" tile on `/stats`. An approved workflow moves the **contract card** to *approved* (source: the workflow). It does not replace drafts: **content edits stay drafts**; the workflow approves a version that already exists. Three example templates are seeded. |
|
||||
| **Dashboard** | workflow-tuned: stat cards, a 14-day redactions/publishes/drafts chart, file-type donut, storage-by-workspace, and an "approvals waiting for you" queue. |
|
||||
| **Viewing** | **clicking any document opens it read-only in the built-in [ReaderJS](https://github.com/Alpaq92/ReaderJS) viewer** (MIT, same-origin iframe; Galena keeps only a tiny shell and loads the viewer's code from `READERJS_BASE_URL` — by default jsDelivr pinned to an immutable ReaderJS commit; point it at your own copy for offline installs. Only code is fetched — documents never leave the box) — PDF, DjVu, DOC/DOCX/PPTX/XLSX, ODF, images, comics (CBZ/CBR), e-books (EPUB/MOBI), code, and more, all client-side. **Editing is a separate action** (the kebab menu's *Edit* / the viewer's *Edit* button → the in-app editors). DjVu is now permissive **core** (DejaView), not a plugin. |
|
||||
| **Viewing** | **clicking any document opens it read-only in the built-in [ReaderJS](https://github.com/Alpaq92/ReaderJS) viewer** (MIT, same-origin iframe; Galena serves its own copy of the viewer, fetched at image build from an immutable ReaderJS commit — no CDN code runs in Galena's origin; documents never leave the box) — PDF, DjVu, DOC/DOCX/PPTX/XLSX, ODF, images, comics (CBZ/CBR), e-books (EPUB/MOBI), code, and more, all client-side. **Editing is a separate action** (the kebab menu's *Edit* / the viewer's *Edit* button → the in-app editors). DjVu is now permissive **core** (DejaView), not a plugin. |
|
||||
| **Sessions** | server-side **cookie** sessions (instant kill-switch). JWT was considered — see roadmap. |
|
||||
| **Password generator** | a top-bar tool to generate strong passwords (length 4–64; toggle upper/lower/numbers/symbols) with a strength estimate, **client-side only** via the Web Crypto CSPRNG (`crypto.getRandomValues`, rejection-sampled — never `Math.random`); plus show/hide on password fields (incl. sign-in). |
|
||||
| **OCR (text recognition)** | a top-bar tool to extract text from an image or PDF **entirely in the browser** (the file never leaves the box), via **Tesseract.js** (Apache-2.0 WASM, 100+ languages, model downloaded on demand). PDFs reuse PDF.js (each page → canvas → OCR); copy or download the result as `.txt`. Higher-accuracy server (PaddleOCR/docTR) and cloud engines are documented operator opt-ins — see [`OCR.md`](OCR.md). |
|
||||
|
||||
@@ -37,6 +37,14 @@ RUN --mount=type=secret,id=dredd_core_token,required=true \
|
||||
GIT_CONFIG_VALUE_0="https://github.com/" \
|
||||
pip install --no-cache-dir --prefix=/install -r requirements.txt
|
||||
|
||||
# ── vendor stage: the console's third-party browser code, pinned and verified ─
|
||||
# ReaderJS (git, by full commit SHA), tesseract.js + its WASM core + language models and PDF.js (npm
|
||||
# tarballs, by their integrity hashes). Served by this backend from static/, so no CDN code ever runs
|
||||
# in Galena's origin (Atrium#68, R2). A mismatch fails the build. No credential needed: all public.
|
||||
FROM base AS vendor
|
||||
COPY scripts/fetch_vendor.py /tmp/fetch_vendor.py
|
||||
RUN python /tmp/fetch_vendor.py /vendor
|
||||
|
||||
# ── runtime stage: no credential, no compiler ────────────────────────────────
|
||||
FROM base
|
||||
|
||||
@@ -51,6 +59,7 @@ COPY . .
|
||||
# and a bare build from backend/ needs `docker build --build-context frontend=../frontend .`.
|
||||
# /frontend is exactly where main.py's default (two levels above app/main.py) looks.
|
||||
COPY --from=frontend . /frontend
|
||||
COPY --from=vendor /vendor /frontend/static
|
||||
|
||||
RUN useradd -m app && mkdir -p /data && chown -R app /data /app
|
||||
ENV DATA_DIR=/data
|
||||
|
||||
+15
-14
@@ -16,11 +16,11 @@ from sqlalchemy.exc import ArgumentError
|
||||
HUB_SESSION_COOKIE = "dredd_session"
|
||||
|
||||
|
||||
# The pinned ReaderJS build (see `readerjs_base_url`). Must equal the <meta name="readerjs-base">
|
||||
# default in frontend/static/readerjs/reader.html, which static hosts serve unmodified (a test checks).
|
||||
READERJS_DEFAULT_BASE = (
|
||||
"https://cdn.jsdelivr.net/gh/Alpaq92/ReaderJS@89d1981e9db55f3eab371eac0811eb72733d849f/dist-embed/"
|
||||
)
|
||||
# The ReaderJS build (see `readerjs_base_url`), served by Galena itself: scripts/fetch_vendor.py puts
|
||||
# ReaderJS's `dist-embed/` at a pinned commit into static/readerjs/dist/ when the image is built, so no
|
||||
# CDN code runs in this origin (Atrium#68, R2). Relative to the shell page. Must equal the
|
||||
# <meta name="readerjs-base"> default in frontend/static/readerjs/reader.html (a test checks).
|
||||
READERJS_DEFAULT_BASE = "dist/"
|
||||
|
||||
|
||||
def _csv(value: str) -> list[str]:
|
||||
@@ -407,25 +407,26 @@ class Settings(BaseSettings):
|
||||
return ""
|
||||
|
||||
# Where the ReaderJS viewer's built code (`dist-embed/`: reader.html + assets) is loaded from.
|
||||
# Galena serves only a tiny same-origin shell (frontend/static/readerjs/reader.html) and pulls
|
||||
# the code from here; documents never leave the box. MUST be immutable (a full commit SHA or an
|
||||
# exact version - never a branch or `latest`): whatever it serves runs in Galena's origin.
|
||||
# Offline / self-hosted: point it at a copy you serve yourself, e.g. `/readerjs-dist/` or
|
||||
# `https://assets.example.com/readerjs/<sha>/`.
|
||||
# Default: Galena's own copy, fetched at image build (`dist/`, relative to the shell page
|
||||
# frontend/static/readerjs/reader.html). An override MUST be immutable (a full commit SHA or an
|
||||
# exact version - never a branch or `latest`): whatever it serves runs in Galena's origin, and a
|
||||
# remote one is added to the viewer's CSP. Documents never leave the box either way.
|
||||
readerjs_base_url: str = READERJS_DEFAULT_BASE
|
||||
|
||||
@field_validator("readerjs_base_url")
|
||||
@classmethod
|
||||
def _readerjs_base(cls, v: str) -> str:
|
||||
# Rendered into the shell's <meta> and into the viewer's CSP - so a same-origin absolute
|
||||
# path or an http(s) URL, with no character that could break out of either.
|
||||
# Rendered into the shell's <meta> and into the viewer's CSP - so a same-origin path
|
||||
# (absolute, or relative to the shell like the default) or an http(s) URL, with no
|
||||
# character that could break out of either.
|
||||
v = (v or "").strip() or READERJS_DEFAULT_BASE
|
||||
if not v.endswith("/"):
|
||||
v += "/"
|
||||
if re.search(r"[\s\"'<>;,\\]", v) or v.startswith("//"):
|
||||
raise ValueError("READERJS_BASE_URL must be a plain URL or path")
|
||||
if not (v.startswith("/") or v.startswith("https://") or v.startswith("http://")):
|
||||
raise ValueError("READERJS_BASE_URL must be an absolute path or an http(s) URL")
|
||||
relative = re.fullmatch(r"[A-Za-z0-9_.-]+(/[A-Za-z0-9_.-]+)*/", v) and ".." not in v.split("/")
|
||||
if not (relative or v.startswith("/") or v.startswith("https://") or v.startswith("http://")):
|
||||
raise ValueError("READERJS_BASE_URL must be a path or an http(s) URL")
|
||||
return v
|
||||
|
||||
# Bootstrap admin (seed)
|
||||
|
||||
+8
-6
@@ -56,9 +56,11 @@ REFERRER_POLICY = "same-origin"
|
||||
def content_security_policy(frame_ancestors: str) -> str:
|
||||
"""The console's CSP (pinned character for character by tests/test_edge.py), with `frame-ancestors`
|
||||
from FRAME_ANCESTORS. 'unsafe-inline' covers the theme pre-paint inline <script> and the inline
|
||||
style="" attributes; frame-src 'self' lets the console frame the ReaderJS viewer; cdnjs is the
|
||||
lazy-loaded PDF.js and jsdelivr tesseract.js (in-browser OCR), both WebAssembly, hence
|
||||
'wasm-unsafe-eval' (WASM compilation only, not eval()), which ReaderJS's libarchive needs too."""
|
||||
style="" attributes; frame-src 'self' lets the console frame the ReaderJS viewer. No CDN: PDF.js
|
||||
and tesseract.js (in-browser OCR) are served from static/vendor/, fetched pinned and verified at
|
||||
image build (scripts/fetch_vendor.py, Atrium#68 R2), so no third party's code runs in this origin.
|
||||
Both are WebAssembly, hence 'wasm-unsafe-eval' (WASM compilation only, not eval()), which
|
||||
ReaderJS's libarchive needs too."""
|
||||
return (
|
||||
"default-src 'self'; "
|
||||
"base-uri 'self'; "
|
||||
@@ -69,9 +71,9 @@ def content_security_policy(frame_ancestors: str) -> str:
|
||||
"img-src 'self' data: blob:; "
|
||||
"font-src 'self' data:; "
|
||||
"style-src 'self' 'unsafe-inline'; "
|
||||
"script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; "
|
||||
"worker-src 'self' blob: https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; "
|
||||
"connect-src 'self' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net"
|
||||
"script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; "
|
||||
"worker-src 'self' blob:; "
|
||||
"connect-src 'self'"
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -102,7 +102,10 @@ def login(body: LoginIn, request: Request, response: Response, db: Session = Dep
|
||||
max_age=settings.session_ttl_hours * 3600, path="/", **_cookie_domain(),
|
||||
)
|
||||
_clear_legacy_cookies(response)
|
||||
return {"token": token, "user": user_out(user)}
|
||||
out = {"user": user_out(user)}
|
||||
if body.issue_token:
|
||||
out["token"] = token
|
||||
return out
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
|
||||
@@ -26,6 +26,10 @@ Email = Annotated[str, AfterValidator(_valid_email)]
|
||||
class LoginIn(BaseModel):
|
||||
email: Email
|
||||
password: str
|
||||
# The raw session token is in the answer only when a non-browser client asks for it (Galena
|
||||
# Connect trades it for an app token at once). The console never asks: it signs in by the
|
||||
# httpOnly cookie alone, so no script in the origin ever holds the session (Atrium#68, R2).
|
||||
issue_token: bool = False
|
||||
|
||||
|
||||
class AppTokenCreate(BaseModel):
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Fetch the console's third-party browser code into the image, pinned and verified (Atrium#68, R2).
|
||||
|
||||
The console used to load ReaderJS, Tesseract.js (OCR) and PDF.js from public CDNs at run time, so
|
||||
code a CDN served ran in Galena's origin, next to every signed-in session. Now nothing executable
|
||||
comes from anywhere but Galena: this script runs once at image build (backend/Dockerfile, the
|
||||
`vendor` stage) and for local development, and writes everything under one output directory that is
|
||||
served as `static/`:
|
||||
|
||||
readerjs/dist/ ReaderJS's built `dist-embed/` at a full commit SHA (git checks the content)
|
||||
vendor/tesseract/ tesseract.js (Apache-2.0) npm tarball, checked by its integrity
|
||||
vendor/tesseract-core tesseract.js-core WASM (Apache-2.0) npm tarball, checked by its integrity
|
||||
vendor/tessdata/ language models (MIT packaging) npm tarball, checked by its integrity
|
||||
vendor/pdfjs/ PDF.js for OCR of PDFs (Apache-2.0) npm tarball, checked by its integrity
|
||||
|
||||
A mismatch stops the build. To update a pin, change the version AND its `integrity` (from
|
||||
`https://registry.npmjs.org/<name>`), or the SHA for ReaderJS (and READERJS_DEFAULT_BASE stays
|
||||
`readerjs/dist/`-relative, so nothing else moves).
|
||||
|
||||
python scripts/fetch_vendor.py ../frontend/static # local development
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
READERJS_REPO = "https://github.com/Alpaq92/ReaderJS"
|
||||
READERJS_SHA = "89d1981e9db55f3eab371eac0811eb72733d849f"
|
||||
|
||||
OCR_LANGS = ("eng", "pol", "deu", "fra", "spa") # app.js OCR_LANGS
|
||||
|
||||
# (tarball URL, npm integrity, [(member inside the tarball, destination under the output dir)])
|
||||
NPM: list[tuple[str, str, list[tuple[str, str]]]] = [
|
||||
("https://registry.npmjs.org/tesseract.js/-/tesseract.js-5.1.1.tgz",
|
||||
"sha512-lzVl/Ar3P3zhpUT31NjqeCo1f+D5+YfpZ5J62eo2S14QNVOmHBTtbchHm/YAbOOOzCegFnKf4B3Qih9LuldcYQ==",
|
||||
[("package/dist/tesseract.min.js", "vendor/tesseract/tesseract.min.js"),
|
||||
("package/dist/worker.min.js", "vendor/tesseract/worker.min.js"),
|
||||
("package/LICENSE.md", "vendor/tesseract/LICENSE.md")]),
|
||||
("https://registry.npmjs.org/tesseract.js-core/-/tesseract.js-core-5.1.1.tgz",
|
||||
"sha512-KX3bYSU5iGcO1XJa+QGPbi+Zjo2qq6eBhNjSGR5E5q0JtzkoipJKOUQD7ph8kFyteCEfEQ0maWLu8MCXtvX5uQ==",
|
||||
[(f"package/{n}", f"vendor/tesseract-core/{n}") for n in (
|
||||
"tesseract-core.wasm.js", "tesseract-core-simd.wasm.js",
|
||||
"tesseract-core-lstm.wasm.js", "tesseract-core-simd-lstm.wasm.js", "LICENSE")]),
|
||||
("https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-3.11.174.tgz",
|
||||
"sha512-TdTZPf1trZ8/UFu5Cx/GXB7GZM30LT+wWUNfsi6Bq8ePLnb+woNKtDymI2mxZYBpMbonNFqKmiz684DIfnd8dA==",
|
||||
[("package/build/pdf.min.js", "vendor/pdfjs/pdf.min.js"),
|
||||
("package/build/pdf.worker.min.js", "vendor/pdfjs/pdf.worker.min.js"),
|
||||
("package/LICENSE", "vendor/pdfjs/LICENSE")]),
|
||||
]
|
||||
_TESSDATA = {
|
||||
"eng": "sha512-mbTumm6KQPUHyzTPQaF3ObXYnx0SqqfV2nabqFVQBwD6Kl7PhGSLSzOlfFTWy0P3BjghaSKA2W9GB19Jk+ZcTg==",
|
||||
"pol": "sha512-e9naSi/5kIXIMsymriFMUXJ2XWxRY/09qU9pkmEN28nAeMyF70EYkn4G3iHoB2oF/HNhZpy8lCIe1/I2L/BqKA==",
|
||||
"deu": "sha512-3ter1p2gFAiCd5CMC+PodZ9YY2UDomkKj+ytlKeeZqOUmhLx1SDnYPf5zog0g5MBbxYveW+8omI3PUflqHfZ4Q==",
|
||||
"fra": "sha512-pp58gMaoyidoBBLd5y5rnf0WW0Y1994QrGqZrYatITqIU/AReUJMykD+YY3JDgvnmgz7uAx1UmhjjuyEmV8JEA==",
|
||||
"spa": "sha512-9Ln+QKq/TNu4Hy4aOp5b4nXo9U0C6IqJMzNDpAJZe/fNtz6jXG9G/hQgR/Irxj+RGf0M7Xy1MNx1yl4wQUIfeg==",
|
||||
}
|
||||
NPM += [(f"https://registry.npmjs.org/@tesseract.js-data/{lang}/-/{lang}-1.0.0.tgz", _TESSDATA[lang],
|
||||
[(f"package/4.0.0_best_int/{lang}.traineddata.gz",
|
||||
f"vendor/tessdata/{lang}.traineddata.gz")]) for lang in OCR_LANGS]
|
||||
|
||||
|
||||
def _verified(url: str, integrity: str) -> bytes:
|
||||
algo, _, want = integrity.partition("-")
|
||||
with urllib.request.urlopen(url, timeout=120) as r: # noqa: S310 - fixed https URLs above
|
||||
data = r.read()
|
||||
got = base64.b64encode(hashlib.new(algo, data).digest()).decode()
|
||||
if got != want:
|
||||
raise SystemExit(f"integrity mismatch for {url}: got {algo}-{got}")
|
||||
return data
|
||||
|
||||
|
||||
def _npm(out: Path) -> None:
|
||||
for url, integrity, members in NPM:
|
||||
with tarfile.open(fileobj=io.BytesIO(_verified(url, integrity)), mode="r:gz") as tar:
|
||||
for member, dest in members:
|
||||
src = tar.extractfile(member)
|
||||
if src is None:
|
||||
raise SystemExit(f"{member} missing from {url}")
|
||||
target = out / dest
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(src.read())
|
||||
|
||||
|
||||
def _readerjs(out: Path) -> None:
|
||||
target = out / "readerjs" / "dist"
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
git = ["git", "-C", tmp]
|
||||
subprocess.run(["git", "init", "-q", tmp], check=True)
|
||||
subprocess.run([*git, "fetch", "-q", "--depth", "1", READERJS_REPO, READERJS_SHA], check=True)
|
||||
subprocess.run([*git, "checkout", "-q", "FETCH_HEAD"], check=True)
|
||||
head = subprocess.run([*git, "rev-parse", "HEAD"], check=True, capture_output=True,
|
||||
text=True).stdout.strip()
|
||||
if head != READERJS_SHA: # the commit id is the content hash: this is the check
|
||||
raise SystemExit(f"ReaderJS checkout is {head}, expected {READERJS_SHA}")
|
||||
if target.exists():
|
||||
shutil.rmtree(target)
|
||||
shutil.copytree(Path(tmp) / "dist-embed", target)
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if len(argv) != 2:
|
||||
print(__doc__, file=sys.stderr)
|
||||
return 2
|
||||
out = Path(argv[1])
|
||||
_npm(out)
|
||||
_readerjs(out)
|
||||
print(f"vendor code written under {out}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv))
|
||||
@@ -27,20 +27,15 @@ INDEX_SRC = (_FRONTEND / "index.html").read_text(encoding="utf-8")
|
||||
PINNED_CONSOLE_CSP = (
|
||||
"default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; frame-src "
|
||||
"'self'; form-action 'self'; img-src 'self' data: blob:; font-src 'self' data:; style-src "
|
||||
"'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' "
|
||||
"https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; worker-src 'self' blob: "
|
||||
"https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; connect-src 'self' "
|
||||
"https://cdnjs.cloudflare.com https://cdn.jsdelivr.net")
|
||||
# The reader's: framable by its own origin, plus the ReaderJS code origin (READERJS_BASE_URL, default
|
||||
# jsDelivr) in the directives that load its code — and nothing else changes.
|
||||
"'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; worker-src "
|
||||
"'self' blob:; connect-src 'self'")
|
||||
# The reader's: the console's, framable by its own origin. ReaderJS is Galena's own copy by default
|
||||
# (static/readerjs/dist/), so no code origin is added: nothing from a CDN runs here (Atrium#68, R2).
|
||||
PINNED_READER_CSP = (
|
||||
"default-src 'self'; base-uri 'self' https://cdn.jsdelivr.net; object-src 'none'; "
|
||||
"frame-ancestors 'self'; frame-src 'self'; form-action 'self'; img-src 'self' data: blob: "
|
||||
"https://cdn.jsdelivr.net; font-src 'self' data: https://cdn.jsdelivr.net; style-src 'self' "
|
||||
"'unsafe-inline' https://cdn.jsdelivr.net; script-src 'self' 'unsafe-inline' "
|
||||
"'wasm-unsafe-eval' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; worker-src 'self' "
|
||||
"blob: https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; connect-src 'self' "
|
||||
"https://cdnjs.cloudflare.com https://cdn.jsdelivr.net")
|
||||
"default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'self'; frame-src "
|
||||
"'self'; form-action 'self'; img-src 'self' data: blob:; font-src 'self' data:; style-src "
|
||||
"'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; worker-src "
|
||||
"'self' blob:; connect-src 'self'")
|
||||
RAW_CSP = "default-src 'none'; sandbox"
|
||||
|
||||
|
||||
|
||||
@@ -194,6 +194,11 @@ def test_cookie_writes_from_another_site_are_refused(monkeypatch):
|
||||
email, password = settings.bootstrap_admin_email, settings.bootstrap_admin_password
|
||||
browser = _client() # its own cookie jar, no bearer header: a signed-in browser
|
||||
login = _login(browser, email, password)
|
||||
# The console signs in by the httpOnly cookie alone: the session is never in a script's reach.
|
||||
assert "token" not in login and login["user"]["email"] == email
|
||||
asked = _client().post("/api/v1/auth/login",
|
||||
json={"email": email, "password": password, "issue_token": True})
|
||||
assert asked.status_code == 200 and asked.json()["token"] # Galena Connect asks for it
|
||||
body = {"parent_id": None, "kind": "workspace", "name": f"CSRF {uuid.uuid4().hex[:6]}"}
|
||||
r = browser.post("/api/v1/nodes", json=body, headers={"Sec-Fetch-Site": "same-site"})
|
||||
assert r.status_code == 403
|
||||
@@ -236,7 +241,7 @@ def test_cookie_writes_from_another_site_are_refused(monkeypatch):
|
||||
headers={**cross_site, "Origin": "http://console.example.test"})
|
||||
assert r.status_code == 200, r.text
|
||||
# Galena Connect and Sygna call with a bearer token — never refused, whatever the headers say.
|
||||
token = login["token"]
|
||||
token = browser.post("/api/v1/auth/tokens", json={"name": "bearer check"}).json()["token"]
|
||||
r = browser.delete(f"/api/v1/nodes/{ws['id']}",
|
||||
headers={**cross_site, "Origin": "http://sygna.example.com",
|
||||
"Authorization": f"Bearer {token}"})
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
"""The ReaderJS viewer shell — no database needed.
|
||||
"""The ReaderJS viewer shell and the console's own copy of third-party code - no database needed.
|
||||
|
||||
Galena no longer vendors ReaderJS's build; it serves a same-origin shell that loads the pinned code
|
||||
from READERJS_BASE_URL (frontend/static/readerjs/reader.html). These pin the parts that fail
|
||||
silently: the shell's framing headers, the CSP naming the code origin, an immutable pin, and the
|
||||
static file's default agreeing with the backend's.
|
||||
Galena serves a same-origin shell (frontend/static/readerjs/reader.html) that loads ReaderJS's build
|
||||
from READERJS_BASE_URL - by default Galena's own copy, fetched pinned and verified at image build by
|
||||
scripts/fetch_vendor.py (Atrium#68, R2: no CDN code in this origin). These pin the parts that fail
|
||||
silently: the shell's framing headers, the CSP, the pins, and the static default agreeing with the
|
||||
backend's.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
@@ -14,14 +16,27 @@ import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.config import READERJS_DEFAULT_BASE, Settings
|
||||
from app.edge import reader_csp
|
||||
from app.main import _CONSOLE_CSP, _READER_CSP, app
|
||||
|
||||
client = TestClient(app, raise_server_exceptions=False)
|
||||
SHELL = Path(__file__).resolve().parents[2] / "frontend" / "static" / "readerjs" / "reader.html"
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SHELL = ROOT / "frontend" / "static" / "readerjs" / "reader.html"
|
||||
_spec = importlib.util.spec_from_file_location(
|
||||
"fetch_vendor", ROOT / "backend" / "scripts" / "fetch_vendor.py")
|
||||
fetch_vendor = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(fetch_vendor)
|
||||
|
||||
|
||||
def test_the_default_is_pinned_to_a_full_commit_sha():
|
||||
assert re.search(r"@[0-9a-f]{40}/", READERJS_DEFAULT_BASE), READERJS_DEFAULT_BASE
|
||||
def test_the_default_is_galenas_own_copy():
|
||||
assert READERJS_DEFAULT_BASE == "dist/"
|
||||
assert re.fullmatch(r"[0-9a-f]{40}", fetch_vendor.READERJS_SHA) # an immutable commit
|
||||
|
||||
|
||||
def test_every_vendored_package_is_an_exact_version_checked_by_its_integrity():
|
||||
for url, integrity, members in fetch_vendor.NPM:
|
||||
assert url.startswith("https://registry.npmjs.org/") and re.search(r"-\d+\.\d+\.\d+\.tgz$", url)
|
||||
assert integrity.startswith("sha512-") and members
|
||||
|
||||
|
||||
def test_the_static_shell_ships_the_same_default():
|
||||
@@ -33,20 +48,29 @@ def test_the_shell_is_served_framable_by_its_own_origin_with_the_reader_csp():
|
||||
assert r.status_code == 200
|
||||
assert r.headers["x-frame-options"] == "SAMEORIGIN"
|
||||
assert r.headers["content-security-policy"] == _READER_CSP
|
||||
assert "frame-ancestors 'self'" in _READER_CSP or "frame-ancestors 'self' " in _READER_CSP
|
||||
assert "frame-ancestors 'self'" in _READER_CSP
|
||||
assert f'content="{Settings().readerjs_base_url}"' in r.text
|
||||
|
||||
|
||||
def test_the_code_origin_is_granted_to_the_viewer_only_and_never_eval():
|
||||
for directive in ("base-uri", "script-src", "style-src", "connect-src"):
|
||||
d = next(x for x in _READER_CSP.split("; ") if x.startswith(directive + " "))
|
||||
assert "https://cdn.jsdelivr.net" in d.split(" "), d
|
||||
assert "base-uri 'self';" in _CONSOLE_CSP # the console itself takes no foreign <base>
|
||||
def test_no_cdn_anywhere_by_default():
|
||||
for policy in (_CONSOLE_CSP, _READER_CSP):
|
||||
assert "https://" not in policy, policy
|
||||
assert "'unsafe-eval'" not in _READER_CSP.replace("'wasm-unsafe-eval'", "")
|
||||
console = (ROOT / "frontend" / "app.js").read_text("utf-8")
|
||||
assert "cdn.jsdelivr.net" not in console and "cdnjs.cloudflare.com" not in console
|
||||
|
||||
|
||||
def test_a_remote_override_is_granted_to_the_viewer_only():
|
||||
csp = reader_csp("https://assets.example.com/readerjs/" + "a" * 40 + "/")
|
||||
for directive in ("base-uri", "script-src", "style-src", "connect-src"):
|
||||
d = next(x for x in csp.split("; ") if x.startswith(directive + " "))
|
||||
assert "https://assets.example.com" in d.split(" "), d
|
||||
assert "base-uri 'self';" in _CONSOLE_CSP # the console itself takes no foreign <base>
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", ["javascript:alert(1)/", "//evil.example/", "https://x/\" onload=",
|
||||
"https://x/; script-src *", "data:text/html,x"])
|
||||
"https://x/; script-src *", "data:text/html,x", "../up/",
|
||||
"dist/../../x/"])
|
||||
def test_a_base_url_that_could_break_out_is_refused(bad):
|
||||
with pytest.raises(ValueError):
|
||||
Settings(readerjs_base_url=bad)
|
||||
@@ -54,3 +78,4 @@ def test_a_base_url_that_could_break_out_is_refused(bad):
|
||||
|
||||
def test_a_self_hosted_base_is_accepted_and_slash_terminated():
|
||||
assert Settings(readerjs_base_url="/readerjs-dist").readerjs_base_url == "/readerjs-dist/"
|
||||
assert Settings(readerjs_base_url="dist").readerjs_base_url == "dist/"
|
||||
|
||||
+11
-5
@@ -182,7 +182,7 @@ function showRefused() {
|
||||
function showApp() { $('login').classList.add('hidden'); $('app').classList.remove('hidden'); }
|
||||
async function doLogin(e) { e && e.preventDefault(); const err = $('loginErr'); err.classList.add('hidden');
|
||||
try { const r = await api('POST', '/auth/login', { email: $('email').value.trim(), password: $('password').value });
|
||||
state.token = r.token; state.user = r.user; await afterLogin();
|
||||
state.user = r.user; await afterLogin(); // the session is the httpOnly cookie, never a script value
|
||||
} catch (ex) { err.textContent = ex.message || 'Sign in failed'; err.classList.remove('hidden'); } }
|
||||
async function doLogout() { try { await api('POST', '/auth/logout'); } catch {} state.token = ''; state.user = null; showLogin(); }
|
||||
async function restore() {
|
||||
@@ -636,12 +636,15 @@ function _pwEye(input, btn) {
|
||||
/* ── text recognition (OCR) — top-bar tool ──────────────────────────────────────────────────────
|
||||
On-demand OCR that runs ENTIRELY in the browser — the file is never uploaded. The engine is
|
||||
Tesseract.js (Apache-2.0 WASM port of Tesseract's LSTM engine; language data is Apache-2.0,
|
||||
downloaded on demand), lazy-loaded from a CDN like PDF.js. PDFs reuse the PDF.js loader: each page
|
||||
loaded on demand), lazy-loaded from Galena's own static/vendor/ like PDF.js. PDFs reuse the PDF.js loader: each page
|
||||
is rendered to a canvas, then OCR'd. Higher-accuracy server/cloud engines stay operator opt-ins
|
||||
(see OCR.md), never a default — cloud OCR would send documents off the box. */
|
||||
const OCRX = { lang: 'eng', file: null };
|
||||
const OCR_LANGS = [['eng', 'English'], ['pol', 'Polish'], ['deu', 'German'], ['fra', 'French'], ['spa', 'Spanish']];
|
||||
const TESSERACT_URL = 'https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js';
|
||||
// Served by Galena itself (static/vendor/, pinned + verified at image build by
|
||||
// backend/scripts/fetch_vendor.py): no CDN code runs in this origin (Atrium#68, R2).
|
||||
const _vendor = (p) => new URL('static/vendor/' + p, document.baseURI).href;
|
||||
const TESSERACT_URL = _vendor('tesseract/tesseract.min.js');
|
||||
|
||||
function viewOcr(C) {
|
||||
setCrumb([{ label: 'Text recognition (OCR)' }]);
|
||||
@@ -684,8 +687,8 @@ async function runOcr() {
|
||||
async function _ocrSources(file, setP) {
|
||||
if (file.type === 'application/pdf' || /\.pdf$/i.test(file.name)) {
|
||||
setP('Rendering PDF…');
|
||||
await loadScript('https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js');
|
||||
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
|
||||
await loadScript(_vendor('pdfjs/pdf.min.js'));
|
||||
pdfjsLib.GlobalWorkerOptions.workerSrc = _vendor('pdfjs/pdf.worker.min.js');
|
||||
const pdf = await pdfjsLib.getDocument({ data: await file.arrayBuffer() }).promise;
|
||||
const out = []; const max = Math.min(pdf.numPages, 20);
|
||||
for (let i = 1; i <= max; i++) {
|
||||
@@ -704,6 +707,9 @@ async function ocrWithTesseract(file, lang, setP) {
|
||||
const sources = await _ocrSources(file, setP);
|
||||
setP('Loading language…');
|
||||
const worker = await Tesseract.createWorker(lang || 'eng', 1, {
|
||||
workerPath: _vendor('tesseract/worker.min.js'),
|
||||
corePath: _vendor('tesseract-core'),
|
||||
langPath: _vendor('tessdata'),
|
||||
logger: (m) => { if (m && m.status && typeof m.progress === 'number') setP(m.status + ' ' + Math.round(m.progress * 100) + '%'); },
|
||||
});
|
||||
try {
|
||||
|
||||
@@ -6,17 +6,18 @@
|
||||
<!--
|
||||
Galena's same-origin SHELL for the ReaderJS viewer (github.com/Alpaq92/ReaderJS, MIT).
|
||||
|
||||
Galena does not vendor ReaderJS's libraries. This page stays on Galena's origin so the console
|
||||
can frame it (frame-ancestors 'self') and talk to it over postMessage exactly as before; it then
|
||||
fetches ReaderJS's built `reader.html` from the base URL below, pins every relative asset to that
|
||||
base with <base href>, and writes it into itself. Only CODE comes from the base URL: documents
|
||||
still reach the viewer as bytes over postMessage and never leave the box.
|
||||
ReaderJS is not committed here: backend/scripts/fetch_vendor.py puts its built `dist-embed/` at a
|
||||
pinned commit into ./dist/ when the image is built (and for local development). This page stays
|
||||
on Galena's origin so the console can frame it (frame-ancestors 'self') and talk to it over
|
||||
postMessage; it fetches ReaderJS's `reader.html` from the base below, pins every relative asset
|
||||
to that base with <base href>, and writes it into itself. Documents still reach the viewer as
|
||||
bytes over postMessage and never leave the box; since Atrium#68 (R2) the code does not either -
|
||||
the default base is Galena's own copy, so no CDN code runs in this origin.
|
||||
|
||||
The base must be IMMUTABLE — a full commit SHA, never a branch or `latest` — because whatever it
|
||||
serves runs in Galena's origin. The backend replaces the content below with READERJS_BASE_URL when
|
||||
that is set (see backend/app/main.py); a static host (Netlify, http.server) serves this default.
|
||||
An override (READERJS_BASE_URL, substituted by the backend, see backend/app/main.py) must be
|
||||
IMMUTABLE - a full commit SHA, never a branch or `latest` - because whatever it serves runs here.
|
||||
-->
|
||||
<meta name="readerjs-base" content="https://cdn.jsdelivr.net/gh/Alpaq92/ReaderJS@89d1981e9db55f3eab371eac0811eb72733d849f/dist-embed/">
|
||||
<meta name="readerjs-base" content="dist/">
|
||||
<title>ReaderJS</title>
|
||||
<script>
|
||||
(function () {
|
||||
|
||||
@@ -27,6 +27,10 @@ if [ -z "${GALENA_BACKEND_URL:-}" ] && [ "${GALENA_DEMO:-1}" != "0" ]; then
|
||||
echo "Netlify prepare: DEMO MODE on (in-browser mock injected, no backend)."
|
||||
fi
|
||||
|
||||
# 1c) The console's third-party browser code (ReaderJS, tesseract.js, PDF.js), pinned and verified,
|
||||
# into frontend/static/ - the console never loads code from a CDN (Atrium#68, R2).
|
||||
python3 backend/scripts/fetch_vendor.py frontend/static
|
||||
|
||||
# 2) Redirects in the publish dir: API proxy (if a backend is configured) + SPA fallback last.
|
||||
{
|
||||
if [ -n "${GALENA_BACKEND_URL:-}" ]; then
|
||||
|
||||
Reference in New Issue
Block a user