Node.js 严格校验 JSON 配置:从字段契约到可定位错误

10-20 4阅读

JSON.parse 成功,只表示文本能被解析,不表示配置能交给应用。把 false 写成字符串、把 timeoutMs 拼错,或者给对象字段传入 null,都可能直到启动后才暴露。本文用 Node.js 标准库实现一个固定配置校验器:不做隐式类型转换,不放过未知字段,并把问题定位到具体路径。

Node.js 严格校验 JSON 配置:从字段契约到可定位错误
AI 生成概念图:用形状筛选比喻配置契约,不是软件界面、运行证据或安全能力示意。

一、先写契约,再写判断

示例是应用自己控制的小型报表任务配置,不包含账户、口令或远程请求。除 note 外,所有字段必填;每层对象都只接受列出的键。把下面内容保存为 config.json:

{
  "appName": "report-worker",
  "enabled": false,
  "port": 8080,
  "limits": { "concurrency": 4, "timeoutMs": 5000 },
  "targets": [{ "name": "daily", "retries": 2 }],
  "note": null
}
  • appName:一至四十个字符,以小写英文字母开头,其余只允许小写字母、数字和连字符。

  • enabled:只接受真正的布尔值;port:安全整数,范围一至六万五千五百三十五。

  • limits:必须是对象;concurrency 为一至三十二,timeoutMs 为一百至六万,均为安全整数。

  • targets:一至八项对象;name 遵循同类命名规则,最多三十二字符且不能重复;retries 为零至五。

  • note:省略时补为 null,也允许显式 null;字符串不能全为空白,最多八十个 Unicode 码点,原文不裁剪。

拒绝未知字段不是为了限制配置文件扩展,而是避免拼写错误被静默忽略。例如把 concurrency 写成 concurency,程序若直接采用默认值,看起来仍能启动,却没有按照操作者的意图运行。新增选项应同步修改契约与测试,而不是先允许任何键进入应用。

二、缺失不是 null,false 也不是错误

不能用 if (!value) 检查必填项,它会把合法的 false 和零一起判为缺失;也不能用 value == null,把“没有键”和“键存在但值为 null”混在一起。这里用独立的 Symbol 标记缺失,再让字段自己的规则处理 null。

必填检查使用 Object.hasOwn,不使用 in,也不调用输入对象自己的 hasOwnProperty。这样,原型链上的同名属性不能满足要求。未知字段通过 Object.keys 枚举当前对象的自有可枚举键。相关语义可核对 ECMAScript 的 Object.hasOwn 与 Object.keys 规范。输入契约是普通 JSON.parse 的结果,不是带访问器或 Proxy 的任意对象。

可选也不等于任意值。note 的省略和显式 null 是特意允许的两种输入,数字零仍应报错;其他必填字段没有偷偷补默认值。把默认值集中在契约允许的位置,能避免一次“方便”的兜底掩盖部署配置缺项。

三、完整校验器与命令行入口

保存为 validate-config.cjs。函数收集相互独立的问题;父对象类型错误时,不继续读取子字段,避免制造一串没有意义的错误。只有全部通过,才构造一个仅含已声明字段的新配置,不对输入做合并或原地修改。

"use strict";

const { readFile } = require("node:fs/promises");

function validateAppConfig(input) {
  const errors = [];
  const MISSING = Symbol("missing");
  const at = (base, key) => base + "/" + String(key)
    .replaceAll("~", "~0").replaceAll("/", "~1");
  const add = (path, code, message) => errors.push({ path, code, message });

  function object(value, path, allowed) {
    if (value === MISSING) return false;
    if (value === null || typeof value !== "object" || Array.isArray(value)) {
      add(path, "type", "必须是非 null 对象");
      return false;
    }
    const keys = new Set(allowed);
    for (const key of Object.keys(value)) {
      if (!keys.has(key)) add(at(path, key), "unknown", "未知字段,请删除或修正拼写");
    }
    return true;
  }

  function required(value, key, base) {
    if (!Object.hasOwn(value, key)) {
      add(at(base, key), "required", "缺少必填字段");
      return MISSING;
    }
    return value[key];
  }

  function name(value, path, max) {
    if (value === MISSING) return;
    if (typeof value !== "string") {
      add(path, "type", "必须是字符串");
    } else if (value.length < 1 || value.length > max || !/^[a-z]/.test(value) || /[^a-z0-9-]/.test(value)) {
      add(path, "format", `须以小写字母开头,仅含小写字母、数字、连字符,长度 1..${max}`);
    }
  }

  function integer(value, path, min, max) {
    if (value === MISSING) return;
    if (!Number.isSafeInteger(value)) {
      add(path, "integer", "必须是安全整数,不能是字符串或小数");
    } else if (value < min || value > max) {
      add(path, "range", `必须在 ${min}..${max} 范围内`);
    }
  }

  if (!object(input, "", ["appName", "enabled", "port", "limits", "targets", "note"])) {
    return { ok: false, errors };
  }
  const appName = required(input, "appName", "");
  const enabled = required(input, "enabled", "");
  const port = required(input, "port", "");
  const limits = required(input, "limits", "");
  const targets = required(input, "targets", "");
  name(appName, "/appName", 40);
  if (enabled !== MISSING && typeof enabled !== "boolean") {
    add("/enabled", "type", "必须是布尔值 true 或 false");
  }
  integer(port, "/port", 1, 65535);

  let concurrency, timeoutMs;
  if (object(limits, "/limits", ["concurrency", "timeoutMs"])) {
    concurrency = required(limits, "concurrency", "/limits");
    timeoutMs = required(limits, "timeoutMs", "/limits");
    integer(concurrency, "/limits/concurrency", 1, 32);
    integer(timeoutMs, "/limits/timeoutMs", 100, 60000);
  }

  const cleanTargets = [];
  if (targets !== MISSING) {
    if (!Array.isArray(targets)) {
      add("/targets", "type", "必须是数组");
    } else if (targets.length < 1 || targets.length > 8) {
      add("/targets", "length", "数组必须包含 1..8 项");
    } else {
      const seen = new Set();
      for (let i = 0; i < targets.length; i++) {
        const path = at("/targets", i);
        const item = required(targets, i, "/targets");
        if (!object(item, path, ["name", "retries"])) continue;
        const targetName = required(item, "name", path);
        const retries = required(item, "retries", path);
        name(targetName, at(path, "name"), 32);
        integer(retries, at(path, "retries"), 0, 5);
        if (typeof targetName === "string") {
          if (seen.has(targetName)) add(at(path, "name"), "duplicate", "目标名称重复");
          seen.add(targetName);
        }
        cleanTargets.push({ name: targetName, retries });
      }
    }
  }

  const note = Object.hasOwn(input, "note") ? input.note : null;
  if (note !== null) {
    if (typeof note !== "string") {
      add("/note", "type", "必须是 null 或字符串");
    } else if (note.trim() === "" || Array.from(note).length > 80) {
      add("/note", "length", "字符串不能全为空白,且最多 80 个 Unicode 码点");
    }
  }

  if (errors.length) return { ok: false, errors };
  return {
    ok: true,
    value: { appName, enabled, port, limits: { concurrency, timeoutMs }, targets: cleanTargets, note }
  };
}

async function main(args) {
  if (args.length !== 1) {
    console.error("用法: node validate-config.cjs <config.json>");
    return 2;
  }
  let text;
  try {
    text = await readFile(args[0], "utf8");
  } catch (error) {
    console.error(`读取失败 (${error.code || "I/O"})`);
    return 2;
  }
  let parsed;
  try {
    parsed = JSON.parse(text);
  } catch {
    console.error("JSON 语法错误:请检查双引号、逗号与括号");
    return 2;
  }
  const result = validateAppConfig(parsed);
  if (!result.ok) {
    for (const error of result.errors) {
      console.error(`${JSON.stringify(error.path)} [${error.code}] ${error.message}`);
    }
    return 1;
  }
  console.log(JSON.stringify(result.value, null, 2));
  return 0;
}

module.exports = { validateAppConfig, main };
if (require.main === module) {
  main(process.argv.slice(2)).then(
    code => { process.exitCode = code; },
    () => { console.error("内部错误"); process.exitCode = 2; }
  );
}

整数检查先调用 Number.isSafeInteger,再检查业务上下限,不使用 parseInt 或 Number 强行转换。“是整数”和“端口可用范围内”是两件事;布尔值、数值字符串、小数和非有限数都会在第一层被拒绝。安全整数的定义见 ECMAScript Number.isSafeInteger。名称检查也明确排除了尾部换行,不把输入清洗成另一个合法名称。

四、让错误指向可以修改的位置

路径使用 JSON Pointer 风格:根节点为空字符串,数组下标从零开始;例如 /targets/0/retries 指向第一个目标的重试次数。键名中的波浪号先转成 ~0,斜杠再转成 ~1,依据 RFC 6901 的转义规则。这里只生成路径,不实现指针求值器;缺失字段路径表示应补的位置。

在同一目录执行 node validate-config.cjs config.json,成功时标准输出是整理后的 JSON。把 timeoutMs 改成五,会在标准错误看到下列信息。路径再经过 JSON.stringify,可避免键名中的换行把一条诊断拆成多行;错误信息不回显字段值。

"/limits/timeoutMs" [range] 必须在 100..60000 范围内

退出码零表示通过,一表示字段契约失败,二表示参数数量、读取或 JSON 语法错误。命令行读取采用 node:fs/promises 的 readFile,库函数则只负责值校验,便于单测和启动阶段复用。

错误对象把 path、code 和 message 分开:界面可以按路径标记输入项,自动化可以判断稳定的错误码,人则阅读说明。测试优先断言路径和类别,不依赖全部中文措辞。数组长度不合格时只报长度问题,修正数量后再检查各项,这是一项明确的诊断取舍。

五、用真实进程测试输出与退出码

下面保存为 config.test.cjs,再执行 node --test config.test.cjs。每个表格案例都会注册为独立测试;CLI 案例实际启动当前 Node 可执行文件,而不只是调用 main。测试使用 内置 node:test,无需安装依赖。

"use strict";
const test = require("node:test");
const assert = require("node:assert/strict");
const { mkdtempSync, writeFileSync, rmSync } = require("node:fs");
const { tmpdir } = require("node:os");
const { join } = require("node:path");
const { spawnSync } = require("node:child_process");
const { validateAppConfig } = require("./validate-config.cjs");
const sample = require("./config.json");
const fresh = () => structuredClone(sample);
const set = (path, value) => c => {
  let target = c;
  for (const key of path.slice(0, -1)) target = target[key];
  target[path.at(-1)] = value;
};
const bad = [
  ["missing enabled", c => { delete c.enabled; }, "/enabled", "required"],
  ["null enabled", set(["enabled"], null), "/enabled", "type"],
  ["string false", set(["enabled"], "false"), "/enabled", "type"],
  ["numeric boolean", set(["enabled"], 0), "/enabled", "type"],
  ["unknown root key", set(["debug"], true), "/debug", "unknown"],
  ["escaped key", set(["a~/b"], 1), "/a~0~1b", "unknown"],
  ["port string", set(["port"], "8080"), "/port", "integer"],
  ["port fraction", set(["port"], 8080.5), "/port", "integer"],
  ["unsafe integer", set(["port"], 9007199254740992), "/port", "integer"],
  ["infinite number", set(["port"], Infinity), "/port", "integer"],
  ["NaN", set(["port"], NaN), "/port", "integer"],
  ["port zero", set(["port"], 0), "/port", "range"],
  ["port too large", set(["port"], 65536), "/port", "range"],
  ["missing limits", c => { delete c.limits; }, "/limits", "required"],
  ["null limits", set(["limits"], null), "/limits", "type"],
  ["array limits", set(["limits"], []), "/limits", "type"],
  ["unknown nested", set(["limits", "extra"], 1), "/limits/extra", "unknown"],
  ["missing nested", c => { delete c.limits.timeoutMs; }, "/limits/timeoutMs", "required"],
  ["concurrency low", set(["limits", "concurrency"], 0), "/limits/concurrency", "range"],
  ["concurrency high", set(["limits", "concurrency"], 33), "/limits/concurrency", "range"],
  ["timeout low", set(["limits", "timeoutMs"], 99), "/limits/timeoutMs", "range"],
  ["timeout high", set(["limits", "timeoutMs"], 60001), "/limits/timeoutMs", "range"],
  ["targets object", set(["targets"], {}), "/targets", "type"],
  ["targets null", set(["targets"], null), "/targets", "type"],
  ["empty targets", set(["targets"], []), "/targets", "length"],
  ["too many targets", set(["targets"], Array(9).fill(null)), "/targets", "length"],
  ["null target", set(["targets", 0], null), "/targets/0", "type"],
  ["missing name", c => { delete c.targets[0].name; }, "/targets/0/name", "required"],
  ["unknown target key", set(["targets", 0, "weight"], 1), "/targets/0/weight", "unknown"],
  ["negative retries", set(["targets", 0, "retries"], -1), "/targets/0/retries", "range"],
  ["high retries", set(["targets", 0, "retries"], 6), "/targets/0/retries", "range"],
  ["boolean retries", set(["targets", 0, "retries"], false), "/targets/0/retries", "integer"],
  ["duplicate name", c => c.targets.push({ name: "daily", retries: 0 }), "/targets/1/name", "duplicate"],
  ["empty app name", set(["appName"], ""), "/appName", "format"],
  ["uppercase app", set(["appName"], "Worker"), "/appName", "format"],
  ["trailing newline name", set(["appName"], "worker\n"), "/appName", "format"],
  ["trailing carriage return", set(["appName"], "worker\r"), "/appName", "format"],
  ["leading hyphen", set(["appName"], "-worker"), "/appName", "format"],
  ["long app", set(["appName"], "a".repeat(41)), "/appName", "format"],
  ["null app", set(["appName"], null), "/appName", "type"],
  ["long target name", set(["targets", 0, "name"], "a".repeat(33)), "/targets/0/name", "format"],
  ["numeric note", set(["note"], 0), "/note", "type"],
  ["blank note", set(["note"], " \t"), "/note", "length"],
  ["long note", set(["note"], "字".repeat(81)), "/note", "length"]
];
for (const [label, mutate, path, code] of bad) {
  test(label, () => {
    const c = fresh(); mutate(c);
    const r = validateAppConfig(c);
    assert.equal(r.ok, false);
    assert.ok(r.errors.some(e => e.path === path && e.code === code));
  });
}
for (const value of [null, [], "hello", 1, true]) {
  test(`non-object root ${JSON.stringify(value)}`, () => {
    const r = validateAppConfig(value);
    assert.deepEqual(r.errors.map(e => [e.path, e.code]), [["", "type"]]);
  });
}
test("valid false, explicit null and detached copy", () => {
  const c = fresh(); const before = structuredClone(c);
  const r = validateAppConfig(c);
  assert.equal(r.ok, true); assert.deepEqual(r.value, c);
  assert.deepEqual(c, before); assert.notEqual(r.value, c);
  assert.notEqual(r.value.limits, c.limits);
  assert.notEqual(r.value.targets[0], c.targets[0]);
});
test("missing optional note defaults to null", () => {
  const c = fresh(); delete c.note;
  assert.equal(validateAppConfig(c).value.note, null);
});
test("valid lower bounds", () => {
  const c = fresh(); c.port = 1;
  c.limits = { concurrency: 1, timeoutMs: 100 }; c.targets[0].retries = 0;
  assert.equal(validateAppConfig(c).ok, true);
});
test("valid upper bounds", () => {
  const c = fresh(); c.port = 65535; c.appName = "a".repeat(40); c.enabled = true;
  c.limits = { concurrency: 32, timeoutMs: 60000 }; c.note = "😀".repeat(80);
  c.targets = Array.from({ length: 8 }, (_, i) => ({ name: `target-${i}`, retries: 5 }));
  assert.equal(validateAppConfig(c).ok, true);
});
test("inherited required key is missing", () => {
  const c = fresh(); delete c.enabled;
  Object.setPrototypeOf(c, { enabled: true });
  assert.ok(validateAppConfig(c).errors.some(e => e.path === "/enabled" && e.code === "required"));
});
test("inherited optional key is ignored", () => {
  const c = fresh(); delete c.note; Object.setPrototypeOf(c, { note: "inherited", extra: 1 });
  assert.equal(validateAppConfig(c).value.note, null);
});
test("inherited nested key is missing", () => {
  const c = fresh(); delete c.limits.concurrency;
  Object.setPrototypeOf(c.limits, { concurrency: 4 });
  assert.ok(validateAppConfig(c).errors.some(e => e.path === "/limits/concurrency" && e.code === "required"));
});
test("__proto__ from JSON is rejected, not merged", () => {
  const c = JSON.parse(JSON.stringify(sample).replace("{", '{"__proto__":{"polluted":true},'));
  assert.ok(validateAppConfig(c).errors.some(e => e.path === "/__proto__" && e.code === "unknown"));
  assert.equal(Object.prototype.polluted, undefined);
});
test("null-prototype object is supported", () => {
  const c = Object.assign(Object.create(null), fresh());
  assert.equal(validateAppConfig(c).ok, true);
});
test("multiple independent errors are collected", () => {
  const c = fresh(); c.enabled = "false"; c.port = 0; c.targets[0].retries = 6;
  assert.deepEqual(validateAppConfig(c).errors.map(e => e.path), ["/enabled", "/port", "/targets/0/retries"]);
});
test("sparse array does not silently skip a target", () => {
  const c = fresh(); c.targets = Array(1);
  assert.ok(validateAppConfig(c).errors.some(e => e.path === "/targets/0" && e.code === "required"));
});
test("native parse replaces duplicate object keys", () => {
  const text = JSON.stringify(sample).replace('"port":8080', '"port":0,"port":8080');
  assert.equal(validateAppConfig(JSON.parse(text)).value.port, 8080);
});
test("native parse accepts exponent form", () => {
  const text = JSON.stringify(sample).replace('"port":8080', '"port":1e3');
  assert.equal(validateAppConfig(JSON.parse(text)).value.port, 1000);
});
test("native parse may round fractional tokens before validation", () => {
  const text = JSON.stringify(sample).replace('"port":8080', '"port":1.00000000000000001');
  assert.equal(validateAppConfig(JSON.parse(text)).value.port, 1);
});
function cli(t, text, extra = []) {
  const dir = mkdtempSync(join(tmpdir(), "node-config-test-"));
  t.after(() => rmSync(dir, { recursive: true, force: true }));
  const file = join(dir, "config.json");
  if (text !== null) writeFileSync(file, text);
  const r = spawnSync(process.execPath, [join(__dirname, "validate-config.cjs"), file, ...extra], { encoding: "utf8" });
  assert.equal(r.error, undefined); return r;
}
test("CLI valid config: code 0 and JSON stdout", t => {
  const r = cli(t, JSON.stringify(sample));
  assert.equal(r.status, 0); assert.equal(r.stderr, ""); assert.deepEqual(JSON.parse(r.stdout), sample);
});
test("CLI invalid field: code 1 and actionable path", t => {
  const c = fresh(); c.limits.timeoutMs = 5; const r = cli(t, JSON.stringify(c));
  assert.equal(r.status, 1); assert.equal(r.stdout, ""); assert.match(r.stderr, /"\/limits\/timeoutMs" \[range\]/);
});
test("CLI syntax error: code 2", t => {
  const r = cli(t, '{"port":}'); assert.equal(r.status, 2); assert.match(r.stderr, /JSON 语法错误/);
});
test("CLI missing file: code 2", t => {
  const r = cli(t, null); assert.equal(r.status, 2); assert.match(r.stderr, /ENOENT/);
});
test("CLI extra argument: code 2", t => {
  const r = cli(t, "{}", ["extra"]); assert.equal(r.status, 2); assert.match(r.stderr, /用法/);
});
test("CLI missing argument: code 2", () => {
  const r = spawnSync(process.execPath, [join(__dirname, "validate-config.cjs")], { encoding: "utf8" });
  assert.equal(r.status, 2); assert.match(r.stderr, /用法/);
});
test("CLI huge exponent is not a safe integer", t => {
  const text = JSON.stringify(sample).replace('"port":8080', '"port":1e400');
  const r = cli(t, text); assert.equal(r.status, 1); assert.match(r.stderr, /"\/port" \[integer\]/);
});
test("CLI escapes newline inside unknown key", t => {
  const c = fresh(); c["line\nbreak"] = 1;
  const r = cli(t, JSON.stringify(c)); assert.equal(r.status, 1);
  assert.equal(r.stderr.trim().split("\n").length, 1); assert.ok(r.stderr.includes('"/line\\nbreak"'));
});

本次在 Node.js v24.19.0 实际运行七十一项测试,全部通过,其中八项检查 CLI。覆盖缺失与 null、继承字段、嵌套未知键、整数上下界、数组数量、重复名称、路径转义和输出分流;还验证返回对象不复用输入中的嵌套对象。

维护时,先给新增规则补一个会失败的用例,再改实现;上下限至少各测边界本身和相邻越界值。若未来引入“启用某功能才需要某字段”之类条件约束,应单独补交叉字段检查,并写出组合用例,而不是依靠单个字段通过来推断整体可用。

六、严格的边界也要写清楚

这里严格的是“解析后的固定应用契约”,不是完整 JSON Schema 实现。原生 JSON.parse 遇到重复对象键时保留后值,校验器看不到被覆盖的前值;数组中重复的目标名称是另一回事,代码会检查它。此行为可核对 ECMAScript JSON.parse 规范。

数字也已经转换成 JavaScript Number:1e3 会成为一千,极接近整数的小数可能先被舍入。安全整数检查不能还原原始数字文本。若要求拒绝重复对象键或严格限制数字写法,就需要能保留相应解析信息的另一层处理,不能声称本文代码已经覆盖。

此外,readFile 会读取完整文件,JSON.parse 也先于字段检查执行;八项数组限制不是解析阶段的内存保护。本文不防超大输入、深层嵌套或资源耗尽,不应直接充当公开上传接口的安全边界。对于可控的小型启动配置,把字段契约、错误路径和回归测试放在一起,才是这段标准库实现的价值。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。