| 1 | import { createHash } from "node:crypto"; |
| 2 | import { existsSync, realpathSync } from "node:fs"; |
| 3 | import { mkdir, readFile, writeFile } from "node:fs/promises"; |
| 4 | import path from "node:path"; |
| 5 | import { inflateRawSync } from "node:zlib"; |
| 6 | |
| 7 | const archiveLimit = 32 << 20, expandedLimit = 128 << 20; |
| 8 | const windowsName = value => value && !/[\\/:<>"|?*\x00-\x1f]/.test(value) && !/[. ]$/.test(value) && |
| 9 | !/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(value) && ![".", ".."].includes(value); |
| 10 | const decoder = new TextDecoder("utf-8", { fatal: true }); |
| 11 | const crcTable = Uint32Array.from({ length: 256 }, (_, value) => { |
| 12 | for (let bit = 0; bit < 8; bit++) value = (value >>> 1) ^ (value & 1 ? 0xedb88320 : 0); |
| 13 | return value >>> 0; |
| 14 | }); |
| 15 | function crc32(data) { let value = 0xffffffff; for (const byte of data) value = (value >>> 8) ^ crcTable[(value ^ byte) & 255]; return (value ^ 0xffffffff) >>> 0; } |
| 16 | export function nativeExtensionID(value, platform = process.platform) { |
| 17 | const normalized = platform === "win32" ? value.replace(/^[a-z]:/, prefix => prefix.toUpperCase()) : value; |
| 18 | const bytes = Buffer.from(normalized, platform === "win32" ? "utf16le" : "utf8"); |
| 19 | return createHash("sha256").update(bytes).digest("hex").slice(0, 32).replace(/./g, c => String.fromCharCode(97 + parseInt(c, 16))); |
| 20 | } |
| 21 | export function nativeExtensionIDForPath(value) { |
| 22 | let ancestor = path.resolve(value); const suffix = []; |
| 23 | |
| 24 | |
| 25 | |
| 26 | while (!existsSync(ancestor)) { suffix.unshift(path.basename(ancestor)); const parent = path.dirname(ancestor); if (parent === ancestor) throw new Error("扩展目录不可用"); ancestor = parent; } |
| 27 | return nativeExtensionID(path.join(realpathSync(ancestor), ...suffix)); |
| 28 | } |
| 29 | |
| 30 | |
| 31 | |
| 32 | export async function extractWindowsExtensionArchive(archive, directory) { |
| 33 | const bytes = await readFile(archive); |
| 34 | if (bytes.length < 22 || bytes.length > archiveLimit) throw new Error("扩展 ZIP 不能超过 32 MB"); |
| 35 | let end = -1; |
| 36 | for (let i = bytes.length - 22; i >= Math.max(0, bytes.length - 65557); i--) if (bytes.readUInt32LE(i) === 0x06054b50 && i + 22 + bytes.readUInt16LE(i + 20) === bytes.length) { end = i; break; } |
| 37 | if (end < 0 || bytes.readUInt16LE(end + 4) || bytes.readUInt16LE(end + 6)) throw new Error("扩展 ZIP 格式无效"); |
| 38 | const count = bytes.readUInt16LE(end + 10), centralSize = bytes.readUInt32LE(end + 12), central = bytes.readUInt32LE(end + 16); |
| 39 | if (count > 3000 || count !== bytes.readUInt16LE(end + 8) || central + centralSize !== end) throw new Error("扩展解压后不能超过 128 MB 或 3000 个文件"); |
| 40 | const entries = [], seen = new Set(); let offset = central, expanded = 0; |
| 41 | for (let index = 0; index < count; index++) { |
| 42 | if (offset + 46 > end || bytes.readUInt32LE(offset) !== 0x02014b50) throw new Error("扩展 ZIP 格式无效"); |
| 43 | const flags = bytes.readUInt16LE(offset + 8), method = bytes.readUInt16LE(offset + 10), crc = bytes.readUInt32LE(offset + 16); |
| 44 | const compressed = bytes.readUInt32LE(offset + 20), size = bytes.readUInt32LE(offset + 24), nameSize = bytes.readUInt16LE(offset + 28); |
| 45 | const extra = bytes.readUInt16LE(offset + 30), comment = bytes.readUInt16LE(offset + 32), attributes = bytes.readUInt32LE(offset + 38), local = bytes.readUInt32LE(offset + 42); |
| 46 | if (offset + 46 + nameSize + extra + comment > end || flags & 1 || ((attributes >>> 16) & 0xf000) === 0xa000 || ![0, 8].includes(method)) throw new Error("扩展包不能包含符号链接、加密文件或不支持的压缩格式"); |
| 47 | const rawName = bytes.subarray(offset + 46, offset + 46 + nameSize), name = decoder.decode(rawName); |
| 48 | const components = name.replace(/\/$/, "").split("/"); |
| 49 | if (!components.length || components.some(part => !windowsName(part) || Buffer.byteLength(part) > 255) || seen.has(name.toLowerCase())) throw new Error("扩展包包含不安全或重复的文件路径"); |
| 50 | seen.add(name.toLowerCase()); expanded += size; |
| 51 | if (size > archiveLimit || expanded > expandedLimit) throw new Error("扩展解压后不能超过 128 MB,单个文件不能超过 32 MB"); |
| 52 | if (local + 30 > central || bytes.readUInt32LE(local) !== 0x04034b50 || bytes.readUInt16LE(local + 8) !== method || bytes.readUInt16LE(local + 6) !== flags) throw new Error("扩展 ZIP 文件头无效"); |
| 53 | const localName = bytes.readUInt16LE(local + 26), localExtra = bytes.readUInt16LE(local + 28), start = local + 30 + localName + localExtra; |
| 54 | if (!bytes.subarray(local + 30, local + 30 + localName).equals(rawName) || start + compressed > central) throw new Error("扩展 ZIP 文件头无效"); |
| 55 | entries.push({ name, size, compressed, method, crc, start, directory: name.endsWith("/") }); offset += 46 + nameSize + extra + comment; |
| 56 | } |
| 57 | if (offset !== end) throw new Error("扩展 ZIP 目录无效"); |
| 58 | for (const entry of entries) { |
| 59 | const output = path.join(directory, ...entry.name.split("/")); |
| 60 | if (entry.directory) { await mkdir(output, { recursive: true, mode: 0o700 }); continue; } |
| 61 | const encoded = bytes.subarray(entry.start, entry.start + entry.compressed); |
| 62 | const data = entry.method === 0 ? encoded : inflateRawSync(encoded, { maxOutputLength: archiveLimit }); |
| 63 | if (data.length !== entry.size || crc32(data) !== entry.crc) throw new Error("扩展 ZIP 文件内容校验失败"); |
| 64 | await mkdir(path.dirname(output), { recursive: true, mode: 0o700 }); await writeFile(output, data, { flag: "wx", mode: 0o600 }); |
| 65 | } |
| 66 | let relative = "", manifestPath = path.join(directory, "manifest.json"); |
| 67 | if (!entries.some(e => e.name === "manifest.json")) { |
| 68 | const matches = entries.filter(e => /^[^/]+\/manifest\.json$/.test(e.name)); |
| 69 | if (matches.length !== 1) throw new Error("扩展包需要在根目录或单层文件夹内包含 manifest.json"); |
| 70 | relative = matches[0].name.split("/")[0]; manifestPath = path.join(directory, relative, "manifest.json"); |
| 71 | } |
| 72 | const manifestBytes = await readFile(manifestPath); |
| 73 | if (manifestBytes.length > 1 << 20) throw new Error("扩展配置过大"); |
| 74 | const manifest = JSON.parse(decoder.decode(manifestBytes).replace(/^\uFEFF/, "")); |
| 75 | if (manifest.manifest_version !== 3 || typeof manifest.name !== "string" || !manifest.name || typeof manifest.version !== "string" || !manifest.version) throw new Error("扩展需要 Manifest V3、名称和版本"); |
| 76 | if (/^[A-Za-z0-9_-]{1,32}$/.test(manifest.default_locale || "")) { |
| 77 | try { |
| 78 | const messages = await readFile(path.join(path.dirname(manifestPath), "_locales", manifest.default_locale, "messages.json")); |
| 79 | if (messages.length < 1 << 20) { |
| 80 | const values = JSON.parse(decoder.decode(messages).replace(/^\uFEFF/, "")); |
| 81 | for (const field of ["name", "description"]) { const match = /^__MSG_(.*)__$/.exec(manifest[field]); if (match && typeof values[match[1]]?.message === "string") manifest[field] = values[match[1]].message; } |
| 82 | } |
| 83 | } catch { } |
| 84 | } |
| 85 | const permissions = manifest.permissions || [], declaredHosts = manifest.host_permissions || []; |
| 86 | if (!Array.isArray(declaredHosts)) throw new Error("扩展权限声明无效"); |
| 87 | const hosts = [...declaredHosts]; |
| 88 | if (!Array.isArray(manifest.content_scripts || [])) throw new Error("扩展权限声明无效"); |
| 89 | for (const script of manifest.content_scripts || []) { if (!Array.isArray(script.matches || [])) throw new Error("扩展权限声明无效"); hosts.push(...(script.matches || [])); } |
| 90 | if (![permissions, hosts].every(items => Array.isArray(items) && items.length <= 300 && items.every(value => typeof value === "string" && value.length <= 2048))) throw new Error("扩展权限声明无效"); |
| 91 | return { relative: relative || ".", name: manifest.name.slice(0, 200), version: manifest.version.slice(0, 100), description: String(manifest.description || "").slice(0, 1000), key: String(manifest.key || "").slice(0, 8192), permissions: [...new Set(permissions)], hostPermissions: [...new Set(hosts)] }; |
| 92 | } |