import { describe, expect, it } from "@effect/vitest";
import { Effect, Schema } from "effect";
import { buildUiDocument, safeJsonForScript } from "./ui-shell";
const decodeJsonUnknown = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
// ---------------------------------------------------------------------------
// Finding 2 regression: the ui document's data island inlines rows/title into an
// inline " must NOT break out of the
// script element and execute. Before the fix, `JSON.stringify(...)` emitted the
// raw "" verbatim, closing the element and running the injected markup.
// ---------------------------------------------------------------------------
const PAYLOAD = ``;
// A minimal valid compiled component bundle: the runtime splices this in place
// of the marker and calls it. It just needs to be syntactically valid JS.
const COMPILED_BUNDLE = `module.exports = function App(){ return null; };`;
describe("ui data island XSS (Fix 2)", () => {
it("safeJsonForScript escapes {
const value = { rows: [{ title: PAYLOAD }], title: "a
b" };
const out = safeJsonForScript(value);
// No raw "", async () => {
const html = await Effect.runPromise(
buildUiDocument({
compiledBundle: COMPILED_BUNDLE,
title: "Dash",
rows: [{ title: PAYLOAD, number: 1 }],
}),
);
// Isolate the data-island script (the one assigning window.__EXECUTOR_UI__).
const marker = "window.__EXECUTOR_UI__ = ";
const start = html.indexOf(marker);
expect(start).toBeGreaterThan(-1);
const islandEnd = html.indexOf("", start);
const island = html.slice(start, islandEnd);
// The malicious ".
expect(/<\/script/i.test(island)).toBe(false);
// And the payload IS present, in escaped form (proving it was serialized,
// not dropped).
expect(island).toContain("\\u003c/script");
});
});