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
109 changes: 109 additions & 0 deletions pkgs/id/web/src/file-op-responses.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { describe, expect, it } from "vitest";
import {
isCopyFileResponse,
isNewFileResponse,
isRenameFileResponse,
isSaveFileResponse,
} from "./file-op-responses";

// Regression tests for #7837: the /api/save, /api/new, /api/rename and
// /api/copy handlers in main.ts shape-trusted their 200 responses via
// bare `as` casts. These guards are the validation the handlers now
// run before any field is used; every wrong-shape body below used to
// be treated as success (dataset.hash = "undefined", navigation to
// /edit/undefined, "renamed!" / "copied!" button text).

const wrongShapes: unknown[] = [{}, null, "abc", [], 42, undefined];

describe("isSaveFileResponse", () => {
it("accepts a valid save response", () => {
expect(isSaveFileResponse({ hash: "abc123", name: "notes.md", archive_name: null })).toBe(true);
expect(
isSaveFileResponse({ hash: "abc123", name: "notes.md", archive_name: "notes-1.md" }),
).toBe(true);
});

it("rejects wrong-shape bodies", () => {
for (const body of wrongShapes) {
expect(isSaveFileResponse(body)).toBe(false);
}
});

it("rejects a numeric hash (silent coercion pre-fix)", () => {
expect(isSaveFileResponse({ hash: 123, name: "notes.md", archive_name: null })).toBe(false);
});

it("rejects empty or missing fields", () => {
expect(isSaveFileResponse({ hash: "", name: "notes.md", archive_name: null })).toBe(false);
expect(isSaveFileResponse({ hash: "abc123", name: "", archive_name: null })).toBe(false);
expect(isSaveFileResponse({ hash: "abc123", name: "notes.md" })).toBe(false);
expect(isSaveFileResponse({ hash: "abc123", name: "notes.md", archive_name: 7 })).toBe(false);
});
});

describe("isNewFileResponse", () => {
it("accepts a valid create response", () => {
expect(isNewFileResponse({ hash: "abc123", name: "new.md" })).toBe(true);
});

it("rejects wrong-shape bodies (navigated to /edit/undefined pre-fix)", () => {
for (const body of wrongShapes) {
expect(isNewFileResponse(body)).toBe(false);
}
expect(isNewFileResponse({ hash: 123, name: "new.md" })).toBe(false);
expect(isNewFileResponse({ name: "new.md" })).toBe(false);
});
});

describe("isRenameFileResponse", () => {
it("accepts a valid rename response", () => {
expect(
isRenameFileResponse({
name: "renamed.md",
hash: "abc123",
archived_original: null,
archived_replaced: "old.md",
}),
).toBe(true);
});

it("rejects wrong-shape bodies (fake 'renamed!' pre-fix)", () => {
for (const body of wrongShapes) {
expect(isRenameFileResponse(body)).toBe(false);
}
expect(
isRenameFileResponse({
name: "renamed.md",
hash: 123,
archived_original: null,
archived_replaced: null,
}),
).toBe(false);
});

it("rejects non-string-or-null archive fields", () => {
expect(
isRenameFileResponse({
name: "renamed.md",
hash: "abc123",
archived_original: 7,
archived_replaced: null,
}),
).toBe(false);
expect(isRenameFileResponse({ name: "renamed.md", hash: "abc123" })).toBe(false);
});
});

describe("isCopyFileResponse", () => {
it("accepts a valid copy response", () => {
expect(isCopyFileResponse({ name: "copy.md", hash: "abc123" })).toBe(true);
});

it("rejects wrong-shape bodies (fake 'copied!' pre-fix)", () => {
for (const body of wrongShapes) {
expect(isCopyFileResponse(body)).toBe(false);
}
expect(isCopyFileResponse({ name: "copy.md", hash: 123 })).toBe(false);
expect(isCopyFileResponse({ hash: "abc123" })).toBe(false);
});
});
77 changes: 77 additions & 0 deletions pkgs/id/web/src/file-op-responses.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/** Runtime shape validation for the editor shell's file-operation API responses. */

/**
* The four file-operation handlers in `main.ts` (POST /api/save,
* /api/new, /api/rename, /api/copy) used to cast their `fetch` JSON
* responses with bare `as` casts and use the fields unchecked (#7837).
* A 200 response with the wrong shape (proxy error page parsed as
* JSON, a partial deploy, a server-side change) was therefore treated
* as success: save reported `{ ok: true }` and set
* `editorContainer.dataset.hash` to the literal string "undefined"
* (corrupting every later save in the session), and new/rename/copy
* navigated to `/edit/undefined` after announcing success.
*
* These guards are the runtime check the casts replaced. Each handler
* validates the parsed body before any field is used; on a wrong
* shape no state is mutated and the failure is reported through the
* same channel as a non-OK response.
*/

export interface SaveFileResponse {
hash: string;
name: string;
archive_name: string | null;
}

export interface NewFileResponse {
hash: string;
name: string;
}

export interface RenameFileResponse {
name: string;
hash: string;
archived_original: string | null;
archived_replaced: string | null;
}

export interface CopyFileResponse {
name: string;
hash: string;
}

const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);

const isNonEmptyString = (value: unknown): value is string =>
typeof value === "string" && value.length > 0;

const isStringOrNull = (value: unknown): value is string | null =>
typeof value === "string" || value === null;

export function isSaveFileResponse(value: unknown): value is SaveFileResponse {
return (
isRecord(value) &&
isNonEmptyString(value.hash) &&
isNonEmptyString(value.name) &&
isStringOrNull(value.archive_name)
);
}

export function isNewFileResponse(value: unknown): value is NewFileResponse {
return isRecord(value) && isNonEmptyString(value.hash) && isNonEmptyString(value.name);
}

export function isRenameFileResponse(value: unknown): value is RenameFileResponse {
return (
isRecord(value) &&
isNonEmptyString(value.name) &&
isNonEmptyString(value.hash) &&
isStringOrNull(value.archived_original) &&
isStringOrNull(value.archived_replaced)
);
}

export function isCopyFileResponse(value: unknown): value is CopyFileResponse {
return isRecord(value) && isNonEmptyString(value.name) && isNonEmptyString(value.hash);
}
46 changes: 34 additions & 12 deletions pkgs/id/web/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ import { clientIdForDisplay } from "./settings-identity";
import { closeImageBrowser } from "./image-browser";
import { createNavigation } from "./navigation";
import { resolveSaveFilename } from "./save-filename";
import {
isCopyFileResponse,
isNewFileResponse,
isRenameFileResponse,
isSaveFileResponse,
} from "./file-op-responses";
import { isSaveShortcut } from "./save-shortcut";
import { cycleTheme, initTheme, setTheme, type Theme } from "./theme";

Expand Down Expand Up @@ -1129,7 +1135,11 @@ async function init(): Promise<void> {
return { ok: false };
}

const result = (await response.json()) as { hash: string; name: string; archive_name: string | null };
const result: unknown = await response.json();
if (!isSaveFileResponse(result)) {
console.error("[id] Save failed: unexpected /api/save response shape", result);
return { ok: false };
}
console.log("[id] File saved:", result);

// Update the hash in the container (doc_id stays as filename)
Expand Down Expand Up @@ -1166,7 +1176,11 @@ async function init(): Promise<void> {
return;
}

const result = (await response.json()) as { hash: string; name: string };
const result: unknown = await response.json();
if (!isNewFileResponse(result)) {
console.error("[id] Create file failed: unexpected /api/new response shape", result);
return;
}
console.log("[id] File created:", result);

// Clear input
Expand Down Expand Up @@ -1279,12 +1293,15 @@ async function init(): Promise<void> {
return;
}

const result = (await response.json()) as {
name: string;
hash: string;
archived_original: string | null;
archived_replaced: string | null;
};
const result: unknown = await response.json();
if (!isRenameFileResponse(result)) {
console.error("[id] Rename failed: unexpected /api/rename response shape", result);
if (renameBtn) renameBtn.textContent = "error!";
setTimeout(() => {
if (renameBtn) renameBtn.textContent = "rename";
}, 2000);
return;
}
console.log("[id] File renamed:", result);

if (renameBtn) {
Expand Down Expand Up @@ -1347,10 +1364,15 @@ async function init(): Promise<void> {
return;
}

const result = (await response.json()) as {
name: string;
hash: string;
};
const result: unknown = await response.json();
if (!isCopyFileResponse(result)) {
console.error("[id] Copy failed: unexpected /api/copy response shape", result);
if (copyBtn) copyBtn.textContent = "error!";
setTimeout(() => {
if (copyBtn) copyBtn.textContent = "copy";
}, 2000);
return;
}
console.log("[id] File copied:", result);

if (copyBtn) {
Expand Down
Loading