AI 代码审查实战:把表单百分号解码写成有界字节状态机

10-19 5阅读

让 AI 写一个表单解析器,最容易得到的答案是:把网络分块转成字符串,再调用 decodeURIComponent,最后按分隔符切开。正常的英文键值对很快就能通过演示;一旦百分号转义、中文 UTF-8 字节和传输分块交错,几个看起来合理的步骤便开始互相破坏。真正值得审查的不是函数名,而是每一层究竟接收字节还是文本,以及哪一层拥有边界。

本文实现的是一个严格 UTF-8 表单字节流方言,格式借鉴 application/x-www-form-urlencoded。它不是完整 URL 解析器,也不是 WHATWG 宽容解析算法的可直接替代品。输入是表单正文的 Uint8Array 分块,Node.js Buffer 同样可以传入;它不处理 HTTP 头、压缩、字符集协商或请求取消,也不自动删除开头的问号。已有完整字符串且需要浏览器兼容行为时,应优先使用标准 API。

AI 代码审查实战:把表单百分号解码写成有界字节状态机
AI 生成的概念插图:分块、转义状态与字段边界各司其职。珠子数量和路径是视觉隐喻,不是协议时序图。

九个例子都可以分别保存为 standalone.mjs,再执行 node --unhandled-rejections=strict standalone.mjs。示例在 Node.js v24.19.0 上逐个运行,输出紧随代码。为保证复制后独立运行,第五至第九例有意重复完整核心实现;实际工程应把经过审查的实现放到一个模块中,再分别组织测试。下面讨论的是输入契约与可证伪的行为,不能把通过这些测试等同于生产安全认证。

一、先约定宽容与严格的分界

WHATWG 表单解析算法先按原始字节中的与号分段,忽略空段,使用第一个等号区分名称和值,然后处理加号、百分号及 UTF-8。它的百分号解码规则遇到不合法转义时会保留百分号,而不是一律抛错;UTF-8 错误也采用替换行为。因此,拒绝坏转义和坏 UTF-8 是本文主动选择的接口契约,不能冒充标准要求。

第一例让差异直接出现:单独的百分号保留下来,非法字节变成替换字符,原始加号变为空格,而百分号编码的加号仍是加号。另一方面,ECMAScript 的 decodeURIComponent针对 URI 组件,并不替你完成表单的加号规则,遇到这些不完整或非法转义会抛出 URIError。拿两者交替调用而不声明语义,会把偶然通过的测试误当作兼容性。

示例 1:

const input = "x=%&y=%FF&z=a+b&p=%2B";
console.log(JSON.stringify([...new URLSearchParams(input)]));
console.log(decodeURIComponent("a+b"));
for (const value of ["%", "%FF", "%E4%B8"]) {
  try { console.log(decodeURIComponent(value)); }
  catch (error) { console.log(error.name); }
}

运行输出:

[["x","%"],["y","�"],["z","a b"],["p","+"]]
a+b
URIError
URIError
URIError

二、原始分隔符只能识别一次

第二例暂时使用完整、已知合法的文本,单独验证切分顺序。名称中编码后的与号属于名称,值中编码后的等号属于值;只有原始第一个等号负责分界。先解码整个正文,会把本来属于数据的与号升级为结构,凭空制造字段。这不是靠换一个正则表达式就能补救的问题,而是处理层次已经颠倒。

本例的小函数只演示已知合法字符串的结构,既没有字节流接口,也没有资源上限。输出保留了重复 tag 的顺序、空名称、无等号字段以及值中的第二个等号。请特别注意最后一个值:原始加号先变为空格,转义加号保持字面意义,百分号编码只解一层。把结果再送进一次解码器,会让原本的字面量变成新语法,调用方应避免二次解码。

示例 2:

function parseKnownValid(text) {
  const decode = s => decodeURIComponent(s.replace(/\+/g, " "));
  return text.split("&").filter(Boolean).map(field => {
    const at = field.indexOf("=");
    const name = at < 0 ? field : field.slice(0, at);
    const value = at < 0 ? "" : field.slice(at + 1);
    return [decode(name), decode(value)];
  });
}
const input = "a%26b=x%3Dy&tag=one&tag=two&&=empty&flag&x=a=b&p=%2B+%2526";
console.log(JSON.stringify(parseKnownValid(input)));
console.log("wrong fields=" + decodeURIComponent("k=a%26b").split("&").length);
console.log("right fields=" + parseKnownValid("k=a%26b").length);

运行输出:

[["a&b","x=y"],["tag","one"],["tag","two"],["","empty"],["flag",""],["x","a=b"],["p","+ %26"]]
wrong fields=2
right fields=1

三、百分号三元组需要三个持久状态

第三例把问题缩小为一个字段组件的百分号字节变换。状态零表示等待普通字节,状态一表示已经读到百分号,状态二表示已经得到第一个十六进制数字。传输分块结束只意味着这次没有更多输入,不能把状态清空,也不能立即把残缺转义判成错误。真正的流结束才有资格判定剩余状态是否完整。

十六进制验证覆盖数字和大小写字母,不能用宽松的数值转换吞掉部分坏输入。得到完整转义后,只把合成出的一个字节写入输出,不重新解释它;因此编码后的加号不会再次变为空格,编码后的百分号也不会启动第二轮转义。此处尚未识别字段分隔符,也没有内存限制和终止状态,作用是展示跨块状态;完整接口会在第五例补齐这些约束。

示例 3:

function percentBytes(chunks) {
  let state = 0, high = 0;
  const result = [];
  const hex = b => b >= 48 && b <= 57 ? b - 48
    : b >= 65 && b <= 70 ? b - 55
    : b >= 97 && b <= 102 ? b - 87 : -1;
  for (const chunk of chunks) {
    for (const b of chunk) {
      if (state !== 0) {
        const d = hex(b);
        if (d < 0) throw new Error("invalid percent");
        if (state === 1) { high = d; state = 2; }
        else { result.push(high * 16 + d); state = 0; }
      } else if (b === 37) {
        state = 1;
      } else {
        result.push(b === 43 ? 32 : b);
      }
    }
  }
  if (state !== 0) throw new Error("unfinished percent");
  return Uint8Array.from(result);
}
const chunks = ["A%", "4", "1+%2", "B%2526"].map(s => Buffer.from(s));
console.log(new TextDecoder().decode(percentBytes(chunks)));
try { percentBytes([Buffer.from("%"), Buffer.from("2")]); }
catch (error) { console.log(error.message); }

运行输出:

AA +%26
unfinished percent

四、UTF-8 可以跨传输块,不能跨字段借字节

百分号层输出的是字节,不是字符。一个汉字可能由三组转义构成,也可能直接以原始 UTF-8 字节到达,甚至两种表示混合。正确的审查问题是:同一个字段组件收集到的字节,最终是否组成完整 UTF-8?第四例刻意把一个合法汉字拆成两份,合起来合法不代表每一份都可以独立成为字段名称或值。

Node.js 的 TextDecoder 文档说明了 fatal 的抛错行为、stream 的残留字节缓存以及 ignoreBOM 的含义。本文为每个名称和值创建独立解码器,使用 fatal: true,并在组件完整后一次解码。ignoreBOM: true 在这里表示保留开头的 BOM 字符。不要被属性名字误导,以为 true 会删除它。示例还验证了过长编码、代理项编码及超出 Unicode 范围的字节序列均被拒绝。

这并不否定流式 TextDecoder。若要更早输出长字段的文本,它同样可用,但必须在名称结束、值结束时分别刷新并重建状态。本文选择有界字段缓冲,换取更直观的错误边界;字段大小按解码后的字节数计算,不按 JavaScript 字符串长度计算。四字节表情符号在字符串里占两个 UTF-16 码元,不能混用这些单位。

示例 4:

const strict = bytes => new TextDecoder("utf-8", {
  fatal: true, ignoreBOM: true
}).decode(Uint8Array.from(bytes));
console.log("combined=" + strict([0xe4, 0xb8, 0xad]));
const failures = [[0xe4], [0xb8, 0xad]].map(bytes => {
  try { return strict(bytes); } catch (error) { return error.name; }
});
console.log("fields=" + failures.join(","));
console.log("bom=" + (strict([0xef, 0xbb, 0xbf, 65]).codePointAt(0) === 0xfeff));
const emoji = "😀";
console.log("emoji=" + Buffer.byteLength(emoji) + "/" + emoji.length);
for (const bytes of [[0xc0, 0xaf], [0xed, 0xa0, 0x80], [0xf4, 0x90, 0x80, 0x80]]) {
  try { strict(bytes); } catch (error) { console.log(error.name); }
}

运行输出:

combined=中
fields=TypeError,TypeError
bom=true
emoji=4/2
TypeError
TypeError
TypeError

五、组合成可独立使用的严格字节流解析器

完整实现只暴露 write 和 finish。write 同步消费字节,不保留调用方的输入视图;finish 声明输入结束,验证最后一个字段,返回按到达顺序排列的二元组数组。普通空分段被跳过,单独一个等号仍是有效的空名称、空值字段;没有等号的非空段得到空值。原始分隔符优先触发边界检查,所以残缺百分号不能跨越名称与值,或跨越两个字段继续拼接。

状态里的 seen 表示当前原始段是否非空,inValue 表示是否已经消费第一个原始等号,state 与 high 只负责百分号三元组。三组职责分开后,不必猜测字段内容是否包含特殊字符。每个原始字节先经过总量限制,再处理结构;新字段在第一个非分隔字节出现时检查字段数量。百分号解码得到的字节只进入当前缓冲,不会回流到结构识别器。

这里的流式是输入和百分号转换增量进行,不代表整份结果零缓存:已经验证的字段会留在内部,直到 finish 成功才交付。这让后半段损坏时不会泄露一个看似完整的部分结果。它适用于大小明确受限的表单;若业务要求逐字段触发外部副作用,就必须另行定义事务或补偿语义,不能简单增加一个回调便宣称等价。

示例 5:

function createFormDecoder(options = {}) {
  const limits = {
    maxBytes: 65536, maxFields: 128,
    maxNameBytes: 1024, maxValueBytes: 8192
  };
  for (const key of Object.keys(options)) {
    if (!Object.hasOwn(limits, key)) throw new TypeError(`unknown ${key}`);
    limits[key] = options[key];
  }
  for (const [key, n] of Object.entries(limits)) {
    if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(`invalid ${key}`);
  }
  let total = 0, count = 0, state = 0, high = 0, percentAt = 0;
  let inValue = false, seen = false, closed = false, failure = null;
  let name = [], value = [], pairs = [];
  const hex = b => b >= 48 && b <= 57 ? b - 48
    : b >= 65 && b <= 70 ? b - 55
    : b >= 97 && b <= 102 ? b - 87 : -1;
  function guard() {
    if (failure) throw failure;
    if (closed) throw new Error("E_CLOSED");
  }
  function fail(code, offset) {
    failure = Object.assign(new Error(`${code}@${offset}`), { code, offset });
    name = []; value = []; pairs = [];
    throw failure;
  }
  function emit(byte, at) {
    const target = inValue ? value : name;
    const max = inValue ? limits.maxValueBytes : limits.maxNameBytes;
    if (target.length >= max) fail(inValue ? "E_VALUE_LIMIT" : "E_NAME_LIMIT", at);
    target.push(byte);
  }
  function text(bytes, code, at) {
    try {
      return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true })
        .decode(Uint8Array.from(bytes));
    } catch (error) {
      if (!(error instanceof TypeError)) throw error;
      fail(code, at);
    }
  }
  function endPair(at) {
    if (state !== 0) fail("E_PERCENT", percentAt);
    if (!seen) return;
    const key = text(name, "E_NAME_UTF8", at);
    const val = text(value, "E_VALUE_UTF8", at);
    pairs.push([key, val]);
    count++;
    name = []; value = []; inValue = false; seen = false;
  }
  return {
    write(chunk) {
      guard();
      if (!(chunk instanceof Uint8Array)) throw new TypeError("expected Uint8Array");
      for (const byte of chunk) {
        const at = total;
        if (total >= limits.maxBytes) fail("E_TOTAL", at);
        total++;
        if (byte === 38) { endPair(at); continue; }
        if (!seen) {
          if (count >= limits.maxFields) fail("E_FIELDS", at);
          seen = true;
        }
        if (byte === 61 && !inValue) {
          if (state !== 0) fail("E_PERCENT", percentAt);
          inValue = true;
          continue;
        }
        if (state !== 0) {
          const digit = hex(byte);
          if (digit < 0) fail("E_PERCENT", percentAt);
          if (state === 1) { high = digit; state = 2; }
          else { emit(high * 16 + digit, at); state = 0; }
        } else if (byte === 37) {
          state = 1; percentAt = at;
        } else {
          emit(byte === 43 ? 32 : byte, at);
        }
      }
    },
    finish() {
      guard();
      endPair(total);
      closed = true;
      return pairs;
    }
  };
}

const parser = createFormDecoder();
for (const chunk of ["q=%E4%B", "8%AD+%2B&tag=a", "&tag=b&literal=%2526"]) {
  parser.write(Buffer.from(chunk));
}
console.log(JSON.stringify(parser.finish()));

运行输出:

[["q","中 +"],["tag","a"],["tag","b"],["literal","%26"]]

六、重复键和原始 Unicode 都要保持身份

第六例把输入拆成一个字节一个分块,直接覆盖原始中文被拆开的情况。缓存的是字节,因此不会在 UTF-8 中途插入替换字符。重复名称不被覆盖,也不自动拼成逗号字符串;它们在数组里保持位置。应用层若只允许一个用户名或金额,应在解析成功后明确拒绝重复值,而不是让某个对象转换步骤悄悄选择第一项或最后一项。

使用普通对象充当解析结果,还可能让特殊属性名参与对象语义。本实现只输出二元组,名为 __proto__ 的键因此只是数据;不过这并不能保证调用方之后的不安全合并操作也安全。空名称、无等号字段和 BOM 同样没有被隐式清洗。若业务希望禁止控制字符、规范化 Unicode 或限制名称集合,那属于下一层规则,应该显式验证并写入测试,而不是塞进百分号解码状态中。

示例 6:

function createFormDecoder(options = {}) {
  const limits = {
    maxBytes: 65536, maxFields: 128,
    maxNameBytes: 1024, maxValueBytes: 8192
  };
  for (const key of Object.keys(options)) {
    if (!Object.hasOwn(limits, key)) throw new TypeError(`unknown ${key}`);
    limits[key] = options[key];
  }
  for (const [key, n] of Object.entries(limits)) {
    if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(`invalid ${key}`);
  }
  let total = 0, count = 0, state = 0, high = 0, percentAt = 0;
  let inValue = false, seen = false, closed = false, failure = null;
  let name = [], value = [], pairs = [];
  const hex = b => b >= 48 && b <= 57 ? b - 48
    : b >= 65 && b <= 70 ? b - 55
    : b >= 97 && b <= 102 ? b - 87 : -1;
  function guard() {
    if (failure) throw failure;
    if (closed) throw new Error("E_CLOSED");
  }
  function fail(code, offset) {
    failure = Object.assign(new Error(`${code}@${offset}`), { code, offset });
    name = []; value = []; pairs = [];
    throw failure;
  }
  function emit(byte, at) {
    const target = inValue ? value : name;
    const max = inValue ? limits.maxValueBytes : limits.maxNameBytes;
    if (target.length >= max) fail(inValue ? "E_VALUE_LIMIT" : "E_NAME_LIMIT", at);
    target.push(byte);
  }
  function text(bytes, code, at) {
    try {
      return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true })
        .decode(Uint8Array.from(bytes));
    } catch (error) {
      if (!(error instanceof TypeError)) throw error;
      fail(code, at);
    }
  }
  function endPair(at) {
    if (state !== 0) fail("E_PERCENT", percentAt);
    if (!seen) return;
    const key = text(name, "E_NAME_UTF8", at);
    const val = text(value, "E_VALUE_UTF8", at);
    pairs.push([key, val]);
    count++;
    name = []; value = []; inValue = false; seen = false;
  }
  return {
    write(chunk) {
      guard();
      if (!(chunk instanceof Uint8Array)) throw new TypeError("expected Uint8Array");
      for (const byte of chunk) {
        const at = total;
        if (total >= limits.maxBytes) fail("E_TOTAL", at);
        total++;
        if (byte === 38) { endPair(at); continue; }
        if (!seen) {
          if (count >= limits.maxFields) fail("E_FIELDS", at);
          seen = true;
        }
        if (byte === 61 && !inValue) {
          if (state !== 0) fail("E_PERCENT", percentAt);
          inValue = true;
          continue;
        }
        if (state !== 0) {
          const digit = hex(byte);
          if (digit < 0) fail("E_PERCENT", percentAt);
          if (state === 1) { high = digit; state = 2; }
          else { emit(high * 16 + digit, at); state = 0; }
        } else if (byte === 37) {
          state = 1; percentAt = at;
        } else {
          emit(byte === 43 ? 32 : byte, at);
        }
      }
    },
    finish() {
      guard();
      endPair(total);
      closed = true;
      return pairs;
    }
  };
}

const parser = createFormDecoder();
const body = Buffer.from("&&=v&flag&x=a=b&x=%2B+%26&__proto__=safe&bom=%EF%BB%BF&raw=中&");
for (const byte of body) parser.write(Uint8Array.of(byte));
const pairs = parser.finish();
console.log(JSON.stringify(pairs.filter(([key]) => key !== "bom")));
console.log("bom=" + pairs.find(([key]) => key === "bom")[1].codePointAt(0));
console.log("x=" + JSON.stringify(pairs.filter(([key]) => key === "x").map(([, val]) => val)));

运行输出:

[["","v"],["flag",""],["x","a=b"],["x","+ &"],["__proto__","safe"],["raw","中"]]
bom=65279
x=["a=b","+ &"]

七、四种上限衡量四件不同的事

总输入上限计算原始字节,包括所有与号、等号和百分号文本。名称与值的上限计算百分号转换完成后的字节,所以一组转义占三个输入字节,却只消耗一个组件字节额度。字段数量只计算非空原始段,连续与号不会增加字段数,但仍消耗总输入额度。第七例同时展示零上限和刚好等于上限,防止比较符号写反。

这些限制服务于不同故障模式:很多小字段会压垮结果结构,一个长名称可能干扰后续索引,一个长值可能造成不必要的分配,而许多空分段仍会消耗解析时间。只设置其中一个限制,很难把这些成本讲清楚。配置必须是非负安全整数,未知配置名称也会被拒绝,以免拼写错误静默关闭保护。默认值只是教程预算,接入业务前需要结合允许的字段与请求大小重新选择。

需要诚实描述内存承诺:JavaScript 数组元素、字符串和对象都有额外开销,maxBytes 不是进程堆内存的精确字节上限。实现不积累整份原始正文,但会积累有界结果和当前组件,且解码时产生临时副本。它避免了反复拼接整份前缀的写法;实际部署仍应限制请求并发,并让外层传输在解析失败后停止继续供给数据。

示例 7:

function createFormDecoder(options = {}) {
  const limits = {
    maxBytes: 65536, maxFields: 128,
    maxNameBytes: 1024, maxValueBytes: 8192
  };
  for (const key of Object.keys(options)) {
    if (!Object.hasOwn(limits, key)) throw new TypeError(`unknown ${key}`);
    limits[key] = options[key];
  }
  for (const [key, n] of Object.entries(limits)) {
    if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(`invalid ${key}`);
  }
  let total = 0, count = 0, state = 0, high = 0, percentAt = 0;
  let inValue = false, seen = false, closed = false, failure = null;
  let name = [], value = [], pairs = [];
  const hex = b => b >= 48 && b <= 57 ? b - 48
    : b >= 65 && b <= 70 ? b - 55
    : b >= 97 && b <= 102 ? b - 87 : -1;
  function guard() {
    if (failure) throw failure;
    if (closed) throw new Error("E_CLOSED");
  }
  function fail(code, offset) {
    failure = Object.assign(new Error(`${code}@${offset}`), { code, offset });
    name = []; value = []; pairs = [];
    throw failure;
  }
  function emit(byte, at) {
    const target = inValue ? value : name;
    const max = inValue ? limits.maxValueBytes : limits.maxNameBytes;
    if (target.length >= max) fail(inValue ? "E_VALUE_LIMIT" : "E_NAME_LIMIT", at);
    target.push(byte);
  }
  function text(bytes, code, at) {
    try {
      return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true })
        .decode(Uint8Array.from(bytes));
    } catch (error) {
      if (!(error instanceof TypeError)) throw error;
      fail(code, at);
    }
  }
  function endPair(at) {
    if (state !== 0) fail("E_PERCENT", percentAt);
    if (!seen) return;
    const key = text(name, "E_NAME_UTF8", at);
    const val = text(value, "E_VALUE_UTF8", at);
    pairs.push([key, val]);
    count++;
    name = []; value = []; inValue = false; seen = false;
  }
  return {
    write(chunk) {
      guard();
      if (!(chunk instanceof Uint8Array)) throw new TypeError("expected Uint8Array");
      for (const byte of chunk) {
        const at = total;
        if (total >= limits.maxBytes) fail("E_TOTAL", at);
        total++;
        if (byte === 38) { endPair(at); continue; }
        if (!seen) {
          if (count >= limits.maxFields) fail("E_FIELDS", at);
          seen = true;
        }
        if (byte === 61 && !inValue) {
          if (state !== 0) fail("E_PERCENT", percentAt);
          inValue = true;
          continue;
        }
        if (state !== 0) {
          const digit = hex(byte);
          if (digit < 0) fail("E_PERCENT", percentAt);
          if (state === 1) { high = digit; state = 2; }
          else { emit(high * 16 + digit, at); state = 0; }
        } else if (byte === 37) {
          state = 1; percentAt = at;
        } else {
          emit(byte === 43 ? 32 : byte, at);
        }
      }
    },
    finish() {
      guard();
      endPair(total);
      closed = true;
      return pairs;
    }
  };
}

const cases = [
  ["bytes", "a=12", { maxBytes: 3 }],
  ["fields", "a=1&b=2", { maxFields: 1 }],
  ["name", "ab=1", { maxNameBytes: 1 }],
  ["value", "x=%E4%B8%AD", { maxValueBytes: 2 }],
  ["empty", "&&", { maxFields: 0 }],
  ["zero", "=", { maxNameBytes: 0, maxValueBytes: 0 }],
  ["exact", "x=%41", { maxBytes: 5, maxValueBytes: 1 }]
];
for (const [label, body, limits] of cases) {
  const parser = createFormDecoder(limits);
  try {
    parser.write(Buffer.from(body));
    console.log(label + ": " + JSON.stringify(parser.finish()));
  } catch (error) { console.log(label + ": " + error.message); }
}
for (const limits of [{ maxBytes: -1 }, { maxFields: Infinity }, { maxBytes: 1.5 }]) {
  try { createFormDecoder(limits); }
  catch (error) { console.log(error.name); }
}

运行输出:

bytes: E_TOTAL@3
fields: E_FIELDS@4
name: E_NAME_LIMIT@1
value: E_VALUE_LIMIT@10
empty: []
zero: [["",""]]
exact: [["x","A"]]
RangeError
RangeError
RangeError

八、错误位置、终止与重试必须有确定语义

所有输入偏移从零开始,基于原始字节位置。坏百分号报告转义开头;组件超限报告造成额外输出字节的那个输入位置,可能是转义的最后一位;总量超限报告第一个超预算字节;字段超限报告额外字段的起始位置。UTF-8 错误在字段结束时发现,因此报告与号的位置,或 EOF 的总长度,不是非法 UTF-8 序列的精确起点。这个区别应写进接口说明。

解析错误和预算错误会锁存同一个异常对象,并清空内部缓存。之后无论再次 write 还是 finish,都抛出原来的错误,不能用追加字节把损坏的输入修好。一次 write 中即使已经处理若干合法字段,也不会返回这些字段。第八例通过对象身份检查证明这种终止语义,而不只比较错误字符串。

调用方用字符串代替 Uint8Array 属于使用错误;检查发生在消费字节之前,所以抛出 TypeError 后仍可传入正确类型继续使用。成功 finish 后则彻底关闭,再次调用会得到 E_CLOSED。只有真正收到输入 EOF 才调用 finish;暂时没有新分块不是 EOF。若一个字节同时触发多项问题,代码的检查顺序决定首个错误,例如总量限制先于该字节的语法解释,这也是稳定契约的一部分。

示例 8:

function createFormDecoder(options = {}) {
  const limits = {
    maxBytes: 65536, maxFields: 128,
    maxNameBytes: 1024, maxValueBytes: 8192
  };
  for (const key of Object.keys(options)) {
    if (!Object.hasOwn(limits, key)) throw new TypeError(`unknown ${key}`);
    limits[key] = options[key];
  }
  for (const [key, n] of Object.entries(limits)) {
    if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(`invalid ${key}`);
  }
  let total = 0, count = 0, state = 0, high = 0, percentAt = 0;
  let inValue = false, seen = false, closed = false, failure = null;
  let name = [], value = [], pairs = [];
  const hex = b => b >= 48 && b <= 57 ? b - 48
    : b >= 65 && b <= 70 ? b - 55
    : b >= 97 && b <= 102 ? b - 87 : -1;
  function guard() {
    if (failure) throw failure;
    if (closed) throw new Error("E_CLOSED");
  }
  function fail(code, offset) {
    failure = Object.assign(new Error(`${code}@${offset}`), { code, offset });
    name = []; value = []; pairs = [];
    throw failure;
  }
  function emit(byte, at) {
    const target = inValue ? value : name;
    const max = inValue ? limits.maxValueBytes : limits.maxNameBytes;
    if (target.length >= max) fail(inValue ? "E_VALUE_LIMIT" : "E_NAME_LIMIT", at);
    target.push(byte);
  }
  function text(bytes, code, at) {
    try {
      return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true })
        .decode(Uint8Array.from(bytes));
    } catch (error) {
      if (!(error instanceof TypeError)) throw error;
      fail(code, at);
    }
  }
  function endPair(at) {
    if (state !== 0) fail("E_PERCENT", percentAt);
    if (!seen) return;
    const key = text(name, "E_NAME_UTF8", at);
    const val = text(value, "E_VALUE_UTF8", at);
    pairs.push([key, val]);
    count++;
    name = []; value = []; inValue = false; seen = false;
  }
  return {
    write(chunk) {
      guard();
      if (!(chunk instanceof Uint8Array)) throw new TypeError("expected Uint8Array");
      for (const byte of chunk) {
        const at = total;
        if (total >= limits.maxBytes) fail("E_TOTAL", at);
        total++;
        if (byte === 38) { endPair(at); continue; }
        if (!seen) {
          if (count >= limits.maxFields) fail("E_FIELDS", at);
          seen = true;
        }
        if (byte === 61 && !inValue) {
          if (state !== 0) fail("E_PERCENT", percentAt);
          inValue = true;
          continue;
        }
        if (state !== 0) {
          const digit = hex(byte);
          if (digit < 0) fail("E_PERCENT", percentAt);
          if (state === 1) { high = digit; state = 2; }
          else { emit(high * 16 + digit, at); state = 0; }
        } else if (byte === 37) {
          state = 1; percentAt = at;
        } else {
          emit(byte === 43 ? 32 : byte, at);
        }
      }
    },
    finish() {
      guard();
      endPair(total);
      closed = true;
      return pairs;
    }
  };
}

for (const body of ["x=%GG", "x=%", "x=%2&y=1", "x=%FF", "%FF=v", "x=%E4&y=%B8%AD"]) {
  const parser = createFormDecoder();
  try { parser.write(Buffer.from(body)); parser.finish(); }
  catch (error) { console.log(body + " -> " + error.message); }
}
const broken = createFormDecoder();
let first;
try { broken.write(Buffer.from("good=yes&bad=%GG")); }
catch (error) { first = error; }
for (const action of [() => broken.finish(), () => broken.write(Buffer.from("x=1"))]) {
  try { action(); } catch (error) { console.log("same error=" + (error === first)); }
}
const usable = createFormDecoder();
try { usable.write("a=1"); } catch (error) { console.log(error.name); }
usable.write(Buffer.from("a=1"));
console.log(JSON.stringify(usable.finish()));
try { usable.finish(); } catch (error) { console.log(error.message); }

运行输出:

x=%GG -> E_PERCENT@2
x=% -> E_PERCENT@2
x=%2&y=1 -> E_PERCENT@2
x=%FF -> E_VALUE_UTF8@5
%FF=v -> E_NAME_UTF8@5
x=%E4&y=%B8%AD -> E_VALUE_UTF8@5
same error=true
same error=true
TypeError
[["a","1"]]
E_CLOSED

九、让分块方式成为可枚举的测试维度

最后一例不再挑几个看起来有代表性的分块,而是在每份输入上枚举两个切点,形成三块输入,允许空块与重合切点,并额外测试逐字节输入。同一份合法正文无论怎样分块,都必须得到同样的字段数组;同一份非法正文也必须保持相同错误类型与原始偏移。这个性质把传输层偶然性从解析结果中剥离出来,比只测试一个正常网络包更有价值。

参考实现刻意采用不同路径:先在完整字节序列上寻找结构边界,再把原始非转义字节转换成百分号表示,交给 decodeURIComponent 验证组件。这样既能覆盖原始 UTF-8 与转义 UTF-8 混合,也没有复用被测三态机。合法样本包括小写十六进制、二次转义字面量、BOM、空字段以及问号和分号作为普通内容的情况。参考实现没有资源限制,只用于这里的小样本对照。

测试通过说明所列样本满足分块不变性,不等于枚举了任意长度的所有输入。继续扩大测试时,应增加随机字节与随机合法字段、各限额边界、不同子视图起点,以及错误后调用顺序。AI 可以帮助生成候选测试,但人仍要审查参考模型是否偷偷复制了同一个错误。尤其要防止测试先把原始字节宽容解成字符串,导致真正要验证的损坏在进入解析器前就被替换掉。

示例 9:

import assert from "node:assert/strict";
function createFormDecoder(options = {}) {
  const limits = {
    maxBytes: 65536, maxFields: 128,
    maxNameBytes: 1024, maxValueBytes: 8192
  };
  for (const key of Object.keys(options)) {
    if (!Object.hasOwn(limits, key)) throw new TypeError(`unknown ${key}`);
    limits[key] = options[key];
  }
  for (const [key, n] of Object.entries(limits)) {
    if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(`invalid ${key}`);
  }
  let total = 0, count = 0, state = 0, high = 0, percentAt = 0;
  let inValue = false, seen = false, closed = false, failure = null;
  let name = [], value = [], pairs = [];
  const hex = b => b >= 48 && b <= 57 ? b - 48
    : b >= 65 && b <= 70 ? b - 55
    : b >= 97 && b <= 102 ? b - 87 : -1;
  function guard() {
    if (failure) throw failure;
    if (closed) throw new Error("E_CLOSED");
  }
  function fail(code, offset) {
    failure = Object.assign(new Error(`${code}@${offset}`), { code, offset });
    name = []; value = []; pairs = [];
    throw failure;
  }
  function emit(byte, at) {
    const target = inValue ? value : name;
    const max = inValue ? limits.maxValueBytes : limits.maxNameBytes;
    if (target.length >= max) fail(inValue ? "E_VALUE_LIMIT" : "E_NAME_LIMIT", at);
    target.push(byte);
  }
  function text(bytes, code, at) {
    try {
      return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true })
        .decode(Uint8Array.from(bytes));
    } catch (error) {
      if (!(error instanceof TypeError)) throw error;
      fail(code, at);
    }
  }
  function endPair(at) {
    if (state !== 0) fail("E_PERCENT", percentAt);
    if (!seen) return;
    const key = text(name, "E_NAME_UTF8", at);
    const val = text(value, "E_VALUE_UTF8", at);
    pairs.push([key, val]);
    count++;
    name = []; value = []; inValue = false; seen = false;
  }
  return {
    write(chunk) {
      guard();
      if (!(chunk instanceof Uint8Array)) throw new TypeError("expected Uint8Array");
      for (const byte of chunk) {
        const at = total;
        if (total >= limits.maxBytes) fail("E_TOTAL", at);
        total++;
        if (byte === 38) { endPair(at); continue; }
        if (!seen) {
          if (count >= limits.maxFields) fail("E_FIELDS", at);
          seen = true;
        }
        if (byte === 61 && !inValue) {
          if (state !== 0) fail("E_PERCENT", percentAt);
          inValue = true;
          continue;
        }
        if (state !== 0) {
          const digit = hex(byte);
          if (digit < 0) fail("E_PERCENT", percentAt);
          if (state === 1) { high = digit; state = 2; }
          else { emit(high * 16 + digit, at); state = 0; }
        } else if (byte === 37) {
          state = 1; percentAt = at;
        } else {
          emit(byte === 43 ? 32 : byte, at);
        }
      }
    },
    finish() {
      guard();
      endPair(total);
      closed = true;
      return pairs;
    }
  };
}

function oracle(bytes) {
  const decode = part => {
    let encoded = "";
    for (let i = 0; i < part.length; i++) {
      const b = part[i];
      if (b === 37) {
        const digits = Buffer.from(part.subarray(i + 1, i + 3)).toString("latin1");
        if (!/^[0-9a-f]{2}$/i.test(digits)) throw new URIError("percent");
        encoded += "%" + digits;
        i += 2;
      } else {
        encoded += b === 43 ? "%20" : "%" + b.toString(16).padStart(2, "0");
      }
    }
    return decodeURIComponent(encoded);
  };
  const result = [];
  let start = 0;
  for (let end = 0; end <= bytes.length; end++) {
    if (end !== bytes.length && bytes[end] !== 38) continue;
    const field = bytes.subarray(start, end);
    start = end + 1;
    if (!field.length) continue;
    const at = field.indexOf(61);
    result.push(at < 0 ? [decode(field), ""]
      : [decode(field.subarray(0, at)), decode(field.subarray(at + 1))]);
  }
  return result;
}
function parse(chunks) {
  const parser = createFormDecoder();
  for (const chunk of chunks) parser.write(chunk);
  return parser.finish();
}
const valid = [
  Buffer.from("q=%E4%B8%AD&tag=a&tag=b"),
  Buffer.from("x=中&z=%F0%9F%98%80"),
  Uint8Array.from([...Buffer.from("x="), 0xe4, ...Buffer.from("%B8%AD")]),
  Buffer.from("a=%26%3d%2b%25&x=%2526"),
  Buffer.from("&&=v&flag&x=a=b&"),
  Buffer.from("bom=%EF%BB%BF"),
  Buffer.from("?q=x;s=1"), Buffer.alloc(0), Buffer.from("=")
];
let validCount = 0;
for (const bytes of valid) {
  const expected = oracle(bytes);
  assert.deepEqual(parse([...bytes].map(b => Uint8Array.of(b))), expected);
  for (let a = 0; a <= bytes.length; a++) {
    for (let b = a; b <= bytes.length; b++) {
      assert.deepEqual(parse([bytes.subarray(0, a), bytes.subarray(a, b), bytes.subarray(b)]), expected);
      validCount++;
    }
  }
}
let invalidCount = 0;
for (const [body, expected] of [
  ["x=%", "E_PERCENT@2"], ["x=%2G", "E_PERCENT@2"],
  ["x=%E4&y=%B8%AD", "E_VALUE_UTF8@5"],
  ["%FF=v", "E_NAME_UTF8@5"], ["x=%C0%AF", "E_VALUE_UTF8@8"]
]) {
  const bytes = Buffer.from(body);
  assert.throws(() => oracle(bytes), URIError);
  for (let a = 0; a <= bytes.length; a++) {
    for (let b = a; b <= bytes.length; b++) {
      assert.throws(() => parse([bytes.subarray(0, a), bytes.subarray(a, b), bytes.subarray(b)]),
        error => error.message === expected);
      invalidCount++;
    }
  }
}
console.log("valid partitions: " + validCount);
console.log("invalid partitions: " + invalidCount);
console.log("all checks passed");

运行输出:

valid partitions: 1169
invalid partitions: 217
all checks passed

合并代码前的审查清单

  • 明确接口是宽容标准解析还是严格业务方言,拒绝原因不能靠函数名猜测。

  • 传输块、百分号三元组、UTF-8 序列和字段结构是不同边界;其中只有字段边界决定组件解码的结束。

  • 分隔符识别只看原始字节,转义结果只当数据,加号规则只执行一次。

  • 总输入、组件字节和字段数量各自计量,默认预算与真实业务约束相匹配。

  • 重复名称保持顺序;成功提交、失败清理、关闭状态和偏移含义都有可运行证据。

这类审查最有价值的产物,是能被测试推翻的承诺。不要只要求 AI 给出一个更短的实现;先让它写清状态、边界与失败语义,再用独立路径验证。对于表单输入这样看起来简单的协议,小而明确的状态机往往比层层字符串替换更容易解释,也更容易判断哪里仍需额外保护。

核验依据

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