Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,5 @@ src/onlyworlds/convert/kanka.json -text
tests/fixtures/pins-known-to.cases.json -text
# The most linked reader's shared cases, the same bytes as the npm SDK's copy (both tests hold its sha256).
tests/fixtures/most-linked.fixture.json -text
# The folder writers' refused and written ids, the same bytes as the npm SDK's copy (both tests hold its sha256).
tests/fixtures/unsafe-ids.cases.json -text
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ The package version runs on its own semver; the schema it is generated from is `

## Unreleased

## 0.158.5 (2026-11-28)

- **Fixed: a folder writer no longer writes outside its folder for an element id that holds a path; such an id is refused.** An element whose name gives no slug is written as `<id>.json`, so an id such as `../../x`, from an export or a server, wrote a file outside the folder it was asked to write. `write_folder` now refuses, whatever the name and before anything is written, an element id that is empty (it would be the hidden file `.json`), holds `/` or `\`, holds a colon (on Windows `D:x.json` is a path on drive D), holds a control character (U+0000 to U+001F), or is `.` or `..`: `ValueError: character element id "../../x" cannot be a file name: it holds a path separator, / or \.` Behind that rule, a second guard refuses any file whose path would not lie inside its folder: in `write_folder` (inside its type folder, both in the temp folder it writes and in the folder that temp folder becomes), in `write_bundle` (the OKF export, whose files are named from ids) and for the LegendKeeper import's board records. Every writer that names files by id goes through these: `write_folder`, `export_world`, `export_okf` and the Kanka, Campfire, LegendKeeper, Notion and World Anvil imports. The world's id names no path and is not checked. The cases are in `tests/fixtures/unsafe-ids.cases.json`, which the npm SDK's folder writer is held to as well.

## 0.158.4 (2026-11-28)

- **Fixed: a date written with its weekday parses back.** `parse_date` read era, month and intercalary names and never a weekday's, so a world whose `format` prints `{weekday}` could not read its own dates: `"Moonday, 3 Frost 454"` answered `unrecognized: "moonday"`. A weekday name is now read after every other name, longest first, as a whole word: a word that is both a month's and a weekday's still reads as the month, a name that reads as a number is never tried, and a calendar whose names do not match its week's length (it prints no weekday) reads none. A weekday that is not the date's own is refused, naming both (`that date falls on Sunday, not Moonday`; `that date has no weekday, not Moonday` for a day outside the week), and a weekday alone names no date. The separators stay whitespace, the comma, the period and the word `year`. Nothing that parsed before parses differently. The npm SDK 4.220.1 reads the same.
Expand Down
2 changes: 1 addition & 1 deletion src/onlyworlds/_version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.158.4"
__version__ = "0.158.5"
71 changes: 67 additions & 4 deletions src/onlyworlds/folder.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

from __future__ import annotations

import json
import os
import re
import shutil
Expand Down Expand Up @@ -185,6 +186,45 @@ def id_tail(element_id: str) -> str:
return raw


_SEPARATOR = re.compile(r"[/\\]")
_CONTROL = re.compile(r"[\x00-\x1f]")


def _unsafe_id_why(element_id: str) -> str | None:
"""Why an element id cannot name a file, or None when it can: used as ``<id>.json`` (a name with
no slug, or the collision rule's full-id form) it must be one plain file name inside its type
folder. Checked in this order: empty (``.json``, a hidden file), a path separator, a colon (on Windows
``C:evil.json`` is a path on drive C, and ``a:b.json`` names a stream of file ``a``), a control
character (U+0000 to U+001F), ``.`` or ``..``. The npm SDK's writer refuses the same ids in the same
words (tests/fixtures/unsafe-ids.cases.json). ``_inside`` is the second guard, on the path itself."""
if not element_id:
return "it is empty"
if _SEPARATOR.search(element_id):
return "it holds a path separator, / or \\"
if ":" in element_id:
return "it holds a colon"
if _CONTROL.search(element_id):
return "it holds a control character"
if element_id in (".", ".."):
return "it is . or .."
return None


def _inside(folder: Path, rel: str) -> bool:
"""True when ``folder / rel``, resolved, is a path under ``folder``, resolved (neither need exist yet):
the second guard of every writer that names a file from an id, behind its character rule, so a path
the rule did not foresee is refused before anything is written."""
base = folder.resolve()
target = (folder / rel).resolve()
return target != base and target.is_relative_to(base)


def _one_file_in(filename: str, folders: Iterable[Path]) -> bool:
"""True when ``filename`` joins as one plain name (a drive-relative ``C:evil.json`` joined to a path on
drive C keeps the folder but names ``evil.json``) and its path lies inside each of ``folders``."""
return Path(filename).name == filename and all(_inside(f, filename) for f in folders)


def element_filename(element_id: str, name: str | None) -> str:
"""``<slug>--<tail8>.json``; an unsluggable name gives ``<full-id>.json`` (§3.2)."""
slug = slugify(name)
Expand Down Expand Up @@ -294,7 +334,11 @@ def write_folder(
Within a type, a repeated id keeps its LAST body (id-keyed overwrite, the
spec's answer to a keyset walk that met a mid-walk write), so a stub that later
arrives whole is written whole, without ``known_of`` (§4.4 rule 4). The same id
under two types is an error.
under two types is an error, and so is an id that cannot name a file (one that
is empty, holds ``/``, ``\\``, ``:`` or a control character, or is ``.`` or ``..``:
as ``<id>.json`` it would leave its type folder or name a hidden file), whatever
the name, and a file name whose path would not lie inside its type folder, all
before anything is written. The world's id names no path.

``root`` must not exist, or be an empty directory: this writes a folder's
birth, never over another folder (stale files from renamed or deleted
Expand All @@ -314,16 +358,35 @@ def write_folder(
slot = by_type.setdefault(etype, {})
for body in bodies:
eid = body.get("id")
if not isinstance(eid, str) or not eid:
if not isinstance(eid, str):
raise ValueError(f"{etype} element without a non-empty string id: {dict(body)!r:.200}")
why = _unsafe_id_why(eid)
if why is not None:
raise ValueError(
f"{etype} element id {json.dumps(eid, ensure_ascii=False)} cannot be a file name: {why}."
)
if owner.setdefault(eid, etype) != etype:
raise ValueError(f"id {eid} appears under both {owner[eid]} and {etype}")
slot.pop(eid, None) # last wins, and takes the last position
slot[eid] = body

# Every file's name, each held inside its type folder, in the temp folder it is written to and in the
# finished folder it is renamed to, before anything is written.
tmp = root.parent / f".{root.name}.tmp-{uuid.uuid4().hex[:8]}"
names_by_type: dict[str, dict[str, str]] = {}
for etype in ELEMENT_TYPES:
if by_type.get(etype):
names = resolve_filenames((eid, _name_of(b)) for eid, b in by_type[etype].items())
for eid, filename in names.items():
if not _one_file_in(filename, (tmp / ELEMENTS_DIR / etype, root / ELEMENTS_DIR / etype)):
raise ValueError(
f"{etype} element id {json.dumps(eid, ensure_ascii=False)} gives the file name "
f"{json.dumps(filename, ensure_ascii=False)}, which does not lie inside its type folder."
)
names_by_type[etype] = names

counts: dict[str, int] = {}
collisions: list[str] = []
tmp = root.parent / f".{root.name}.tmp-{uuid.uuid4().hex[:8]}"
tmp.mkdir(parents=True)
try:
for etype in ELEMENT_TYPES:
Expand All @@ -332,7 +395,7 @@ def write_folder(
continue # §4: empty type directories are omitted
tdir = tmp / ELEMENTS_DIR / etype
tdir.mkdir(parents=True)
names = resolve_filenames((eid, _name_of(b)) for eid, b in bodies_by_id.items())
names = names_by_type[etype]
for eid, body in bodies_by_id.items():
filename = names[eid]
if filename != element_filename(eid, _name_of(body)):
Expand Down
11 changes: 10 additions & 1 deletion src/onlyworlds/legendkeeper.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@
from ._version import __version__
from .calendar import CALENDAR_FIELD, CALENDAR_SUPERTYPE
from .errors import parse_retry_after
from .folder import FORMAT_VERSION, ONE_SOURCE_ONE_WORLD, write_folder
from .folder import FORMAT_VERSION, ONE_SOURCE_ONE_WORLD, _inside, write_folder
from .http import Response, Transport, UrllibTransport
from .worldfile import RECORDS_MANIFEST

Expand Down Expand Up @@ -4043,12 +4043,21 @@ def import_legendkeeper(
if plan_only:
return report
assert out is not None
_check_records(out, conv.board_records)
write_folder(out, report.world, elements)
_write_records(out, conv.board_records, private=report.records_private)
report.out = out
return report


def _check_records(out: Path, boards: Mapping[str, dict[str, Any]]) -> None:
"""Every board's record path lies inside ``out`` (it is named from a document id, or the Map's when that is
not a plain name): a ValueError before the folder is written, the second guard behind ``_SAFE_NAME``."""
for rel in boards:
if not _inside(out, rel):
raise ValueError(f"the board record path {rel!r} does not lie inside {out}; nothing was written")


def _write_records(out: Path, boards: Mapping[str, dict[str, Any]], *, private: bool) -> None:
"""The boards' records into the finished folder (folder spec §4.5): one file a board under
``records/legendkeeper/``, in the folder's own JSON (UTF-8, LF, two-space indent), and the
Expand Down
7 changes: 6 additions & 1 deletion src/onlyworlds/okf.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@
WORLD_FILE,
WORLD_FOLDER_KEYS,
Folder,
_inside,
is_hidden,
is_known_of,
read_folder,
Expand Down Expand Up @@ -659,8 +660,12 @@ def noted(msg: str) -> None:


def write_bundle(files: Mapping[str, str], out: str | os.PathLike[str]) -> None:
"""Write ``files`` under ``out``, which must not exist (``FileExistsError``)."""
"""Write ``files`` under ``out``, which must not exist (``FileExistsError``). A path that would not lie
inside ``out`` (the element files are named from their ids) is a ValueError before anything is written."""
out = Path(out)
for rel in files:
if not _inside(out, rel):
raise ValueError(f"the bundle path {rel!r} does not lie inside {out}; nothing was written")
out.mkdir(parents=True, exist_ok=False)
for rel in sorted(files):
path = out / rel
Expand Down
128 changes: 128 additions & 0 deletions tests/fixtures/unsafe-ids.cases.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
{
"about": "Element ids a world folder writer refuses and ids it writes: the npm SDK's folder writer (worldFolderFiles, convertKanka) and the Python package's write_folder. The same bytes in both repositories; both suites hold its sha256. An id is refused when used as <id>.json it would not be one plain file name: it is empty, it holds / or a backslash, it holds a colon (on Windows C:evil.json is a path on drive C), it holds a control character U+0000 to U+001F, or it is . or .. (checked in that order), whatever the name, since the collision rule can fall back to the full id. A refusal names the type, the id as JSON text and the why given here; no file is written. A written case gives the file's path. Cases written by hand.",
"version": 1,
"refused": [
{
"id": "a/b",
"name": "",
"why": "it holds a path separator, / or \\"
},
{
"id": "a\\b",
"name": "",
"why": "it holds a path separator, / or \\"
},
{
"id": "../../x",
"name": "",
"why": "it holds a path separator, / or \\"
},
{
"id": "../../x",
"name": "Escape",
"why": "it holds a path separator, / or \\"
},
{
"id": "/abs",
"name": "Abs",
"why": "it holds a path separator, / or \\"
},
{
"id": "..",
"name": "",
"why": "it is . or .."
},
{
"id": ".",
"name": "",
"why": "it is . or .."
},
{
"id": "..",
"name": "Two Dots",
"why": "it is . or .."
},
{
"id": "a\u0000b",
"name": "",
"why": "it holds a control character"
},
{
"id": "tab\tid",
"name": "Tab",
"why": "it holds a control character"
},
{
"id": "\u001f",
"name": "",
"why": "it holds a control character"
},
{
"id": "../\u0000",
"name": "",
"why": "it holds a path separator, / or \\"
},
{
"id": "",
"name": "",
"why": "it is empty"
},
{
"id": "",
"name": "Named",
"why": "it is empty"
},
{
"id": "a:b",
"name": "",
"why": "it holds a colon"
},
{
"id": "C:evil",
"name": "",
"why": "it holds a colon"
},
{
"id": "C:evil",
"name": "Evil",
"why": "it holds a colon"
},
{
"id": "D:/x",
"name": "",
"why": "it holds a path separator, / or \\"
},
{
"id": ":\u0000",
"name": "",
"why": "it holds a colon"
}
],
"written": [
{
"id": "v1.2",
"name": "",
"path": "elements/character/v1.2.json"
},
{
"id": "élan",
"name": "",
"path": "elements/character/élan.json"
},
{
"id": "...",
"name": "",
"path": "elements/character/....json"
},
{
"id": "a..b",
"name": "Dots",
"path": "elements/character/dots--a..b.json"
},
{
"id": "c-",
"name": "",
"path": "elements/character/c-.json"
}
]
}
Loading
Loading