The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
Launcher, server hardening, settings backup, coordinate parsing parity (#15)
OsintMeThat2199a6a69c6b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d5d2f12..ca7f3cc 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -16,9 +16,9 @@ jobs:strategy:fail-fast: falsematrix:- # The three OSes we ship binaries for, plus both ends of the Python range- # pyproject claims. Testing one Linux/3.12 box and shipping a Windows exe- # was a guess; this is the part that makes "works everywhere" checkable.+ # The three OSes we ship binaries for, plus the floor and ceiling of the+ # Python range pyproject claims. Testing one Linux/3.12 box and shipping a+ # Windows exe was a guess; this is what makes "works everywhere" checkable.# Filesystem behaviour is where they actually differ — engine/scrapers.py# swaps directories, and Windows won't delete an open file.os: [ubuntu-latest, windows-latest, macos-latest]@@ -26,6 +26,8 @@ jobs:include:- os: ubuntu-latestpython: "3.11" # the floor in requires-python+ - os: ubuntu-latest+ python: "3.13" # the ceiling we've tested againststeps:- uses: actions/checkout@v4- uses: astral-sh/setup-uv@v5diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex ddb97de..4b612b1 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -54,6 +54,10 @@ jobs:asset: azimut-windows-x86_64.exe- os: macos-latestasset: azimut-macos-arm64+ # macos-latest is Apple Silicon; macos-13 is the last Intel runner,+ # so Intel Macs get a native binary too (PyInstaller can't cross-build).+ - os: macos-13+ asset: azimut-macos-x86_64steps:- uses: actions/checkout@v4- uses: actions/setup-node@v4diff --git a/.gitignore b/.gitignoreindex f1c9dd1..824c2c3 100644--- a/.gitignore+++ b/.gitignore@@ -9,64 +9,29 @@ secrets/# Python__pycache__/*.py[cod]-*$py.class*.egg-info/-.eggs/.venv/-venv/-env/-.Pythonbuild/dist/*.whl.pytest_cache/.mypy_cache/.ruff_cache/-.tox/-pip-log.txt# Node / JSnode_modules/npm-debug.log*-yarn-debug.log*-yarn-error.log*-pnpm-debug.log*-.pnpm-store/-dist/-build/-.next/-.nuxt/-.turbo/-.parcel-cache/# Editors / IDE-.vscode/-!.vscode/extensions.json.idea/*.swp-*.swo*~.DS_StoreThumbs.db# Workspace / OS*.code-workspace-.cache/-.tmp/-tmp/*.log-logs/--# Data / local artifacts-*.sqlite3-*.db-data/-*.csv-!docs/**/*.csv--# Docker-*.pid-.docker/# Misc*.bakdiff --git a/README.md b/README.mdindex 56bdf04..5a836e7 100644--- a/README.md+++ b/README.md@@ -1,54 +1,78 @@# Azimut-**The OSINT investigator's workbench.** One case, one folder, every tool.-Local-first: your media and your investigations never leave your machine.+The OSINT investigator's workbench: one case, one folder, every tool.+Local-first, so your media and your investigations stay on your machine.-Built for the open-source-investigation community — GeoConfirmed contributors,-journalists, researchers.+Built for the open-source-investigation community: GeoConfirmed contributors,+journalists, researchers. Reopen a case months later and everything is still+there, in one plain folder you can zip, git, or share.-> Close Azimut. Reopen the case six months later. Everything is there: the-> downloaded media, the annotated proofs, the entities and their links, the-> notes, the exports — in one plain folder you can zip, git, or share.--*The name is the French word **azimut** — the compass bearing you sight along to-fix a point on the map (English *azimuth*). A fitting namesake for a geolocation-workbench: fix a direction, fix a location.*+*The name is the French word for azimuth, the compass bearing you sight along+to fix a point on the map.*## v0.1.1 — Proof Studio| Tool | What it does ||------|--------------|-| **Media Library** | Import local files or download by URL (X, Telegram, TikTok, YouTube, Instagram… via yt-dlp, with a gallery-dl fallback for image-only posts) → clean local file + metadata + SHA-256. Multi-photo posts open a picker. |-| **Inspect** | Scratch workspace over any photo/video: frame adjustments, editable crop, sharpest-frame capture, hand-made collage with per-piece warp/scale/rotate, and **auto-stitch** to solve a panorama's layout for you (then hand-tune it) — nothing enters the case until you save. |-| **Satellite** | Coordinates or place name → imagery crop, with select-area capture, map rotation, measurement tools, and reference-image overlays. Esri/OSM by default; add your own Mapbox/Google key for more basemaps (stored locally, never shared). |-| **Proof Composer** | Compose panels in a grid or free layout, annotate with colored shapes and text (same color = same feature), reorderable legend → export `proof.png` + a re-editable spec. |-| **Post Composer** | Turn a proof into a publishable thread: coordinates in all formats, plus code, attribution, character count, RTL-safe text. Copy-paste ready — Azimut never posts for you. |--Every tool works **one-shot** (no setup, scratch session) or inside a **case**-— a plain directory holding the whole investigation.--**New in v0.1.1** — a polish pass over the v1 tools:--- **Satellite** — OSM labels overlay, true browser fullscreen, Esri overzoom- (upscales past World Imagery's last level instead of a "not available" tile),- and imagery acquisition dates surfaced on the map and in captures.-- **Keyed providers** — a Settings tab for Mapbox/Google keys with per-provider- toggles, monthly usage counters, a soft block at 90% of the free tier, an eco- mode that falls back to free imagery when zoomed out, and a disk tile cache.- Free by default: keys stay optional and local.-- **Proof Composer** — free layout mode (drag panels anywhere, overlap with- z-order), corner-drag panel resize, and satellite panels that auto-caption- with provider · coordinates · imagery date.-- **Inspect** — shift-click a block of collage pieces to move, scale and rotate+| **Media Library** | Import local files or download by URL (X, Telegram, TikTok, YouTube, Instagram and more via yt-dlp, with a gallery-dl fallback for image-only posts). Each item gets a clean local file, metadata and a SHA-256. Multi-photo posts open a picker. |+| **Inspect** | A scratch workspace over any photo or video: frame adjustments, editable crop, sharpest-frame capture, hand-made collage with per-piece warp/scale/rotate, and auto-stitch to solve a panorama's layout for you. Nothing enters the case until you save. |+| **Satellite** | Coordinates or a place name become an imagery crop, with select-area capture, map rotation, measurement tools and reference-image overlays. Esri/OSM by default; add a Mapbox or Google key for more basemaps. |+| **Proof Composer** | Compose panels in a grid or free layout, annotate with colored shapes and text (same color = same feature), write a per-color legend, and export `proof.png` plus a re-editable spec. |+| **Post Composer** | Turn a proof into a publishable thread: coordinates, plus code, attribution, character count, RTL-safe text, ready to paste into X. |++Every tool works one-shot (a scratch session, no setup) or inside a case, a+plain directory holding the whole investigation.++New in v0.1.1, a polish pass over the v1 tools:++- Satellite: OSM labels overlay, true browser fullscreen, Esri overzoom past+ World Imagery's last level, and imagery acquisition dates on the map and in+ captures.+- Keyed providers: a Settings tab for Mapbox/Google keys with per-provider+ toggles, monthly usage counters, a soft block at 90% of the free tier, an+ eco mode that uses free imagery when zoomed out, and a disk tile cache.+ Keys stay optional and local.+- Proof Composer: free layout mode with z-order, corner-drag panel resize,+ and satellite panels that auto-caption with provider, coordinates and+ imagery date.+- Inspect: shift-click a block of collage pieces to move, scale and rotatethem as one.## Install & run```bashpip install azimut-azimut # starts on http://127.0.0.1:8477 and opens your browser+azimut # starts on http://127.0.0.1:8477 and opens a browser tab```+Azimut runs in a normal browser tab (Firefox/Chrome); there is no separate+window. Closing the terminal it prints its URL into stops the app.++### Ready-to-run binary (no Python)++Each release attaches a self-contained binary per OS. Download it from the+[Releases page](https://github.com/OsintMeThat/azimut/releases) and run it; it+opens Azimut in your browser.++| OS | Asset |+|----|-------|+| Windows | `azimut-windows-x86_64.exe` |+| macOS (Apple Silicon) | `azimut-macos-arm64` |+| macOS (Intel) | `azimut-macos-x86_64` |+| Linux | `azimut-linux-x86_64` |++First run, the binaries are **unsigned**, so the OS warns before letting them+open:+- **macOS**: right-click the file → **Open** → **Open** (Gatekeeper only+ offers "Open" from the context menu for unidentified developers), or run+ `xattr -d com.apple.quarantine ./azimut-macos-*` once.+- **Windows**: SmartScreen shows "Windows protected your PC"; click **More+ info** → **Run anyway**.+- **Linux**: mark it executable with `chmod +x azimut-linux-x86_64`.++Optional: install **ffmpeg** on your `PATH` for video thumbnails and video+metadata (dimensions/duration). Everything else works without it.+From source:```bash@@ -67,33 +91,33 @@ cd frontend && npm run dev # UI on :5173### Capture extension (optional)-A small browser extension (Chrome/Edge + Firefox) files the map you are-looking at straight into a case: external map sites (Google Maps & Earth,-Bing, Yandex, OSM, Apple Maps, Zoom Earth, Satellites.pro — one screenshot-per click, coordinates parsed from the URL), and it is also what powers the-Capture button on the Google (Maps JS) basemap. Install it from **Settings →-Capture extension** (download the zip, load unpacked, pair with the token-shown there) — full instructions in [extension/README.md](extension/README.md).+A browser extension (Chrome/Edge and Firefox) captures external map sites+straight into a case: Google Maps & Earth, Bing, Yandex, OSM, Apple Maps,+Zoom Earth, Copernicus Browser and Satellites.pro, one screenshot per click+with coordinates parsed from the URL. It also powers the Capture button on+the Google (Maps JS) basemap. Install it from **Settings → Capture extension**+(download the zip, load unpacked, pair with the token shown there); full+instructions in [extension/README.md](extension/README.md).## Building & releasingThe Svelte frontend builds into `src/azimut/static/` (git-ignored) and isbundled into the Python wheel via hatchling `artifacts`. So `npm run build`-**must** run before building the package, or the shipped UI is stale/missing.+**must** run before building the package, or the shipped UI is stale.```bash-cd frontend && npm run build && cd .. # refresh the bundled UI+cd frontend && npm run build && cd .. # refresh the bundled UIuv sync --frozen # the exact deps CI tested-python -m build # wheel + sdist (UI included)+pipx run build # wheel + sdist (UI included)uv run pyinstaller packaging/azimut.spec # optional: standalone binary```### Dependencies-`pyproject.toml` declares **ranges** (that's the contract for `pip install-azimut` users); `uv.lock` pins the **exact** set, and is what CI and the release+`pyproject.toml` declares **ranges** (the contract for `pip install azimut`+users); `uv.lock` pins the **exact** set, and is what CI and the releasebuilds install. The wheel only declares its dependencies, but the binary-*contains* them — so building it outside the lock ships whatever the resolver+*contains* them, so building it outside the lock ships whatever the resolverhappened to pick that day.```bash@@ -107,9 +131,9 @@ Raising an upper bound is a deliberate act: bump it in `pyproject.toml`, run"latest deps" CI job re-resolves past the lock, so upstream breakage shows upas a red run of ours rather than a broken install for someone else.-**yt-dlp and gallery-dl are deliberately unbounded** — they track sites that-change, so an old version is a broken version. They're also updatable from-inside the app (Settings → About → Downloaders), which is what keeps a+**yt-dlp and gallery-dl are deliberately unbounded**: they track sites that+change, so pinning them just schedules a breakage. They can also be updated+from inside the app (Settings → About → Downloaders), which is what keeps amonths-old binary working.Releases are automated: push a semver tag and GitHub Actions@@ -127,21 +151,22 @@ One-time setup: register the repo as a## Principles-1. **Local-first, privacy-first** — no account, no telemetry, no upload; the- server binds to `127.0.0.1` only.-2. **The case is the product** — plain JSON + media files, versionable,+1. **Local-first, privacy-first.** No account, no telemetry, no upload; the+ server binds to `127.0.0.1` only, and Azimut never posts anywhere on your+ behalf.+2. **The case is the product.** Plain JSON + media files, versionable,portable.-3. **One tab = one tool**, useful in 30 seconds.-4. **Orchestrator, not replacer** — integrate specialized services, don't clone- them.-5. **Tools emit facts, the analyst decides** — no automated "magic button".-6. **Honest output** — every artifact records how it was produced.-7. **Free and open source** — no paid keys required, ever. Optional- bring-your-own-key providers.+3. One tab = one tool, useful in 30 seconds.+4. **Orchestrator, not replacer.** Integrate specialized services rather than+ cloning them.+5. Tools emit facts; the analyst decides. No automated "magic button".+6. **Honest output.** Every artifact records how it was produced.+7. Free and open source. No paid key is ever required; bring your own for+ more basemaps.Full spec: [docs/SPEC.md](docs/SPEC.md).## License-[AGPL-3.0-only](LICENSE) — free and open source; hosted or modified versions+[AGPL-3.0-only](LICENSE): free and open source; hosted or modified versionsmust share their source.diff --git a/docs/ONTOLOGY.md b/docs/ONTOLOGY.mdindex 8fdff03..a9e25c2 100644--- a/docs/ONTOLOGY.md+++ b/docs/ONTOLOGY.md@@ -5,8 +5,9 @@> extensible, **versioned** — grown from real tool needs, never a whiteboard> taxonomy. Nothing enters a case without a human click (SPEC principle 5).-**Schema version: `0`** (draft, 2026-07-10, aligns with spec v0.2). Bump on any-breaking change to entity/link shape; ship a migration when you do.+**Schema version: `1`** (what `case.json` carries as `{"azimut": {"schema": 1}}`;+aligns with spec v0.2). Bump on any breaking change to entity/link shape; ship a+migration when you do.Legend: ✅ implemented in code · 🔶 machinery exists, unused · ⬜ proposed.@@ -50,7 +51,7 @@ just doesn't get a custom renderer for them (SPEC §5 escape hatch, keep it).|---|---|---|---|---|| `media` | ✅ | media-library | `path`, `sha256`, `source_url?` | yes (+ sidecar) || `capture` | ✅ | satellite | `coords`, `lat`, `lon`, `plus_code`, `zoom`, `bearing`, `path` | yes (image) |-| `place` | ✅ | satellite | `coords`, `lat`, `lon`, `plus_code`, `dms`, `zoom`, `bearing`, `notes?` | no (a point) |+| `place` | ✅ | satellite | `coords`, `lat`, `lon`, `plus_code`, `zoom`, `bearing`, `notes?` | no (a point) || `proof` | ✅ | proof-composer | `spec` (json), `path` (png) | yes || `post` | ✅ | post-composer | `draft` (json) | yes || `inspect-session` | ✅ | inspect | `spec` (json) | yes |@@ -156,7 +157,9 @@ How it is wired (`engine/links.py`):(UTC), `status`, optional `source` (a URL). Borrow the *shape* of W3C PROV(entity/activity/agent) conceptually — don't adopt the standard wholesale.- **Confidence** = `status`: `confirmed` (analyst-made or analyst-accepted) vs- `suggested` (a tool proposed it, awaiting a click). ✅ Binary on purpose —+ `suggested` (a tool proposed it, awaiting a click). 🔶 `suggested` has no+ producer yet — the sidebar section and the PATCH validator exist, but no tool+ emits it until the v2 EXIF/OCR tools land. ✅ Binary on purpose —honest and simple; resist finer grading until a tool truly needs it.**A derivation is `confirmed`**: `derived-from`/`depends-on` record what theanalyst's own click just made, not what a tool inferred. `suggested` is fordiff --git a/docs/SPEC.md b/docs/SPEC.mdindex 463b8bc..32bf2f0 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -78,9 +78,12 @@ media/ # source videos/photos/audio + download/import metadataproofs/ # composed proofs: exported PNGs + their editable JSON specsexports/ # post drafts, reports, shared bundlesevidence.jsonl # append-only journal: sha256, timestamp, source, action (v3)-frames/ panoramas/ satellite/ ... # per-tool artifact folders, added as tools ship+inspect/ # saved Inspect session specs```+Satellite captures and extracted frames are media too, so they land in+`media/` — no per-tool imagery folders.+Rules:- **Every tool reads and writes here.** A proof spec saved once reopens for@@ -157,7 +160,7 @@ get media in, annotate the match, publish the proof.| ✅ **Inspect** | A scratch workspace over any photo/video — **nothing enters the case until Save**. **Selection** (video): scrub, step, scan *sharpest* frames (**every** frame scored in one streamed pass, on a **contrast-invariant** focus measure so a soft-but-punchy frame can't outrank a sharp flat one; picks are spread across distinct moments), capture into a transient tray; a gear tunes the whole clip (brightness…) for an optional enhanced-video export. **Frame**: per-frame brightness/contrast/saturation/gamma/sharpness/grayscale/invert, a **view-only zoom/pan/rotate** viewer (never saved — middle-drag turns the image around the grabbed point, marked by a "target", Google-Earth style; composes over any prior zoom/pan/rotate), and an **editable crop** — draw or nudge its 8 handles, **aspect-lock presets + numeric px entry**, **Enter/Apply** commits to a cropped preview, re-open (button or **double-click**) to edit the original — with a fold-out **Analyze** (histogram, EXIF, ELA *hint*). **Collage**: **multiple collages per session** (tab strip to add/switch/delete). Per piece: drag, **round corner handles warp**, **square side handles uniform-scale** (composes with the warp, holds up on an already-warped piece), a **rotate knob** on a stem that **follows the piece**; a small top bar carries only the **ghost** preview + **±1 stacking**, while the right panel keeps precise scale/rotate (±/↺↻) and all-the-way **Front/Back**; **Delete** removes it. **Shift-click selects several pieces**: a dashed **block frame** then moves / corner-scales / rotates them as one rigid unit about the block's centre (right panel mirrors it with precise ±/↺↻ + bulk remove), a plain click collapses back to one, and **Delete** clears the block. **Per-piece crop** is the same editable box (handles, aspect lock, numeric) over the piece's snapshot, baked before the warp — the quad is re-projected to the crop so proportions stay correct and it stays in place. Tray frames (thumbnails show each frame's current adjustments) compose on a full-bleed scratch surface into a hand-made panorama. Each collage exports as a **transparent PNG of just its pieces, auto-trimmed to their bounds** — no manual canvas size. ✅ **Auto-stitch** solves the pieces' layout from the imagery itself and drops them back as ordinary pieces — machine stitch first, hand-tune after; a **mode** picks the projection (**Planar** quads, still corner-warpable, vs **Cylindrical**/**Spherical** for a panning camera — see § Panorama). Pieces it can't place are **left where they were, never guessed at**, and a coincidental match is refused rather than invented. **Save**: tick which of {enhanced video, adjusted frames, each collage} to file — each re-derived full-res on the backend with provenance back to its source, into an optional folder; every collage shows a **true-to-export composited miniature** (the real backend warp, on a transparency checker) in the picker. Frames captured from a tuned clip inherit its look; collage pieces are **frozen snapshots** taken when added. The whole workspace can be **saved as a reopenable session** (`inspect-session` entity, spec in `inspect/`) — reload it later from the sidebar with every frame/adjustment/collage (all of them) intact; re-saving a reopened session **overwrites it in place** (even after a rename). Adjust/analysis controls come from self-describing filter/analysis registries. || ✅ **Satellite** | Enter/click coordinates, then **Save place** (a navigable `place` — coordinates only, no image, clickable to fly back) **or Capture** (a sourced imagery crop → `capture` image entity, **filed in `media/`** so it also lists in the Media Library and opens in Inspect). A single **split capture button** re-runs whichever mode was used last — **Capture** for a centred **standard size** (Tweet 16:9 / Square / OG card / Wide / custom), or **Select area**, which arms a **mouse marquee** to drag a rectangle (live px/dimension readout) for an optional **ratio lock** (16:9 / 4:3 / 1:1 / free) — with its arrow opening a compact **mode/size/ratio/resolution popover** (closes on outside click) and a **resolution** control (1× / 2× / provider max-zoom, sized so 2×/max always yield a sharper file on every built-in preset) that captures a deeper zoom. **Marker style** (crosshair / Google-Maps pin / none) baked in; centred-Capture **frame outline** previewed on hover. **Map rotation** — **middle-drag turns the map around the grabbed point** (sober target marker, Google-Earth style), click the bearing to **type an exact angle**, click the compass rose to reset north (capture matches the on-screen heading, bearing in provenance). **Move-pin mode** decouples the marker from center — drag it anywhere in frame (e.g. bottom of shot) and the **recorded coordinates follow the pin** for both actions. **Two dates per capture**: the **capture timestamp** and the **imagery acquisition date** (Esri best-effort, if known) — both recorded and shown. **Map workspace**: toggle an **OSM labels overlay** (roads / place names over the imagery — disabled over a street base map, where it'd only double the labels), read the imagery acquisition date under the crosshair (shown as an unobtrusive corner pill), go **true browser fullscreen** (dialogs follow the map in, and actions that would leave it — another tool, another tab — grey out), **measure** distance / area / **angle** (reported as the acute + obtuse pair), and float **reference windows** over the map (pick any case **image or video**; drag / roll-up / resize — images wheel-zoom & pan, videos get a native player) to eyeball the shot you're geolocating against the imagery — a **session-only scratch aid, never captured or saved**. The tool's side panel lists both in **collapsible** sections — **Places** (fly the map back) and **Captures** (open the full image, or **go to** their coordinates — also from the case sidebar) — each with an inline **title + note editor**; the case sidebar's info panel is the same editor for any capture/place/media. A collapsible **Open in…** list jumps to external maps we can't embed (Google/Earth, Apple, Bing, Yandex, Satellites.pro, Copernicus, Zoom Earth) at the current target. Provenance (provider, zoom, both dates, bearing, marker, center) recorded — feeds the composer. XYZ tile-provider abstraction (see note below). Editable title + notes per capture. || ✅ **Proof Composer** | The heart of v1. Compose panels in a **multi-row grid** (frames, photos, satellite crops, imported screenshots) — arrange side by side *and* stack rows (select a panel — canvas click or side list — and move it with **on-canvas arrows**) so the composite stays near-square instead of a wide bandeau. Each panel can be **resized** (corner-drag the selected panel, or ± in the side list; 40–250%) — its drawn elements scale with it, and shorter panels bottom-align in their row. A grid/free **mode switcher** can drop the grid for a **free layout**: **drag panels anywhere** (their elements follow), **overlap allowed** with array order as **z-order** (front/back per panel), select a panel to **corner-drag resize** it (aspect locked, no rotation); saved per proof, magic tweet-fit snaps back to the grid. A toggleable **tweet-crop guide** (16:9 / 4:5) dims whatever X would centre-crop; a **magic tweet-fit** button auto-repacks the panels into rows to land closest to the active guide's aspect (16:9 default) and resets panel sizes. Draw colored boxes/ellipses/lines/arrows, multi-point **curves** (rounded, click points + double-click to finish) and **text labels** (optional **frame and/or background box**, from the Elements tab) with the mouse — same color = same feature across panels. Every element stays **editable after placing**: boxes/ellipses/text via transformer handles (text corner-drag = font size), lines/arrows/curves via draggable per-vertex handles; selecting an element lets you change its **color and stroke/font size live**, **copy/paste/duplicate** it (Ctrl+C/V/D, cascading offset), and **drag it onto any panel** (it re-binds to whatever panel it's dropped over). Palette presets **+ custom color picker**. Legend **annotations are written per color** (one note per feature), **manually reorderable** from the Annotations tab, and auto-flow into up to 3 columns; a separate **element list** (id + kind) selects/copies/deletes/**reorders** individual shapes (order = z-order within their panel). Optional per-panel captions (**off by default**; a satellite crop auto-captions with provider · coordinates · **imagery acquisition date** — the date omitted when unknown, never the fetch date). A **Coordinates + Source** header (above the panels) auto-fills from them: coordinates from the first satellite panel (falls back to the next if it's deleted), source **traced through the derivation chain** back to the downloaded original (a collage/frame from a video resolves to that video's link) — a source is **always a link**, so a disk-uploaded file counts as none; both are editable and flag a **!** while empty. These carry into the **Post Composer** (on *To Post* export or when attaching the proof there). An **Advanced** panel exposes the trickier knobs: independent **caption / legend / footer font sizes**, an **editable footer** (blank = automatic imagery/source attribution), and a **signature** tick that stamps your Settings logo on the composite — pick a **corner**, size (share of doc width) and opacity, then **drag it on canvas** to nudge; stored as an anchor + offset, so it holds its corner as the document grows. Feature legend (color dot only, numbered in the Annotations tab for reference); export `proof.png` + re-editable JSON spec (`notes`/`legendOrder` per color, `layout`, panel `row`/`scale`/`x,y`, `coords`/`coordsText`, `source`, `caption/legend/footerSize`, `footer`, `signature`) saved in `proofs/`. |-| ✅ **Post Composer** | Build a GeoConfirmed-style thread from a proof. Tweet 1 = `Place - Plus code`, description, decimal coordinates (6 digits — the posting convention, unaffected by the coordinate-format preference), mention (defaults to `@GeoConfirmed`, configurable in Settings → Preferences), source. Tweet 2 = optional media (Video / Image(s), removable), with media picked from the case library. Add extra context tweets; per-tweet character count; copy-per-tweet or copy-all. **Save drafts** (in `exports/`, reopenable from the sidebar as `post` entities) and **Publish** (copies the thread and opens X compose prefilled). Copy-paste ready — Azimut never posts on your behalf. |+| ✅ **Post Composer** | Build a GeoConfirmed-style thread from a proof. Tweet 1 = `Place - Plus code`, description, decimal coordinates (6 digits — the posting convention, unaffected by the coordinate-format preference), mention (defaults to `@GeoConfirmed`, configurable in Settings → Preferences), source. Tweet 2 = optional media (Video / Image, removable), with media picked from the case library. Add extra context tweets; per-tweet character count; copy-per-tweet or copy-all. **Save drafts** (in `exports/`, reopenable from the sidebar as `post` entities) and **Publish** (copies the thread and opens X compose prefilled). Copy-paste ready — Azimut never posts on your behalf. || ✅ **Case sidebar** | Always visible; **drag its left edge to resize** (240–640 px, never past half the window — width remembered across sessions, double-click to reset). **Case Notes** (`notes.md`). **Suggestions** — tool-suggested entities, confirm or dismiss. **My work** — every saved artifact under the analyst's own **nested folders** (`/`-separated, e.g. `Sources/Telegram`) plus an **Unfiled** inbox; file items by **dragging onto a folder** or from the **details panel** (folder field); unfiling deletes nothing, removing a folder just unfiles its subtree. **Details panel** — selection editor for any artifact: preview, title/notes, provenance (created by/at, source), My-work folder, open-in-tool / open-file / go-to-coords, and **Delete everywhere** (drops the file — danger confirm). Saved artifacts are reopened **in their tools** (Open lists in Proof/Post/Inspect — each row deletable — plus the Media & Satellite shelves); the sidebar no longer duplicates a by-tool listing. Styled confirm dialogs, not browser popups. Create/open/promote/**rename**/**delete** cases from the switcher — names must be **unique** (case-insensitive, enforced on create/rename/promote); delete wipes the **whole case folder** and everything in it, gated behind typing `DELETE` in uppercase. |v1 notes:@@ -315,7 +318,8 @@ it stops making sense. One line each.the account and providers change it silently, so it's the user's to correct),**About** (version, workspace path, license,links, + **Downloaders** ✅ — one-click update for yt-dlp/gallery-dl, see- below). Core features never require a key (principle 7); key-less providers+ below). **Settings backup** ✅ — export `settings.json` to a file and import+ it on another machine, so keys and preferences survive a machine move. Core features never require a key (principle 7); key-less providersare always the default.**Display preferences are presentation only**: artifacts keep decimal degreesand metres on disk, so a case reads the same for every reader. A default@@ -349,6 +353,17 @@ it stops making sense. One line each.version. Keeps a months-old binary useful instead of quietly broken.- **Storage**: plain files as described in §4. No database server; SQLite only forrebuildable indexes/caches.+- **Security posture** ✅ (single-user localhost workbench):+ - The server binds `127.0.0.1` and a middleware refuses non-loopback `Host`+ headers (DNS rebinding) and cross-origin web `Origin`s; the token-gated+ ingest island stays open to browser-extension origins only.+ - `settings.json` and the workspace are chmod'd owner-only; Pillow decoding+ is capped at 100 MP (decompression bombs).+ - Accepted risks, on purpose: `GET /settings` returns keys in cleartext (the+ Settings UI edits them in place; localhost + the guard above is the wall),+ the scraper updater executes hash-verified code from PyPI, and the tile+ proxy / media download fetch user-supplied URLs — SSRF only matters if the+ localhost assumption is ever broken.## 8. Milestones@@ -384,7 +399,8 @@ it stops making sense. One line each.per-case** ✅ (30-day TTL under the workspace, never Google — see[IMAGERY_PROVIDERS.md](IMAGERY_PROVIDERS.md)). Sentinel-2 via a key-less WMTSstays open.-- One-shot scratch cases: where do they live, when are they cleaned up, what does- "promote to case" look like?+- **Decided: one-shot scratch cases live under the workspace `scratch/`,+ promotable to a named case; empty ones idle for 14 days are reaped at server+ start** ✅ (a scratch holding any entity, link or file is never touched).- Déjà Vu community index: needs infra + moderation; out of scope until v4.- Name/handle availability check: GitHub org/repo `azimut`, x.com handle, domain.diff --git a/extension/README.md b/extension/README.mdindex 649731f..596c0a2 100644--- a/extension/README.md+++ b/extension/README.md@@ -14,7 +14,8 @@ fixes it and the extension never needs a reinstall.It serves two flows:- **External map sites** — Google Maps, Google Earth (web), Bing Maps, Yandex- Maps, OpenStreetMap, Apple Maps, Zoom Earth, Copernicus Browser, and+ Maps, OpenStreetMap, Apple Maps, Zoom Earth, Copernicus Browser,+ Satellites.pro, andwhatever Azimut learns to recognize later. Click the toolbar icon (or`Alt+Shift+A`): a popup shows what Azimut parsed from the URL (correctable),a case picker, and one button — drag the area to capture. The resultdiff --git a/extension/background.js b/extension/background.jsindex 720ab20..271a047 100644--- a/extension/background.js+++ b/extension/background.js@@ -75,7 +75,11 @@ async function ingest(blob, meta) {if (r.status === 401) throw new Error("pairing token rejected — re-pair in the extension options");if (!r.ok) throw new Error(`Azimut refused the capture (${r.status}): ${(await r.text()).slice(0, 200)}`);const body = await r.json();- if (meta.caseId) api.storage.local.set({ lastCaseId: meta.caseId });+ // Remember where this capture landed — including a freshly minted scratch+ // (body.case_id), so repeated captures reuse it instead of minting one each.+ if (body.case_id || meta.caseId) {+ api.storage.local.set({ lastCaseId: body.case_id || meta.caseId });+ }return body;}diff --git a/frontend/src/components/CaseSidebar.svelte b/frontend/src/components/CaseSidebar.svelteindex f535bb4..cd93cdf 100644--- a/frontend/src/components/CaseSidebar.svelte+++ b/frontend/src/components/CaseSidebar.svelte@@ -377,8 +377,17 @@const detailsFilePath = $derived(infoData?.path ?? (infoEntity?.type === 'capture' ? infoEntity.attrs?.path : null));- // which types get title/notes editors straight from the sidebar- const EDITABLE = new Set(['capture', 'place', 'media']);+ // Every artifact type gets the title/notes editor (UI.md §4). Media and+ // captures go through their sidecar PATCH; the rest edit the entity itself.+ const EDITABLE = new Set([+ 'capture',+ 'place',+ 'media',+ 'proof',+ 'post',+ 'inspect-session',+ 'note',+ ]);// The derivation chain around the selection: what it was made from, what was// made from it, and the sources it has outlived (ONTOLOGY §3). An entity withdiff --git a/frontend/src/lib/extension.test.js b/frontend/src/lib/extension.test.jsnew file mode 100644index 0000000..5c2bc4e--- /dev/null+++ b/frontend/src/lib/extension.test.js@@ -0,0 +1,174 @@+// Tests for the capture extension's background worker (extension/background.js).+//+// The worker is a classic MV3 script — no exports — so the suite evaluates its+// source with a stubbed `chrome` global and exercises the internals it returns.+// This keeps the extension test-covered from the existing frontend harness+// instead of a second npm project inside extension/.+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';++const here = dirname(fileURLToPath(import.meta.url));+const source = readFileSync(join(here, '../../../extension/background.js'), 'utf8');++function makeChrome(overrides = {}) {+ return {+ storage: {+ local: {+ get: vi.fn(async (defaults) => ({+ ...defaults,+ backendUrl: 'http://127.0.0.1:8477/',+ token: 'tok-123',+ })),+ set: vi.fn(),+ },+ session: { get: vi.fn(async () => ({})), set: vi.fn(), remove: vi.fn() },+ },+ tabs: { captureVisibleTab: vi.fn(async () => 'data:image/png;base64,xyz') },+ scripting: { executeScript: vi.fn() },+ notifications: { create: vi.fn() },+ runtime: {+ getManifest: () => ({ version: '9.9.9' }),+ getURL: (p) => `chrome-extension://id/${p}`,+ onMessage: { addListener: vi.fn() },+ },+ ...overrides,+ };+}++/** Evaluate background.js with stubs; returns its internal functions. */+function load({ chrome = makeChrome(), fetchImpl, imageBitmap, canvasLog } = {}) {+ const OffscreenCanvasStub = class {+ constructor(w, h) {+ canvasLog?.push({ canvas: [w, h] });+ }+ getContext() {+ return {+ drawImage: (...args) => canvasLog?.push({ drawImage: args.slice(1) }),+ };+ }+ convertToBlob({ type }) {+ return Promise.resolve({ type });+ }+ };+ const factory = new Function(+ 'chrome',+ 'browser',+ 'fetch',+ 'createImageBitmap',+ 'OffscreenCanvas',+ `${source}\n;return { cropDataUrl, ingest, handle, settings };`+ );+ return factory(+ chrome,+ undefined,+ fetchImpl ?? vi.fn(),+ async () => imageBitmap ?? { width: 2000, height: 1200 },+ OffscreenCanvasStub+ );+}++describe('cropDataUrl', () => {+ let canvasLog;+ const fetchImpl = vi.fn(async () => ({ blob: async () => 'BLOB' }));+ beforeEach(() => {+ canvasLog = [];+ fetchImpl.mockClear();+ });++ it('scales the CSS-px rect by the measured image/viewport ratio', async () => {+ const { cropDataUrl } = load({ fetchImpl, canvasLog });+ // image 2000 px wide over a 1000 px viewport → scale 2+ const blob = await cropDataUrl('data:x', { x: 10, y: 20, w: 100, h: 50 }, 1000);+ expect(blob.type).toBe('image/png');+ expect(canvasLog).toContainEqual({ canvas: [200, 100] });+ expect(canvasLog).toContainEqual({ drawImage: [20, 40, 200, 100, 0, 0, 200, 100] });+ });++ it('clamps the crop to the captured frame', async () => {+ const { cropDataUrl } = load({ fetchImpl, canvasLog });+ // rect runs past the right edge: sw shrinks to what the image has left+ await cropDataUrl('data:x', { x: 950, y: 0, w: 100, h: 50 }, 1000);+ expect(canvasLog).toContainEqual({ drawImage: [1900, 0, 100, 100, 0, 0, 100, 100] });+ });++ it('refuses a selection smaller than 8 px on either side', async () => {+ const { cropDataUrl } = load({ fetchImpl, canvasLog });+ await expect(cropDataUrl('data:x', { x: 0, y: 0, w: 2, h: 50 }, 1000)).rejects.toThrow(+ /selection too small/+ );+ });+});++describe('ingest', () => {+ const meta = { url: 'https://www.google.com/maps/@48.85,2.29,17z', caseId: '' };+ const blob = new Blob(['\x89PNG'], { type: 'image/png' }); // a real Blob: FormData.append rejects a bare string++ it('posts the form the API expects and remembers the filed case', async () => {+ const chrome = makeChrome();+ const fetchImpl = vi.fn(async () => ({+ ok: true,+ status: 200,+ json: async () => ({ case_id: 'scratch_fresh1', title: 'T', path: 'media/x.png' }),+ }));+ const { ingest } = load({ chrome, fetchImpl });++ await ingest(blob, { ...meta, title: 'Spot', lat: 48.85, lon: 2.29 });++ const [url, options] = fetchImpl.mock.calls[0];+ expect(url).toBe('http://127.0.0.1:8477/api/ingest/screenshot'); // trailing slash trimmed+ expect(options.headers['X-Azimut-Token']).toBe('tok-123');+ const form = options.body;+ expect(form.get('url')).toBe(meta.url);+ expect(form.get('case_id')).toBe('');+ expect(form.get('title')).toBe('Spot');+ expect(form.get('lat')).toBe('48.85');+ expect(form.get('extension')).toBe('9.9.9');+ expect(form.has('site')).toBe(false); // the URL is the source of truth++ // a capture into "new scratch" must reuse that scratch next time+ expect(chrome.storage.local.set).toHaveBeenCalledWith({ lastCaseId: 'scratch_fresh1' });+ });++ it('fails up front when unpaired', async () => {+ const chrome = makeChrome();+ chrome.storage.local.get = vi.fn(async (d) => ({ ...d, token: '' }));+ const { ingest } = load({ chrome });+ await expect(ingest(blob, meta)).rejects.toThrow(/not paired/);+ });++ it('maps a 401 to a re-pair message', async () => {+ const fetchImpl = vi.fn(async () => ({ ok: false, status: 401 }));+ const { ingest } = load({ fetchImpl });+ await expect(ingest(blob, meta)).rejects.toThrow(/pairing token rejected/);+ });+});++describe('handle: capture-tab (the app relay)', () => {+ it('refuses a page that is not the local app', async () => {+ const { handle } = load({});+ const res = await handle(+ { type: 'capture-tab' },+ { tab: { url: 'https://evil.example/', windowId: 1 } }+ );+ expect(res.ok).toBe(false);+ });++ it('captures for the localhost app tab', async () => {+ const chrome = makeChrome();+ const { handle } = load({ chrome });+ const res = await handle(+ { type: 'capture-tab' },+ { tab: { url: 'http://127.0.0.1:8477/', windowId: 7 } }+ );+ expect(res).toEqual({ ok: true, dataUrl: 'data:image/png;base64,xyz' });+ expect(chrome.tabs.captureVisibleTab).toHaveBeenCalledWith(7, { format: 'png' });+ });++ it('rejects unknown message types', async () => {+ const { handle } = load({});+ const res = await handle({ type: 'nope' }, { tab: null });+ expect(res.ok).toBe(false);+ });+});diff --git a/frontend/src/lib/maplinks.js b/frontend/src/lib/maplinks.jsindex 61e4807..c410b05 100644--- a/frontend/src/lib/maplinks.js+++ b/frontend/src/lib/maplinks.js@@ -34,5 +34,10 @@ export function mapLinks(lat, lon, zoom = 17) {url: `https://browser.dataspace.copernicus.eu/?zoom=${z}&lat=${lat}&lng=${lon}`,},{ id: 'zoom_earth', label: 'Zoom Earth', url: `https://zoom.earth/#view=${lat},${lon},${z}z` },+ {+ id: 'satellites_pro',+ label: 'Satellites.pro',+ url: `https://satellites.pro/#${lat},${lon},${z}`,+ },];}diff --git a/frontend/src/lib/maplinks.test.js b/frontend/src/lib/maplinks.test.jsindex 75cce32..639f1ed 100644--- a/frontend/src/lib/maplinks.test.js+++ b/frontend/src/lib/maplinks.test.js@@ -13,6 +13,7 @@ describe('mapLinks', () => {'google','google_earth','google_sat',+ 'satellites_pro','sentinel','yandex','zoom_earth',@@ -20,11 +21,9 @@ describe('mapLinks', () => {);});- it('deliberately excludes the in-tool tile providers (Esri, OSM) and duplicates', () => {+ it('deliberately excludes the in-tool tile providers (Esri, OSM)', () => {expect(byId.esri).toBeUndefined();expect(byId.osm).toBeUndefined();- // Satellites.pro was dropped: its basemaps are the other links' imagery- expect(byId.satellites_pro).toBeUndefined();});it('embeds the coordinates in each URL', () => {diff --git a/frontend/src/lib/prefs.test.js b/frontend/src/lib/prefs.test.jsdeleted file mode 100644index 3d61c40..0000000--- a/frontend/src/lib/prefs.test.js+++ /dev/null@@ -1,58 +0,0 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';--// state.svelte.js reaches for the API on import-time module state, so the-// transport is stubbed and the module re-imported fresh per test.-vi.mock('./api.js', () => ({ api: { get: vi.fn() } }));--async function freshState() {- vi.resetModules();- return import('./state.svelte.js');-}--describe('prefsReady — tools must not race the settings fetch', () => {- let api;- beforeEach(async () => {- ({ api } = await import('./api.js'));- api.get.mockReset();- });-- it('does not resolve before the preferences land', async () => {- let release;- api.get.mockReturnValue(new Promise((r) => (release = r)));- const { prefsReady, loadPrefs, prefs } = await freshState();-- let ready = false;- prefsReady.then(() => (ready = true));- loadPrefs();- await Promise.resolve();- expect(ready).toBe(false); // a tool awaiting this is still parked-- release({ home_view: { lat: -33.8568, lon: 151.2153, zoom: 17 } });- await prefsReady;- // the home view is readable the moment prefsReady resolves — that ordering- // is what keeps the Satellite map off its built-in default- expect(prefs.homeView).toEqual({ lat: -33.8568, lon: 151.2153, zoom: 17 });- });-- it('resolves even when the settings read fails, leaving the defaults', async () => {- api.get.mockRejectedValue(new Error('offline'));- const { prefsReady, loadPrefs, prefs } = await freshState();-- await loadPrefs().catch(() => {});- await expect(prefsReady).resolves.toBeUndefined(); // never hangs a tool- expect(prefs.homeView).toEqual({ lat: 48.8584, lon: 2.2945, zoom: 16 });- });-});--describe('applyPrefs', () => {- it('adopts a settings payload and ignores absent fields', async () => {- const { applyPrefs, prefs } = await freshState();- applyPrefs({ coord_format: 'mgrs', units: 'imperial' });- expect(prefs.coordFormat).toBe('mgrs');- expect(prefs.units).toBe('imperial');- expect(prefs.postMention).toBe('@GeoConfirmed'); // untouched by a partial payload-- applyPrefs({ post_mention: '' }); // an empty mention is a real choice, not absence- expect(prefs.postMention).toBe('');- });-});diff --git a/frontend/src/lib/state.test.js b/frontend/src/lib/state.test.jsindex 0873ea9..e4a252d 100644--- a/frontend/src/lib/state.test.js+++ b/frontend/src/lib/state.test.js@@ -2,6 +2,16 @@ import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';import { caseState, uiState, closeCase, setSidebarWidth } from './state.svelte.js';import { MIN_W, MAX_W } from './sidebar.js';+// The prefs tests below exercise import-time module state, so the transport is+// stubbed and the module re-imported fresh per test. The static import above+// still works: these tests never call the API.+vi.mock('./api.js', () => ({ api: { get: vi.fn() } }));++async function freshState() {+ vi.resetModules();+ return import('./state.svelte.js');+}+describe('closeCase', () => {beforeEach(() => {caseState.current = { id: 'case-a', name: 'Case A' };@@ -51,3 +61,51 @@ describe('setSidebarWidth', () => {expect(uiState.sidebarW).toBe(MIN_W);});});++describe('prefsReady — tools must not race the settings fetch', () => {+ let api;+ beforeEach(async () => {+ ({ api } = await import('./api.js'));+ api.get.mockReset();+ });++ it('does not resolve before the preferences land', async () => {+ let release;+ api.get.mockReturnValue(new Promise((r) => (release = r)));+ const { prefsReady, loadPrefs, prefs } = await freshState();++ let ready = false;+ prefsReady.then(() => (ready = true));+ loadPrefs();+ await Promise.resolve();+ expect(ready).toBe(false); // a tool awaiting this is still parked++ release({ home_view: { lat: -33.8568, lon: 151.2153, zoom: 17 } });+ await prefsReady;+ // the home view is readable the moment prefsReady resolves — that ordering+ // is what keeps the Satellite map off its built-in default+ expect(prefs.homeView).toEqual({ lat: -33.8568, lon: 151.2153, zoom: 17 });+ });++ it('resolves even when the settings read fails, leaving the defaults', async () => {+ api.get.mockRejectedValue(new Error('offline'));+ const { prefsReady, loadPrefs, prefs } = await freshState();++ await loadPrefs().catch(() => {});+ await expect(prefsReady).resolves.toBeUndefined(); // never hangs a tool+ expect(prefs.homeView).toEqual({ lat: 48.8584, lon: 2.2945, zoom: 16 });+ });+});++describe('applyPrefs', () => {+ it('adopts a settings payload and ignores absent fields', async () => {+ const { applyPrefs, prefs } = await freshState();+ applyPrefs({ coord_format: 'mgrs', units: 'imperial' });+ expect(prefs.coordFormat).toBe('mgrs');+ expect(prefs.units).toBe('imperial');+ expect(prefs.postMention).toBe('@GeoConfirmed'); // untouched by a partial payload++ applyPrefs({ post_mention: '' }); // an empty mention is a real choice, not absence+ expect(prefs.postMention).toBe('');+ });+});diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelteindex c1ac0b2..5a4ecb2 100644--- a/frontend/src/tools/Inspector.svelte+++ b/frontend/src/tools/Inspector.svelte@@ -1072,7 +1072,7 @@{#if discardConfirm}<ConfirmDialogtitle="Discard this session?"- message="The current workspace — captured frames, adjustments and collage layout — will be cleared."+ message="This clears the current workspace."detail={openedSession ? 'This does not delete the saved session, only the unsaved changes in this workspace.' : 'Anything not saved yet will be lost.'}confirmLabel="Discard"tone="danger"@@ -1097,7 +1097,7 @@</div>{#if sessionModal.mode === 'save'}- <p class="modal-hint">Persist the whole workspace (frames, adjustments, collages) to reopen later. Saving the session does not file any media.</p>+ <p class="modal-hint">Saves the workspace to reopen later; no media is filed.</p><inputclass="input"placeholder="Session name"diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelteindex f10b14b..21c4602 100644--- a/frontend/src/tools/PostComposer.svelte+++ b/frontend/src/tools/PostComposer.svelte@@ -182,7 +182,7 @@}function tweet2Text() {- const label = mediaType === 'video' ? '2/ Video:' : '2/ Image(s):';+ const label = mediaType === 'video' ? '2/ Video:' : '2/ Image:';return mediaText.trim() ? `${label}\n${mediaText.trim()}` : label;}@@ -503,7 +503,7 @@<button class="btn btn-ghost btn-sm" onclick={saveDraft} disabled={saving}><Icon name="save" size={14} /> {draftName ? 'Save draft' : 'Save as draft'}</button>- <button class="btn btn-primary btn-sm" onclick={publish} disabled={!tweet1.trim()} title="Copy the thread and open X compose prefilled — Azimut never posts for you">+ <button class="btn btn-primary btn-sm" onclick={publish} disabled={!tweet1.trim()} title="Copy the thread and open X compose"><Icon name="post" size={14} /> Publish on X</button></div>@@ -644,7 +644,7 @@></textarea></div>- <!-- Tweet 2: media (Video / Image(s)) -->+ <!-- Tweet 2: media (Video / Image) -->{#if mediaEnabled}<div class="tweet-block card"><div class="tweet-head">@@ -662,7 +662,7 @@class:btn-primary={mediaType === 'images'}class:btn-ghost={mediaType !== 'images'}onclick={() => (mediaType = mediaType === 'images' ? 'none' : 'images')}- >Image(s)</button>+ >Image</button></div>{#if mediaType !== 'none'}<span class="counter">{weightedLength(tweet2Text())}/{X_LIMIT}</span>@@ -675,7 +675,7 @@</button></div>{#if mediaType !== 'none'}- <div class="media-prefix">{mediaType === 'video' ? '2/ Video:' : '2/ Image(s):'}</div>+ <div class="media-prefix">{mediaType === 'video' ? '2/ Video:' : '2/ Image:'}</div><textareaclass="textarea post-text mono"dir="auto"@@ -712,7 +712,7 @@{/if}</div>{:else}- <span class="muted">Toggle Video or Image(s) to add a media tweet</span>+ <span class="muted">Toggle Video or Image to add a media tweet</span>{/if}</div>{/if}@@ -802,7 +802,7 @@{#if discardConfirm}<ConfirmDialogtitle="Discard this draft?"- message="The current post — description, coordinates, media and extra tweets — will be cleared."+ message="This clears the current post."detail={draftName ? 'This does not delete the saved draft, only the unsaved changes here.' : 'Anything not saved yet will be lost.'}confirmLabel="Discard"tone="danger"diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelteindex ec7d301..300dbc5 100644--- a/frontend/src/tools/ProofComposer.svelte+++ b/frontend/src/tools/ProofComposer.svelte@@ -1621,7 +1621,7 @@class="btn"onclick={copyPng}disabled={!proof.panels.length || copying}- title="Copy the composed PNG to the clipboard — paste it in a chat or a tweet"+ title="Copy the composed PNG to the clipboard"><Icon name="copy" size={15} /> {copying ? 'Copying…' : 'Copy PNG'}</button>@@ -1697,7 +1697,7 @@<buttonclass="tb-btn"class:active={proof.layout !== 'free'}- title="Grid layout — panels flow in rows; select one to move it with the on-canvas arrows"+ title="Grid layout: panels flow in rows"onclick={() => setLayoutMode('grid')}><Icon name="grid" size={18} />@@ -1705,7 +1705,7 @@<buttonclass="tb-btn"class:active={proof.layout === 'free'}- title="Free layout — drag panels anywhere (overlap allowed), corner handles resize"+ title="Free layout: drag panels anywhere"onclick={() => setLayoutMode('free')}><Icon name="layers" size={18} />@@ -1794,7 +1794,7 @@<Icon name="link" size={13} /><span>Source</span>{#if !displayedSource}- <span class="meta-warn" title="A source is a link — add media downloaded from a URL, or paste one">+ <span class="meta-warn" title="Missing source link"><Icon name="alert" size={13} /></span>{/if}@@ -2088,7 +2088,7 @@{#if discardConfirm}<ConfirmDialogtitle="Discard this proof?"- message="The current document — panels, annotations and layout — will be cleared."+ message="This clears the current document."detail={savedName ? 'This does not delete the saved proof, only the unsaved changes here.' : 'Anything not saved yet will be lost.'}confirmLabel="Discard"tone="danger"diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelteindex 0ee84b0..3c0266c 100644--- a/frontend/src/tools/Satellite.svelte+++ b/frontend/src/tools/Satellite.svelte@@ -1661,7 +1661,7 @@class="input"placeholder={'50.4501, 30.5234 · 48°51\'29"N 2°17\'40"E · a place name'}bind:value={coordsText}- title="Coordinates (decimal or DMS) or a place name (geocoded via Nominatim)"+ title="Coordinates (decimal, DMS, MGRS, plus code) or a place name"/><button type="submit" class="btn" disabled={!coordsText.trim() || searching}><Icon name="search" size={15} /> {searching ? '…' : 'Go'}@@ -1715,7 +1715,7 @@class="mtbtn"class:on={uiState.refViewers.length}onclick={openRefPicker}- title="Add a reference image or video over the map (scratch only — never captured or saved)"+ title="Add a reference image or video over the map"aria-label="Add reference"><Icon name="image" size={16} />@@ -2021,7 +2021,7 @@{#if usagePill}<spanclass="usage-pill mono"- title="Requests made to this billed provider this month — local counter, see Settings"+ title="Requests to this billed provider this month">{usagePill}</span>{/if}{#if currentProvider?.meter && displayedBaseId !== providerId}@@ -2046,7 +2046,7 @@class:on={moveMode}onclick={toggleMoveMode}disabled={markerStyle === 'none'}- title="Move the marker off-center — recorded coordinates follow the pin"+ title="Move the marker (coordinates follow it)"><Icon name="crosshair" size={14} /> {moveMode ? 'Moving' : 'Move pin'}</button>@@ -2056,7 +2056,7 @@class="btn place-save-main"onclick={savePlace}disabled={savingPlace}- title="Save just this point (the pin, or the crop center) as a navigable place — no image"+ title="Save this point as a place (no image)"><Icon name="pin" size={15} /> {savingPlace ? 'Saving…' : 'Save place'}</button>@@ -2661,8 +2661,8 @@{#if refPicker}<Modal title="Add reference" onclose={() => (refPicker = false)} width="560px"><p class="ref-hint">- Float one of the case's images or videos over the map to eyeball against the imagery.- It's a scratch aid — never captured or saved.+ Float a case image or video over the map to compare against the imagery.+ Reference windows are never captured or saved.</p>{#if refLoading}<div class="ref-empty">Loading…</div>diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelteindex 56dfb64..2c5f900 100644--- a/frontend/src/tools/Settings.svelte+++ b/frontend/src/tools/Settings.svelte@@ -52,7 +52,7 @@help: 'https://account.mapbox.com/access-tokens/',usage: USAGE_LINKS.mapbox,overage:- 'Past the free tier Mapbox bills extra tiles automatically — pay-as-you-go, no hard cap. Set a spending alert in your Mapbox account.',+ 'Past the tier, Mapbox bills extra tiles automatically; set a spending alert in your account.',},{id: 'google',@@ -66,7 +66,7 @@warning:'EEA billing accounts: since 8 July 2025 Google no longer serves satellite tiles to Europe (403). Use a Maps JavaScript API key instead.',overage:- 'Extra tiles are billed to your Cloud project, and Google also enforces 15k tiles/day. A quota cap in the Cloud Console makes it stop serving instead of billing.',+ 'Extra tiles are billed to your Cloud project; a quota cap in the Cloud Console makes it stop serving instead.',},{id: 'google_js',@@ -85,7 +85,7 @@'Optional but recommended: restrict the key to your own referrers.',],overage:- 'A map load is one widget instantiation (~10k free/month) — pan and zoom on an open map are free. Azimut builds the widget once per session and reuses it, so normal use stays far under the tier.',+ 'One load per widget, ~10k free a month; Azimut reuses one widget per session, so normal use stays far under the tier.',},{id: 'sentinelhub',@@ -105,10 +105,10 @@'Copy the ID under "Service endpoints" and paste it here.',],overage:- 'A free Copernicus account gets 30,000 requests and 30,000 processing units a month (one tile = 1 request = 1 PU; a date lookup is 1 request but ~0.01 PU) and simply stops serving until the 1st — it never bills you.',+ 'A free account gets 30,000 requests a month and simply stops serving until the 1st. It never bills.',// the correction the free-allowance box exists for, told where it's usefultierNote:- 'Copernicus still documents 10,000 while provisioning 30,000, and the figure is per-account — check yours on the dashboard.',+ 'Copernicus documents 10,000 but provisions 30,000, per account; check yours on the dashboard.',},];@@ -162,6 +162,7 @@async function copyToken() {try {+ await ensureToken();await navigator.clipboard.writeText(ingestToken);toast('Pairing token copied', 'ok');} catch {@@ -170,6 +171,16 @@}}+ // The token is no longer minted just by opening Settings (the server stopped+ // doing that) — it's created the first time the user reveals or copies it to+ // pair the capture extension.+ async function ensureToken() {+ if (ingestToken) return ingestToken;+ const r = await api.post('/api/settings/ingest-token');+ ingestToken = r.ingest_token;+ return ingestToken;+ }+async function rotateToken() {const r = await api.post('/api/settings/ingest-token/rotate');ingestToken = r.ingest_token;@@ -186,6 +197,25 @@let sigBust = $state(0);let sigInput = $state(null);+ // Move settings between machines: export writes settings.json to disk,+ // import merges a previously exported file back (config keys only).+ let settingsFile = $state(null);++ async function importSettings(event) {+ const file = event.currentTarget.files?.[0];+ if (!file) return;+ try {+ const parsed = JSON.parse(await file.text());+ await api.post('/api/settings/import', { settings: parsed });+ toast('Settings imported', 'ok');+ await load();+ } catch (e) {+ toast(`Could not import settings: ${e.message}`, 'danger');+ } finally {+ event.currentTarget.value = '';+ }+ }+// The downloaders age faster than Azimut releases: sites change, and a stale// yt-dlp just stops finding media. They can be refreshed from PyPI in place,// without waiting for (or reinstalling) the app — see engine/scrapers.py.@@ -635,7 +665,7 @@type="checkbox"bind:checked={enabled[k.id]}onchange={saveProviderPrefs}- title="Show or hide this basemap in the Satellite tab — the key stays saved"+ title="Show or hide this basemap in the Satellite tab"aria-label="Show {k.label} in the Satellite tab"/>{/if}@@ -725,7 +755,7 @@{#if share >= BLOCK_SHARE || overrides[k.id]}<labelclass="toggle override"- title="Serve past the pause — extra tiles are billed by the provider"+ title="Serve past the pause (extra tiles are billed)"><inputtype="checkbox"@@ -766,7 +796,7 @@{:else}<labelclass="ctrl"- title="Own threshold for this basemap — blank inherits the global one, 0 turns eco off for it"+ title="Threshold for this basemap (blank inherits the global one, 0 turns eco off)"><span>Eco below z ≤</span><input@@ -811,7 +841,7 @@<h3>Eco mode</h3><labelclass="toggle eco"- title="Zoomed out this far, billed basemaps silently swap to free imagery — paid detail only matters up close"+ title="Zoomed out this far, billed basemaps swap to free imagery"><input type="checkbox" bind:checked={eco} onchange={saveEcoZoom} />Use free imagery when zoomed out, up to z ≤@@ -827,7 +857,7 @@/></label><p class="note">- Paid detail only matters up close. Each provider can override this from its card.+ Applies when zoomed out. Each provider can override this from its card.</p></section>@@ -859,13 +889,9 @@<section class="group"><h3>Capture extension</h3><p class="note">- A small browser extension (Chrome/Edge and Firefox) that files the map you- are looking at into Azimut as a capture — one screenshot per click,- coordinates parsed from the page URL, source and timestamp recorded. It- serves two things: <strong>capturing external map sites</strong> (Google- Maps & Earth, Bing, Yandex, OpenStreetMap, Apple Maps, Zoom Earth,- Satellites.pro), and the <strong>Capture button on the Google (Maps JS)- basemap</strong>, whose imagery may only leave the widget as a screenshot.+ A browser extension (Chrome/Edge and Firefox) that captures external map+ sites into Azimut and powers the Capture button on the Google (Maps JS)+ basemap.</p><div class="row"><div class="row-label">@@ -883,24 +909,16 @@</a></div><p class="note">- Browsers do not let an app install extensions for you — it's two manual- steps, once: <strong>Chrome/Edge</strong>: unzip somewhere permanent →- <span class="mono">chrome://extensions</span> → enable Developer mode →- "Load unpacked" → pick the folder. <strong>Firefox</strong>:- <span class="mono">about:debugging</span> → "This Firefox" → "Load- Temporary Add-on" → pick <span class="mono">manifest.json</span> (Firefox- forgets temporary add-ons on exit — see the README in the zip for a- permanent install). Then reload this tab.+ Unzip it somewhere permanent and load it as an unpacked extension, then+ reload this tab. Step-by-step instructions are in the README inside the zip.</p></section><section class="group"><h3>Pairing</h3><p class="note">- Pairing lets the extension file captures from <em>external</em> map sites- into your local Azimut. Paste this token once into the extension's- options page. The Google (Maps JS) capture inside Azimut does not need- pairing. Rotating the token instantly unpairs every extension.+ Paste this token once into the extension's options page. Rotating it+ unpairs every extension.</p><div class="row"><div class="row-label">@@ -908,7 +926,7 @@<span class="row-hint mono">{tokenShown ? ingestToken : '•'.repeat(24)}</span></div><div class="scraper-actions">- <button class="btn btn-sm" onclick={() => (tokenShown = !tokenShown)}>+ <button class="btn btn-sm" onclick={async () => { await ensureToken(); tokenShown = !tokenShown; }}>{tokenShown ? 'Hide' : 'Show'}</button><button class="btn btn-sm btn-primary" onclick={copyToken}>@@ -938,10 +956,9 @@<dd>AGPL-3.0-or-later</dd></dl><p class="note">- The workspace is a plain folder: cases, media and proofs are files you can- zip, back up or put under git. No account, no telemetry, no upload — network- access only happens when a tool inherently needs it (map tiles, geocoding,- media download), always directly to the third party.+ The workspace is a plain folder you can zip, back up or put under git.+ No account, no telemetry; the network is only used when a tool needs it+ (tiles, geocoding, downloads), always directly to the third party.</p><div class="links"><a class="btn btn-sm" href={REPO_URL} target="_blank" rel="noreferrer">@@ -953,6 +970,29 @@</div></section>+ <section class="group">+ <h3>Backup</h3>+ <p class="note">+ Export all settings, including your keys, to a file you can import on+ another machine. Keep the file private.+ </p>+ <div class="links">+ <a class="btn btn-sm" href="/api/settings/export" download>+ <Icon name="save" size={13} /> Export settings+ </a>+ <button class="btn btn-sm" onclick={() => settingsFile?.click()}>+ <Icon name="file" size={13} /> Import settings+ </button>+ <input+ type="file"+ accept="application/json,.json"+ bind:this={settingsFile}+ onchange={importSettings}+ hidden+ />+ </div>+ </section>+<section class="group"><h3>Downloaders</h3><p class="note">@@ -1001,11 +1041,8 @@</button></div><p class="note">- Checking and updating are the only things here that use the network, and only- when you press them — the newest release is fetched from PyPI into your- workspace, verified against the hash PyPI publishes, and used instead of the- bundled copy. <strong>Revert</strong> goes back to the version this build- shipped with, if an update ever makes things worse.+ Updates are fetched from PyPI (hash-verified) only when you press the+ button. Revert goes back to the bundled version.</p></section>{/if}diff --git a/frontend/src/tools/inspect/CollageMenu.svelte b/frontend/src/tools/inspect/CollageMenu.svelteindex c494aae..4854d96 100644--- a/frontend/src/tools/inspect/CollageMenu.svelte+++ b/frontend/src/tools/inspect/CollageMenu.svelte@@ -195,7 +195,7 @@</div></div>- <p class="hint">Pieces are the frames you captured. Add them, drag to arrange, pull corners to warp into a panorama. Shift-click to select several and move them as one block.</p>+ <p class="hint">Drag pieces to arrange them, pull corners to warp; shift-click selects several.</p><div class="section"><div class="section-head"><span>Frames</span></div>@@ -251,7 +251,7 @@{#if selectedGroup.length > 1}<div class="section"><div class="section-head"><span>Selected block <span class="count">{selectedGroup.length}</span></span></div>- <p class="hint">Scales and turns as one, about the block's centre. Shift-click a piece to add or drop it.</p>+ <p class="hint">Moves as one block; shift-click a piece to add or drop it.</p><div class="scale-row"><span class="lbl">Scale</span><button class="btn btn-sm sq" onclick={() => scaleGroupBy(1 / 1.1)} aria-label="Shrink block">−</button>diff --git a/frontend/src/tools/inspect/PieceCropModal.svelte b/frontend/src/tools/inspect/PieceCropModal.svelteindex 7c76378..4832325 100644--- a/frontend/src/tools/inspect/PieceCropModal.svelte+++ b/frontend/src/tools/inspect/PieceCropModal.svelte@@ -37,7 +37,7 @@</script><Modal title="Crop piece" width="560px" {onclose}>- <p class="hint">Drag to draw a region, then nudge the handles or type exact values. Lock an aspect ratio to match a panel. Applied before the warp, so the collage updates in place.</p>+ <p class="hint">Drag to draw a region, then nudge the handles or type exact values.</p><div class="stage"><imgbind:this={imgEl}diff --git a/frontend/src/tools/inspect/SaveMenu.svelte b/frontend/src/tools/inspect/SaveMenu.svelteindex 2ccfd21..ea2e7c1 100644--- a/frontend/src/tools/inspect/SaveMenu.svelte+++ b/frontend/src/tools/inspect/SaveMenu.svelte@@ -19,7 +19,7 @@</script><div class="module">- <p class="hint">Tick items on the left, pick a folder, and save. Everything lands in the Media Library with provenance back to its source.</p>+ <p class="hint">Tick what to save; it lands in the Media Library with its provenance.</p><div class="pickers"><button class="btn btn-sm" onclick={selectAll} disabled={!savables.length}>Select all</button>diff --git a/pyproject.toml b/pyproject.tomlindex 6327584..34d4db0 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -18,6 +18,7 @@ classifiers = ["Operating System :: OS Independent","Programming Language :: Python :: 3.11","Programming Language :: Python :: 3.12",+ "Programming Language :: Python :: 3.13",]# Upper bounds stop at the next major we haven't tested against: a range is a# claim about what works, and we can't make that claim for code that doesn'tdiff --git a/src/azimut/__init__.py b/src/azimut/__init__.pyindex 43bec69..3a37e0e 100644--- a/src/azimut/__init__.py+++ b/src/azimut/__init__.py@@ -1,3 +1,14 @@"""Azimut — the OSINT investigator's workbench."""+from PIL import Image as _Image+__version__ = "0.1.1"++# Cap the pixels Pillow will decode from a file, process-wide. A tiny,+# highly-compressed image can otherwise expand to gigabytes in memory and take+# the process down (a local denial of service). 100 MP sits far above any+# legitimate input — a screenshot, a satellite crop (≤4096²) or a proof — and+# well under Pillow's ~179 MP default. This only guards *decoding untrusted+# files*; composites built with Image.new() are unaffected. Set here because+# importing azimut is the one thing every entry point does first.+_Image.MAX_IMAGE_PIXELS = 100_000_000diff --git a/src/azimut/api/ingest.py b/src/azimut/api/ingest.pyindex c08e0c5..98a0831 100644--- a/src/azimut/api/ingest.py+++ b/src/azimut/api/ingest.py@@ -134,7 +134,6 @@ async def ingest_screenshot(image: UploadFile,url: str = Form(min_length=1, max_length=4000),case_id: str = Form(default=""),- site: str = Form(default="", max_length=64),lat: float | None = Form(default=None, ge=-90, le=90),lon: float | None = Form(default=None, ge=-180, le=180),zoom: float | None = Form(default=None, ge=0, le=23),diff --git a/src/azimut/api/inspect.py b/src/azimut/api/inspect.pyindex 0a38ab0..9d957ef 100644--- a/src/azimut/api/inspect.py+++ b/src/azimut/api/inspect.py@@ -24,17 +24,6 @@ from .cases import delete_by_path, get_caserouter = APIRouter(prefix="/api", tags=["inspect"])-class FrameIn(BaseModel):- path: str- time: float = Field(ge=0)- label: str | None = None---class FramesIn(BaseModel):- path: str- times: list[float]--class SuggestIn(BaseModel):path: str# How many suggestions to return. Every frame is scanned regardless — this@@ -48,26 +37,6 @@ class Op(BaseModel):params: dict[str, Any] = {}-class BakeIn(BaseModel):- path: str- ops: list[Op]- label: str | None = None---class CollageIn(BaseModel):- paths: list[str] = Field(min_length=1)- columns: int = Field(default=2, ge=1, le=8)- gap: int = Field(default=8, ge=0, le=64)- background: str = "#12141c"- cell: int = Field(default=480, ge=64, le=1024)- label: str | None = None---class PreviewIn(BaseModel):- path: str- time: float = Field(ge=0)--class RenderPreviewIn(BaseModel):path: strtime: float | None = Field(default=None, ge=0)@@ -151,32 +120,6 @@ def probe(case_id: str, path: str) -> dict[str, Any]:raise HTTPException(status_code=404, detail=str(exc)) from exc[email protected]("/cases/{case_id}/inspect/frame")-def capture_frame(case_id: str, body: FrameIn) -> dict[str, Any]:- case = get_case(case_id)- try:- return inspect_engine.capture_frame(case, body.path, body.time, body.label)- except CaseError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc- except (RuntimeError, OSError) as exc:- raise HTTPException(status_code=422, detail=str(exc)) from exc--[email protected]("/cases/{case_id}/inspect/frames")-def capture_frames(case_id: str, body: FramesIn) -> dict[str, str]:- case = get_case(case_id)-- def work(set_progress):- results = []- total = len(body.times) or 1- for i, t in enumerate(body.times):- results.append(inspect_engine.capture_frame(case, body.path, t))- set_progress({"percent": round((i + 1) * 100 / total, 1)})- return {"captured": results}-- return {"job_id": jobs.start("frames", work)}--@router.post("/cases/{case_id}/inspect/suggest")def suggest_frames(case_id: str, body: SuggestIn) -> dict[str, str]:case = get_case(case_id)@@ -191,45 +134,6 @@ def suggest_frames(case_id: str, body: SuggestIn) -> dict[str, str]:return {"job_id": jobs.start("suggest", work)}[email protected]("/cases/{case_id}/inspect/bake")-def bake(case_id: str, body: BakeIn) -> dict[str, Any]:- case = get_case(case_id)- ops = [op.model_dump() for op in body.ops]- try:- return inspect_engine.bake(case, body.path, ops, body.label)- except CaseError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc- except (ValueError, OSError) as exc:- raise HTTPException(status_code=422, detail=str(exc)) from exc--[email protected]("/cases/{case_id}/inspect/collage")-def collage(case_id: str, body: CollageIn) -> dict[str, Any]:- case = get_case(case_id)- try:- return inspect_engine.collage(- case, body.paths, columns=body.columns, gap=body.gap,- background=body.background, cell=body.cell, label=body.label,- )- except CaseError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc- except (ValueError, OSError) as exc:- raise HTTPException(status_code=422, detail=str(exc)) from exc--[email protected]("/cases/{case_id}/inspect/frame/preview")-def preview_frame(case_id: str, body: PreviewIn) -> Response:- """Decode one video frame and return the PNG — nothing is filed (tray preview)."""- case = get_case(case_id)- try:- png = inspect_engine.preview_frame_png(case, body.path, body.time)- except CaseError as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc- except (RuntimeError, OSError) as exc:- raise HTTPException(status_code=422, detail=str(exc)) from exc- return Response(content=png, media_type="image/png")--@router.post("/cases/{case_id}/inspect/render-preview")def render_preview(case_id: str, body: RenderPreviewIn) -> Response:"""Render a recipe (frame/image + ops) to a PNG — nothing is filed.diff --git a/src/azimut/api/proofs.py b/src/azimut/api/proofs.pyindex 4616c10..20cb103 100644--- a/src/azimut/api/proofs.py+++ b/src/azimut/api/proofs.py@@ -108,7 +108,12 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:# upsert the proof entity (analyst action → confirmed)existing = case.find_entity(attr="spec", value=f"proofs/{name}.json")if existing:- case.update_entity(existing["id"], {"label": body.title})+ patch: dict[str, Any] = {"label": body.title}+ if png_rel and existing["attrs"].get("path") != png_rel:+ # a spec-only proof exported later gains its PNG here — without the+ # path the sidebar preview and delete_by_path can't see the file+ patch["attrs"] = {"path": png_rel}+ case.update_entity(existing["id"], patch)entity_id = existing["id"]else:entity_id = case.add_entity(diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.pyindex 7fb2630..17be134 100644--- a/src/azimut/api/satellite.py+++ b/src/azimut/api/satellite.py@@ -274,6 +274,8 @@ def tile_proxy(provider_id: str, z: int, x: int, y: int) -> Response:(404s / "not yet available" placeholders) are overzoomed — the parenttile's quadrant upscaled — instead of breaking the map."""+ if z < 0 or not (0 <= x < (1 << z)) or not (0 <= y < (1 << z)):+ raise HTTPException(status_code=422, detail="tile coordinates out of range")try:provider = tiles.get_provider(provider_id)except KeyError as exc:diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.pyindex 9017527..8b5d2b2 100644--- a/src/azimut/api/settings.py+++ b/src/azimut/api/settings.py@@ -9,11 +9,12 @@ settings.json, reaching a case only as pixels in a rendered proof PNG.from __future__ import annotations+import jsonimport refrom typing import Anyimport httpx-from fastapi import APIRouter, HTTPException, UploadFile+from fastapi import APIRouter, HTTPException, Response, UploadFilefrom fastapi.responses import FileResponsefrom pydantic import BaseModel, Field@@ -95,6 +96,9 @@ def _prefs(settings: dict[str, Any]) -> dict[str, Any]:def get_settings() -> dict[str, Any]:settings = config.load_settings()return {+ # keys travel in cleartext by decision: the Settings UI edits them in+ # place, and the loopback bind + Host/Origin guard (server.py) is what+ # keeps other pages from reading them"api_keys": settings.get("api_keys", {}),"usage": settings.get("usage", {}),"month": config.month_key(),@@ -114,14 +118,25 @@ def get_settings() -> dict[str, Any]:# About tab: what this build is, and where it keeps its files"version": __version__,"workspace_root": str(config.workspace_root()),- # capture-extension pairing token (api/ingest.py) — minted on first read- "ingest_token": config.ingest_token(),+ # capture-extension pairing token (api/ingest.py) — reported only if it+ # already exists; loading Settings no longer mints a credential (POST+ # /settings/ingest-token does, on the user's explicit reveal/copy)+ "ingest_token": settings.get("ingest_token") or "",}@router.put("/settings/prefs")def put_prefs(body: PrefsIn) -> dict[str, Any]:- settings = config.load_settings()+ # validate before taking the settings lock — a 422 must not hold it+ if body.coord_format is not None and body.coord_format not in config.COORD_FORMATS:+ raise HTTPException(status_code=422, detail=f"unknown coord_format '{body.coord_format}'")+ if body.units is not None and body.units not in config.UNIT_SYSTEMS:+ raise HTTPException(status_code=422, detail=f"unknown units '{body.units}'")+ settings = config.update_settings(lambda s: _apply_prefs(s, body))+ return _prefs(settings)+++def _apply_prefs(settings: dict[str, Any], body: PrefsIn) -> None:if body.providers_enabled is not None:merged = dict(settings.get("providers_enabled", {}))merged.update({k: bool(v) for k, v in body.providers_enabled.items() if k in KEYED_PROVIDERS})@@ -157,42 +172,37 @@ def put_prefs(body: PrefsIn) -> dict[str, Any]:merged[name] = max(1, min(10_000_000, int(value)))settings["free_tiers"] = mergedif body.coord_format is not None:- if body.coord_format not in config.COORD_FORMATS:- raise HTTPException(status_code=422, detail=f"unknown coord_format '{body.coord_format}'")settings["coord_format"] = body.coord_formatif body.units is not None:- if body.units not in config.UNIT_SYSTEMS:- raise HTTPException(status_code=422, detail=f"unknown units '{body.units}'")settings["units"] = body.unitsif body.home_view is not None:settings["home_view"] = body.home_view.model_dump()if body.post_mention is not None:settings["post_mention"] = body.post_mention.strip()[:64]- config.save_settings(settings)- return _prefs(settings)@router.put("/settings/keys")def put_keys(body: KeysIn) -> dict[str, Any]:- settings = config.load_settings()- keys = settings.setdefault("api_keys", {})- status = settings.setdefault("provider_status", {})- for name in KEYED_PROVIDERS:- value = getattr(body, name)- if value is None:- continue- value = value.strip()- if value != keys.get(name):- # a different credential gets a clean slate: the old verdict was- # about the old key, and a stale failure would keep the basemap- # benched (tiles.key_for) with no way back but a manual re-test- status.pop(name, None)- if value:- keys[name] = value- else:- keys.pop(name, None)- config.save_settings(settings)- return {"api_keys": keys}+ def apply(settings: dict[str, Any]) -> None:+ keys = settings.setdefault("api_keys", {})+ status = settings.setdefault("provider_status", {})+ for name in KEYED_PROVIDERS:+ value = getattr(body, name)+ if value is None:+ continue+ value = value.strip()+ if value != keys.get(name):+ # a different credential gets a clean slate: the old verdict was+ # about the old key, and a stale failure would keep the basemap+ # benched (tiles.key_for) with no way back but a manual re-test+ status.pop(name, None)+ if value:+ keys[name] = value+ else:+ keys.pop(name, None)++ settings = config.update_settings(apply)+ return {"api_keys": settings.get("api_keys", {})}class StatusIn(BaseModel):@@ -210,6 +220,51 @@ def rotate_ingest_token() -> dict[str, Any]:return {"ingest_token": config.ingest_token(rotate=True)}[email protected]("/settings/ingest-token")+def mint_ingest_token() -> dict[str, Any]:+ """Return the pairing token, minting it if it doesn't exist yet.++ Split out from GET /settings so merely opening Settings can't create a+ credential: the token is minted only when the user reveals/copies it to+ pair the capture extension."""+ return {"ingest_token": config.ingest_token()}++[email protected]("/settings/export")+def export_settings() -> Response:+ """Download the whole settings.json (keys, providers, preferences) so it can+ be restored on another machine (POST /settings/import). It carries the+ user's own keys by design — it's a local download to their own disk, the+ same secrets that already live in the workspace."""+ payload = json.dumps(config.load_settings(), indent=2, ensure_ascii=False)+ return Response(+ content=payload,+ media_type="application/json",+ headers={"Content-Disposition": 'attachment; filename="azimut-settings.json"'},+ )+++class ImportIn(BaseModel):+ """A previously exported settings blob. Only keys Azimut recognises are+ applied — anything else in the file is ignored, so a hand-edited or foreign+ JSON can't inject arbitrary state."""++ settings: dict[str, Any]++[email protected]("/settings/import")+def import_settings(body: ImportIn) -> dict[str, Any]:+ known = set(config.DEFAULT_SETTINGS)+ applied = sorted(k for k in body.settings if k in known)++ def apply(settings: dict[str, Any]) -> None:+ for key in applied:+ settings[key] = body.settings[key]++ config.update_settings(apply)+ return {"imported": applied}++@router.post("/settings/keys/{provider}/status")def report_key_status(provider: str, body: StatusIn) -> dict[str, Any]:"""Persist a key verdict the frontend established itself.diff --git a/src/azimut/cli.py b/src/azimut/cli.pyindex df7f855..1384986 100644--- a/src/azimut/cli.py+++ b/src/azimut/cli.py@@ -1,14 +1,11 @@-"""`azimut` command: start the local server and open the browser."""+"""`azimut` command: start the local server and open the browser tab."""from __future__ import annotationsimport argparse-import threading-import webbrowser--import uvicornfrom . import __version__+from .launcher import serveDEFAULT_PORT = 8477 # uncommon high port, clear of common dev ranges@@ -16,22 +13,13 @@ DEFAULT_PORT = 8477 # uncommon high port, clear of common dev rangesdef main() -> None:parser = argparse.ArgumentParser(prog="azimut", description="Azimut — the OSINT investigator's workbench")parser.add_argument("--port", type=int, default=DEFAULT_PORT)- parser.add_argument("--no-browser", action="store_true", help="don't open the browser")+ parser.add_argument("--no-browser", action="store_true", help="don't open the browser tab")parser.add_argument("--version", action="version", version=f"azimut {__version__}")args = parser.parse_args()- url = f"http://127.0.0.1:{args.port}"- if not args.no_browser:- threading.Timer(0.8, webbrowser.open, args=(url,)).start()-- print(f"Azimut {__version__} — {url} (local only, nothing leaves this machine)")- uvicorn.run(- "azimut.server:create_app",- factory=True,- host="127.0.0.1", # local-first: never bind beyond localhost- port=args.port,- log_level="warning",- )+ print(f"Azimut {__version__} — http://127.0.0.1:{args.port} (local only, nothing leaves this machine)")+ print("Runs in your browser tab. Close this window to stop Azimut.")+ serve(args.port, open_browser=not args.no_browser)if __name__ == "__main__":diff --git a/src/azimut/config.py b/src/azimut/config.pyindex 361a6f5..39997e3 100644--- a/src/azimut/config.py+++ b/src/azimut/config.py@@ -21,7 +21,7 @@ import osimport threadingfrom datetime import datetime, timezonefrom pathlib import Path-from typing import Any+from typing import Any, CallableDEFAULT_SETTINGS: dict[str, Any] = {# Extra XYZ tile providers added by the user (spec §6 v1 notes).@@ -159,10 +159,22 @@ def ensure_workspace() -> None:"""Create the workspace skeleton if missing (idempotent)."""cases_dir().mkdir(parents=True, exist_ok=True)scratch_dir().mkdir(parents=True, exist_ok=True)+ # The workspace holds API keys and the pairing token — keep it owner-only+ # so another account on a shared machine can't read them. Best-effort:+ # Windows ignores POSIX modes, which is fine (its ACLs already scope $HOME).+ _restrict(workspace_root(), 0o700)if not settings_path().exists():save_settings(DEFAULT_SETTINGS)+def _restrict(path: Path, mode: int) -> None:+ """chmod, ignoring platforms/filesystems that don't support it."""+ try:+ os.chmod(path, mode)+ except OSError:+ pass++def load_settings() -> dict[str, Any]:# deep copies: callers mutate nested dicts (usage counters, prefs), and a# shallow copy would let that leak into DEFAULT_SETTINGS itself@@ -180,6 +192,8 @@ def save_settings(settings: dict[str, Any]) -> None:settings_path().write_text(json.dumps(settings, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")+ # Holds the user's API keys and pairing token — owner-read/write only.+ _restrict(settings_path(), 0o600)def month_key(when: datetime | None = None) -> str:@@ -190,6 +204,21 @@ def month_key(when: datetime | None = None) -> str:_usage_lock = threading.Lock() # tile proxy bumps the counter from many threads+def update_settings(mutate: Callable[[dict[str, Any]], None]) -> dict[str, Any]:+ """Load → mutate → save settings.json under the writer lock.++ Every read-modify-write of the file must go through this (or take+ ``_usage_lock`` itself): the tile proxy bumps counters from worker threads,+ and an unlocked save can drop either the counter bump or the caller's+ change (last writer wins on the whole file).+ """+ with _usage_lock:+ settings = load_settings()+ mutate(settings)+ save_settings(settings)+ return settings++def record_usage(meter: str, count: int = 1, when: datetime | None = None) -> int:"""Bump a provider's tile counter for the month; returns the new total.diff --git a/src/azimut/engine/coords.py b/src/azimut/engine/coords.pyindex 1069a51..3a10498 100644--- a/src/azimut/engine/coords.py+++ b/src/azimut/engine/coords.py@@ -13,6 +13,7 @@ reference vectors (tests/test_coords.py, frontend/src/lib/coords.test.js).from __future__ import annotationsimport math+import refrom .. import config@@ -141,6 +142,97 @@ def to_utm(lat: float, lon: float) -> tuple[int, float, float]:return zone, easting, northing+def from_utm(zone: int, easting: float, northing: float, southern: bool) -> tuple[float, float]:+ """Inverse UTM projection: (lat, lon) for a zone/easting/northing triple."""+ x = easting - 500000+ y = northing - (10000000 if southern else 0)++ m = y / _K0+ mu = m / (_A * (1 - _E2 / 4 - 3 * _E2**2 / 64 - 5 * _E2**3 / 256))+ e1 = (1 - math.sqrt(1 - _E2)) / (1 + math.sqrt(1 - _E2))+ phi1 = (+ mu+ + (3 * e1 / 2 - 27 * e1**3 / 32) * math.sin(2 * mu)+ + (21 * e1**2 / 16 - 55 * e1**4 / 32) * math.sin(4 * mu)+ + (151 * e1**3 / 96) * math.sin(6 * mu)+ + (1097 * e1**4 / 512) * math.sin(8 * mu)+ )++ sin1 = math.sin(phi1)+ cos1 = math.cos(phi1)+ tan1 = math.tan(phi1)+ c1 = _EP2 * cos1 * cos1+ t1 = tan1 * tan1+ n1 = _A / math.sqrt(1 - _E2 * sin1 * sin1)+ r1 = _A * (1 - _E2) / (1 - _E2 * sin1 * sin1) ** 1.5+ d = x / (n1 * _K0)++ lat = phi1 - (n1 * tan1 / r1) * (+ d * d / 2+ - (5 + 3 * t1 + 10 * c1 - 4 * c1 * c1 - 9 * _EP2) * d**4 / 24+ + (61 + 90 * t1 + 298 * c1 + 45 * t1 * t1 - 252 * _EP2 - 3 * c1 * c1) * d**6 / 720+ )+ lon0 = math.radians((zone - 1) * 6 - 180 + 3)+ lon = lon0 + (+ d+ - (1 + 2 * t1 + c1) * d**3 / 6+ + (5 - 2 * c1 + 28 * t1 - 3 * c1 * c1 + 8 * _EP2 + 24 * t1 * t1) * d**5 / 120+ ) / cos1+ return math.degrees(lat), math.degrees(lon)+++_MGRS_RE = (+ r"(?P<zone>\d{1,2})\s*(?P<band>[C-HJ-NP-X])\s*"+ r"(?P<col>[A-HJ-NP-Z])(?P<row>[A-HJ-NP-V])\s*(?P<digits>\d[\d ]*)?"+)+++def parse_mgrs(text: str) -> tuple[float, float] | None:+ """Parse an MGRS reference ("31U DQ 48250 11951", spacing optional) to the+ centre of its cell. None when the text isn't MGRS or the square is invalid.+ """+ m = re.fullmatch(_MGRS_RE, text.strip().upper())+ if not m:+ return None+ zone = int(m.group("zone"))+ band = m.group("band")+ if not 1 <= zone <= 60:+ return None+ groups = (m.group("digits") or "").split()+ if len(groups) == 2 and len(groups[0]) != len(groups[1]):+ return None # "482 11951" is a typo, not a 10 m reference+ digits = "".join(groups)+ if len(digits) % 2 or len(digits) > 10:+ return None+ half = len(digits) // 2+ unit = 10 ** (5 - half) # metres per least-significant digit+ e_in = (int(digits[:half]) if half else 0) * unit + unit / 2+ n_in = (int(digits[half:]) if half else 0) * unit + unit / 2++ col_set = _COL_SETS[(zone - 1) % 3]+ if m.group("col") not in col_set:+ return None+ e100k = (col_set.index(m.group("col")) + 1) * 100000+ row_index = _ROW_LETTERS.index(m.group("row"))+ if zone % 2 == 0:+ row_index = (row_index - 5) % 20+ n100k = row_index * 100000++ # The 100 km row letters repeat every 2,000 km; the band letter picks which+ # repeat. Try each candidate and keep the one that lands inside the band.+ southern = band < "N"+ band_bottom = -80 + _BANDS.index(band) * 8+ band_top = 84 if band == "X" else band_bottom + 8+ for k in range(0, 10):+ northing = n100k + n_in + k * 2000000+ lat, lon = from_utm(zone, e100k + e_in, northing, southern)+ # half a degree of slack: points near a band edge round across it+ if band_bottom - 0.5 <= lat <= band_top + 0.5:+ if -90 <= lat <= 90 and -180 <= lon <= 180:+ return lat, lon+ return None++def format_mgrs(lat: float, lon: float) -> str | None:"""Military Grid Reference System, 1 m precision — e.g. "31U DQ 48250 11951".diff --git a/src/azimut/engine/geo.py b/src/azimut/engine/geo.pyindex 1a87b84..0ad8b2b 100644--- a/src/azimut/engine/geo.py+++ b/src/azimut/engine/geo.py@@ -8,6 +8,7 @@ from typing import Anyimport httpx+from . import coordsfrom .tiles import USER_AGENT# -- parsing -------------------------------------------------------------------@@ -20,7 +21,11 @@ _DMS = (def parse_coords(text: str) -> tuple[float, float] | None:- """Parse 'lat, lon' in decimal or DMS. Returns (lat, lon) or None."""+ """Parse coordinates in decimal, DMS, MGRS or plus-code form.++ Every format the app can display is accepted back — a reference copied out+ of Azimut must always paste back in. Returns (lat, lon) or None.+ """text = text.strip()# decimal: "50.4501, 30.5234" / "50.4501 30.5234"@@ -44,7 +49,34 @@ def parse_coords(text: str) -> tuple[float, float] | None:lon = next((v for v, h in values if h in "EW"), None)if lat is not None and lon is not None and -90 <= lat <= 90 and -180 <= lon <= 180:return lat, lon- return None++ # MGRS: "31U DQ 48250 11951" (spacing optional)+ mgrs = coords.parse_mgrs(text)+ if mgrs:+ return mgrs++ # full plus code: "8FW4V75V+8Q"+ return parse_plus_code(text)+++def parse_plus_code(text: str) -> tuple[float, float] | None:+ """Decode a full Open Location Code to its cell centre. None otherwise.++ Only full codes (the 8+2 form the app generates) — a short code needs a+ reference location to resolve, which a paste doesn't carry.+ """+ code = text.strip().upper()+ if not re.fullmatch(rf"[{_OLC_ALPHABET}]{{8}}\+[{_OLC_ALPHABET}]{{2}}", code):+ return None+ digits = code.replace("+", "")+ lat, lon = 0.0, 0.0+ res = 20.0+ for i in range(0, 10, 2):+ lat += _OLC_ALPHABET.index(digits[i]) * res+ lon += _OLC_ALPHABET.index(digits[i + 1]) * res+ res /= 20+ res *= 20 # the last pair's cell size+ return lat - 90 + res / 2, lon - 180 + res / 2# -- formatting ------------------------------------------------------------------@@ -94,11 +126,13 @@ def map_links(lat: float, lon: float, zoom: int = 17) -> dict[str, str]:"google": f"https://www.google.com/maps/@{lat},{lon},{zoom}z","google_sat": f"https://www.google.com/maps/@{lat},{lon},2000m/data=!3m1!1e3","google_earth": f"https://earth.google.com/web/@{lat},{lon},0a,1000d,35y,0h,0t,0r",+ "apple": f"https://maps.apple.com/?ll={lat},{lon}&z={zoom}&t=k","osm": f"https://www.openstreetmap.org/?mlat={lat}&mlon={lon}#map={zoom}/{lat}/{lon}","bing": f"https://www.bing.com/maps?cp={lat}~{lon}&lvl={zoom}&style=h","yandex": f"https://yandex.com/maps/?ll={lon},{lat}&z={zoom}&l=sat","sentinel": f"https://browser.dataspace.copernicus.eu/?zoom={zoom}&lat={lat}&lng={lon}","zoom_earth": f"https://zoom.earth/#view={lat},{lon},{zoom}z",+ "satellites_pro": f"https://satellites.pro/#{lat},{lon},{zoom}",}diff --git a/src/azimut/engine/inspect.py b/src/azimut/engine/inspect.pyindex 18d2fb8..f104313 100644--- a/src/azimut/engine/inspect.py+++ b/src/azimut/engine/inspect.py@@ -439,19 +439,6 @@ def _stamp() -> str:return datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")-def capture_frame(case: Case, video_rel: str, time_s: float, label: str | None = None) -> dict[str, Any]:- """Extract one frame and file it as case media."""- video_path = case.resolve_inside(video_rel)- frame = extract_frame(video_path, time_s)- stem = Path(video_path.name).stem[:40]- name = f"{stem}_t{time_s:.2f}s_{_stamp()}.png"- source = _derivation(video_rel, _source_sha(case, video_rel), op="frame", time=round(time_s, 3))- result = media_engine.import_image(case, frame, name, source, by="inspect")- if label and not result.get("duplicate"):- media_engine.update_media(case, result["item"]["path"], {"label": label})- return result--def scan_focus(case: Case, video_rel: str, set_progress: Callable[[dict], None] | None = None) -> list[dict[str, Any]]:@@ -538,67 +525,6 @@ def suggest_frames(return picks-# ----------------------------------------------------------------------------# Adjustments & collage (operate on images / captured frames)-# ------------------------------------------------------------------------------def bake(case: Case, rel_path: str, ops: list[dict[str, Any]], label: str | None = None) -> dict[str, Any]:- """Apply an adjustment pipeline to an image and file the result as new media."""- with Image.open(case.resolve_inside(rel_path)) as img:- rendered = apply_ops(img, ops)- stem = Path(rel_path).stem[:40]- name = f"{stem}_edit_{_stamp()}.png"- source = _derivation(rel_path, _source_sha(case, rel_path), op="adjust", ops=ops)- result = media_engine.import_image(case, rendered, name, source, by="inspect")- if label and not result.get("duplicate"):- media_engine.update_media(case, result["item"]["path"], {"label": label})- return result---def collage(- case: Case,- rel_paths: list[str],- *,- columns: int = 2,- gap: int = 8,- background: str = "#12141c",- cell: int = 480,- label: str | None = None,-) -> dict[str, Any]:- """Assemble several images into a contact-sheet / collage (one derivative)."""- if not rel_paths:- raise ValueError("collage needs at least one image")- columns = max(1, min(columns, len(rel_paths)))- cell = max(64, min(cell, 1024))- gap = max(0, min(gap, 64))-- tiles: list[Image.Image] = []- for rel in rel_paths:- with Image.open(case.resolve_inside(rel)) as img:- thumb = img.convert("RGB")- thumb.thumbnail((cell, cell))- tiles.append(thumb)-- rows = (len(tiles) + columns - 1) // columns- width = columns * cell + (columns + 1) * gap- height = rows * cell + (rows + 1) * gap- canvas = Image.new("RGB", (width, height), background)-- for idx, tile in enumerate(tiles):- r, c = divmod(idx, columns)- cx = gap + c * (cell + gap) + (cell - tile.width) // 2- cy = gap + r * (cell + gap) + (cell - tile.height) // 2- canvas.paste(tile, (cx, cy))-- source = _derivation("", None, op="collage", sources=rel_paths, columns=columns)- name = f"collage_{_stamp()}.png"- result = media_engine.import_image(case, canvas, name, source, by="inspect")- if label and not result.get("duplicate"):- media_engine.update_media(case, result["item"]["path"], {"label": label})- return result--# ---------------------------------------------------------------------------# Session workspace: recipes -> filed entities (Inspect Selection/Frame/Collage/Save)# ---------------------------------------------------------------------------@@ -627,14 +553,6 @@ def _source_image(return img-def preview_frame_png(case: Case, video_rel: str, time_s: float) -> bytes:- """Decode one video frame and return PNG bytes — for the transient tray only."""- frame = extract_frame(case.resolve_inside(video_rel), time_s)- buf = io.BytesIO()- frame.save(buf, "PNG")- return buf.getvalue()--def render_preview_png(case: Case, rel_path: str, *, time_s: float | None = None, ops: list[dict[str, Any]] | None = None) -> bytes:@@ -678,7 +596,7 @@ def save_frame(if not result.get("duplicate"):patch: dict[str, Any] = {}if label:- patch["label"] = label+ patch["title"] = labelif folder:patch["folder"] = folderif patch:@@ -814,7 +732,7 @@ def compose_perspective(if not result.get("duplicate"):patch: dict[str, Any] = {}if label:- patch["label"] = label+ patch["title"] = labelif folder:patch["folder"] = folderif patch:@@ -930,7 +848,7 @@ def enhance_video(if not result.get("duplicate"):patch: dict[str, Any] = {}if label:- patch["label"] = label+ patch["title"] = labelif folder:patch["folder"] = folderif patch:diff --git a/src/azimut/engine/media.py b/src/azimut/engine/media.pyindex f61548f..e2dce9e 100644--- a/src/azimut/engine/media.py+++ b/src/azimut/engine/media.py@@ -541,7 +541,11 @@ def download_url(downloaded = Path(ydl.prepare_filename(info))if not downloaded.exists(): # extension may differ after post-processing- candidates = sorted(tmp_dir.glob(f"*[{info['id']}]*"), key=lambda p: p.stat().st_mtime)+ # literal substring match — glob would treat "[id]" as a character class+ candidates = sorted(+ (p for p in tmp_dir.iterdir() if f"[{info['id']}]" in p.name),+ key=lambda p: p.stat().st_mtime,+ )if not candidates:raise RuntimeError("yt-dlp reported success but no file was produced")downloaded = candidates[-1]@@ -597,7 +601,7 @@ def list_media(case: Case) -> list[dict[str, Any]]:def update_media(case: Case, rel_path: str, patch: dict[str, Any]) -> dict[str, Any]:- """Update mutable sidecar fields (notes, folder, label) and mirror them onto+ """Update mutable sidecar fields (notes, folder, title) and mirror them ontothe media entity so the case sidebar stays in sync."""media_path = case.resolve_inside(rel_path)sidecar = _sidecar_path(media_path)@@ -619,8 +623,10 @@ def update_media(case: Case, rel_path: str, patch: dict[str, Any]) -> dict[str,entity = case.find_entity(attr="path", value=rel_path)if entity:entity_patch: dict[str, Any] = {}- if patch.get("title"):- entity_patch["label"] = patch["title"]+ if "title" in patch:+ # a cleared title falls back to the filename, like a fresh import —+ # the sidebar label must never freeze on a title that no longer exists+ entity_patch["label"] = str(patch["title"] or "") or media_path.nameattrs: dict[str, Any] = {}if "folder" in patch:attrs["folder"] = patch["folder"] or ""diff --git a/src/azimut/engine/tiles.py b/src/azimut/engine/tiles.pyindex f978e07..07231ba 100644--- a/src/azimut/engine/tiles.py+++ b/src/azimut/engine/tiles.py@@ -486,6 +486,9 @@ def fetch_crop(# A rotated crop needs a bigger north-up source so its corners stay covered# after rotation; the diagonal is the smallest square that always fits.+ # Near the SIZE_MAX cap the enlarged square is clamped back to SIZE_MAX, so+ # an extreme size+bearing combination can leave fill-coloured corners — the+ # cap wins over corner coverage by design.if bearing:fetch_w = fetch_h = min(math.ceil(math.hypot(width, height)) + 2, SIZE_MAX)else:diff --git a/src/azimut/jobs.py b/src/azimut/jobs.pyindex 37f9c7e..1e5e9e6 100644--- a/src/azimut/jobs.py+++ b/src/azimut/jobs.py@@ -13,11 +13,23 @@ from typing import Any, Callable_jobs: dict[str, dict[str, Any]] = {}_lock = threading.Lock()+# Finished jobs kept for late polls; older ones are dropped when a new job+# starts, so a long session doesn't grow the registry without bound.+MAX_FINISHED = 100+++def _evict_finished() -> None:+ """Drop the oldest finished jobs past MAX_FINISHED. Call under _lock."""+ finished = [jid for jid, job in _jobs.items() if job["status"] != "running"]+ for jid in finished[: max(0, len(finished) - MAX_FINISHED)]:+ del _jobs[jid]+def start(kind: str, work: Callable[[Callable[[dict[str, Any]], None]], Any]) -> str:"""Run `work(set_progress)` in a thread; returns the job id."""job_id = uuid.uuid4().hex[:12]with _lock:+ _evict_finished()_jobs[job_id] = {"id": job_id, "kind": kind, "status": "running", "progress": {}}def set_progress(progress: dict[str, Any]) -> None:diff --git a/src/azimut/launcher.py b/src/azimut/launcher.pynew file mode 100644index 0000000..813c6a6--- /dev/null+++ b/src/azimut/launcher.py@@ -0,0 +1,58 @@+"""Start the local server and open Azimut in a browser tab.++Azimut is a browser app: the UI lives in a normal Firefox/Chrome tab, not a+separate desktop window. So the launcher does the minimum — run the server and+open the tab once the server is actually accepting connections (rather than+after a fixed guess), which is the one thing the frozen binary needs to feel+like "double-click and it opens". The console stays the control surface: close+it (or Ctrl-C) to stop the server.++No GUI toolkit, no tray — those would pull per-OS native libraries (the kind of+dependency the packaging deliberately avoids), and the app is meant to run in+the browser anyway.+"""++from __future__ import annotations++import threading+import time+import webbrowser++import uvicorn+++def _build_server(port: int) -> uvicorn.Server:+ config = uvicorn.Config(+ "azimut.server:create_app",+ factory=True,+ host="127.0.0.1", # local-first: never bind beyond localhost+ port=port,+ log_level="warning",+ )+ return uvicorn.Server(config)+++def _open_when_ready(server: uvicorn.Server, url: str) -> None:+ """Open the browser tab once the server reports it's started.++ Polls ``server.started`` on a daemon thread so the open lands after the+ port is listening, not before — no white "can't connect" tab, and no fixed+ sleep that's too short on a cold frozen binary.+ """++ def wait_and_open() -> None:+ for _ in range(200): # up to ~10 s, then open anyway+ if server.started:+ break+ time.sleep(0.05)+ webbrowser.open(url)++ threading.Thread(target=wait_and_open, daemon=True).start()+++def serve(port: int, *, open_browser: bool = True) -> None:+ """Run the server (blocking) and, unless told not to, open the browser tab."""+ server = _build_server(port)+ if open_browser:+ _open_when_ready(server, f"http://127.0.0.1:{port}")+ server.run()diff --git a/src/azimut/server.py b/src/azimut/server.pyindex 4d6c485..8038f88 100644--- a/src/azimut/server.py+++ b/src/azimut/server.py@@ -4,14 +4,62 @@ from __future__ import annotationsfrom pathlib import Path-from fastapi import FastAPI-from fastapi.responses import FileResponse, JSONResponse+from fastapi import FastAPI, Request+from fastapi.responses import FileResponse, JSONResponse, PlainTextResponsefrom fastapi.staticfiles import StaticFilesfrom . import __version__, configSTATIC_DIR = Path(__file__).parent / "static"+# The server binds localhost only, but that alone doesn't stop a web page the+# browser has open from reaching it — a page can hit 127.0.0.1 directly (its+# own Origin travels along), or point a name it controls at 127.0.0.1 (DNS+# rebinding, where the Host header becomes that name). Both are refused here:+# the Host must be a loopback name (defeats rebinding), and a cross-origin+# web Origin is turned away on every route except the token-gated ingest+# island, which opens itself to browser-extension origins on purpose.+LOCAL_HOSTNAMES = frozenset({"127.0.0.1", "localhost", "::1", "[::1]"})+++def _hostname(value: str) -> str:+ """The bare host of a Host or Origin header — no scheme, path or port."""+ host = value.strip().lower()+ if "://" in host:+ host = host.split("://", 1)[1]+ host = host.split("/", 1)[0]+ if host.startswith("["): # bracketed IPv6, e.g. [::1]:8477 -> [::1]+ return host.split("]", 1)[0] + "]"+ return host.split(":", 1)[0]+++def _is_local(hostname: str) -> bool:+ return hostname in LOCAL_HOSTNAMES or hostname.endswith(".localhost")+++def install_local_guard(app: FastAPI) -> None:+ """Reject requests that don't originate from this machine's own loopback.++ Added last so it runs first (outermost middleware): a bad Host or a+ cross-origin web Origin is refused before any router — or the ingest CORS+ layer — sees it. Extension origins are still allowed, but only on the+ ingest routes they're scoped to.+ """+ from .api.ingest import EXTENSION_ORIGIN_SCHEMES++ @app.middleware("http")+ async def local_guard(request: Request, call_next):+ if not _is_local(_hostname(request.headers.get("host", ""))):+ return PlainTextResponse("invalid host header", status_code=400)+ origin = request.headers.get("origin")+ if origin and not _is_local(_hostname(origin)):+ ingest_extension = request.url.path.startswith(+ "/api/ingest/"+ ) and origin.startswith(EXTENSION_ORIGIN_SCHEMES)+ if not ingest_extension:+ return PlainTextResponse("cross-origin request refused", status_code=403)+ return await call_next(request)+def create_app() -> FastAPI:config.ensure_workspace()@@ -21,6 +69,14 @@ def create_app() -> FastAPI:scrapers.activate()+ # Reap stale empty scratch sessions; never let housekeeping block startup.+ from .workspace import Case++ try:+ Case.cleanup_scratch()+ except OSError:+ pass+app = FastAPI(title="Azimut", version=__version__, docs_url="/api/docs")from .api import cases, drafts, events, files, ingest, inspect, media, proofs, satellite, settings@@ -37,6 +93,8 @@ def create_app() -> FastAPI:app.include_router(events.router)# extension-origin CORS, /api/ingest/* only (see ingest.install_cors)ingest.install_cors(app)+ # last, so it wraps everything: refuse non-loopback Host / cross-origin web+ install_local_guard(app)@app.get("/api/health")def health() -> dict[str, str]:diff --git a/src/azimut/workspace.py b/src/azimut/workspace.pyindex 2d44233..6806c60 100644--- a/src/azimut/workspace.py+++ b/src/azimut/workspace.py@@ -29,6 +29,9 @@ from . import configCASE_SUBDIRS = ("media", "proofs", "exports", "inspect")+# Empty scratch sessions older than this are reaped at startup (spec §9).+SCRATCH_MAX_AGE_DAYS = 14+# One lock per case directory, shared across every Case instance that points# at it (a fresh instance is constructed per request). Without it, concurrent# read-modify-write of case.json — e.g. several media downloads from the@@ -175,6 +178,52 @@ class Case:return cls(path)raise CaseError(f"case '{case_id}' not found")+ @classmethod+ def cleanup_scratch(cls, max_age_days: int = SCRATCH_MAX_AGE_DAYS) -> int:+ """Delete scratch cases that hold nothing and haven't been touched in+ ``max_age_days``. Returns how many were removed.++ "Nothing" means no entities, no links and no files under the case+ subdirs — a scratch with any content is never touched (promote or+ delete it deliberately). Closes the spec §9 question: one-shot+ sessions and unpicked extension captures stop accumulating forever.+ """+ parent = config.scratch_dir()+ if not parent.is_dir():+ return 0+ cutoff = datetime.now(timezone.utc).timestamp() - max_age_days * 86400+ removed = 0+ for path in list(parent.iterdir()):+ if not (path / "case.json").exists():+ continue+ case = cls(path)+ try:+ data = case.read()+ except (OSError, json.JSONDecodeError):+ continue+ if data.get("entities") or data.get("links"):+ continue+ stamp = data.get("updated_at") or data.get("created_at") or ""+ try:+ when = datetime.strptime(stamp, "%Y-%m-%dT%H:%M:%SZ")+ except ValueError:+ continue+ if when.replace(tzinfo=timezone.utc).timestamp() > cutoff:+ continue+ if any(+ p.is_file()+ for sub in CASE_SUBDIRS+ if (path / sub).is_dir()+ for p in (path / sub).rglob("*")+ ):+ continue+ try:+ case.delete()+ removed += 1+ except OSError:+ continue # a file may be open elsewhere (Windows) — next start+ return removed+@classmethoddef list_all(cls) -> list[dict[str, Any]]:out: list[dict[str, Any]] = []diff --git a/tests/conftest.py b/tests/conftest.pyindex 1ad61d8..29f3692 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -20,5 +20,7 @@ def client(monkeypatch):monkeypatch.setenv("AZIMUT_HOME", home)from azimut.server import create_app- with TestClient(create_app()) as c:+ # base_url is a loopback host so the app's own Host guard (server.py+ # install_local_guard) lets requests through, as a real browser would.+ with TestClient(create_app(), base_url="http://127.0.0.1") as c:yield cdiff --git a/tests/test_cases_api.py b/tests/test_cases_api.pyindex 16590e5..e857f67 100644--- a/tests/test_cases_api.py+++ b/tests/test_cases_api.py@@ -309,3 +309,36 @@ def test_delete_media_entity_removes_file(client):e["type"] == "media" for e in client.get(f"/api/cases/{cid}").json()["entities"])+++def test_cleanup_scratch_reaps_only_old_empty_sessions(tmp_workspace):+ import json as jsonlib++ from azimut.workspace import Case++ old_stamp = "2000-01-01T00:00:00Z"++ def _age(case):+ data = jsonlib.loads(case.json_path.read_text(encoding="utf-8"))+ data["updated_at"] = old_stamp+ case.json_path.write_text(jsonlib.dumps(data), encoding="utf-8")++ # old and empty → reaped+ empty_old = Case.create("Scratch session", scratch=True)+ _age(empty_old)+ # old but holding an entity → kept+ with_entity = Case.create("Scratch session", scratch=True)+ with_entity.add_entity("place", "Somewhere", attrs={}, by="test")+ _age(with_entity)+ # old but holding a media file → kept+ with_file = Case.create("Scratch session", scratch=True)+ (with_file.path / "media" / "shot.png").write_bytes(b"png")+ _age(with_file)+ # fresh and empty → kept (it may be in use right now)+ empty_new = Case.create("Scratch session", scratch=True)++ assert Case.cleanup_scratch() == 1+ assert not empty_old.path.exists()+ assert with_entity.path.exists()+ assert with_file.path.exists()+ assert empty_new.path.exists()diff --git a/tests/test_coords.py b/tests/test_coords.pyindex f55660f..dd0aaee 100644--- a/tests/test_coords.py+++ b/tests/test_coords.py@@ -44,6 +44,32 @@ def test_format_mgrs_is_none_beyond_the_utm_limits():assert coords.format_mgrs(-85, 10) is None[email protected]("lat,lon,expected", MGRS_VECTORS)+def test_parse_mgrs_round_trips_the_reference(lat, lon, expected):+ import math++ parsed = coords.parse_mgrs(expected)+ assert parsed is not None+ plat, plon = parsed+ # the reference cell is 1 m; the parse answers its centre, so the+ # round-trip error must stay within a few metres+ assert abs(plat - lat) * 111320 < 5+ assert abs(plon - lon) * 111320 * math.cos(math.radians(lat)) < 5+++def test_parse_mgrs_accepts_compact_spacing_and_lowercase():+ reference = coords.parse_mgrs("31U DQ 48250 11951")+ assert coords.parse_mgrs("31UDQ4825011951") == reference+ assert coords.parse_mgrs("31u dq 48250 11951") == reference+++def test_parse_mgrs_rejects_non_mgrs_text():+ assert coords.parse_mgrs("hello world") is None+ assert coords.parse_mgrs("31U DQ 482 11951") is None # odd digit count+ assert coords.parse_mgrs("31U IQ 48250 11951") is None # I is never a column+ assert coords.parse_mgrs("99U DQ 48250 11951") is None # zone out of range++def test_utm_zone_exceptions():assert coords.utm_zone(48.8583701, 2.2944813) == 31assert coords.utm_zone(59.9, 4.9) == 32 # plain formula would say 31diff --git a/tests/test_events_api.py b/tests/test_events_api.pyindex e02c2ac..151bf2a 100644--- a/tests/test_events_api.py+++ b/tests/test_events_api.py@@ -50,7 +50,7 @@ def test_a_full_queue_drops_the_nudge_instead_of_failing_the_producer():def test_ingest_publishes_a_capture_nudge(client):- token = client.get("/api/settings").json()["ingest_token"]+ token = client.post("/api/settings/ingest-token").json()["ingest_token"]cid = client.post("/api/cases", json={"name": "Live"}).json()["id"]q = events.subscribe()try:@@ -58,7 +58,7 @@ def test_ingest_publishes_a_capture_nudge(client):"/api/ingest/screenshot",files={"image": ("shot.png", _png_bytes(), "image/png")},data={"url": "https://www.openstreetmap.org/#map=17/48.85/2.29",- "site": "openstreetmap", "case_id": cid,+ "case_id": cid,"lat": "48.85", "lon": "2.29", "title": "Test spot"},headers={"X-Azimut-Token": token},)diff --git a/tests/test_hardening.py b/tests/test_hardening.pynew file mode 100644index 0000000..56d5196--- /dev/null+++ b/tests/test_hardening.py@@ -0,0 +1,23 @@+"""Local hardening: the decompression-bomb clamp and owner-only secrets file."""++import os+import stat+import sys++import pytest+from PIL import Image++from azimut import config+++def test_decompression_bomb_guard_is_set():+ import azimut # noqa: F401 (importing the package installs the clamp)++ assert Image.MAX_IMAGE_PIXELS == 100_000_000++[email protected](sys.platform == "win32", reason="POSIX file modes")+def test_settings_and_workspace_are_owner_only(tmp_workspace):+ config.ensure_workspace()+ assert stat.S_IMODE(os.stat(config.workspace_root()).st_mode) == 0o700+ assert stat.S_IMODE(os.stat(config.settings_path()).st_mode) == 0o600diff --git a/tests/test_ingest_api.py b/tests/test_ingest_api.pyindex 181b98c..0ad4dfb 100644--- a/tests/test_ingest_api.py+++ b/tests/test_ingest_api.py@@ -21,7 +21,9 @@ def _png_bytes(w=320, h=200, color=(30, 90, 30)):def _token(client):- return client.get("/api/settings").json()["ingest_token"]+ # minting is an explicit user action (POST), never a side effect of opening+ # Settings — see mint_ingest_token in api/settings.py+ return client.post("/api/settings/ingest-token").json()["ingest_token"]def _post(client, token=None, **overrides):@@ -39,9 +41,13 @@ def _post(client, token=None, **overrides):def test_token_is_minted_once_and_survives_reads(client):+ # opening Settings must not mint a credential — only the explicit POST does+ assert client.get("/api/settings").json()["ingest_token"] == ""token = _token(client)assert len(token) >= 24assert _token(client) == token # stable across reads — pairing must not churn+ # once minted, it does show up in Settings+ assert client.get("/api/settings").json()["ingest_token"] == tokendef test_rotation_orphans_the_old_token(client):diff --git a/tests/test_inspect_api.py b/tests/test_inspect_api.pyindex 6f6b7c4..3cf6c00 100644--- a/tests/test_inspect_api.py+++ b/tests/test_inspect_api.py@@ -44,15 +44,16 @@ def test_probe_image(client):assert probe["width"] == 120 and probe["height"] == 90-def test_bake_creates_derivative_media(client):+def test_save_frames_files_adjusted_derivative(client):cid = client.post("/api/cases", json={"name": "Bake"}).json()["id"]item = _upload(client, cid, "orig.png")res = client.post(- f"/api/cases/{cid}/inspect/bake",- json={"path": item["path"], "ops": [{"op": "brightness", "params": {"amount": 1.4}}],- "label": "Brightened"},- ).json()+ f"/api/cases/{cid}/inspect/save-frames",+ json={"items": [{"path": item["path"],+ "ops": [{"op": "brightness", "params": {"amount": 1.4}}],+ "label": "Brightened"}]},+ ).json()["saved"][0]assert res["duplicate"] is Falsenew_path = res["item"]["path"]assert new_path != item["path"]@@ -70,13 +71,18 @@ def test_bake_creates_derivative_media(client):assert updated["source"]["op"] == "adjust"assert updated["source"]["from"] == item["path"]+ # the label reaches the sidecar title and the entity label — a labeled+ # save must never be a silent no-op+ assert updated["title"] == "Brightened"+ assert derived["label"] == "Brightened"-def test_bake_unknown_filter_is_rejected(client):++def test_save_frames_unknown_filter_is_rejected(client):cid = client.post("/api/cases", json={"name": "BadOp"}).json()["id"]item = _upload(client, cid, "x.png")res = client.post(- f"/api/cases/{cid}/inspect/bake",- json={"path": item["path"], "ops": [{"op": "nope", "params": {}}]},+ f"/api/cases/{cid}/inspect/save-frames",+ json={"items": [{"path": item["path"], "ops": [{"op": "nope", "params": {}}]}]},)assert res.status_code == 422@@ -85,37 +91,46 @@ def test_crop_op_reduces_dimensions(client):cid = client.post("/api/cases", json={"name": "Crop"}).json()["id"]item = _upload(client, cid, "big.png", _png_bytes(size=(200, 100)))res = client.post(- f"/api/cases/{cid}/inspect/bake",- json={"path": item["path"],- "ops": [{"op": "crop", "params": {"x": 0.25, "y": 0.25, "w": 0.5, "h": 0.5}}]},- ).json()+ f"/api/cases/{cid}/inspect/save-frames",+ json={"items": [{"path": item["path"],+ "ops": [{"op": "crop",+ "params": {"x": 0.25, "y": 0.25, "w": 0.5, "h": 0.5}}]}]},+ ).json()["saved"][0]probe = client.get(f"/api/cases/{cid}/inspect/probe", params={"path": res["item"]["path"]}).json()assert probe["width"] == 100 and probe["height"] == 50-def test_collage_combines_images(client):+def test_compose_combines_images(client):cid = client.post("/api/cases", json={"name": "Collage"}).json()["id"]a = _upload(client, cid, "a.png", _png_bytes(color=(10, 20, 30)))b = _upload(client, cid, "b.png", _png_bytes(color=(200, 100, 50)))res = client.post(- f"/api/cases/{cid}/inspect/collage",- json={"paths": [a["path"], b["path"]], "columns": 2, "cell": 100, "gap": 10},+ f"/api/cases/{cid}/inspect/compose",+ json={"width": 230, "height": 120,+ "nodes": [+ {"src": {"path": a["path"]},+ "quad": [[10, 10], [110, 10], [110, 110], [10, 110]]},+ {"src": {"path": b["path"]},+ "quad": [[120, 10], [220, 10], [220, 110], [120, 110]]},+ ]},).json()assert res["duplicate"] is Falseprobe = client.get(f"/api/cases/{cid}/inspect/probe", params={"path": res["item"]["path"]}).json()- # 2 columns × 100 cell + 3 gaps × 10 = 230 wide, 1 row = 120 tallassert probe["width"] == 230 and probe["height"] == 120assert client.get(f"/api/cases/{cid}/media").json().__len__() == 3-def test_collage_requires_paths(client):+def test_compose_requires_nodes(client):cid = client.post("/api/cases", json={"name": "Empty"}).json()["id"]- res = client.post(f"/api/cases/{cid}/inspect/collage", json={"paths": []})+ res = client.post(+ f"/api/cases/{cid}/inspect/compose",+ json={"width": 100, "height": 100, "nodes": []},+ )assert res.status_code == 422@@ -585,7 +600,7 @@ def test_frame_preview_returns_png_without_filing(client, tmp_path):before = len(client.get(f"/api/cases/{cid}/media").json())res = client.post(- f"/api/cases/{cid}/inspect/frame/preview", json={"path": item["path"], "time": 1.0}+ f"/api/cases/{cid}/inspect/render-preview", json={"path": item["path"], "time": 1.0})assert res.status_code == 200assert res.headers["content-type"] == "image/png"@@ -799,8 +814,9 @@ def test_frame_capture_from_video(client, tmp_path):).json()["item"]res = client.post(- f"/api/cases/{cid}/inspect/frame", json={"path": item["path"], "time": 1.0}- ).json()+ f"/api/cases/{cid}/inspect/save-frames",+ json={"items": [{"path": item["path"], "time": 1.0}]},+ ).json()["saved"][0]assert res["item"]["kind"] == "image"assert client.get(f"/files/{cid}/{res['item']['path']}").status_code == 200diff --git a/tests/test_jobs.py b/tests/test_jobs.pynew file mode 100644index 0000000..b61dcbd--- /dev/null+++ b/tests/test_jobs.py@@ -0,0 +1,43 @@+"""The in-memory job registry: finished jobs are evicted, running ones never."""++import threading++from azimut import jobs+++def test_start_evicts_old_finished_jobs_but_keeps_running_ones(monkeypatch):+ registry = {}+ monkeypatch.setattr(jobs, "_jobs", registry)+ monkeypatch.setattr(jobs, "MAX_FINISHED", 3)++ for i in range(5):+ registry[f"done{i}"] = {"id": f"done{i}", "kind": "t", "status": "done", "progress": {}}+ registry["busy"] = {"id": "busy", "kind": "t", "status": "running", "progress": {}}++ finished = threading.Event()+ job_id = jobs.start("t", lambda set_progress: finished.set())+ assert finished.wait(timeout=5)++ # the two oldest finished jobs were dropped; running and recent ones stay+ assert "done0" not in registry and "done1" not in registry+ assert all(key in registry for key in ("done2", "done3", "done4", "busy", job_id))+++def test_get_reports_completion(monkeypatch):+ monkeypatch.setattr(jobs, "_jobs", {})+ finished = threading.Event()++ def work(set_progress):+ set_progress({"percent": 50})+ finished.set()+ return {"answer": 42}++ job_id = jobs.start("t", work)+ assert finished.wait(timeout=5)+ for _ in range(200): # the runner thread updates status after `finished`+ job = jobs.get(job_id)+ if job["status"] == "done":+ break+ threading.Event().wait(0.01)+ assert job["status"] == "done"+ assert job["result"] == {"answer": 42}diff --git a/tests/test_launcher.py b/tests/test_launcher.pynew file mode 100644index 0000000..db5197d--- /dev/null+++ b/tests/test_launcher.py@@ -0,0 +1,63 @@+"""The launcher: build a localhost server and open the browser tab once it's up.++Azimut runs in a browser tab (no desktop window), so the launcher's whole job+is to bind loopback and open the tab when the server is actually listening.+"""++import sys+import time++from azimut import cli, launcher+++def test_build_server_binds_localhost():+ server = launcher._build_server(9123)+ assert server.config.host == "127.0.0.1"+ assert server.config.port == 9123+++def test_serve_runs_the_server_without_opening_a_browser(monkeypatch):+ calls = {"run": 0, "open": 0}++ class FakeServer:+ started = True++ def run(self):+ calls["run"] += 1++ monkeypatch.setattr(launcher, "_build_server", lambda port: FakeServer())+ monkeypatch.setattr(launcher.webbrowser, "open", lambda url: calls.__setitem__("open", 1))++ launcher.serve(8477, open_browser=False)+ assert calls["run"] == 1+ assert calls["open"] == 0+++def test_serve_opens_the_browser_tab_when_ready(monkeypatch):+ opened = []++ class FakeServer:+ started = True++ def run(self):+ pass++ monkeypatch.setattr(launcher, "_build_server", lambda port: FakeServer())+ monkeypatch.setattr(launcher.webbrowser, "open", opened.append)++ launcher.serve(8477, open_browser=True)+ for _ in range(200): # the open lands on a daemon thread — wait for it+ if opened:+ break+ time.sleep(0.01)+ assert opened == ["http://127.0.0.1:8477"]+++def test_cli_forwards_arguments_to_serve(monkeypatch):+ captured = {}+ monkeypatch.setattr(+ cli, "serve", lambda port, open_browser: captured.update(port=port, open_browser=open_browser)+ )+ monkeypatch.setattr(sys, "argv", ["azimut", "--port", "9999", "--no-browser"])+ cli.main()+ assert captured == {"port": 9999, "open_browser": False}diff --git a/tests/test_links_api.py b/tests/test_links_api.pyindex fbaa599..2b0e6b3 100644--- a/tests/test_links_api.py+++ b/tests/test_links_api.py@@ -150,6 +150,18 @@ def test_session_save_depends_on_its_subject(client):assert depends[0]["to"] == _entity(client, cid, path=a)["id"]+def _compose_two(client, cid, a, b):+ """Compose two case images side by side (the modern collage save)."""+ return client.post(+ f"/api/cases/{cid}/inspect/compose",+ json={"width": 220, "height": 100,+ "nodes": [+ {"src": {"path": a}, "quad": [[0, 0], [100, 0], [100, 100], [0, 100]]},+ {"src": {"path": b}, "quad": [[110, 0], [210, 0], [210, 100], [110, 100]]},+ ]},+ ).json()++def test_a_derived_media_links_to_its_sources(client):# Frames, collages and enhanced videos are all filed through one registration# point, so the chain is wired once for every tool that makes imagery — the@@ -158,9 +170,7 @@ def test_a_derived_media_links_to_its_sources(client):a = _upload(client, cid, "a.png", _png_bytes((1, 2, 3)))["item"]["path"]b = _upload(client, cid, "b.png", _png_bytes((4, 5, 6)))["item"]["path"]- res = client.post(- f"/api/cases/{cid}/inspect/collage", json={"paths": [a, b], "columns": 2}- ).json()+ res = _compose_two(client, cid, a, b)collage = _entity(client, cid, path=res["item"]["path"])targets = {l["to"] for l in _links(client, cid, "derived-from") if l["from"] == collage["id"]}@@ -179,10 +189,9 @@ def test_a_deduped_derivative_still_gets_its_chain_once(client):cid = _new_case(client, "Dedupe")a = _upload(client, cid, "a.png", _png_bytes((1, 2, 3)))["item"]["path"]b = _upload(client, cid, "b.png", _png_bytes((4, 5, 6)))["item"]["path"]- body = {"paths": [a, b], "columns": 2}- first = client.post(f"/api/cases/{cid}/inspect/collage", json=body).json()- second = client.post(f"/api/cases/{cid}/inspect/collage", json=body).json()+ first = _compose_two(client, cid, a, b)+ second = _compose_two(client, cid, a, b)assert second["duplicate"] is Trueassert second["entity"]["id"] == first["entity"]["id"]diff --git a/tests/test_media_api.py b/tests/test_media_api.pyindex 4f96502..57f2204 100644--- a/tests/test_media_api.py+++ b/tests/test_media_api.py@@ -128,6 +128,11 @@ def test_update_media_title(client):).json()assert "title" not in cleared+ # the entity label falls back to the filename — it must not freeze on the+ # old title once that title is gone+ entities = client.get(f"/api/cases/{cid}").json()["entities"]+ assert entities[0]["label"] == item["path"].rsplit("/", 1)[-1]+def test_update_media_clear_notes(client):cid = client.post("/api/cases", json={"name": "Clear"}).json()["id"]diff --git a/tests/test_proofs_api.py b/tests/test_proofs_api.pyindex 0cf05bb..bb6e099 100644--- a/tests/test_proofs_api.py+++ b/tests/test_proofs_api.py@@ -70,6 +70,30 @@ def test_save_load_roundtrip(client):assert entities[0]["label"] == "Renamed proof"+def test_resave_with_png_adds_the_path_to_the_entity(client):+ cid = client.post("/api/cases", json={"name": "SpecFirst"}).json()["id"]++ # first save is spec-only: no PNG, so the entity has no path+ saved = client.post(+ f"/api/cases/{cid}/proofs", json={"title": "Draft proof", "spec": SPEC}+ ).json()+ entity = next(+ e for e in client.get(f"/api/cases/{cid}").json()["entities"] if e["type"] == "proof"+ )+ assert "path" not in entity["attrs"]++ # exporting later re-saves with the PNG — the entity must gain the path,+ # or the sidebar preview and delete_by_path can't see the file+ client.post(+ f"/api/cases/{cid}/proofs",+ json={"name": saved["name"], "title": "Draft proof", "spec": SPEC, "png_base64": _png_b64()},+ )+ entity = next(+ e for e in client.get(f"/api/cases/{cid}").json()["entities"] if e["type"] == "proof"+ )+ assert entity["attrs"]["path"] == f"proofs/{saved['name']}.png"++def test_invalid_png_rejected(client):cid = client.post("/api/cases", json={"name": "Bad"}).json()["id"]res = client.post(diff --git a/tests/test_satellite_api.py b/tests/test_satellite_api.pyindex be6d39d..2bd4979 100644--- a/tests/test_satellite_api.py+++ b/tests/test_satellite_api.py@@ -492,6 +492,13 @@ def test_screenshot_capture_refused_for_tile_providers(client):assert r.status_code == 422+def test_tile_proxy_rejects_out_of_range_coordinates(client):+ # a negative z used to reach `1 << z` and 500; bad input is a 422, not a crash+ assert client.get("/api/tiles/esri-world-imagery/-1/0/0").status_code == 422+ assert client.get("/api/tiles/esri-world-imagery/2/4/0").status_code == 422+ assert client.get("/api/tiles/esri-world-imagery/2/0/-1").status_code == 422++def test_tile_proxy_benches_google_on_a_persistent_403(client, monkeypatch):"""A 403 that survives the session re-mint names the key (EEA policy,revoked key) — the basemap must stop being offered, with Google's owndiff --git a/tests/test_server_guard.py b/tests/test_server_guard.pynew file mode 100644index 0000000..395c8c5--- /dev/null+++ b/tests/test_server_guard.py@@ -0,0 +1,44 @@+"""The loopback Host / Origin guard (server.install_local_guard).++The server binds localhost, but a page the browser already has open can still+reach 127.0.0.1 directly, or point a name it controls at it (DNS rebinding).+The guard is the wall: the Host must be a loopback name, and a cross-origin web+Origin is turned away everywhere except the token-gated ingest island, which+opens itself to browser-extension origins on purpose.++The shared ``client`` fixture already uses a loopback base_url, so per-request+header overrides are exactly what the guard sees.+"""+++def test_loopback_host_is_allowed(client):+ for host in ("127.0.0.1", "127.0.0.1:8477", "localhost", "[::1]:8477"):+ assert client.get("/api/health", headers={"host": host}).status_code == 200+ # a *.localhost name still resolves to loopback and defeats rebinding+ assert client.get("/api/health", headers={"host": "app.localhost"}).status_code == 200+++def test_non_loopback_host_is_refused(client):+ # DNS rebinding: a name the attacker controls now points at 127.0.0.1+ r = client.get("/api/health", headers={"host": "evil.example"})+ assert r.status_code == 400+ assert r.text == "invalid host header"+++def test_cross_origin_web_page_is_refused(client):+ r = client.get("/api/health", headers={"origin": "https://evil.example"})+ assert r.status_code == 403+++def test_same_origin_web_page_is_allowed(client):+ assert client.get("/api/health", headers={"origin": "http://127.0.0.1:8477"}).status_code == 200+ assert client.get("/api/health", headers={"origin": "http://localhost:8477"}).status_code == 200+++def test_extension_origin_reaches_only_the_ingest_island(client):+ ext = "chrome-extension://abcdefghijklmnop"+ # the guard lets the extension through on ingest routes — it fails later at+ # the token wall (401), not at the guard (403)+ assert client.get("/api/ingest/ping", headers={"origin": ext}).status_code == 401+ # but anywhere else the extension origin is a cross-origin web page+ assert client.get("/api/health", headers={"origin": ext}).status_code == 403diff --git a/tests/test_settings_backup.py b/tests/test_settings_backup.pynew file mode 100644index 0000000..a51c3e8--- /dev/null+++ b/tests/test_settings_backup.py@@ -0,0 +1,44 @@+"""Settings backup (export/import) and the lazy pairing-token mint."""++from azimut import config+++def test_opening_settings_does_not_mint_the_pairing_token(client):+ # loading Settings must not create a credential (it used to mint on read)+ assert client.get("/api/settings").json()["ingest_token"] == ""+ minted = client.post("/api/settings/ingest-token").json()["ingest_token"]+ assert minted+ # once minted, it's reported and stable across reads+ assert client.get("/api/settings").json()["ingest_token"] == minted+ assert client.post("/api/settings/ingest-token").json()["ingest_token"] == minted+++def test_export_then_import_restores_keys_and_prefs(client):+ client.put("/api/settings/keys", json={"mapbox": "pk.exported"})+ client.put("/api/settings/prefs", json={"units": "imperial"})++ exported = client.get("/api/settings/export")+ assert exported.headers["content-disposition"].startswith("attachment")+ blob = exported.json()+ assert blob["api_keys"]["mapbox"] == "pk.exported"+ assert blob["units"] == "imperial"++ # wipe both, then restore from the exported blob+ client.put("/api/settings/keys", json={"mapbox": ""})+ client.put("/api/settings/prefs", json={"units": "metric"})+ res = client.post("/api/settings/import", json={"settings": blob}).json()+ assert "api_keys" in res["imported"]++ restored = client.get("/api/settings").json()+ assert restored["api_keys"]["mapbox"] == "pk.exported"+ assert restored["units"] == "imperial"+++def test_import_ignores_unknown_keys(client):+ res = client.post(+ "/api/settings/import", json={"settings": {"evil": "boom", "units": "imperial"}}+ ).json()+ assert res["imported"] == ["units"]+ stored = config.load_settings()+ assert "evil" not in stored+ assert stored["units"] == "imperial"diff --git a/tests/test_tiles.py b/tests/test_tiles.pyindex d70c3ab..bdefa23 100644--- a/tests/test_tiles.py+++ b/tests/test_tiles.py@@ -627,6 +627,13 @@ def test_parse_coords():lat, lon = geo.parse_coords("""48°51'29.6"N 2°17'40.2"E""")assert abs(lat - 48.85822) < 1e-4assert abs(lon - 2.29450) < 1e-4+ # every displayable format pastes back in: MGRS…+ lat, lon = geo.parse_coords("31U DQ 48250 11951")+ assert abs(lat - 48.85837) < 1e-3 and abs(lon - 2.29448) < 1e-3+ # …and full plus codes (round-trip through the app's own encoder)+ lat, lon = geo.parse_coords(geo.plus_code(48.8584, 2.2945))+ assert abs(lat - 48.8584) < 1e-3 and abs(lon - 2.2945) < 1e-3+assert geo.parse_coords("hello world") is Noneassert geo.parse_coords("91, 0") is None@@ -643,7 +650,10 @@ def test_dms_format():def test_map_links_cover_external_maps():links = geo.map_links(48.8584, 2.2945, 16)- for key in ("google", "google_earth", "bing", "yandex", "sentinel", "zoom_earth"):+ for key in (+ "google", "google_earth", "apple", "bing", "yandex",+ "sentinel", "zoom_earth", "satellites_pro",+ ):assert key in links and links[key].startswith("https://")# Yandex takes lon,lat orderassert "ll=2.2945,48.8584" in links["yandex"]