Files

245 lines
15 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict'
// src/storage-zip.js 的单测(P1 拆分批 5:ZIP 读写族自 app.js 收编)
//
// ⚠️ 这个族在迁出前**零测试覆盖**(wCreateStoreZip / wZipParseEntries / wZipReadEntry /
// wOpenZipBlob / wCrc32Chunk / wDosDateTime 全都没有测试)。
// 而它们是「备份能导出 / 备份能还原」的根基 —— 写不出来 = 用户拿不到备份;
// 读不回来 = 备份变废纸(CHANGELOG 里记过一次「备份里的设置还原不回来」的用户实测缺陷)。
// 所以本文件的价值不在"搬移正确",而在**把这条链路第一次纳入自动化保护**。
//
// ⚠️ 非确定性:wCreateStoreZip 用 new Date() 编 DOS 时间 ⇒ 同输入两次输出字节可能不同。
// 因此所有断言都走「写 → 读往返」比对**内容**,绝不比对 zip 字节。
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const vm = require('vm')
const root = path.resolve(__dirname, '..')
const sandbox = {
console: { log() {}, warn() {}, error() {} },
TextEncoder, TextDecoder, Blob, DataView, Uint8Array, Uint32Array,
Response, DecompressionStream, Date, Error, Math, String, Number, Array, Object, JSON, Promise, Set, Map, Boolean, isNaN, parseInt,
}
vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'storage-zip.js'), 'utf8'), sandbox)
const Z = sandbox.IWBStorageZip
assert.ok(Z, '应导出 IWBStorageZip')
for (const fn of ['wZipParseEntries', 'wZipReadEntry', 'wOpenZipBlob', 'wCreateStoreZip']) {
assert.strictEqual(typeof Z[fn], 'function', '应导出 ' + fn)
}
// 内部实现不该泄漏到导出面(CRC 表 / DOS 时间 / 签名常量属私有)
for (const internal of ['wCrc32Chunk', 'wDosDateTime', 'W_CRC_TABLE', 'W_ZIP_SIG_EOCD', 'W_ZIP_SIG_CEN']) {
assert.strictEqual(Z[internal], undefined, '内部实现不应导出: ' + internal)
}
// ⚠️ 跨 realm 比较:模块在 vm 沙箱里创建数组/对象,原型与本文件不同 ⇒
// `assert.deepStrictEqual` 会因原型不一致误报(§13.48/§13.50 已记两次)。统一用 JSON 比较。
const eqJson = (a, b, msg) => assert.strictEqual(JSON.stringify(a), JSON.stringify(b), msg)
const eqBytes = (a, b, msg) => eqJson(Array.from(a), Array.from(b), msg)
;(async () => {
// ── 1. 写 → 解析 → 条目表 ──────────────────────────────────────────────
{
const w = Z.wCreateStoreZip()
await w.add('data.json', new Blob([JSON.stringify({ hello: '世界' })], { type: 'application/json' }))
await w.add('images/a.png', new Blob([new Uint8Array([1, 2, 3, 4, 5])], { type: 'image/png' }))
const blob = w.finish()
assert.ok(blob && blob.size > 0, '应产出非空 ZIP Blob')
assert.strictEqual(blob.type, 'application/zip', 'ZIP 的 MIME 应是 application/zip')
const zip = Z.wZipParseEntries(await blob.arrayBuffer())
assert.strictEqual(zip.entries.length, 2, '应解析出 2 个条目')
eqJson(zip.entries.map((e) => e.name), ['data.json', 'images/a.png'], '条目名与顺序应对应写入顺序')
for (const e of zip.entries) {
assert.strictEqual(e.method, 0, '写入用 STORE(method=0):图片已压缩,STORE 体积几乎不变还省 CPU')
assert.strictEqual(e.compSize, e.rawSize, 'STORE 下压缩后大小 == 原始大小')
}
// 内容往返(含中文,验证 UTF-8 编码没坏)
const dataEntry = zip.entries[0]
const bytes = await Z.wZipReadEntry(zip, dataEntry)
eqJson(JSON.parse(new TextDecoder().decode(bytes)), { hello: '世界' }, '往返内容应一致(含中文 UTF-8)')
const pngEntry = zip.entries[1]
eqBytes(await Z.wZipReadEntry(zip, pngEntry), new Uint8Array([1, 2, 3, 4, 5]), '二进制内容往返应逐字节一致')
}
// ── 2. 大文件:触发**分片 CRC** 路径(>1MB 才会走多分片)─────────────────
// 这条是内存优化的关键:整块 arrayBuffer 会把 200 张原图重新堆回 V8 堆(历史峰值 ~979MB)。
{
const BIG = 2.5 * 1024 * 1024 // > 1MB 分片阈值 ⇒ 至少 3 个分片
const payload = new Uint8Array(BIG)
for (let i = 0; i < BIG; i += 4096) payload[i] = i % 251
const w = Z.wCreateStoreZip()
await w.add('big.bin', new Blob([payload]))
const zip = Z.wZipParseEntries(await w.finish().arrayBuffer())
assert.strictEqual(zip.entries.length, 1)
assert.strictEqual(zip.entries[0].rawSize, BIG, '大文件大小应正确(分片累加没丢字节)')
const backBytes = await Z.wZipReadEntry(zip, zip.entries[0])
assert.strictEqual(backBytes.length, BIG, '大文件读回长度应一致')
eqBytes(backBytes, payload, '大文件(多 CRC 分片)往返应逐字节一致')
}
// ── 3. CRC32 正确性(用标准校验向量)──────────────────────────────────
// CRC32("123456789") = 0xCBF43926 是 CRC-32/ISO-HDLC 的公开标准测试向量。
// 如果 CRC 算错,zip 能被我们自己的解析器读(我们不校验 CRC),但**第三方工具会报损坏**。
{
const w = Z.wCreateStoreZip()
await w.add('crc.txt', new Blob(['123456789']))
const zip = Z.wZipParseEntries(await w.finish().arrayBuffer())
const entry = zip.entries[0]
// 中央目录条目里 CRC 在 +16(相对条目起点)
let crc = null
// 直接扫中央目录找该条目
const eocd = zip.u8.length - 22
let p = zip.dv.getUint32(eocd + 16, true)
for (let i = 0; i < zip.entries.length; i++) {
if (zip.dv.getUint32(p, true) === 0x02014b50) {
const nameLen = zip.dv.getUint16(p + 28, true)
const name = new TextDecoder().decode(zip.u8.subarray(p + 46, p + 46 + nameLen))
if (name === 'crc.txt') { crc = zip.dv.getUint32(p + 16, true); break }
p += 46 + nameLen + zip.dv.getUint16(p + 30, true) + zip.dv.getUint16(p + 32, true)
}
}
assert.strictEqual(crc, 0xCBF43926, 'CRC32("123456789") 应为标准值 0xCBF43926(否则第三方解压工具会报损坏)')
}
// ── 4. DOS 日期时间:能被解析出合理值(不早于 1980,不晚于当前+1 天)─────
{
const w = Z.wCreateStoreZip()
await w.add('t.txt', new Blob(['x']))
const zip = Z.wZipParseEntries(await w.finish().arrayBuffer())
const eocd = zip.u8.length - 22
const p = zip.dv.getUint32(eocd + 16, true)
const dosTime = zip.dv.getUint16(p + 12, true)
const dosDate = zip.dv.getUint16(p + 14, true)
const year = 1980 + ((dosDate >> 9) & 0x7f)
const month = (dosDate >> 5) & 0x0f
const day = dosDate & 0x1f
assert.ok(year >= 1980 && year <= new Date().getFullYear() + 1, 'DOS 年份应在合理范围,实得 ' + year)
assert.ok(month >= 1 && month <= 12, 'DOS 月份应在 1-12,实得 ' + month)
assert.ok(day >= 1 && day <= 31, 'DOS 日期应在 1-31,实得 ' + day)
assert.ok(dosTime >= 0 && dosTime <= 0xffff, 'DOS 时间应是 16 位')
}
// ── 5. wOpenZipBlob:接口对齐原 JSZip 用法(file()/async()/files)────────
{
const w = Z.wCreateStoreZip()
await w.add('a.json', new Blob(['{"k":1}']))
await w.add('dir/b.bin', new Blob([new Uint8Array([9, 8, 7])]))
const z = await Z.wOpenZipBlob(w.finish())
eqJson(Object.keys(z.files).sort(), ['a.json', 'dir/b.bin'], 'files 应含全部条目')
assert.strictEqual(await z.file('a.json').async('string'), '{"k":1}', 'async(string) 应返回文本')
eqBytes(await z.file('dir/b.bin').async('uint8array'), new Uint8Array([9, 8, 7]), 'async(uint8array) 应返回字节')
assert.strictEqual(z.file('nope.txt'), null, '不存在的条目应返回 null(对齐 JSZip)')
}
// ── 6. 非法输入:必须显式报错,不能静默返回空 ──────────────────────────
{
assert.throws(() => Z.wZipParseEntries(new Uint8Array(100).buffer), /不是有效的 ZIP/,
'非 ZIP 字节应抛「不是有效的 ZIP」')
assert.throws(() => Z.wZipParseEntries(new ArrayBuffer(0)), /不是有效的 ZIP/,
'空 buffer 应抛错(不能静默当成功,否则还原会假装完成)')
}
// ── 6b. EOCD 必须从**文件尾部往前**扫描 ────────────────────────────────
// 负例验证发现的缺口:把扫描方向改成「从前往后」时,原有断言**全都不红** ——
// 因为测试用的文件内容里不含 EOCD 签名字节 0x06054b50。
// 但真实备份里完全可能出现这四个字节(图片/JSON 里任何位置)。
// 从前往后扫会在文件内容里**误命中**一个假的 EOCD ⇒ 解析出错。
{
const evil = new Uint8Array([0x50, 0x4b, 0x05, 0x06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
const w = Z.wCreateStoreZip()
await w.add('evil.bin', new Blob([evil]))
await w.add('after.txt', new Blob(['ok']))
const zip = Z.wZipParseEntries(await w.finish().arrayBuffer())
eqJson(zip.entries.map((e) => e.name), ['evil.bin', 'after.txt'],
'文件内容含 EOCD 签名字节时仍应正确解析(必须从尾部往前扫,不能误命中内容里的假签名)')
eqBytes(await Z.wZipReadEntry(zip, zip.entries[0]), evil, '含签名字节的文件内容应完整读回')
}
// ── 6c. 带「扩展字段(extra)」的 ZIP:数据偏移必须算上 extraLen ──────────
// 负例验证发现的缺口:把 `dataAt = lh+30+nameLen+extraLen` 改成漏掉 extraLen,
// 原有断言**全都不红** —— 因为我们自己写的 ZIP 里 extraLen 恒为 0。
// 但用户可能导入**别的工具**生成的 ZIP(macOS 归档 / 老版本 / 第三方打包),
// 那些几乎都带 extra 字段 ⇒ 这条路径必须测。
const buildZipWithExtra = (name, data, extraLen) => {
const enc = new TextEncoder()
const nameBytes = enc.encode(name)
const extra = new Uint8Array(extraLen) // 内容随意,长度才是关键
// CRC32
let c = 0xFFFFFFFF >>> 0
for (const b of data) { c = (c ^ b) >>> 0; for (let k = 0; k < 8; k++) c = (c & 1) ? ((c >>> 1) ^ 0xEDB88320) >>> 0 : (c >>> 1) >>> 0 }
const crc = (c ^ 0xFFFFFFFF) >>> 0
const lhLen = 30 + nameBytes.length + extra.length
const cdLen = 46 + nameBytes.length + extra.length
const total = lhLen + data.length + cdLen + 22
const buf = new Uint8Array(total); const dv = new DataView(buf.buffer)
let o = 0
dv.setUint32(o, 0x04034b50, true); dv.setUint16(o + 4, 20, true); dv.setUint16(o + 6, 0, true); dv.setUint16(o + 8, 0, true)
dv.setUint16(o + 10, 0, true); dv.setUint16(o + 12, 0x21, true)
dv.setUint32(o + 14, crc, true); dv.setUint32(o + 18, data.length, true); dv.setUint32(o + 22, data.length, true)
dv.setUint16(o + 26, nameBytes.length, true); dv.setUint16(o + 28, extra.length, true)
buf.set(nameBytes, o + 30); buf.set(extra, o + 30 + nameBytes.length)
const dataAt = o + lhLen
buf.set(data, dataAt)
const cdAt = dataAt + data.length
dv.setUint32(cdAt, 0x02014b50, true); dv.setUint16(cdAt + 4, 20, true); dv.setUint16(cdAt + 6, 20, true); dv.setUint16(cdAt + 8, 0, true)
dv.setUint16(cdAt + 10, 0, true); dv.setUint16(cdAt + 12, 0, true); dv.setUint16(cdAt + 14, 0x21, true)
dv.setUint32(cdAt + 16, crc, true); dv.setUint32(cdAt + 20, data.length, true); dv.setUint32(cdAt + 24, data.length, true)
dv.setUint16(cdAt + 28, nameBytes.length, true); dv.setUint16(cdAt + 30, extra.length, true); dv.setUint16(cdAt + 32, 0, true)
dv.setUint16(cdAt + 34, 0, true); dv.setUint16(cdAt + 36, 0, true); dv.setUint32(cdAt + 38, 0, true); dv.setUint32(cdAt + 42, 0, true)
buf.set(nameBytes, cdAt + 46); buf.set(extra, cdAt + 46 + nameBytes.length)
const eocdAt = cdAt + cdLen
dv.setUint32(eocdAt, 0x06054b50, true); dv.setUint16(eocdAt + 4, 0, true); dv.setUint16(eocdAt + 6, 0, true)
dv.setUint16(eocdAt + 8, 1, true); dv.setUint16(eocdAt + 10, 1, true)
dv.setUint32(eocdAt + 12, cdLen, true); dv.setUint32(eocdAt + 16, lhLen + data.length, true); dv.setUint16(eocdAt + 20, 0, true)
return buf.buffer
}
{
const data = new Uint8Array([11, 22, 33, 44])
const zip = Z.wZipParseEntries(buildZipWithExtra('extra-test.bin', data, 12))
assert.strictEqual(zip.entries.length, 1, '带 extra 字段的 ZIP 应能解析')
assert.strictEqual(zip.entries[0].name, 'extra-test.bin')
eqBytes(await Z.wZipReadEntry(zip, zip.entries[0]), data,
'带 extra 字段时数据偏移必须算上 extraLen(否则读出的是错位字节 —— 用户导入第三方 ZIP 会拿到错数据)')
}
// ── 7. 空 ZIP(0 条目):已修复(2026-10-28,BACKLOG §3.0)──────────────
// 原缺陷:`if (p + 46 > u8.length) throw` 在算完中央目录偏移后**无条件**执行,
// 没先判 count。空 ZIP 只有 22 字节(仅 EOCD),偏移是 0 ⇒ `0 + 46 > 22` ⇒ 误抛「位置非法」。
// 修法:`if (count > 0 && p + 46 > u8.length) throw` —— 只在有条目时才校验位置。
//
// ⚠️ 修这个洞时**不能顺手把校验去掉**,否则「非空但中央目录损坏」的 ZIP 会静默变成"空备份",
// 那比抛错更糟(用户会以为还原成功)。所以下面同时断言两件事:
// ① 空 ZIP 能解析出 0 条目
// ② 非空但中央目录偏移非法的 ZIP **仍然**抛错
{
const w = Z.wCreateStoreZip()
const emptyZipBuf = await w.finish().arrayBuffer()
assert.strictEqual(emptyZipBuf.byteLength, 22, '空 ZIP 就是 22 字节的 EOCD(结构可核准)')
const emptyZip = Z.wZipParseEntries(emptyZipBuf)
assert.strictEqual(emptyZip.entries.length, 0, '空 ZIP 应解析出 0 个条目(不再抛错)')
// 空 ZIP 打开也应得到空文件表,而不是报错
const opened = await Z.wOpenZipBlob(new Blob([emptyZipBuf]))
eqJson(Object.keys(opened.files), [], '空 ZIP 的 files 应为空对象')
// 关键回归:非空但中央目录位置非法 ⇒ 必须仍抛错(证明校验没被去掉)
const w2 = Z.wCreateStoreZip()
await w2.add('a.json', new Blob(['{}']))
const badBuf = await w2.finish().arrayBuffer()
const badDv = new DataView(badBuf)
const eocdAt = badBuf.byteLength - 22
badDv.setUint32(eocdAt + 16, 999999, true) // 把中央目录偏移改成越界值
assert.throws(() => Z.wZipParseEntries(badBuf), /ZIP 中央目录位置非法/,
'非空但中央目录偏移越界的 ZIP 必须仍然抛错(修空 ZIP 时不能把校验一起去掉)')
}
console.log('storage zip checks passed(往返 + 大文件分片 CRC + 标准 CRC 向量 + DOS 时间 + JSZip 兼容 + 错误路径)')
// ⚠️ 显式退出:否则 vm/Blob 相关句柄可能让事件循环挂着(§13.44 教训)
process.exit(0)
})().catch((e) => {
console.error('storage zip checks FAILED:', e && e.message)
process.exit(1)
})