AI 代码审查实战:用九个测试构建严格增量 Base64 解码状态机
让 AI 写一个 Base64 解码函数很快,让它写一个跨任意分片仍严格遵守协议的解码器,则需要可执行的审查标准。本文不再介绍调用现成 API 的基本用法,而是从输入状态机出发,逐个拆开字母表、等号、规范填充位、真实 EOF 和输出预算之间的关系。目标是把一句支持流式的承诺,变成九个可以独立运行的反例与断言。

运行方式与阅读约定
以下九个示例均自包含,包含同一份完整解码器,不需要复制前一节的变量或安装依赖。任选一个代码块保存为 example.mjs,使用 node --unhandled-rejections=strict example.mjs 运行;本文在 Node.js v24.19.0 实测。每个代码块后面的普通文本框是逐字对应的标准输出。断言失败会令进程以非零状态退出,而不是继续输出一个看似成功的结果。
示例使用 node:assert/strict 的严格断言和 .mjs 模块入口。实现中的错误码为本文自行定义,示例默认上限为 1024 × 1024 个解码字节;没有后台服务、外部请求、定时器或第三方包。Node.js 严格断言文档与模块启用方式可用于核对运行环境。
一、先冻结协议,再谈 AI 生成的实现
这次审查从一个具体接口出发:调用方连续调用 push,最后调用一次 end。每次 push 返回当前块里已经完成的字节组,end 负责声明真实输入结束。解码器只接受字符串,返回 Buffer;它不猜测文件编码,也不把任意对象强制转换成字符串。把这一层约定写清楚,可以阻止 AI 顺手加上自动补齐、去空格、替换 URL 字符等看似友好的行为。
本文选择标准字母表 A–Z、a–z、0–9、加号和斜线。尾部不足三字节时必须带等号,不接受空白,不接受 Base64URL 的连字符与下划线,并额外拒绝非零填充位。这是明确选定的严格配置,而不是宣称所有协议都只能这样使用 Base64。RFC 4648 的第 3.2、3.3、3.5 节分别讨论补位、字母表以外字符和规范编码;其中解码端拒绝非零填充位是允许选择的检查,本文把它写进契约。核对 RFC 4648 第 3 节。
下面第一个完整程序同时给出实现和七个基础向量。不要因为这一轮全绿就批准代码:这些输入几乎没有触及状态转换。四个六位值还原三个字节只是算术部分,真正的审查重点是尚未完成的组、已经遇到填充符的尾部,以及永远不能再继续写入的失败对象。
import assert from 'node:assert/strict';
import { Buffer } from 'node:buffer';
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
class StrictBase64 {
#q = []; #state = 'open'; #at = 0; #size = 0; #limit;
constructor(maxOutput = 1024 * 1024) {
if (!Number.isSafeInteger(maxOutput) || maxOutput < 0) {
throw new RangeError('maxOutput must be a nonnegative safe integer');
}
this.#limit = maxOutput;
}
#fail(code, offset = this.#at) {
this.#state = 'failed';
throw Object.assign(new Error(code), { code, offset });
}
#guard() {
if (this.#state === 'failed' || this.#state === 'ended') {
const code = this.#state === 'failed' ? 'E_FAILED' : 'E_CLOSED';
throw Object.assign(new Error(code), { code, offset: this.#at });
}
}
push(text) {
this.#guard();
if (typeof text !== 'string') this.#fail('E_TYPE');
const out = [];
const emit = (count, offset) => {
if (count > this.#limit - this.#size) this.#fail('E_LIMIT', offset);
const [a, b, c = 0, d = 0] = this.#q;
const bytes = [(a << 2) | (b >> 4), ((b & 15) << 4) | (c >> 2),
((c & 3) << 6) | d];
for (let n = 0; n < count; n++) out.push(bytes[n]);
this.#size += count;
this.#q = [];
};
for (let i = 0; i < text.length; i++) {
const ch = text[i], offset = this.#at++;
if (this.#state === 'sealed') this.#fail('E_TRAILING', offset);
if (this.#state === 'pad') {
if (ch !== '=') this.#fail('E_PADDING', offset);
emit(1, offset); this.#state = 'sealed'; continue;
}
if (ch === '=') {
if (this.#q.length === 2) {
if ((this.#q[1] & 15) !== 0) this.#fail('E_PAD_BITS', offset);
this.#state = 'pad'; continue;
}
if (this.#q.length === 3) {
if ((this.#q[2] & 3) !== 0) this.#fail('E_PAD_BITS', offset);
emit(2, offset); this.#state = 'sealed'; continue;
}
this.#fail('E_PADDING', offset);
}
const value = ALPHABET.indexOf(ch);
if (value < 0) this.#fail('E_ALPHABET', offset);
this.#q.push(value);
if (this.#q.length === 4) emit(3, offset);
}
return Buffer.from(out);
}
end() {
this.#guard();
if (this.#state === 'pad' || this.#q.length !== 0) this.#fail('E_EOF');
this.#state = 'ended';
return Buffer.alloc(0);
}
}
const vectors = [
['', ''], ['Zg==', 'f'], ['Zm8=', 'fo'], ['Zm9v', 'foo'],
['Zm9vYg==', 'foob'], ['Zm9vYmE=', 'fooba'], ['Zm9vYmFy', 'foobar']
];
for (const [encoded, plain] of vectors) {
const d = new StrictBase64();
const result = Buffer.concat([d.push(encoded), d.end()]);
assert.equal(result.toString('utf8'), plain);
}
console.log(`vectors: ${vectors.length}`);
console.log('empty: accepted');预期输出:
vectors: 7 empty: accepted
二、跨块保存的是语法状态,不是整条输入
实现把状态压缩为 open、pad、sealed、ended、failed 五种。open 允许继续积累字母表数值,待处理数组最多保留三个值;第四个值到来就计算并返回三字节。读到两个有效字符之后的第一个等号,进入 pad,必须再等到一个等号才能输出单字节。读到三个有效字符之后的等号则直接输出两字节并进入 sealed。sealed 表示合法尾部已经封口,仍然不是传输结束。
这种区分专门对付网络分片:第一个等号和第二个等号可以落在不同块;一个块可以只包含一个字符;空块也可能出现。空块只是不提供新字符,绝不能被解释为 EOF。下面把 ManM 拆成七块,单字节尾部直到第二个等号到来才出现。审查 AI 提交时,要求它指出每个 continue 之后的状态,比让它口头解释支持流式更加有效。
这里没有累计完整编码字符串,内部语法状态大小是常数。但返回值的大小随本次 push 完成的输出增长,临时数字数组也占内存,所以不能把整个 API 宣称为恒定内存。调用方同样可以通过不断保存返回的 Buffer 消耗内存;真正的内存边界还需要上游分块和下游消费策略。
import assert from 'node:assert/strict';
import { Buffer } from 'node:buffer';
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
class StrictBase64 {
#q = []; #state = 'open'; #at = 0; #size = 0; #limit;
constructor(maxOutput = 1024 * 1024) {
if (!Number.isSafeInteger(maxOutput) || maxOutput < 0) {
throw new RangeError('maxOutput must be a nonnegative safe integer');
}
this.#limit = maxOutput;
}
#fail(code, offset = this.#at) {
this.#state = 'failed';
throw Object.assign(new Error(code), { code, offset });
}
#guard() {
if (this.#state === 'failed' || this.#state === 'ended') {
const code = this.#state === 'failed' ? 'E_FAILED' : 'E_CLOSED';
throw Object.assign(new Error(code), { code, offset: this.#at });
}
}
push(text) {
this.#guard();
if (typeof text !== 'string') this.#fail('E_TYPE');
const out = [];
const emit = (count, offset) => {
if (count > this.#limit - this.#size) this.#fail('E_LIMIT', offset);
const [a, b, c = 0, d = 0] = this.#q;
const bytes = [(a << 2) | (b >> 4), ((b & 15) << 4) | (c >> 2),
((c & 3) << 6) | d];
for (let n = 0; n < count; n++) out.push(bytes[n]);
this.#size += count;
this.#q = [];
};
for (let i = 0; i < text.length; i++) {
const ch = text[i], offset = this.#at++;
if (this.#state === 'sealed') this.#fail('E_TRAILING', offset);
if (this.#state === 'pad') {
if (ch !== '=') this.#fail('E_PADDING', offset);
emit(1, offset); this.#state = 'sealed'; continue;
}
if (ch === '=') {
if (this.#q.length === 2) {
if ((this.#q[1] & 15) !== 0) this.#fail('E_PAD_BITS', offset);
this.#state = 'pad'; continue;
}
if (this.#q.length === 3) {
if ((this.#q[2] & 3) !== 0) this.#fail('E_PAD_BITS', offset);
emit(2, offset); this.#state = 'sealed'; continue;
}
this.#fail('E_PADDING', offset);
}
const value = ALPHABET.indexOf(ch);
if (value < 0) this.#fail('E_ALPHABET', offset);
this.#q.push(value);
if (this.#q.length === 4) emit(3, offset);
}
return Buffer.from(out);
}
end() {
this.#guard();
if (this.#state === 'pad' || this.#q.length !== 0) this.#fail('E_EOF');
this.#state = 'ended';
return Buffer.alloc(0);
}
}
const d = new StrictBase64();
const parts = ['T', 'W', 'Fu', 'TQ', '=', '=', ''];
const outputs = parts.map(part => d.push(part));
assert.deepEqual(outputs.map(b => b.length), [0, 0, 3, 0, 0, 1, 0]);
assert.equal(d.end().length, 0);
const text = Buffer.concat(outputs).toString('utf8');
assert.equal(text, 'ManM');
console.log('chunks: ' + outputs.map(b => b.length).join(','));
console.log('text: ' + text);预期输出:
chunks: 0,0,3,0,0,1,0 text: ManM
三、宽松运行库不能充当严格验证器
Node.js 的 Buffer 文档明确说明,base64 解码接受 URL 安全字母表,也忽略空格、制表符和换行。因此,直接调用 Buffer.from 后检查是否抛错,并不能实现本文的契约。这并不表示运行库有缺陷:通用兼容接口与协议边界验证本来就是两个目标。本文只在最终创建输出 Buffer 时使用运行库,字符识别由显式字母表负责。查看 Node.js 编码说明。
不要先 trim 再验证,也不要用正则清理后继续处理。清理会改变输入证据,日志偏移量跟着失真,不同服务还可能对同一串文本得出不同判断。下面覆盖块内空格、换行、制表符、URL 字母、全角字母、不换行空格和孤立代理项;它们都不会被悄悄折叠成合法字母。错误偏移量从零开始,以原字符串的 UTF-16 代码单元累计;对于合法输入,它也就是 ASCII 字符位置。
类型错误也进入 failed,防止调用方误把异常当成暂时无输入,然后在半旧半新的解析状态上继续。测试只需要比较结构化 code 与 offset,不依赖平台堆栈、错误展示风格或整段异常文本。
import assert from 'node:assert/strict';
import { Buffer } from 'node:buffer';
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
class StrictBase64 {
#q = []; #state = 'open'; #at = 0; #size = 0; #limit;
constructor(maxOutput = 1024 * 1024) {
if (!Number.isSafeInteger(maxOutput) || maxOutput < 0) {
throw new RangeError('maxOutput must be a nonnegative safe integer');
}
this.#limit = maxOutput;
}
#fail(code, offset = this.#at) {
this.#state = 'failed';
throw Object.assign(new Error(code), { code, offset });
}
#guard() {
if (this.#state === 'failed' || this.#state === 'ended') {
const code = this.#state === 'failed' ? 'E_FAILED' : 'E_CLOSED';
throw Object.assign(new Error(code), { code, offset: this.#at });
}
}
push(text) {
this.#guard();
if (typeof text !== 'string') this.#fail('E_TYPE');
const out = [];
const emit = (count, offset) => {
if (count > this.#limit - this.#size) this.#fail('E_LIMIT', offset);
const [a, b, c = 0, d = 0] = this.#q;
const bytes = [(a << 2) | (b >> 4), ((b & 15) << 4) | (c >> 2),
((c & 3) << 6) | d];
for (let n = 0; n < count; n++) out.push(bytes[n]);
this.#size += count;
this.#q = [];
};
for (let i = 0; i < text.length; i++) {
const ch = text[i], offset = this.#at++;
if (this.#state === 'sealed') this.#fail('E_TRAILING', offset);
if (this.#state === 'pad') {
if (ch !== '=') this.#fail('E_PADDING', offset);
emit(1, offset); this.#state = 'sealed'; continue;
}
if (ch === '=') {
if (this.#q.length === 2) {
if ((this.#q[1] & 15) !== 0) this.#fail('E_PAD_BITS', offset);
this.#state = 'pad'; continue;
}
if (this.#q.length === 3) {
if ((this.#q[2] & 3) !== 0) this.#fail('E_PAD_BITS', offset);
emit(2, offset); this.#state = 'sealed'; continue;
}
this.#fail('E_PADDING', offset);
}
const value = ALPHABET.indexOf(ch);
if (value < 0) this.#fail('E_ALPHABET', offset);
this.#q.push(value);
if (this.#q.length === 4) emit(3, offset);
}
return Buffer.from(out);
}
end() {
this.#guard();
if (this.#state === 'pad' || this.#q.length !== 0) this.#fail('E_EOF');
this.#state = 'ended';
return Buffer.alloc(0);
}
}
const bad = [
['TW Fu', 2], ['TW\nFu', 2], ['TW\tFu', 2], ['-w==', 0],
['_w==', 0], ['TQ==', 0], ['T\u00a0Q==', 1], ['\ud800', 0]
];
for (const [text, offset] of bad) {
assert.throws(() => new StrictBase64().push(text), { code: 'E_ALPHABET', offset });
}
const d = new StrictBase64();
assert.throws(() => d.push(new String('TQ==')), { code: 'E_TYPE', offset: 0 });
assert.throws(() => d.push('TQ=='), { code: 'E_FAILED' });
console.log('alphabet rejections: ' + bad.length);
console.log('type: E_TYPE@0');预期输出:
alphabet rejections: 8 type: E_TYPE@0
四、等号是终止语法,不能作为可忽略字符
许多 AI 版本会把等号当成零值加入六位数组,或遇到等号就提前返回。这两种写法都容易放过尾部垃圾。本文把等号当成状态转换事件:它只能出现在当前组已有两个或三个字母的位置;在 pad 中只允许第二个等号;在 sealed 中任何后续字符都失败,包括另一个等号和换行。完整的四字符组没有等号,仍可继续下一组。
下面的反例刻意混合位置错误和封口后的输入。TQ=A 在第四个字符失败,因为正在等待第二个等号;TQ=== 在第五个字符失败,因为尾部已经封口。这些不同错误码不是互联网通用标准,而是本文 API 的诊断设计。它们帮助审查者确认实现确实经过了对应分支,不能被一个无条件拒绝所有等号的假修复糊弄过去。
已经封口后收到空块仍然允许,因为没有新增字符;但若用户已经调用 end,则空块也属于非法调用。输入内容终止与对象生命周期终止分别处理,是后续排查重复关闭和上游重试时的重要线索。
import assert from 'node:assert/strict';
import { Buffer } from 'node:buffer';
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
class StrictBase64 {
#q = []; #state = 'open'; #at = 0; #size = 0; #limit;
constructor(maxOutput = 1024 * 1024) {
if (!Number.isSafeInteger(maxOutput) || maxOutput < 0) {
throw new RangeError('maxOutput must be a nonnegative safe integer');
}
this.#limit = maxOutput;
}
#fail(code, offset = this.#at) {
this.#state = 'failed';
throw Object.assign(new Error(code), { code, offset });
}
#guard() {
if (this.#state === 'failed' || this.#state === 'ended') {
const code = this.#state === 'failed' ? 'E_FAILED' : 'E_CLOSED';
throw Object.assign(new Error(code), { code, offset: this.#at });
}
}
push(text) {
this.#guard();
if (typeof text !== 'string') this.#fail('E_TYPE');
const out = [];
const emit = (count, offset) => {
if (count > this.#limit - this.#size) this.#fail('E_LIMIT', offset);
const [a, b, c = 0, d = 0] = this.#q;
const bytes = [(a << 2) | (b >> 4), ((b & 15) << 4) | (c >> 2),
((c & 3) << 6) | d];
for (let n = 0; n < count; n++) out.push(bytes[n]);
this.#size += count;
this.#q = [];
};
for (let i = 0; i < text.length; i++) {
const ch = text[i], offset = this.#at++;
if (this.#state === 'sealed') this.#fail('E_TRAILING', offset);
if (this.#state === 'pad') {
if (ch !== '=') this.#fail('E_PADDING', offset);
emit(1, offset); this.#state = 'sealed'; continue;
}
if (ch === '=') {
if (this.#q.length === 2) {
if ((this.#q[1] & 15) !== 0) this.#fail('E_PAD_BITS', offset);
this.#state = 'pad'; continue;
}
if (this.#q.length === 3) {
if ((this.#q[2] & 3) !== 0) this.#fail('E_PAD_BITS', offset);
emit(2, offset); this.#state = 'sealed'; continue;
}
this.#fail('E_PADDING', offset);
}
const value = ALPHABET.indexOf(ch);
if (value < 0) this.#fail('E_ALPHABET', offset);
this.#q.push(value);
if (this.#q.length === 4) emit(3, offset);
}
return Buffer.from(out);
}
end() {
this.#guard();
if (this.#state === 'pad' || this.#q.length !== 0) this.#fail('E_EOF');
this.#state = 'ended';
return Buffer.alloc(0);
}
}
const cases = [
['=', 'E_PADDING', 0], ['A===', 'E_PADDING', 1],
['T=Q=', 'E_PADDING', 1], ['TQ=A', 'E_PADDING', 3],
['TQ===', 'E_TRAILING', 4], ['TQ==AAAA', 'E_TRAILING', 4],
['TWE==', 'E_TRAILING', 4], ['TWFu=', 'E_PADDING', 4]
];
for (const [text, code, offset] of cases) {
assert.throws(() => new StrictBase64().push(text), { code, offset });
}
const d = new StrictBase64();
assert.equal(d.push('TQ=').length, 0);
assert.equal(d.push('=').toString(), 'M');
assert.equal(d.push('').length, 0);
assert.throws(() => d.push('\n'), { code: 'E_TRAILING', offset: 4 });
console.log('padding rejections: ' + cases.length);
console.log('sealed newline: E_TRAILING@4');预期输出:
padding rejections: 8 sealed newline: E_TRAILING@4
五、解出来相同,也可能不是规范表示
在一字节尾部,第二个六位值只有高两位参与还原,其低四位必须为零;在两字节尾部,第三个值只使用高四位,低两位必须为零。只检查字母表与等号位置,会让若干不同文本还原为同一组字节。对于把编码文本作为缓存键、签名输入或唯一标识的应用,这种表示别名值得在协议设计阶段明确处理。
本文在读到第一个相关等号时检查这些低位:一字节情形使用与 15 按位与,两字节情形使用与 3 按位与。因此非规范尾部的诊断位置指向等号,而不是指向携带低位的前一个字母;这是有意且统一的偏移语义。下面遍历两类尾部的所有低位组合,一共二十个候选,仅两个规范编码通过。测试并不通过宽松解码器倒推合法性,而是直接断言可接受集合。
还要提醒 AI:规范表示不是身份验证。攻击者可以提供一段完全规范但恶意的内容,Base64 也不提供保密性、完整性或来源保证。通过这一层检查后,业务数据仍需按自己的格式、权限和大小限制进一步验证。
import assert from 'node:assert/strict';
import { Buffer } from 'node:buffer';
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
class StrictBase64 {
#q = []; #state = 'open'; #at = 0; #size = 0; #limit;
constructor(maxOutput = 1024 * 1024) {
if (!Number.isSafeInteger(maxOutput) || maxOutput < 0) {
throw new RangeError('maxOutput must be a nonnegative safe integer');
}
this.#limit = maxOutput;
}
#fail(code, offset = this.#at) {
this.#state = 'failed';
throw Object.assign(new Error(code), { code, offset });
}
#guard() {
if (this.#state === 'failed' || this.#state === 'ended') {
const code = this.#state === 'failed' ? 'E_FAILED' : 'E_CLOSED';
throw Object.assign(new Error(code), { code, offset: this.#at });
}
}
push(text) {
this.#guard();
if (typeof text !== 'string') this.#fail('E_TYPE');
const out = [];
const emit = (count, offset) => {
if (count > this.#limit - this.#size) this.#fail('E_LIMIT', offset);
const [a, b, c = 0, d = 0] = this.#q;
const bytes = [(a << 2) | (b >> 4), ((b & 15) << 4) | (c >> 2),
((c & 3) << 6) | d];
for (let n = 0; n < count; n++) out.push(bytes[n]);
this.#size += count;
this.#q = [];
};
for (let i = 0; i < text.length; i++) {
const ch = text[i], offset = this.#at++;
if (this.#state === 'sealed') this.#fail('E_TRAILING', offset);
if (this.#state === 'pad') {
if (ch !== '=') this.#fail('E_PADDING', offset);
emit(1, offset); this.#state = 'sealed'; continue;
}
if (ch === '=') {
if (this.#q.length === 2) {
if ((this.#q[1] & 15) !== 0) this.#fail('E_PAD_BITS', offset);
this.#state = 'pad'; continue;
}
if (this.#q.length === 3) {
if ((this.#q[2] & 3) !== 0) this.#fail('E_PAD_BITS', offset);
emit(2, offset); this.#state = 'sealed'; continue;
}
this.#fail('E_PADDING', offset);
}
const value = ALPHABET.indexOf(ch);
if (value < 0) this.#fail('E_ALPHABET', offset);
this.#q.push(value);
if (this.#q.length === 4) emit(3, offset);
}
return Buffer.from(out);
}
end() {
this.#guard();
if (this.#state === 'pad' || this.#q.length !== 0) this.#fail('E_EOF');
this.#state = 'ended';
return Buffer.alloc(0);
}
}
let accepted = 0, rejected = 0;
for (const [prefix, start, count, suffix, hex] of [
['/', 48, 16, '==', 'ff'], ['//', 60, 4, '=', 'ffff']
]) {
for (let i = 0; i < count; i++) {
const encoded = prefix + ALPHABET[start + i] + suffix;
const d = new StrictBase64();
if (i === 0) {
assert.equal(d.push(encoded).toString('hex'), hex);
d.end(); accepted++;
} else {
assert.throws(() => d.push(encoded), { code: 'E_PAD_BITS', offset: prefix.length + 1 });
rejected++;
}
}
}
assert.equal(accepted, 2);
assert.equal(rejected, 18);
console.log('canonical tails: ' + accepted);
console.log('pad-bit rejections: ' + rejected);预期输出:
canonical tails: 2 pad-bit rejections: 18
六、EOF 是独立事件,异常之后不恢复旧对象
收到 TQ 只能说明当前还缺输入,不能在 push 返回时判死刑,因为后续块可能提供两个等号。相反,真实 EOF 到来之后仍然剩有一个、两个、三个普通值,或者停在等待第二个等号的 pad,都必须失败。end 不自动补齐,不刷新半组字节,也不把缺失尾部当成正常结束。
对象一旦解析失败,所有后续 push 和 end 都返回 E_FAILED;成功 end 后返回 E_CLOSED。最初的解析错误包含准确位置,调用方应该立即记录它,而不是通过重试覆盖首个错误。这里故意不提供 reset,因为跨请求复用很容易把上一个请求的状态泄漏到下一个请求;为新消息创建新实例更容易审计。
这也解释了为何生命周期错误不能与输入错误混在一起。一个完整四字符组之后直接 EOF 是有效的,完全空的输入也是有效的;二者都不能因为没看见等号而被拒绝。对 AI 的审查问题应当是哪些状态可以结束,而不是字符串最后是否出现等号。
import assert from 'node:assert/strict';
import { Buffer } from 'node:buffer';
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
class StrictBase64 {
#q = []; #state = 'open'; #at = 0; #size = 0; #limit;
constructor(maxOutput = 1024 * 1024) {
if (!Number.isSafeInteger(maxOutput) || maxOutput < 0) {
throw new RangeError('maxOutput must be a nonnegative safe integer');
}
this.#limit = maxOutput;
}
#fail(code, offset = this.#at) {
this.#state = 'failed';
throw Object.assign(new Error(code), { code, offset });
}
#guard() {
if (this.#state === 'failed' || this.#state === 'ended') {
const code = this.#state === 'failed' ? 'E_FAILED' : 'E_CLOSED';
throw Object.assign(new Error(code), { code, offset: this.#at });
}
}
push(text) {
this.#guard();
if (typeof text !== 'string') this.#fail('E_TYPE');
const out = [];
const emit = (count, offset) => {
if (count > this.#limit - this.#size) this.#fail('E_LIMIT', offset);
const [a, b, c = 0, d = 0] = this.#q;
const bytes = [(a << 2) | (b >> 4), ((b & 15) << 4) | (c >> 2),
((c & 3) << 6) | d];
for (let n = 0; n < count; n++) out.push(bytes[n]);
this.#size += count;
this.#q = [];
};
for (let i = 0; i < text.length; i++) {
const ch = text[i], offset = this.#at++;
if (this.#state === 'sealed') this.#fail('E_TRAILING', offset);
if (this.#state === 'pad') {
if (ch !== '=') this.#fail('E_PADDING', offset);
emit(1, offset); this.#state = 'sealed'; continue;
}
if (ch === '=') {
if (this.#q.length === 2) {
if ((this.#q[1] & 15) !== 0) this.#fail('E_PAD_BITS', offset);
this.#state = 'pad'; continue;
}
if (this.#q.length === 3) {
if ((this.#q[2] & 3) !== 0) this.#fail('E_PAD_BITS', offset);
emit(2, offset); this.#state = 'sealed'; continue;
}
this.#fail('E_PADDING', offset);
}
const value = ALPHABET.indexOf(ch);
if (value < 0) this.#fail('E_ALPHABET', offset);
this.#q.push(value);
if (this.#q.length === 4) emit(3, offset);
}
return Buffer.from(out);
}
end() {
this.#guard();
if (this.#state === 'pad' || this.#q.length !== 0) this.#fail('E_EOF');
this.#state = 'ended';
return Buffer.alloc(0);
}
}
const prefixes = ['T', 'TQ', 'TQ=', 'TWE'];
for (const text of prefixes) {
const d = new StrictBase64();
assert.equal(d.push(text).length, 0);
assert.throws(() => d.end(), { code: 'E_EOF', offset: text.length });
assert.throws(() => d.push('=='), { code: 'E_FAILED' });
assert.throws(() => d.end(), { code: 'E_FAILED' });
}
const empty = new StrictBase64();
assert.equal(empty.end().length, 0);
assert.throws(() => empty.end(), { code: 'E_CLOSED' });
assert.throws(() => empty.push(''), { code: 'E_CLOSED' });
const full = new StrictBase64();
assert.equal(full.push('TWFu').toString(), 'Man');
full.end();
console.log('truncated endings: ' + prefixes.length);
console.log('lifecycle: failed stays failed, ended stays closed');预期输出:
truncated endings: 4 lifecycle: failed stays failed, ended stays closed
七、输出限额必须在每个完成组提交之前检查
默认输出上限为一兆字节,构造时允许设置非负安全整数。每次准备提交一、二、三个字节之前,先比较本组长度与剩余额度;超过限额立即失败,不返回本组的一部分。使用剩余额度做减法,可以避免先相加再检查的写法引入不必要的整数精度问题。上限按解码后的字节计数,既不是编码字符数,也不是 JavaScript 字符串长度。
下面同时覆盖零上限、恰好命中上限、第一组就超限和跨块累计超限。特别要让 AI 看到同一个实例的总量:如果限额在每次 push 内重新归零,攻击者只需发送大量小块就能绕过。超限位置指向使当前量子完成的字符;对 TQ== 来说是第二个等号,因为到这里才实际提交单字节。
输出限额不是完整的拒绝服务防线。输入字符串在进入 API 之前已经分配,上游还需要限制单块大小、请求总大小、等待时间及调用频率;无限空块不会增加输出计数。非常大的安全整数在数值上合法,不等于机器能承受相应内存。本文示范的是解码边界,不替代传输层预算与背压。
import assert from 'node:assert/strict';
import { Buffer } from 'node:buffer';
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
class StrictBase64 {
#q = []; #state = 'open'; #at = 0; #size = 0; #limit;
constructor(maxOutput = 1024 * 1024) {
if (!Number.isSafeInteger(maxOutput) || maxOutput < 0) {
throw new RangeError('maxOutput must be a nonnegative safe integer');
}
this.#limit = maxOutput;
}
#fail(code, offset = this.#at) {
this.#state = 'failed';
throw Object.assign(new Error(code), { code, offset });
}
#guard() {
if (this.#state === 'failed' || this.#state === 'ended') {
const code = this.#state === 'failed' ? 'E_FAILED' : 'E_CLOSED';
throw Object.assign(new Error(code), { code, offset: this.#at });
}
}
push(text) {
this.#guard();
if (typeof text !== 'string') this.#fail('E_TYPE');
const out = [];
const emit = (count, offset) => {
if (count > this.#limit - this.#size) this.#fail('E_LIMIT', offset);
const [a, b, c = 0, d = 0] = this.#q;
const bytes = [(a << 2) | (b >> 4), ((b & 15) << 4) | (c >> 2),
((c & 3) << 6) | d];
for (let n = 0; n < count; n++) out.push(bytes[n]);
this.#size += count;
this.#q = [];
};
for (let i = 0; i < text.length; i++) {
const ch = text[i], offset = this.#at++;
if (this.#state === 'sealed') this.#fail('E_TRAILING', offset);
if (this.#state === 'pad') {
if (ch !== '=') this.#fail('E_PADDING', offset);
emit(1, offset); this.#state = 'sealed'; continue;
}
if (ch === '=') {
if (this.#q.length === 2) {
if ((this.#q[1] & 15) !== 0) this.#fail('E_PAD_BITS', offset);
this.#state = 'pad'; continue;
}
if (this.#q.length === 3) {
if ((this.#q[2] & 3) !== 0) this.#fail('E_PAD_BITS', offset);
emit(2, offset); this.#state = 'sealed'; continue;
}
this.#fail('E_PADDING', offset);
}
const value = ALPHABET.indexOf(ch);
if (value < 0) this.#fail('E_ALPHABET', offset);
this.#q.push(value);
if (this.#q.length === 4) emit(3, offset);
}
return Buffer.from(out);
}
end() {
this.#guard();
if (this.#state === 'pad' || this.#q.length !== 0) this.#fail('E_EOF');
this.#state = 'ended';
return Buffer.alloc(0);
}
}
for (const limit of [-1, 0.5, Infinity, Number.MAX_SAFE_INTEGER + 1]) {
assert.throws(() => new StrictBase64(limit), RangeError);
}
const zero = new StrictBase64(0);
assert.equal(zero.push('').length, 0); zero.end();
const exact = new StrictBase64(4);
assert.equal(exact.push('TWFuTQ==').toString(), 'ManM'); exact.end();
assert.throws(() => new StrictBase64(2).push('TWFu'), { code: 'E_LIMIT', offset: 3 });
const d = new StrictBase64(3);
assert.equal(d.push('TWFu').toString(), 'Man');
assert.equal(d.push('TQ=').length, 0);
assert.throws(() => d.push('='), { code: 'E_LIMIT', offset: 7 });
assert.throws(() => d.end(), { code: 'E_FAILED' });
console.log('exact budget: 4 bytes');
console.log('split overflow: E_LIMIT@7');预期输出:
exact budget: 4 bytes split overflow: E_LIMIT@7
八、分片不变性要比较最终结果与首个错误
现在把审查从列举案例提升为一个性质:同一串输入,不论在哪些字符之间切开,成功时拼接返回字节应当相同,失败时首个错误码和全局偏移量也应相同。下面枚举短输入所有非空分片方式,并在片段之间插入空块,再分别以三种限额运行。它涵盖尾部、低位错误、空白、缺失结束和预算边界,能抓住按块重置计数、按块补等号等实现缺陷。
这里有一条必须写在测试旁的限制:失败之前调用方已经拿到多少字节,并不具有分片不变性。单次 push 先解出合法组、随后发现错误时,该次调用抛异常,局部返回数组不会交付;若合法组恰好在上一块,之前返回的字节已经离开解码器。测试因此只比较成功的最终字节,或者失败的首个诊断,不错误地要求失败过程具有事务性。
这个例子不是数学证明,也不能保证生产环境没有内存耗尽等外部故障。它是一组可重复、确定性的契约测试,用于约束正常资源条件下的解析语义。真实项目还应加入长输入和随机切片,并让独立审查者尝试构造新的反例,而不是仅让生成代码的同一个提示词再次表示自信。
import assert from 'node:assert/strict';
import { Buffer } from 'node:buffer';
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
class StrictBase64 {
#q = []; #state = 'open'; #at = 0; #size = 0; #limit;
constructor(maxOutput = 1024 * 1024) {
if (!Number.isSafeInteger(maxOutput) || maxOutput < 0) {
throw new RangeError('maxOutput must be a nonnegative safe integer');
}
this.#limit = maxOutput;
}
#fail(code, offset = this.#at) {
this.#state = 'failed';
throw Object.assign(new Error(code), { code, offset });
}
#guard() {
if (this.#state === 'failed' || this.#state === 'ended') {
const code = this.#state === 'failed' ? 'E_FAILED' : 'E_CLOSED';
throw Object.assign(new Error(code), { code, offset: this.#at });
}
}
push(text) {
this.#guard();
if (typeof text !== 'string') this.#fail('E_TYPE');
const out = [];
const emit = (count, offset) => {
if (count > this.#limit - this.#size) this.#fail('E_LIMIT', offset);
const [a, b, c = 0, d = 0] = this.#q;
const bytes = [(a << 2) | (b >> 4), ((b & 15) << 4) | (c >> 2),
((c & 3) << 6) | d];
for (let n = 0; n < count; n++) out.push(bytes[n]);
this.#size += count;
this.#q = [];
};
for (let i = 0; i < text.length; i++) {
const ch = text[i], offset = this.#at++;
if (this.#state === 'sealed') this.#fail('E_TRAILING', offset);
if (this.#state === 'pad') {
if (ch !== '=') this.#fail('E_PADDING', offset);
emit(1, offset); this.#state = 'sealed'; continue;
}
if (ch === '=') {
if (this.#q.length === 2) {
if ((this.#q[1] & 15) !== 0) this.#fail('E_PAD_BITS', offset);
this.#state = 'pad'; continue;
}
if (this.#q.length === 3) {
if ((this.#q[2] & 3) !== 0) this.#fail('E_PAD_BITS', offset);
emit(2, offset); this.#state = 'sealed'; continue;
}
this.#fail('E_PADDING', offset);
}
const value = ALPHABET.indexOf(ch);
if (value < 0) this.#fail('E_ALPHABET', offset);
this.#q.push(value);
if (this.#q.length === 4) emit(3, offset);
}
return Buffer.from(out);
}
end() {
this.#guard();
if (this.#state === 'pad' || this.#q.length !== 0) this.#fail('E_EOF');
this.#state = 'ended';
return Buffer.alloc(0);
}
}
function partitions(text) {
if (text.length === 0) return [[]];
const all = [];
for (let mask = 0; mask < 2 ** (text.length - 1); mask++) {
const parts = []; let start = 0;
for (let i = 1; i < text.length; i++) {
if (mask & (2 ** (i - 1))) { parts.push(text.slice(start, i)); start = i; }
}
parts.push(text.slice(start)); all.push(parts);
}
return all;
}
function outcome(parts, limit) {
const d = new StrictBase64(limit), bytes = [];
try {
for (const part of parts) bytes.push(d.push(part));
bytes.push(d.end());
return ['ok', Buffer.concat(bytes).toString('hex')];
} catch (e) { return ['error', e.code, e.offset]; }
}
const inputs = ['', 'TQ==', 'TWE=', 'TWFu', 'TWFuTQ==', 'TQ=',
'TQ=A', 'TR==', 'TWF=', 'TQ===', 'TW Fu', 'TQ==A'];
let checks = 0;
for (const text of inputs) for (const limit of [0, 3, 20]) {
const expected = outcome([text], limit);
for (const parts of partitions(text)) {
const withEmpty = ['', ...parts.flatMap(p => [p, ''])];
assert.deepEqual(outcome(withEmpty, limit), expected);
checks++;
}
}
assert.equal(checks, 687);
console.log('partition checks: ' + checks);
console.log('result and first error: invariant');预期输出:
partition checks: 687 result and first error: invariant
九、把字节入口与整条消息提交边界接好
若上游交付的是 Buffer,严格检查应保留原始字节,不能先用 ascii 解码,因为 Node 文档说明该模式会清除每个字节的最高位。下面用 latin1 一对一保留字节值;高位字节变成非字母表字符后会被拒绝。这个适配器只接收 Buffer,不暗中猜测字符串、对象或其他视图的语义。真正的二进制输出也保持 Buffer,不强行解释为 UTF-8 文本。
readWhole 在受控的输出预算内暂存所有成功块,只有 end 通过后才返回整条消息。这是调用方的提交策略,而不是增量解码器自身承诺的事务性。如果业务不能接受失败之前已经处理的内容,就不要边解码边执行不可撤回的操作;可以选择类似的有界缓冲,或者具有回滚能力的暂存目标。大文件场景需要另行设计磁盘配额、清理和提交协议。
最后一条测试把非 ASCII 的原始字节挡在入口,再验证包含零字节与 255 的输出。审查收尾时,让 AI 逐项说明字母表、填充、低位、EOF、限额和提交边界由哪条断言守住。能指出具体证据,才是这份实现值得合入的理由。
import assert from 'node:assert/strict';
import { Buffer } from 'node:buffer';
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
class StrictBase64 {
#q = []; #state = 'open'; #at = 0; #size = 0; #limit;
constructor(maxOutput = 1024 * 1024) {
if (!Number.isSafeInteger(maxOutput) || maxOutput < 0) {
throw new RangeError('maxOutput must be a nonnegative safe integer');
}
this.#limit = maxOutput;
}
#fail(code, offset = this.#at) {
this.#state = 'failed';
throw Object.assign(new Error(code), { code, offset });
}
#guard() {
if (this.#state === 'failed' || this.#state === 'ended') {
const code = this.#state === 'failed' ? 'E_FAILED' : 'E_CLOSED';
throw Object.assign(new Error(code), { code, offset: this.#at });
}
}
push(text) {
this.#guard();
if (typeof text !== 'string') this.#fail('E_TYPE');
const out = [];
const emit = (count, offset) => {
if (count > this.#limit - this.#size) this.#fail('E_LIMIT', offset);
const [a, b, c = 0, d = 0] = this.#q;
const bytes = [(a << 2) | (b >> 4), ((b & 15) << 4) | (c >> 2),
((c & 3) << 6) | d];
for (let n = 0; n < count; n++) out.push(bytes[n]);
this.#size += count;
this.#q = [];
};
for (let i = 0; i < text.length; i++) {
const ch = text[i], offset = this.#at++;
if (this.#state === 'sealed') this.#fail('E_TRAILING', offset);
if (this.#state === 'pad') {
if (ch !== '=') this.#fail('E_PADDING', offset);
emit(1, offset); this.#state = 'sealed'; continue;
}
if (ch === '=') {
if (this.#q.length === 2) {
if ((this.#q[1] & 15) !== 0) this.#fail('E_PAD_BITS', offset);
this.#state = 'pad'; continue;
}
if (this.#q.length === 3) {
if ((this.#q[2] & 3) !== 0) this.#fail('E_PAD_BITS', offset);
emit(2, offset); this.#state = 'sealed'; continue;
}
this.#fail('E_PADDING', offset);
}
const value = ALPHABET.indexOf(ch);
if (value < 0) this.#fail('E_ALPHABET', offset);
this.#q.push(value);
if (this.#q.length === 4) emit(3, offset);
}
return Buffer.from(out);
}
end() {
this.#guard();
if (this.#state === 'pad' || this.#q.length !== 0) this.#fail('E_EOF');
this.#state = 'ended';
return Buffer.alloc(0);
}
}
function readWhole(chunks, limit) {
const d = new StrictBase64(limit), output = [];
for (const chunk of chunks) {
if (!Buffer.isBuffer(chunk)) throw new TypeError('Buffer required');
output.push(d.push(chunk.toString('latin1')));
}
output.push(d.end());
return Buffer.concat(output);
}
const bad = Buffer.from([0xd4, 0x51, 0x3d, 0x3d]);
assert.throws(() => readWhole([bad], 3), { code: 'E_ALPHABET', offset: 0 });
const bytes = readWhole([Buffer.from('AP'), Buffer.from('8=')], 2);
assert.equal(bytes.toString('hex'), '00ff');
let committed = 0;
assert.throws(() => {
const message = readWhole([Buffer.from('TWFu'), Buffer.from('!')], 8);
committed += message.length;
}, { code: 'E_ALPHABET', offset: 4 });
assert.equal(committed, 0);
console.log('binary result: ' + bytes.toString('hex'));
console.log('failed message committed: ' + committed);预期输出:
binary result: 00ff failed message committed: 0
合入前的最小审查清单
协议是否明确选择标准字母表、必要填充与零填充位,并拒绝额外字符?
分块是否只改变调用时机,不改变成功内容、首个错误码与全局错误位置?
空块、封口、EOF、失败与关闭是否是不同事件,且生命周期不可被悄悄重置?
限额是否跨块累计,是否在完整量子输出前检查,并配合上游资源约束?
调用方是否知道增量输出可能先于后续错误,是否选择了合适的提交策略?
AI 的价值是帮助迅速展开分支与测试矩阵,审查者的责任是把可接受的输入语言、资源预算和失败后果说清楚。Base64 是二进制到文本的编码,不是加密;本教程完成的是严格解码边界,后续安全性仍取决于业务验证、认证机制和正确的消息提交方式。

