src / settings.ts
// MSI chat plugin: reads and checks the fields of settings.json (build contract 3.1) that main() needs.
// Pure functions; the only outside access is the injected `exists` probe. Erasable TypeScript only.
export const SETTINGS_SCHEMA = 1;
export const MAX_SETTINGS_BYTES = 1_000_000;
const MAX_PATH_CHARS = 1024;
const MAX_ENV_NAMES = 64;
const MAX_ENV_VALUE_CHARS = 8192;
// The test guard (build contract rules 4 and 5). With MSI_CHAT_TEST=1 the test must also give MSI_CHAT_TEST_ROOT, its
// sandbox: one absolute folder, or several separated by ";" (a test area on one drive and one under TEMP). Every place
// the plugin writes or starts (the run folder, the settings file, the keepalive, the launcher) must lie under one of
// them; anything else is refused. The shipped code names no place of any PC: the allow-list is the test's own.
export const TEST_ROOT_NAME = "MSI_CHAT_TEST_ROOT";
export const REAL_PORTS: readonly number[] = [8744, 8745];
export interface PluginSettings {
readonly version: string;
readonly startWithLmstudio: boolean;
readonly runDir: string;
readonly stateDir: string;
readonly logsDir: string;
readonly python: string;
readonly keepalive: string;
readonly launcher: string;
readonly adminHost: string;
readonly adminPort: number;
readonly launchEnv: Readonly<Record<string, string>>;
readonly testMode: boolean;
}
export type CheckResult =
| { readonly ok: true; readonly settings: PluginSettings }
| { readonly ok: false; readonly reason: string; readonly refused: boolean; readonly logsDir: string | null };
export interface FileProbe {
exists(path: string): boolean;
}
export interface CheckOptions {
readonly testMode?: boolean;
// The plugin's own MSI_CHAT_TEST_ROOT (start.ts gives process.env's); without it launch_env's is read.
readonly testRoot?: string;
}
type Json = Record<string, unknown>;
function isPlainObject(value: unknown): value is Json {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
// An absolute Windows path with a drive letter ("<drive>:\...") with plain parts only: no UNC or device path, no ".."
// or "." part, no empty part (except one trailing separator), no part ending in a dot or a space (Windows drops those,
// so "folder." would open "folder"), no stream (":" after the drive), no wildcard.
export function isAbsWinPath(value: unknown): value is string {
if (typeof value !== "string" || value.length < 3 || value.length > MAX_PATH_CHARS) return false;
if (!/^[A-Za-z]:[\\/]/.test(value)) return false;
if (/[\u0000-\u001f\u007f"<>|?*]/.test(value)) return false;
if (value.indexOf(":", 2) !== -1) return false;
const parts = value.split(/[\\/]/).slice(1);
return parts.every((part, i) => (part === "" ? i === parts.length - 1 : part !== "." && part !== ".." && !/[. ]$/.test(part)));
}
function normalizeWin(p: string): string {
return p.replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase();
}
// A part that looks like an 8.3 short name ("MSI-CH~1"): it could name any folder, so it is never trusted.
function hasShortName(p: string): boolean {
return /(^|\\)[^\\]*~\d/.test(normalizeWin(p));
}
function splitRoots(value: string): readonly string[] {
return value.split(";").filter((part) => part !== "");
}
// null when `value` is a usable MSI_CHAT_TEST_ROOT, else why not (the text after "refused under MSI_CHAT_TEST: ").
// launcher.js and bootstrap.js hold the same rules (the tests hold them to one table).
export function testRootProblem(value: unknown): string | null {
if (typeof value !== "string" || splitRoots(value).length === 0) {
return TEST_ROOT_NAME + " is missing (set it to the test's sandbox folder)";
}
for (const root of splitRoots(value)) {
if (!isAbsWinPath(root)) return TEST_ROOT_NAME + " holds a path that is not an absolute Windows path";
if (normalizeWin(root).length <= 2) return TEST_ROOT_NAME + " must name a folder, not a whole drive";
if (hasShortName(root)) return TEST_ROOT_NAME + " holds an 8.3 short name";
}
return null;
}
// True when `p` is one of the test roots or lies inside one (names compared: no "..", no short name reaches here
// through isAbsWinPath, and an 8.3 part is refused anyway). An unusable root holds nothing.
export function isUnderTestRoot(p: string, rootValue: string): boolean {
if (testRootProblem(rootValue) !== null || hasShortName(p)) return false;
const n = normalizeWin(p);
return splitRoots(rootValue).some((root) => {
const r = normalizeWin(root);
return n === r || n.startsWith(r + "\\");
});
}
// "refused under MSI_CHAT_TEST: <name> ..." for a place that is not under the test root, else null.
export function testPathProblem(name: string, p: unknown, rootValue: string): string | null {
if (typeof p === "string" && hasShortName(p)) return "refused under MSI_CHAT_TEST: " + name + " holds an 8.3 short name";
if (typeof p !== "string" || !isUnderTestRoot(p, rootValue)) return "refused under MSI_CHAT_TEST: " + name + " is outside " + TEST_ROOT_NAME;
return null;
}
const SECRET_NAME = /(KEY|TOKEN|SECRET|PASS|CREDENTIAL|AUTH|COOKIE|SESSION)/i;
const SECRET_PREFIX = /^(CF_|CLOUDFLARE|NEWT_|TUNNEL)/i;
const LONG_TOKEN = /[A-Za-z0-9_-]{40,}/;
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_()]*$/;
function envLookup(env: Json, name: string): unknown {
const key = Object.keys(env).find((k) => k.toLowerCase() === name.toLowerCase());
return key === undefined ? undefined : env[key];
}
// The launch environment (3.1 `launch_env`): strings only, no LMS_* name, nothing secret-shaped,
// a SystemRoot that really holds System32 (a wrong SystemRoot crashed Node in M0), PATH, TEMP, USERPROFILE.
export function launchEnvProblem(env: unknown, probe: FileProbe): string | null {
if (!isPlainObject(env)) return "launch_env: not an object";
const names = Object.keys(env);
if (names.length === 0 || names.length > MAX_ENV_NAMES) return "launch_env: wrong number of names";
const seen = new Set<string>();
for (const name of names) {
if (!ENV_NAME.test(name)) return "launch_env: a name is not a plain variable name";
if (/^LMS_/i.test(name)) return "launch_env: LMS_* names are refused (" + name + ")";
if (SECRET_NAME.test(name) || SECRET_PREFIX.test(name)) return "launch_env: a secret-like name is refused (" + name + ")";
const lower = name.toLowerCase();
if (seen.has(lower)) return "launch_env: a name appears twice (" + name + ")";
seen.add(lower);
const value = env[name];
if (typeof value !== "string") return "launch_env: " + name + " is not a string";
if (value.length > MAX_ENV_VALUE_CHARS || value.includes("\u0000")) return "launch_env: " + name + " is too long or holds NUL";
if (LONG_TOKEN.test(value)) return "launch_env: " + name + " holds a token-like value";
}
for (const name of ["SystemRoot", "PATH", "TEMP", "USERPROFILE"]) {
const value = envLookup(env, name);
if (typeof value !== "string" || value.length === 0) return "launch_env: " + name + " is missing";
}
const systemRoot = envLookup(env, "SystemRoot");
if (!isAbsWinPath(systemRoot) || !probe.exists(systemRoot.replace(/[\\/]+$/, "") + "\\System32")) {
return "launch_env: SystemRoot does not hold System32";
}
for (const name of ["TEMP", "USERPROFILE"]) {
if (!isAbsWinPath(envLookup(env, name))) return "launch_env: " + name + " is not an absolute path";
}
return null;
}
function fail(reason: string, logsDir: string | null, refused = false): CheckResult {
return { ok: false, reason, refused, logsDir };
}
const PATH_FIELDS = ["run_dir", "state_dir", "logs_dir", "python", "keepalive", "launcher"] as const;
// Under MSI_CHAT_TEST these must lie under the test root: the plugin writes into the run folder and starts the
// launcher and the keepalive. python is a real interpreter and may be anywhere.
const GUARDED_FIELDS = ["run_dir", "state_dir", "logs_dir", "keepalive", "launcher"] as const;
function pathProblem(raw: Json, probe: FileProbe): string | null {
for (const field of PATH_FIELDS) {
if (!isAbsWinPath(raw[field])) return field + ": not an absolute path";
}
const python = raw.python as string;
if (!/(^|[\\/])python\.exe$/i.test(python) || python.includes(" ")) return "python: must be a python.exe path without spaces";
if (!/\.py$/i.test(raw.keepalive as string)) return "keepalive: not a .py file";
if (!/\.js$/i.test(raw.launcher as string)) return "launcher: not a .js file";
for (const field of ["python", "keepalive", "launcher"] as const) {
if (!probe.exists(raw[field] as string)) return field + ": file not found";
}
return null;
}
function adminProblem(admin: unknown): string | null {
if (!isPlainObject(admin)) return "admin: not an object";
if (admin.host !== "127.0.0.1") return "admin.host: must be 127.0.0.1";
const port = admin.port;
if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535) return "admin.port: not 1-65535";
return null;
}
// The test root in force: the plugin's own (options), else launch_env's; undefined when neither gives one.
function testRootOf(raw: Json, options: CheckOptions): string | undefined {
if (typeof options.testRoot === "string") return options.testRoot;
const fromEnv = isPlainObject(raw.launch_env) ? envLookup(raw.launch_env, TEST_ROOT_NAME) : undefined;
return typeof fromEnv === "string" ? fromEnv : undefined;
}
function testModeProblem(raw: Json, root: string | undefined): string | null {
const rootProblem = testRootProblem(root);
if (rootProblem !== null) return "refused under MSI_CHAT_TEST: " + rootProblem;
for (const field of GUARDED_FIELDS) {
const problem = testPathProblem(field, raw[field], root as string);
if (problem !== null) return problem;
}
const port = (raw.admin as Json).port as number;
if (REAL_PORTS.includes(port)) return "refused under MSI_CHAT_TEST: admin.port " + port;
return null;
}
// Checks a parsed settings object. Never throws.
export function checkSettingsObject(raw: unknown, probe: FileProbe, options: CheckOptions = {}): CheckResult {
if (!isPlainObject(raw)) return fail("settings: not a JSON object", null);
const envTest = isPlainObject(raw.launch_env) && raw.launch_env.MSI_CHAT_TEST === "1";
const testMode = options.testMode === true || envTest;
const root = testMode ? testRootOf(raw, options) : undefined;
// Under the test a logs dir is only trusted (for the line that says why) when it lies under the root.
const logsOk = isAbsWinPath(raw.logs_dir) && (!testMode || (root !== undefined && isUnderTestRoot(raw.logs_dir, root)));
const logsDir = logsOk ? (raw.logs_dir as string) : null;
if (raw.schema !== SETTINGS_SCHEMA) return fail("schema: not " + SETTINGS_SCHEMA, logsDir);
const problem = pathProblem(raw, probe) ?? adminProblem(raw.admin);
if (problem !== null) return fail(problem, logsDir);
if (typeof raw.start_with_lmstudio !== "boolean") return fail("start_with_lmstudio: not true or false", logsDir);
const envProblem = launchEnvProblem(raw.launch_env, probe);
if (envProblem !== null) return fail(envProblem, logsDir);
if (testMode) {
const refusal = testModeProblem(raw, root);
if (refusal !== null) return fail(refusal, logsDir, true);
}
const admin = raw.admin as Json;
const settings: PluginSettings = {
version: typeof raw.version === "string" ? raw.version : "",
startWithLmstudio: raw.start_with_lmstudio,
runDir: raw.run_dir as string,
stateDir: raw.state_dir as string,
logsDir: raw.logs_dir as string,
python: raw.python as string,
keepalive: raw.keepalive as string,
launcher: raw.launcher as string,
adminHost: admin.host as string,
adminPort: admin.port as number,
launchEnv: Object.freeze({ ...(raw.launch_env as Record<string, string>) }),
testMode,
};
return { ok: true, settings: Object.freeze(settings) };
}
// Parses the text of settings.json (UTF-8; a BOM is tolerated) and checks it. Never throws.
export function parseSettingsText(text: string, probe: FileProbe, options: CheckOptions = {}): CheckResult {
if (text.length > MAX_SETTINGS_BYTES) return fail("settings: file too large", null);
let raw: unknown;
try {
raw = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
} catch {
return fail("settings: not valid JSON", null);
}
return checkSettingsObject(raw, probe, options);
}