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
13 changes: 13 additions & 0 deletions Commands/ExportFolderCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import { LOCAL_WORLD_KEY_TOKEN } from "../vault/world-key-core";
import {
worldFolderName,
planElementPaths,
isPlainFileId,
escapesFolder,
buildFolderElementBody,
folderServerFields,
wikilinksToOwMentions,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 };
}

Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
76 changes: 76 additions & 0 deletions test/export-paths.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, string>) {
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<string, string> = {
"名": 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);
});
17 changes: 16 additions & 1 deletion vault/folder-format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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}`;
}
Expand Down
3 changes: 2 additions & 1 deletion versions.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Loading