Skip to content
Open
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ All notable changes to `sessionpipe-gui`. The format follows

## [Unreleased]

### Fixed

- JSON configuration and other BOM-aware JSON readers accept UTF-16 files with a byte-order mark.

## [0.8.18] - 2026-12-04

### Fixed
Expand Down
8 changes: 4 additions & 4 deletions server/app.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// Owned by: server-core (composition root). Every module plugs in here and nowhere
// else. Module boundaries and who owns what: ARCHITECTURE.md.
import { type FSWatcher, readFileSync, statSync, watch } from "node:fs";
import { type FSWatcher, statSync, watch } from "node:fs";
import http from "node:http";
import https from "node:https";
import type net from "node:net";
Expand All @@ -17,6 +17,7 @@ import {
RETIRED_MAX,
readGuiConfig,
readRetired,
readText,
renewUiKey,
retire,
rotateSinkToken,
Expand All @@ -29,7 +30,6 @@ import {
setSpacesheep,
setTlsPreference,
takeWrite,
withoutBom,
writeChanged,
} from "./config.js";
import { type Control, createControl } from "./control/index.js";
Expand Down Expand Up @@ -233,7 +233,7 @@ export async function createApp(opts: AppOptions = {}): Promise<App> {
const configFile = path.join(stateDir, "config.json");
const fileText = (): string | null => {
try {
return readFileSync(configFile, "utf8");
return readText(configFile);
} catch {
return null;
}
Expand All @@ -254,7 +254,7 @@ export async function createApp(opts: AppOptions = {}): Promise<App> {
lastRead = text;
let disk: unknown;
try {
disk = JSON.parse(withoutBom(text));
disk = JSON.parse(text);
} catch {
return config;
}
Expand Down
38 changes: 38 additions & 0 deletions server/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ import { ConfigError, readGuiConfig, setTlsPreference } from "./config.js";

const KEPT = { sinkToken: "spg_test_keepme", uiKey: "uik_keepme", createdAt: "2026-01-01T00:00:00.000Z" };
const BOM = String.fromCharCode(0xfeff);
/** `text` as UTF-16 with a byte-order mark: what Windows PowerShell 5.1's `Out-File` and
* `>` write (little-endian), and `-Encoding BigEndianUnicode` (big-endian). */
const utf16 = (text: string, be = false): Buffer => {
const b = Buffer.from(`${BOM}${text}`, "utf16le");
return be ? b.swap16() : b;
};

let tmp: { dir: string; cleanup: () => void };
let file: string;
Expand Down Expand Up @@ -46,6 +52,38 @@ describe("readGuiConfig", () => {
expect(JSON.parse(text)).toMatchObject({ ...KEPT, tls: false });
});

it("reads a config.json saved as UTF-16 with a byte-order mark, and writes it back as UTF-8", () => {
const dir = fresh("utf16");
for (const be of [false, true]) {
// PowerShell 5.1 ends its lines with CRLF.
writeFileSync(file, utf16(`${JSON.stringify({ ...KEPT, tls: true, enabled: ["plugin:é"] }, null, 2)}\r\n`, be));
const before = readFileSync(file);
const cfg = readGuiConfig(dir);
expect(cfg).toMatchObject({ ...KEPT, tls: true, enabled: ["plugin:é"] });
// Nothing was missing, so nothing was written: the file is as the person saved it.
expect(readFileSync(file).equals(before)).toBe(true);
// The next write is in the GUI's own format, keeping what the file held.
setTlsPreference(dir, cfg, false);
const text = readFileSync(file, "utf8");
expect(text.startsWith("{")).toBe(true);
expect(JSON.parse(text)).toMatchObject({ ...KEPT, tls: false, enabled: ["plugin:é"] });
}
});

it("stops on a UTF-16 config.json cut short or without a byte-order mark, leaving it byte for byte", () => {
const dir = fresh("utf16-bad");
const whole = utf16(JSON.stringify(KEPT));
// An odd number of bytes (a write that died halfway), and UTF-16 with no mark to say
// so, which is not guessed at.
for (const bytes of [whole.subarray(0, whole.length - 1), whole.subarray(2)]) {
writeFileSync(file, bytes);
expect(() => readGuiConfig(dir)).toThrow(ConfigError);
expect(() => readGuiConfig(dir)).toThrow(/is not valid JSON/);
expect(() => readGuiConfig(dir)).not.toThrow(/keepme/);
expect(readFileSync(file).equals(bytes)).toBe(true);
}
});

it("stops on a config.json that does not parse, leaving it byte for byte, and never quotes it", () => {
const dir = fresh("cut");
// What a write that died halfway leaves (the token's first bytes, no closing quote), and
Expand Down
22 changes: 19 additions & 3 deletions server/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,21 @@ export class ConfigError extends Error {
* older Windows editors write one, and JSON.parse refuses it. */
export const withoutBom = (text: string): string => (text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);

/** A JSON file's text, past its byte-order mark. One that starts with a UTF-16 mark is
* decoded from UTF-16: Windows PowerShell 5.1's `Out-File` and `>` write UTF-16LE with
* one (and `-Encoding BigEndianUnicode` UTF-16BE). Any other is read as UTF-8 past a
* UTF-8 mark; a UTF-16 file without a mark is not guessed at, and so does not parse. */
export function readText(file: string): string {
let b = readFileSync(file);
if (b[0] === 0xfe && b[1] === 0xff) {
// Big-endian, swapped to little-endian here: a Node without full ICU has no utf-16be decoder.
b = Buffer.from(b);
b.subarray(0, b.length & ~1).swap16();
}
const utf16 = b[0] === 0xff && b[1] === 0xfe;
return withoutBom(utf16 ? new TextDecoder("utf-16le", { ignoreBOM: true }).decode(b) : b.toString("utf8"));
}

const WHAT_IT_HOLDS =
"it holds the sink token every sender presents and the UI key every phone and browser holds. " +
"Fix it, or move it aside to start fresh (senders and phones then pair again), then run this again.";
Expand All @@ -126,7 +141,7 @@ const WHAT_IT_HOLDS =
export function readConfigFile(f: string): Partial<GuiConfig> | undefined {
let text: string;
try {
text = withoutBom(readFileSync(f, "utf8"));
text = readText(f);
} catch (e) {
const code = (e as NodeJS.ErrnoException).code;
if (code === "ENOENT") return undefined;
Expand All @@ -150,8 +165,9 @@ export function readConfigFile(f: string): Partial<GuiConfig> | undefined {

/** Read the config, making it (or any missing secret) on first run. A file that cannot be
* read or does not parse throws a ConfigError and is left byte for byte as it was; one
* with a byte-order mark is read past it (and written back without one, the GUI's own
* format). A file it reads is also brought to mode 0600 if it is looser (tightenMode). */
* with a byte-order mark is read past it (a UTF-16 one decoded: readText) and written
* back as UTF-8 without one, the GUI's own format. A file it reads is also brought to
* mode 0600 if it is looser (tightenMode). */
export function readGuiConfig(dir: string): GuiConfig {
const f = path.join(dir, "config.json");
const cfg = readConfigFile(f) ?? {};
Expand Down
17 changes: 17 additions & 0 deletions server/control/machines-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,23 @@ describe("control/machines.json at start", () => {
expect(readFileSync(queue, "utf8")).toBe(queued);
});

it("reads a machines.json saved as UTF-16 with a byte-order mark, as PowerShell 5.1's Out-File writes it", () => {
writeFileSync(machines, Buffer.from(BOM + readFileSync(machines, "utf8"), "utf16le"));
expect(
start()
.allMachines()
.map((m) => m.id),
).toEqual(["m_machinesfile00000001"]);
expect(readFileSync(queue, "utf8")).toBe(queued);
});

it("keeps a machine's queue file saved as UTF-16 with a byte-order mark", () => {
const wide = Buffer.from(BOM + queued, "utf16le");
writeFileSync(queue, wide);
start();
expect(readFileSync(queue).equals(wide)).toBe(true);
});

it("stops on a machines.json that is empty, cut short or without a machines list, leaving it and every queue as they were", () => {
const whole = readFileSync(machines, "utf8");
for (const [text, says] of [
Expand Down
8 changes: 4 additions & 4 deletions server/control/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@
// signature, only verify one. Tokens are stored hashed; a leaked state file hands
// nobody a machine's queue.
import { createHash, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
import path from "node:path";
import { ulid } from "sessionpipe-core";
import type { ControlCommand, SignedCommand } from "sessionpipe-core/control";
import type { Applied, ControlActivity, ControlOutcome, MachineControl, TrustedKey } from "../../shared/api.js";
import { ConfigError, withoutBom } from "../config.js";
import { ConfigError, readText } from "../config.js";
import { DISPLAY_KEEP_MS, FileStore, PICTURE_TYPES } from "./files.js";
import { type AckIn, type Hello, isFinal, MACHINE_RE } from "./parse.js";
import { type RemoteJobWord, RemoteSlice } from "./remote.js";
Expand Down Expand Up @@ -123,7 +123,7 @@ function writeAtomic(file: string, data: unknown): void {

function readJson<T>(file: string): T | null {
try {
return existsSync(file) ? (JSON.parse(withoutBom(readFileSync(file, "utf8"))) as T) : null;
return existsSync(file) ? (JSON.parse(readText(file)) as T) : null;
} catch {
return null;
}
Expand All @@ -142,7 +142,7 @@ const MACHINES_HOLD =
function readMachinesFile(file: string): MachinesFile | null {
let text: string;
try {
text = withoutBom(readFileSync(file, "utf8"));
text = readText(file);
} catch (e) {
const code = (e as NodeJS.ErrnoException).code;
if (code === "ENOENT") return null;
Expand Down
6 changes: 3 additions & 3 deletions server/extensions/kind.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
// a validator, and the scan that lists what is installed. Views (server/themes), skins
// (server/skins) and plugins (server/plugins) each describe themselves as an ExtensionKind
// and share the installer in ./install.ts and the bundled folders below.
import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
import { existsSync, lstatSync, readdirSync, realpathSync, statSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { withoutBom } from "../config.js";
import { readText } from "../config.js";

export type ExtensionKindName = "view" | "skin" | "plugin";

Expand Down Expand Up @@ -60,7 +60,7 @@ export function readManifestOf<M extends BaseManifest>(kind: ExtensionKind<M>, d
if (!existsSync(file)) throw new Error(`no ${kind.manifestFile}`);
let raw: unknown;
try {
raw = JSON.parse(withoutBom(readFileSync(file, "utf8")));
raw = JSON.parse(readText(file));
} catch (e) {
throw new Error(`${kind.manifestFile} is not valid JSON: ${(e as Error).message}`);
}
Expand Down
10 changes: 10 additions & 0 deletions server/keyRules.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,16 @@ describe("a key or token this receiver replaced never comes back", () => {
expect(a.config().uiKey).toBe("short");
}, 60_000);

it("a key written by hand as UTF-16 (PowerShell 5.1's Out-File) is taken while running", async () => {
const a = await boot();
writeFileSync(
file(),
Buffer.from(`\uFEFF${JSON.stringify({ ...disk(), uiKey: "OwnerChoseThisKey" }, null, 2)}\r\n`, "utf16le"),
);
await until(() => a.config().uiKey === "OwnerChoseThisKey");
expect(await visitor(a, "OwnerChoseThisKey")).toBe(200);
}, 30_000);

it("the retired list is in config.json, as hashes, and holds across a start", async () => {
let a = await boot();
const k1 = a.config().uiKey;
Expand Down
12 changes: 12 additions & 0 deletions server/skins/skins.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,18 @@ describe("skin manifest validation", () => {
}
});

it("readSkinManifest reads a skin.json saved as UTF-16 with a byte-order mark, as PowerShell 5.1's Out-File writes one", () => {
const tmp = tempDir();
try {
const dir = makeSkin(path.join(tmp.dir, "wide"));
const file = path.join(dir, "skin.json");
writeFileSync(file, Buffer.from(`\uFEFF${readFileSync(file, "utf8")}`, "utf16le"));
expect(readSkinManifest(dir)).toMatchObject({ id: "wide", scheme: "dark" });
} finally {
tmp.cleanup();
}
});

it("skinFromManifest normalises the tokens per scheme and names the files' URL", () => {
const one = skinFromManifest(validateSkinManifest({ ...BASE, scheme: "light", tokens: LIGHT, source: "s" }), "/d");
expect(one).toEqual({
Expand Down
6 changes: 3 additions & 3 deletions server/ui/colorThemes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
// a `ColorTheme` (shared/color-theme.ts); the web app lists them after its built-ins.
// Read on every request (the folder is small and edits should show on reload); a file
// that does not parse or validate is reported, never served.
import { readdirSync, readFileSync } from "node:fs";
import { readdirSync } from "node:fs";
import path from "node:path";
import { type ColorThemesResponse, parseColorTheme } from "../../shared/color-theme.js";
import { withoutBom } from "../config.js";
import { readText } from "../config.js";

export function readColorThemes(dir: string): ColorThemesResponse {
const out: ColorThemesResponse = { themes: [], errors: [] };
Expand All @@ -22,7 +22,7 @@ export function readColorThemes(dir: string): ColorThemesResponse {
for (const file of files) {
let doc: unknown;
try {
doc = JSON.parse(withoutBom(readFileSync(path.join(dir, file), "utf8")));
doc = JSON.parse(readText(path.join(dir, file)));
} catch (err) {
out.errors.push({ file, error: `not JSON: ${err instanceof Error ? err.message : String(err)}` });
continue;
Expand Down
13 changes: 13 additions & 0 deletions server/ui/docFile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,19 @@ describe("docFile", () => {
}
});

it("reads a file saved as UTF-16 with a byte-order mark, as PowerShell 5.1's Out-File writes it", () => {
const tmp = tempDir();
try {
const file = path.join(tmp.dir, "doc.json");
writeFileSync(file, Buffer.from(`${BOM}{"a":"é"}\r\n`, "utf16le"));
expect(docFile(file).load()).toEqual({ a: "é" });
writeFileSync(file, Buffer.from(`${BOM}{"a":1}`, "utf16le").swap16());
expect(docFile(file).load()).toEqual({ a: 1 });
} finally {
tmp.cleanup();
}
});

it("still throws on a broken file, with or without a byte-order mark", () => {
const tmp = tempDir();
try {
Expand Down
9 changes: 5 additions & 4 deletions server/ui/docFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,19 @@
// Owned by: server-core. A DocKeep (docKeep.ts) that is one JSON file: read whole, written
// whole and atomically (a temp file, then rename) for its owner alone, and renamed to
// `<file>.bad-<time>` when it cannot be read, so a broken file is never lost. A leading
// UTF-8 byte-order mark (an editor's, on a hand edit) is read past, not taken for damage.
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
// byte-order mark (an editor's, on a hand edit; a UTF-16 one is decoded: config.ts
// readText) is read past, not taken for damage.
import { mkdirSync, renameSync, writeFileSync } from "node:fs";
import path from "node:path";
import { withoutBom } from "../config.js";
import { readText } from "../config.js";
import type { DocKeep } from "./docKeep.js";

export function docFile(file: string): DocKeep {
return {
load() {
let text: string;
try {
text = withoutBom(readFileSync(file, "utf8"));
text = readText(file);
} catch {
return undefined;
}
Expand Down
8 changes: 8 additions & 0 deletions server/ui/ui.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,14 @@ describe("UI API", () => {
expect(readColorThemes(dir)).toEqual({ themes: [theme], errors: [] });
});

it("reads a color theme saved as UTF-16 with a byte-order mark, as PowerShell 5.1's Out-File writes one", () => {
const dir = path.join(tmp.dir, "color-themes-utf16");
mkdirSync(dir, { recursive: true });
const theme = { id: "wide", name: "Wide", scheme: "dark", tokens: { "--bg": "#000", "--fg": "#fff" } };
writeFileSync(path.join(dir, "wide.json"), Buffer.from(`\uFEFF${JSON.stringify(theme)}`, "utf16le"));
expect(readColorThemes(dir)).toEqual({ themes: [theme], errors: [] });
});

it("serves the color themes dropped into <state>/color-themes, reporting bad files", async () => {
const dir = path.join(tmp.dir, "color-themes");
mkdirSync(dir, { recursive: true });
Expand Down