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
15 changes: 13 additions & 2 deletions Commands/ImportFolderCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
typeFromFolderPath,
owMentionsToWikilinks,
isUuid,
textTooDeep,
type ElementRef,
} from "../vault/folder-format";

Expand Down Expand Up @@ -108,7 +109,12 @@ export class ImportFolderCommand {
}
let worldMeta: Record<string, unknown>;
try {
worldMeta = JSON.parse(await this.app.vault.read(worldFile));
const text = await this.app.vault.read(worldFile);
if (textTooDeep(text)) {
new Notice("world.json nests more than 200 levels deep, so nothing was imported.", 8000);
return;
}
worldMeta = JSON.parse(text);
} catch (e) {
new Notice(`world.json is not valid JSON: ${e instanceof Error ? e.message : String(e)}`);
return;
Expand Down Expand Up @@ -168,7 +174,12 @@ export class ImportFolderCommand {
};
for (const file of elementFiles) {
try {
const json = JSON.parse(await this.app.vault.read(file)) as Record<string, unknown>;
const text = await this.app.vault.read(file);
if (textTooDeep(text)) {
failed.push({ path: file.path, reason: "nested more than 200 levels deep, so not read" });
continue;
}
const json = JSON.parse(text) as Record<string, unknown>;
// Fallback type from the file's place: elements/<type>/file, or a
// flat elements/<type>_<slug>.json. A declared
// `type` in the body wins (spec §4).
Expand Down
56 changes: 56 additions & 0 deletions test/import-too-deep.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* Folder format 0.3.25: a file in which an object or array sits more than 200 levels deep (objects and
* arrays both count, the top object at 1) is not read. Import names it as failed and reads the rest.
*/
import "./support/obsidian-shim"; // MUST stay first: routes `obsidian` to the mock
import { test } from "node:test";
import assert from "node:assert/strict";
import type { App } from "obsidian";
import { makeApp, __modals, __notices } from "./support/obsidian-mock";
import { ImportFolderCommand } from "../Commands/ImportFolderCommand";
import { textTooDeep } from "../vault/folder-format";

const WID = "0199d000-0000-7000-8000-0000000000ee";
const AT = "0199d000-0000-7000-8000-0000000000c1";
const OVER = "0199d000-0000-7000-8000-0000000000c2";

/** The text of an object whose `x_deep` makes its deepest array sit at `levels`, the top object at 1. */
const nested = (head: Record<string, unknown>, levels: number): string =>
JSON.stringify(head).slice(0, -1) + `,"x_deep":${"[".repeat(levels - 1)}${"]".repeat(levels - 1)}}`;

type Report = { created: string[]; failed: { path: string; reason: string }[] };

async function run(world: string, files: Record<string, string>): Promise<Report | undefined> {
const { app, vault } = makeApp();
await vault.seed("in/b/world.json", world);
for (const [rel, text] of Object.entries(files)) await vault.seed(`in/b/${rel}`, text);
__modals.length = 0;
await (new ImportFolderCommand(app as App) as unknown as { importFolder(d: string): Promise<void> }).importFolder("in/b");
return (__modals.find((m) => m.constructor.name === "ImportReportModal") as unknown as { result: Report } | undefined)?.result;
}

test("textTooDeep: 200 is read, 201 is not; brackets in a string and after an escaped quote do not count", () => {
assert.equal(textTooDeep(nested({ a: 1 }, 200)), false);
assert.equal(textTooDeep(nested({ a: 1 }, 201)), true);
assert.equal(textTooDeep(JSON.stringify({ a: '"' + "[".repeat(500) })), false);
assert.equal(textTooDeep("{".repeat(100) + "[".repeat(101)), true);
});

test("★ Import folder: an element file past 200 levels is not read and is named; the file at 200 is read", async () => {
const r = await run(JSON.stringify({ id: WID, name: "Deep" }), {
"elements/character/at.json": nested({ id: AT, type: "character", name: "At" }, 200),
"elements/character/over.json": nested({ id: OVER, type: "character", name: "Over" }, 201),
});
assert.equal(r?.created.length, 1, JSON.stringify(r));
assert.deepEqual(r?.failed.map((f) => f.path), ["in/b/elements/character/over.json"]);
assert.match(r!.failed[0].reason, /more than 200 levels/);
});

test("★ Import folder: a world.json past 200 levels imports nothing and says why", async () => {
__notices.length = 0;
const r = await run(nested({ id: WID, name: "Deep" }, 201), {
"elements/character/at.json": JSON.stringify({ id: AT, type: "character", name: "At" }),
});
assert.equal(r, undefined);
assert.match(JSON.stringify(__notices), /more than 200 levels/);
});
27 changes: 27 additions & 0 deletions vault/folder-format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,33 @@ export function typeFromFolderPath(rel: string): string | null {
return null;
}

/** The deepest an object or array may sit in a file that is read (folder format 0.3.25): the file's top object is 1. */
export const MAX_FILE_DEPTH = 200;

/**
* True when an object or array in `text` sits more than `MAX_FILE_DEPTH` levels deep, counted in the
* text as each one opens, so a key written twice counts with each of its values. Brackets inside a
* string are not counted. The SDK's `textTooDeep`, which the pinned version does not export.
*/
export function textTooDeep(text: string): boolean {
let depth = 0;
let inString = false;
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (inString) {
if (c === "\\") i++; // the next character is escaped
else if (c === '"') inString = false;
} else if (c === '"') {
inString = true;
} else if (c === "{" || c === "[") {
if (++depth > MAX_FILE_DEPTH) return true;
} else if (c === "}" || c === "]") {
depth--;
}
}
return false;
}

/** Is this a valid UUID string (used to validate world.json / mention ids). */
export function isUuid(s: unknown): s is string {
return typeof s === "string" && UUID_RE.test(s);
Expand Down
Loading