| 1 | import { mkdirSync, readFileSync, writeFileSync, renameSync, rmSync } from 'node:fs'; |
| 2 | import { join } from 'node:path'; |
| 3 | import { randomUUID, createHash } from 'node:crypto'; |
| 4 | import { execFile } from 'node:child_process'; |
| 5 | import { promisify } from 'node:util'; |
| 6 | import { fileURLToPath } from 'node:url'; |
| 7 | const run = promisify(execFile); |
| 8 | const extensionID = /^[a-p]{32}$/; |
| 9 | const idFor = value => createHash('sha256').update(value).digest('hex').slice(0, 32) |
| 10 | .replace(/./g, char => String.fromCharCode(97 + parseInt(char, 16))); |
| 11 | export const extensionUploadLimit = 32 << 20; |
| 12 | |
| 13 | export class BrowserExtensions { |
| 14 | constructor({ directory, cdp, control, protectedID, extractArchive, idForPath = idFor }) { |
| 15 | this.root = join(directory, 'extensions'); |
| 16 | this.cdp = cdp; this.control = control; this.protectedID = protectedID; |
| 17 | this.idForPath = idForPath; |
| 18 | this.extractArchive = extractArchive || (async (archive, destination) => { |
| 19 | const { stdout } = await run('/usr/bin/python3', [fileURLToPath(new URL('./browser-extension-archive.py', import.meta.url)), archive, destination], { maxBuffer: 1 << 20, timeout: 15000 }); |
| 20 | return JSON.parse(stdout); |
| 21 | }); |
| 22 | this.records = new Map(); this.pending = new Map(); |
| 23 | mkdirSync(join(this.root, 'packages'), { recursive: true, mode: 0o700 }); |
| 24 | rmSync(join(this.root, 'staging'), { recursive: true, force: true }); |
| 25 | mkdirSync(join(this.root, 'staging'), { mode: 0o700 }); |
| 26 | try { |
| 27 | for (const entry of JSON.parse(readFileSync(join(this.root, 'registry.json'), 'utf8'))) { |
| 28 | if (extensionID.test(entry.id) && /^[a-f0-9-]{36}$/.test(entry.package) && |
| 29 | typeof entry.relative === 'string' && entry.relative !== '..' && /^[^/\\]+$/.test(entry.relative)) |
| 30 | this.records.set(entry.id, entry); |
| 31 | } |
| 32 | } catch {} |
| 33 | } |
| 34 | persist() { |
| 35 | const temporary = join(this.root, 'registry.json.tmp'); |
| 36 | writeFileSync(temporary, JSON.stringify([...this.records.values()]), { mode: 0o600 }); |
| 37 | renameSync(temporary, join(this.root, 'registry.json')); |
| 38 | } |
| 39 | path(entry) { return join(this.root, 'packages', entry.package, entry.relative); } |
| 40 | async management(input) { |
| 41 | const evaluate = async repair => this.cdp('Runtime.evaluate', { |
| 42 | expression: `manageCageExtensions(${JSON.stringify(input)})`, awaitPromise: true, |
| 43 | returnByValue: true, userGesture: true, |
| 44 | }, await this.control(repair), 15000); |
| 45 | let response; |
| 46 | try { response = await evaluate(false); } |
| 47 | catch { response = await evaluate(true); } |
| 48 | if (response.exceptionDetails && /not defined|context|session/i.test(response.exceptionDetails.exception?.description || response.exceptionDetails.text || '')) response = await evaluate(true); |
| 49 | if (response.exceptionDetails || !response.result?.value) throw new Error('扩展操作未完成,请重试或打开 Chromium 扩展管理'); |
| 50 | return response.result.value; |
| 51 | } |
| 52 | async restore() { |
| 53 | for (const entry of this.records.values()) { |
| 54 | if (!entry.enabled) continue; |
| 55 | try { |
| 56 | const { id } = await this.cdp('Extensions.loadUnpacked', { path: this.path(entry) }); |
| 57 | if (id !== entry.id) throw new Error('扩展标识已变化'); |
| 58 | entry.error = ''; |
| 59 | } catch { entry.error = '扩展未能加载,请检查扩展文件或重新安装'; } |
| 60 | } |
| 61 | } |
| 62 | async upload(stream) { |
| 63 | if (this.pending.size >= 4) throw new Error('请先安装或取消之前选择的扩展'); |
| 64 | const token = randomUUID(), directory = join(this.root, 'staging', token), archive = directory + '.zip'; |
| 65 | const chunks = []; let size = 0; |
| 66 | try { |
| 67 | for await (const chunk of stream) { |
| 68 | size += chunk.length; |
| 69 | if (size > extensionUploadLimit) throw new Error('扩展 ZIP 不能超过 32 MB'); |
| 70 | chunks.push(chunk); |
| 71 | } |
| 72 | writeFileSync(archive, Buffer.concat(chunks), { mode: 0o600 }); |
| 73 | mkdirSync(directory, { mode: 0o700 }); |
| 74 | const entry = await this.extractArchive(archive, directory); |
| 75 | this.pending.set(token, { ...entry, directory }); |
| 76 | return { session: token, name: entry.name, version: entry.version, description: entry.description, |
| 77 | permissions: entry.permissions, hostPermissions: entry.hostPermissions }; |
| 78 | } catch (error) { |
| 79 | rmSync(directory, { recursive: true, force: true }); |
| 80 | throw new Error(error.stderr?.trim().split('\n').at(-1)?.replace(/^ValueError: /, '') || error.message); |
| 81 | } finally { rmSync(archive, { force: true }); } |
| 82 | } |
| 83 | async request(input) { |
| 84 | const mode = input.mode || 'list'; |
| 85 | if (mode === 'cancel' || mode === 'install') { |
| 86 | const entry = this.pending.get(input.session); |
| 87 | if (!entry) throw new Error('扩展选择已过期,请重新选择 ZIP'); |
| 88 | if (mode === 'cancel') { |
| 89 | rmSync(entry.directory, { recursive: true, force: true }); this.pending.delete(input.session); |
| 90 | return { ok: true }; |
| 91 | } |
| 92 | const packageID = input.session, directory = join(this.root, 'packages', packageID); |
| 93 | if (input.target && this.records.size && [...this.records.values()].some(item => item.source === input.target)) throw new Error('此本机扩展已经导入'); |
| 94 | const expectedID = entry.key ? idFor(Buffer.from(entry.key, 'base64')) : this.idForPath(join(directory, entry.relative)); |
| 95 | if (expectedID === this.protectedID || this.records.has(expectedID)) throw new Error('此扩展已经安装,请先移除原有版本'); |
| 96 | renameSync(entry.directory, directory); this.pending.delete(input.session); |
| 97 | let id, inserted = false; |
| 98 | try { |
| 99 | if (input.enabled === false) id = expectedID; |
| 100 | else ({ id } = await this.cdp('Extensions.loadUnpacked', { path: join(directory, entry.relative) })); |
| 101 | if (id === this.protectedID || this.records.has(id)) throw new Error('此扩展标识已存在'); |
| 102 | const { directory: unused, key: publicKey, ...metadata } = entry; |
| 103 | this.records.set(id, { ...metadata, id, package: packageID, enabled: input.enabled !== false, |
| 104 | ...(typeof input.target === 'string' && /^[a-f0-9]{32}:[a-p]{32}$/.test(input.target) ? { source: input.target } : {}), |
| 105 | }); |
| 106 | inserted = true; |
| 107 | this.persist(); |
| 108 | } catch (error) { |
| 109 | if (inserted) this.records.delete(id); |
| 110 | if (id && id !== this.protectedID && !this.records.has(id)) await this.cdp('Extensions.uninstall', { id }).catch(() => {}); |
| 111 | rmSync(directory, { recursive: true, force: true }); throw error; |
| 112 | } |
| 113 | return this.request({ mode: 'list' }); |
| 114 | } |
| 115 | if (!['list', 'enable', 'disable', 'remove', 'options'].includes(mode)) throw new Error('扩展操作无效'); |
| 116 | if (mode !== 'list' && (!extensionID.test(input.id || '') || input.id === this.protectedID)) throw new Error('扩展标识无效'); |
| 117 | const record = this.records.get(input.id); |
| 118 | if (mode === 'enable' && record) { |
| 119 | const loaded = await this.cdp('Extensions.loadUnpacked', { path: this.path(record) }); |
| 120 | if (loaded.id !== input.id) { |
| 121 | await this.cdp('Extensions.uninstall', { id: loaded.id }).catch(() => {}); |
| 122 | throw new Error('扩展标识已变化,请重新安装'); |
| 123 | } |
| 124 | } |
| 125 | if (mode === 'remove') { |
| 126 | if (!record) return { native: true, id: input.id }; |
| 127 | const installed = (await this.management({ mode: 'list' })).items.some(item => item.id === input.id); |
| 128 | if (installed) await this.cdp('Extensions.uninstall', { id: input.id }); |
| 129 | this.records.delete(input.id); |
| 130 | try { this.persist(); } catch (error) { this.records.set(input.id, record); throw error; } |
| 131 | rmSync(join(this.root, 'packages', record.package), { recursive: true, force: true }); |
| 132 | } else if (mode !== 'list') { |
| 133 | const result = await this.management({ mode, id: input.id }); |
| 134 | if (mode === 'options') return result; |
| 135 | if (record) { record.enabled = mode === 'enable'; record.error = ''; this.persist(); } |
| 136 | } |
| 137 | const { items } = await this.management({ mode: 'list' }); |
| 138 | const byID = new Map(items.map(item => [item.id, { ...item, managed: this.records.has(item.id) }])); |
| 139 | for (const entry of this.records.values()) { |
| 140 | if (!byID.has(entry.id)) byID.set(entry.id, { ...entry, enabled: false, managed: true, optionsUrl: '' }); |
| 141 | if (entry.source) byID.get(entry.id).source = entry.source; |
| 142 | if (entry.error) byID.get(entry.id).error = entry.error; |
| 143 | } |
| 144 | return { items: [...byID.values()].map(({ directory, package: path, relative, ...entry }) => entry) }; |
| 145 | } |
| 146 | } |