diff --git a/Commands/ExportFolderCommand.ts b/Commands/ExportFolderCommand.ts index d5e0b17..48c75d5 100644 --- a/Commands/ExportFolderCommand.ts +++ b/Commands/ExportFolderCommand.ts @@ -24,6 +24,8 @@ import { LOCAL_WORLD_KEY_TOKEN } from "../vault/world-key-core"; import { worldFolderName, planElementPaths, + isPlainFileId, + escapesFolder, buildFolderElementBody, folderServerFields, wikilinksToOwMentions, @@ -356,6 +358,14 @@ export class ExportFolderCommand { elements.splice(elements.indexOf(el), 1); byPath.delete(el.path); } + // A file is named from the id (§3.2): one that could name a path is not written, by note. + for (const el of [...elements]) { + if (isPlainFileId(String(el.payload.id))) continue; + failed.push({ path: el.path, reason: "its id holds characters that cannot be part of a file name, so it is not exported" }); + refusedPaths.add(el.path); + elements.splice(elements.indexOf(el), 1); + byPath.delete(el.path); + } if (elements.length === 0) { new Notice(`Export aborted — no readable elements in ${world}.`); return null; @@ -416,6 +426,9 @@ export class ExportFolderCommand { const held = await readRecordsTree(this.app, worldRecordsRoot(world)); const records = held.length > 0 ? planRecords(held, opts.includePrivateRecords === true) : null; if (records) planned.push(...records.files); + // The last wall, for every file of every kind: nothing is written that could land outside the export folder. + const outside = planned.find((f) => escapesFolder(f.rel)); + if (outside) throw new Error(`${outside.rel} would be written outside the export folder, so nothing was exported`); return { files: planned, failed, hidden, records }; } diff --git a/manifest.json b/manifest.json index 03965d7..82adf20 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "onlyworlds-builder", "name": "OnlyWorlds Builder", - "version": "3.24.0", + "version": "3.24.1", "minAppVersion": "1.4.0", "description": "Build and sync OnlyWorlds worlds from Obsidian.", "author": "Titus", diff --git a/package-lock.json b/package-lock.json index 5dad041..3a55117 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "onlyworlds-obsidian-plugin", - "version": "3.24.0", + "version": "3.24.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "onlyworlds-obsidian-plugin", - "version": "3.24.0", + "version": "3.24.1", "license": "MIT", "dependencies": { "@onlyworlds/sdk": "^4.176.0", diff --git a/package.json b/package.json index a80b5ae..1540bf9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "onlyworlds-obsidian-plugin", - "version": "3.24.0", + "version": "3.24.1", "description": "Obsidian plugin for the OnlyWorlds worldbuilding framework", "main": "main.js", "type": "module", diff --git a/test/export-paths.test.ts b/test/export-paths.test.ts new file mode 100644 index 0000000..c087730 --- /dev/null +++ b/test/export-paths.test.ts @@ -0,0 +1,76 @@ +/** + * Export as OnlyWorlds folder names each element's file from its id (folder spec §3.2). An id that cannot be part of + * one plain file name is left out and named, and every file an export writes stays inside the export folder. + */ +import "./support/obsidian-shim"; // MUST stay first: routes `obsidian` to the mock +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { makeApp } from "./support/obsidian-mock"; +import { ExportFolderCommand } from "../Commands/ExportFolderCommand"; +import { escapesFolder, isPlainFileId, worldFolderName } from "../vault/folder-format"; + +const W = "OnlyWorlds/Worlds/W"; +const GOOD = "019e0000-0000-7000-8000-0000000000a1"; +const note = (name: string, id: string) => `---\nname: ${name}\nid: ${JSON.stringify(id)}\n---\n\n### Description\n\nx\n`; + +const filesUnder = (root: string, at = root): string[] => + fs.readdirSync(at, { withFileTypes: true }).flatMap((e) => + e.isDirectory() ? filesUnder(root, path.join(at, e.name)) : [path.relative(root, path.join(at, e.name)).replace(/\\/g, "/")]); + +async function exportOut(notes: Record) { + const { app, vault } = makeApp(); + await vault.seed(`${W}/World.md`, "# World Overview: W\n"); + for (const [p, t] of Object.entries(notes)) await vault.seed(`${W}/Elements/Character/${p}.md`, t); + const root = fs.mkdtempSync(path.join(os.tmpdir(), "ow-exp-")); + const dest = path.join(root, "a", "b", "c"); + fs.mkdirSync(dest, { recursive: true }); + const cmd = new ExportFolderCommand(app) as any; + const real = cmd.planFiles.bind(cmd); + let failed: { path: string; reason: string }[] = []; + cmd.planFiles = async (...args: unknown[]) => { + const plan = await real(...args); + failed = plan?.failed ?? []; + return plan; + }; + await cmd.exportWorld("W", { kind: "external", dir: dest }); + const written = filesUnder(root); + fs.rmSync(root, { recursive: true, force: true }); + return { written, failed }; +} + +test("★ an id with path characters is left out and named; nothing is written outside the export folder", async () => { + const bad: Record = { + "名": note("名", "../../../../escaped"), // no slug: the file would be named by the whole id + Bob: note("Bob", "../../../../../x"), // named: the id's tail goes into the name + Back: note("Back", "..\\..\\..\\..\\y"), + Dots: note("名二", ".."), + Ctl: note("Ctl", "a\u0001b"), + Good: note("Good", GOOD), + }; + const r = await exportOut(bad); + assert.deepEqual(r.written.filter((f) => !/^a\/b\/c\/w-[^/]+\/(world\.json|elements\/character\/good--000000a1\.json)$/.test(f)), [], JSON.stringify(r.written)); + assert.equal(r.written.length, 2, JSON.stringify(r.written)); + assert.equal(r.failed.length, 5, JSON.stringify(r.failed)); + assert.ok(r.failed.every((f) => /cannot be part of a file name/.test(f.reason)), JSON.stringify(r.failed)); +}); + +test("an id that is no UUID and is one plain name is still exported", async () => { + const r = await exportOut({ List: note("List", "checklist-7") }); + assert.equal(r.failed.length, 0, JSON.stringify(r.failed)); + assert.ok(r.written.some((f) => f.endsWith("elements/character/list--cklist7.json") || /elements\/character\/list--[^/]+\.json$/.test(f)), JSON.stringify(r.written)); +}); + +test("isPlainFileId and escapesFolder", () => { + for (const ok of [GOOD, "checklist-7", "a.b", "..a"]) assert.equal(isPlainFileId(ok), true, ok); + for (const no of ["", ".", "..", "a/b", "a\\b", "a\nb", "a\u007fb", "C:evil", "urn:uuid:1"]) assert.equal(isPlainFileId(no), false, JSON.stringify(no)); + for (const ok of ["world.json", "elements/character/a--b.json", "records/x/.hidden", "records/..keep"]) assert.equal(escapesFolder(ok), false, ok); + for (const no of ["../x.json", "elements/character/../../x", "a\\..\\b", "/etc/x", "C:/x", "a//b", "./a"]) assert.equal(escapesFolder(no), true, no); +}); + +test("★ a world id never climbs out through the export folder's name", () => { + assert.equal(worldFolderName("W", "0695db52-5433-7332-8000-db7fe10da375"), "w-0695db52"); + for (const id of ["../../..", "..\\..\\abc", "/etc/passwd"]) assert.doesNotMatch(worldFolderName("W", id), /[/\\]|\.\./, id); +}); diff --git a/vault/folder-format.ts b/vault/folder-format.ts index ffe749f..5e1194c 100644 --- a/vault/folder-format.ts +++ b/vault/folder-format.ts @@ -109,6 +109,20 @@ export function slugify(name: string, max = SLUG_MAX_LEN): string { .replace(/-+$/g, ""); } +/** + * True when `id` can be part of one plain file name: not empty, not `.` or `..`, and holding no `/`, no `\`, no `:` + * and no control character. A writer names a file from the id (spec §3.2), so any other id could name a path; on + * Windows a colon names a drive, or a hidden stream of another file. + */ +export function isPlainFileId(id: string): boolean { + return id !== "" && id !== "." && id !== ".." && !/[/\\:\u0000-\u001f\u007f]/.test(id); +} + +/** True when the relative path `rel` could leave the folder it is written under: absolute, a drive, or a `.`, `..` or empty part. */ +export function escapesFolder(rel: string): boolean { + return /^[A-Za-z]:/.test(rel) || rel.split(/[/\\]/).some((part) => part === "" || part === "." || part === ".."); +} + /** 8-char id tail: strip dashes, take the last 8 chars (spec §3.2). */ export function idTail(id: string): string { return id.replace(/-/g, "").slice(-8); @@ -131,7 +145,8 @@ export function filenameFor(element: { id: string; name?: unknown }, fullId = fa * the cap stays at 60 so an existing export's folder keeps its name. */ export function worldFolderName(worldName: string, worldId: string): string { - const head = worldId.replace(/-/g, "").slice(0, 8); + // Letters and digits only (a UUID has nothing else but its dashes): the id is read from a file in the vault. + const head = worldId.replace(/[^0-9a-zA-Z]/g, "").slice(0, 8); const slug = slugify(worldName, 60); return slug ? `${slug}-${head}` : `world-${head}`; } diff --git a/versions.json b/versions.json index ebb3cb3..439fbcf 100644 --- a/versions.json +++ b/versions.json @@ -57,5 +57,6 @@ "3.23.0": "1.4.0", "3.23.1": "1.4.0", "3.23.2": "1.4.0", - "3.24.0": "1.4.0" + "3.24.0": "1.4.0", + "3.24.1": "1.4.0" } \ No newline at end of file