Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
0bad42e
fix: never save a movie over another movie whose name differs only by…
gbarnai Nov 29, 2026
a509db5
test: saves under a case or cleaned twin name keep the other movie
gbarnai Nov 29, 2026
6c0be12
fix: start npm shims on Windows without the command interpreter and c…
gbarnai Nov 29, 2026
8710edb
test: npm shims start directly and interpreter arguments are checked …
gbarnai Nov 29, 2026
bc02592
fix: import conversions read only the local file they are given
gbarnai Nov 29, 2026
538001f
test: import conversions keep ffmpeg to the one local file
gbarnai Nov 29, 2026
558bea4
fix: settings writers read, change and write under one lock so none u…
gbarnai Nov 29, 2026
a64f992
test: setting changes made during a library copy or at the same time …
gbarnai Nov 29, 2026
91b96b1
fix: keep arguments to a Windows .cmd intact when its path has a space
gbarnai Nov 29, 2026
48b08e5
fix: treat movie names that differ only by Unicode form as the same name
gbarnai Nov 29, 2026
ee56e9d
docs: record the command interpreter and Unicode name decisions
gbarnai Nov 29, 2026
a5ab7c3
fix: refuse every interpreter character in words passed to a Windows …
gbarnai Nov 29, 2026
6c3ea94
test: words for a Windows .cmd are refused on any interpreter charact…
gbarnai Nov 29, 2026
93346df
fix: import conversions read only real media containers
gbarnai Nov 29, 2026
9961a54
test: import conversions are pinned to the probed container and refus…
gbarnai Nov 29, 2026
c452a34
docs: record the interpreter word rule and the pinned import container
gbarnai Nov 29, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion NOTICE.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ FormMorpheus is licensed under the Apache License 2.0 (`LICENSE`). It includes o
| formvis design system and shell (shell, panel and dialog styles, theme boot, DOM helpers, menus, native menus, caption buttons, Home screen, dialogs, toasts, command registry and palette, number fields, controls), by nodemode-ai | `frontend/src/styles`, `frontend/src/ui`, `frontend/index.html` | Apache-2.0 |
| formvis desktop shell (splash and reveal sequence, traffic light placement, text edit routing, packaged engine lookup, window state), by nodemode-ai | `src-tauri/src`, `frontend/public/splash.html`, `setup/` | Apache-2.0 |
| formvfx engine patterns (typed event emitter, timeline mapping, ruler ticks, gesture merge for undo), by nodemode-ai | `frontend/src/engine/events.ts`, `frontend/src/ui/timeline.ts`, `frontend/src/engine/history.ts` | Apache-2.0 |
| formvis dock module 2.2.1 (terminal panel, agent tabs, the question an outside agent raises; version in `frontend/src/dock/MANIFEST.json`) and the shared agent program finder 1.0.1, shared Form family code copied unchanged, by nodemode-ai | `frontend/src/dock/`, `backend/app/services/agent_lookup.py` | Apache-2.0 |
| formvis dock module 2.2.1 (terminal panel, agent tabs, the question an outside agent raises; version in `frontend/src/dock/MANIFEST.json`) and the shared agent program finder 1.0.2, shared Form family code copied unchanged, by nodemode-ai | `frontend/src/dock/`, `backend/app/services/agent_lookup.py` | Apache-2.0 |
| Remix Icon: the `paintbrush` and `hand` icon paths in `frontend/src/ui/icons.ts`, identical to FormVis's, which credits them to Remix Icon | inline SVG icons | Apache-2.0 (Remix Icon's license through its 4.9 releases; the project changed its license terms in January 2026, and the release these two paths come from was not recorded) |
| fflate | `.fmo` movie files (zip), exported frame archives | MIT |
| mediabunny 1.61.5 (Vanilagy), used unmodified from npm; source: https://github.com/Vanilagy/mediabunny | reading video and sound files, writing MP4, WebM and MOV exports | MPL-2.0 (file-level copyleft: its files are shipped unedited) |
Expand Down
34 changes: 34 additions & 0 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,40 @@ Last updated: 2026-11-27 · scenes of your own

---

## unreleased · a save never replaces a different movie

- refers-to: routers/library.py :: _all_movies, _lands_on_other_movie, write_project
- kind: decision
- logged: 2026-11-28

- `PUT /api/library/{name}` answers 409 when the name only cleans into another movie's name (a trailing dot or space, a separator) or differs from a movie in the library only by case or Unicode form (NFC against NFD). On a case-insensitive or form-insensitive disk both are one file, so the save would have replaced that movie with no copy in Recently Deleted. A first save under a name that needs cleaning still works, and the window carries on with the cleaned name the engine answers with.

## unreleased · agent programs from an npm shim start without the command interpreter

- refers-to: services/agent_lookup.py :: _shim_target, _CMD_REFUSED, _cmd_words, start_argv (finder 1.0.2); setup/agents.py :: LOOKUP_HASHES
- kind: decision
- logged: 2026-11-28

- On Windows an npm `.cmd` shim is read and started as what it names: the program, or the script with the `node.exe` beside the shim or the `node` on PATH. The program then gets its arguments exactly as given, quotes and `&` included.
- Any other `.cmd` or `.bat` still goes through the command interpreter (`/d /c`, so no AutoRun command runs first). Quoting does not protect a word there: the interpreter and the `.cmd`, which reads its `%*` again, act on `& | < > ^ ( ) ! %` and `"` even inside quotes. So every word, the program's path included, with any of those or a control character (`\x00`-`\x1f`, `\x7f`) is refused, spaces or not, and the message says to pass long text through standard input or a file when the program supports it. Words are passed unchanged; the earlier apostrophe swap for quotes and the space-based exceptions are gone. A quoted path keeps its quotes only when it is the one quoted word on the line, so when the path has a space no other word may have one. A name ending in dots or spaces counts as a `.cmd` or `.bat`, a shim whose node is itself a `.cmd` or `.bat` keeps the interpreter, and a `--version` check that is refused reports the program as broken.

## unreleased · import conversions read only the file they are given

- refers-to: routers/transcode.py :: LOCAL_ONLY, CONVERT_LOCAL_ONLY, MEDIA_DEMUXERS, LIST_DEMUXERS, LIST_ENDINGS, LIST_HEADS, _input_name, _starts_as_a_list, demuxer_of, _duration, _pinned_input, _command, _heif_with_ffmpeg, start
- kind: decision
- logged: 2026-11-28

- Every ffmpeg read of an imported file passes `-protocol_whitelist file`, as the proxy and the audio encodes do. An import that starts as a text list of other files (a playlist, a concat list, an SDP description) answers 400, and a playlist or list ending is stored as `in.bin`, so ffmpeg goes by the content.
- The first-bytes check is a quick early answer, not the guard. The guard is the container: the probe runs with `-format_whitelist` set to MEDIA_DEMUXERS (real containers only), and the container it names is checked again against that list and LIST_DEMUXERS (hls, dash, concat, imf, sdp, image sequences and the like), so a list or manifest is refused whatever its first bytes. The conversion is then pinned with `-f` to that container, held to the same list, and given `-protocol_whitelist file,pipe`. A HEIC picture read by ffmpeg is pinned to the mov demuxer. No ffprobe is needed: the probe is the person's ffmpeg itself, so an install without ffprobe still converts.

## unreleased · settings writers never undo each other

- refers-to: core/config.py :: write_settings, update_settings; routers/system.py :: set_library; services/agent_access.py :: set_choice; services/voice_remote.py :: save_local
- kind: decision
- logged: 2026-11-28

- `update_settings(change)` reads, changes and writes settings.json under one lock, and each write uses its own part file, removed if the swap fails. Choosing a library folder reads the settings again after the copy, so an outside-agents choice or a voice setting made while a large library was copied is kept.

## v0.37.0 · scenes of your own

- refers-to: routers/scenes.py; services/scenes.py; routers/trash.py :: _meta, restore; main.py
Expand Down
23 changes: 20 additions & 3 deletions backend/app/core/config.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import json
import os
import sys
import threading
import uuid
from collections.abc import Callable
from pathlib import Path

from app import __version__

_settings_lock = threading.RLock()

APP_NAME = "formmorpheus"
VERSION = __version__
FRONTEND_PORT = 5194
Expand Down Expand Up @@ -75,9 +80,21 @@ def read_settings() -> dict:

def write_settings(data: dict) -> None:
path = settings_path()
tmp = path.with_name(f".{path.name}.{os.getpid()}.part")
tmp.write_text(json.dumps(data), "utf-8")
os.replace(tmp, path)
tmp = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}.part")
with _settings_lock:
try:
tmp.write_text(json.dumps(data), "utf-8")
os.replace(tmp, path)
finally:
tmp.unlink(missing_ok=True)


def update_settings(change: Callable[[dict], dict]) -> dict:
"""Reads, changes and writes settings.json as one step, so two writers never undo each other's change."""
with _settings_lock:
data = change(read_settings())
write_settings(data)
return data


def library_source() -> str:
Expand Down
30 changes: 26 additions & 4 deletions backend/app/routers/library.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import shutil
import threading
import time
import unicodedata
import zipfile
from pathlib import Path

Expand Down Expand Up @@ -61,6 +62,28 @@ def project_path(name: str) -> Path:
return find_movie(stem) or config.library_dir() / f"{stem}{config.PROJECT_EXT}"


def _all_movies() -> list[Path]:
paths = [p for p in config.library_dir().glob(f"*{config.PROJECT_EXT}") if p.is_file()]
for d in _stack_dirs():
paths += [p for p in d.glob(f"*{config.PROJECT_EXT}") if p.is_file()]
return paths


def _lands_on_other_movie(name: str, path: Path) -> bool:
"""A save names one movie: a name that only cleans into an existing movie's name, or that differs from one
only by case or by Unicode form (one file on a case-insensitive or form-insensitive disk), would replace that other
movie, so it is refused."""
raw = name[: -len(config.PROJECT_EXT)] if name.lower().endswith(config.PROJECT_EXT) else name
if raw != path.stem and path.is_file():
return True
key = _name_key(path.stem)
return any(p.stem != path.stem and _name_key(p.stem) == key for p in _all_movies())


def _name_key(stem: str) -> str:
return unicodedata.normalize("NFC", stem).casefold()


def entry(path: Path) -> dict:
st = path.stat()
out = {"name": path.stem, "file": path.name, "path": str(path), "size": st.st_size, "modified": st.st_mtime,
Expand All @@ -84,10 +107,7 @@ def unique_path(stem: str, folder: Path | None = None) -> Path:
def list_projects() -> dict:
_migrate()
folder = config.library_dir()
paths = [p for p in folder.glob(f"*{config.PROJECT_EXT}") if p.is_file()]
for d in _stack_dirs():
paths += [p for p in d.glob(f"*{config.PROJECT_EXT}") if p.is_file()]
items = [entry(p) for p in paths]
items = [entry(p) for p in _all_movies()]
items.sort(key=lambda e: e["modified"], reverse=True)
return {"folder": str(folder), "items": items}

Expand Down Expand Up @@ -429,6 +449,8 @@ def read_preview(name: str, v: str | None = None) -> Response:
@router.put("/{name}")
async def write_project(name: str, request: Request) -> dict:
path = project_path(name)
if _lands_on_other_movie(name, path):
raise HTTPException(409, "Another movie already has that name.")
body = await read_limited(request, config.MAX_PROJECT_BYTES, "The project is too large to save.")
if body[:4] != b"PK\x03\x04":
raise HTTPException(400, "That is not a FormMorpheus project.")
Expand Down
9 changes: 5 additions & 4 deletions backend/app/routers/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,13 @@ def set_library(body: LibraryBody) -> dict:
if config.library_source() == "override":
raise HTTPException(409, "The library folder is set by FORMMORPHEUS_LIBRARY_DIR, so it cannot be changed here.")
old = config.library_dir()
settings = config.read_settings()
if body.dir is None or not body.dir.strip():
settings.pop("libraryDir", None)
chosen = None
target = config.default_library_dir()
target.mkdir(parents=True, exist_ok=True)
else:
target = _safe_folder(body.dir)
settings["libraryDir"] = str(target)
chosen = str(target)
copied = 0
if body.copyMovies and target.resolve() != old.resolve():
# Top-level movies and order file, the legacy stacks file, then each stack folder (movies + hidden order file).
Expand All @@ -100,7 +99,9 @@ def _copy(src: Path, dst: Path) -> int:
sub.mkdir(exist_ok=True)
for src in list(d.glob(f"*{config.PROJECT_EXT}")) + [d / ".order.json"]:
copied += _copy(src, sub / src.name)
config.write_settings(settings)
# read again after the copy: a choice made in Preferences while it ran is kept
rest = lambda s: {k: v for k, v in s.items() if k != "libraryDir"}
config.update_settings(lambda s: rest(s) if chosen is None else {**rest(s), "libraryDir": chosen})
return {"dir": str(config.library_dir()), "copied": copied, "source": config.library_source()}


Expand Down
66 changes: 56 additions & 10 deletions backend/app/routers/transcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,32 @@ class Transcode:
MAX_CONCURRENT = 2
PROBE_TIMEOUT = 30
_slots: asyncio.Semaphore | None = None
# ffmpeg reads only the one local file it is given: playlist and list formats name other files to open
LOCAL_ONLY = ("-protocol_whitelist", "file")
CONVERT_LOCAL_ONLY = ("-protocol_whitelist", "file,pipe")
# Real containers only. Every read is held to these, and the conversion is pinned to the one the probe found, so a
# list or manifest demuxer (hls, dash, concat, imf, sdp, image sequences and the like) never opens the input.
MEDIA_DEMUXERS = ("mov", "matroska", "avi", "mpegts", "mpeg", "mxf", "flv", "asf", "ogg", "wav", "w64", "aiff", "caf",
"mp3", "flac", "aac", "ac3", "eac3", "dts", "truehd", "amr", "au", "wv")
LIST_DEMUXERS = frozenset({"hls", "applehttp", "dash", "concat", "imf", "sdp", "rtp", "rtsp", "ffmetadata", "webm_dash_manifest",
"image2", "tee", "data"})
MEDIA_ONLY = ("-format_whitelist", ",".join(MEDIA_DEMUXERS))
NOT_MEDIA = "That file is not a picture, a video or a sound."
LIST_ENDINGS = frozenset({".m3u", ".m3u8", ".ffconcat", ".concat", ".txt", ".sdp", ".pls", ".xspf", ".cue"})
LIST_HEADS = (b"#extm3u", b"ffconcat", b"<", b"#ext", b"file ", b"[playlist]", b"v=0")


def _input_name(name: str) -> str:
suffix = Path(name).suffix[:12]
if not re.fullmatch(r"\.[A-Za-z0-9]+", suffix) or suffix.lower() in LIST_ENDINGS:
return "in.bin"
return "in" + suffix


def _starts_as_a_list(src: Path) -> bool:
with open(src, "rb") as f:
head = f.read(64).lstrip(b"\xef\xbb\xbf \t\r\n").lower()
return head.startswith(LIST_HEADS)


def _get(job_id: str) -> Transcode:
Expand Down Expand Up @@ -115,24 +141,41 @@ def capabilities() -> dict:
return {"ffmpeg": info is not None, "heif": heif_available() or ffmpeg_reads_heif(info)}


async def _duration(path: str, src: Path) -> tuple[float, bool]:
"""Seconds and whether the first video stream carries alpha, from `ffmpeg -i`."""
def demuxer_of(probe_text: str) -> str:
"""The container `ffmpeg -i` read, by its first name, when it is one of MEDIA_DEMUXERS; else the file is refused."""
m = re.search(r"^Input #0, ([^\s,]+)[^\n]*, from ", probe_text, re.M)
name = m.group(1).lower() if m else ""
if name in LIST_DEMUXERS or name not in MEDIA_DEMUXERS:
raise RuntimeError(NOT_MEDIA)
return name


async def _duration(path: str, src: Path) -> tuple[float, bool, str]:
"""Seconds, whether the first video stream carries alpha and the container, from `ffmpeg -i` held to the local file
and to MEDIA_DEMUXERS."""
proc = await asyncio.create_subprocess_exec(
path, "-hide_banner", "-nostdin", "-i", str(src), stdin=asyncio.subprocess.DEVNULL,
path, "-hide_banner", "-nostdin", *LOCAL_ONLY, *MEDIA_ONLY, "-i", str(src), stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE,
)
_, err = await _communicate(proc)
text = err.decode("utf-8", "replace")
demuxer = demuxer_of(text)
seconds = 0.0
m = re.search(r"Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)", text)
if m:
seconds = int(m.group(1)) * 3600 + int(m.group(2)) * 60 + float(m.group(3))
alpha = bool(re.search(r"Video:.*\b(yuva\w*|argb|rgba|bgra|abgr|gbrap\w*|ya8|ya16\w*)\b", text))
return seconds, alpha
return seconds, alpha, demuxer


def _pinned_input(src: Path, demuxer: str) -> list[str]:
if demuxer not in MEDIA_DEMUXERS:
raise RuntimeError(NOT_MEDIA)
return [*CONVERT_LOCAL_ONLY, *MEDIA_ONLY, "-f", demuxer, "-i", str(src)]


def _command(info: ff.FfmpegInfo, src: Path, out: Path, kind: str, alpha: bool, encoder: str) -> list[str]:
cmd = [info.path, "-hide_banner", "-nostdin", "-y", "-loglevel", "error", "-progress", "pipe:1", "-nostats", "-i", str(src)]
def _command(info: ff.FfmpegInfo, src: Path, out: Path, kind: str, alpha: bool, encoder: str, demuxer: str) -> list[str]:
cmd = [info.path, "-hide_banner", "-nostdin", "-y", "-loglevel", "error", "-progress", "pipe:1", "-nostats", *_pinned_input(src, demuxer)]
if kind == "audio":
return cmd + ["-vn", "-map", "0:a:0", "-c:a", "pcm_s16le", "-ar", "48000", str(out)]
# sizes must be even for 4:2:0
Expand Down Expand Up @@ -164,7 +207,7 @@ async def _convert(job: Transcode, src: Path) -> None:
try:
if info is None:
raise RuntimeError("ffmpeg was not found. Install it, or set FORMMORPHEUS_FFMPEG to its path.")
seconds, alpha = await _duration(info.path, src)
seconds, alpha, demuxer = await _duration(info.path, src)
job.alpha = alpha and job.kind == "video"
if job.kind == "audio":
out, encoder, job.mime = job.folder / "out.wav", "pcm_s16le", "audio/wav"
Expand All @@ -182,7 +225,7 @@ async def _convert(job: Transcode, src: Path) -> None:
err_path = job.folder / "ffmpeg.err"
with open(err_path, "wb") as err:
proc = await asyncio.create_subprocess_exec(
*_command(info, src, out, job.kind, job.alpha, encoder), stdin=asyncio.subprocess.DEVNULL,
*_command(info, src, out, job.kind, job.alpha, encoder, demuxer), stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.PIPE, stderr=err,
)
job.proc = proc
Expand Down Expand Up @@ -231,7 +274,8 @@ def _heif_with_ffmpeg(info: ff.FfmpegInfo, src: Path, out: Path) -> None:
import subprocess

done = subprocess.run(
[info.path, "-hide_banner", "-nostdin", "-y", "-loglevel", "error", "-i", str(src), "-frames:v", "1", "-an", "-pix_fmt", "rgba", str(out)],
# HEIF is read by the mov demuxer
[info.path, "-hide_banner", "-nostdin", "-y", "-loglevel", "error", *_pinned_input(src, "mov"), "-frames:v", "1", "-an", "-pix_fmt", "rgba", str(out)],
capture_output=True, text=True, timeout=120, check=False, stdin=subprocess.DEVNULL,
)
if done.returncode != 0 or not out.is_file() or out.stat().st_size == 0:
Expand Down Expand Up @@ -276,9 +320,11 @@ async def start(request: Request, kind: str, name: str = "import") -> dict:
job_id = uuid.uuid4().hex[:16]
folder = config.jobs_dir() / f"import-{job_id}"
folder.mkdir(parents=True, exist_ok=True)
src = folder / ("in" + (Path(name).suffix[:12] if re.fullmatch(r"\.[A-Za-z0-9]+", Path(name).suffix[:12]) else ".bin"))
src = folder / _input_name(name)
try:
await _stream_to(request, src, MAX_IMPORT_BYTES)
if _starts_as_a_list(src):
raise HTTPException(400, NOT_MEDIA)
except BaseException:
shutil.rmtree(folder, ignore_errors=True)
raise
Expand Down
13 changes: 7 additions & 6 deletions backend/app/services/agent_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ def choice() -> str:
def set_choice(value: str) -> dict:
if value not in CHOICES:
raise ValueError(f"The choice is one of {', '.join(CHOICES)}.")
stored = {k: v for k, v in config.read_settings().items() if k not in ("agentsAllowed", "agentsBlocked", seal.FIELD)}
if value == "allowed":
stored["agentsAllowed"] = True
elif value == "blocked":
stored["agentsBlocked"] = True
config.write_settings(seal.sign(stored))
mark = {"allowed": {"agentsAllowed": True}, "blocked": {"agentsBlocked": True}}.get(value, {})

def change(settings: dict) -> dict:
stored = {k: v for k, v in settings.items() if k not in ("agentsAllowed", "agentsBlocked", seal.FIELD)}
return seal.sign({**stored, **mark})

config.update_settings(change)
return state()
Loading
Loading