diff --git a/CHANGELOG.md b/CHANGELOG.md index 5299e266..330adffb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/server/app.ts b/server/app.ts index 856cf68a..461cf7c6 100644 --- a/server/app.ts +++ b/server/app.ts @@ -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"; @@ -17,6 +17,7 @@ import { RETIRED_MAX, readGuiConfig, readRetired, + readText, renewUiKey, retire, rotateSinkToken, @@ -29,7 +30,6 @@ import { setSpacesheep, setTlsPreference, takeWrite, - withoutBom, writeChanged, } from "./config.js"; import { type Control, createControl } from "./control/index.js"; @@ -233,7 +233,7 @@ export async function createApp(opts: AppOptions = {}): Promise { const configFile = path.join(stateDir, "config.json"); const fileText = (): string | null => { try { - return readFileSync(configFile, "utf8"); + return readText(configFile); } catch { return null; } @@ -254,7 +254,7 @@ export async function createApp(opts: AppOptions = {}): Promise { lastRead = text; let disk: unknown; try { - disk = JSON.parse(withoutBom(text)); + disk = JSON.parse(text); } catch { return config; } diff --git a/server/config.test.ts b/server/config.test.ts index e2224d3d..a79de93b 100644 --- a/server/config.test.ts +++ b/server/config.test.ts @@ -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; @@ -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 diff --git a/server/config.ts b/server/config.ts index 7be3b363..e3082e39 100644 --- a/server/config.ts +++ b/server/config.ts @@ -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."; @@ -126,7 +141,7 @@ const WHAT_IT_HOLDS = export function readConfigFile(f: string): Partial | 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; @@ -150,8 +165,9 @@ export function readConfigFile(f: string): Partial | 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) ?? {}; diff --git a/server/control/machines-file.test.ts b/server/control/machines-file.test.ts index f770848f..8738703f 100644 --- a/server/control/machines-file.test.ts +++ b/server/control/machines-file.test.ts @@ -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 [ diff --git a/server/control/state.ts b/server/control/state.ts index 89fd3a80..d531a111 100644 --- a/server/control/state.ts +++ b/server/control/state.ts @@ -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"; @@ -123,7 +123,7 @@ function writeAtomic(file: string, data: unknown): void { function readJson(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; } @@ -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; diff --git a/server/extensions/kind.ts b/server/extensions/kind.ts index c3696d1e..a66a3aab 100644 --- a/server/extensions/kind.ts +++ b/server/extensions/kind.ts @@ -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"; @@ -60,7 +60,7 @@ export function readManifestOf(kind: ExtensionKind, 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}`); } diff --git a/server/keyRules.test.ts b/server/keyRules.test.ts index 9de60a62..8b5784d5 100644 --- a/server/keyRules.test.ts +++ b/server/keyRules.test.ts @@ -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; diff --git a/server/skins/skins.test.ts b/server/skins/skins.test.ts index 40f1f082..f164af8a 100644 --- a/server/skins/skins.test.ts +++ b/server/skins/skins.test.ts @@ -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({ diff --git a/server/ui/colorThemes.ts b/server/ui/colorThemes.ts index 4f84a511..973f270f 100644 --- a/server/ui/colorThemes.ts +++ b/server/ui/colorThemes.ts @@ -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: [] }; @@ -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; diff --git a/server/ui/docFile.test.ts b/server/ui/docFile.test.ts index 57cbebfe..7055c932 100644 --- a/server/ui/docFile.test.ts +++ b/server/ui/docFile.test.ts @@ -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 { diff --git a/server/ui/docFile.ts b/server/ui/docFile.ts index b961d2f9..94734c5a 100644 --- a/server/ui/docFile.ts +++ b/server/ui/docFile.ts @@ -2,10 +2,11 @@ // 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 // `.bad-