From 116989a091fe3bddadb958788695411d9ccf2676 Mon Sep 17 00:00:00 2001 From: Wxw-Gu <84499436+Wxw-Gu@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:55:00 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=8B=93=E5=B1=95=E4=B8=AD=E5=BF=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 + electron-builder.win.yml | 5 + electron-builder.yml | 6 + .../douyin-sender/background/index.js | 95 +- .../extensions/douyin-sender/manifest.json | 9 +- examples/extensions/douyin-sender/ui/app.js | 22 +- .../keyword-bot/background/index.js | 6 + .../extensions/keyword-bot/lib/matcher.js | 11 + examples/extensions/keyword-bot/manifest.json | 6 +- examples/extensions/template-lock.json | 25 + index.html | 19 + package.json | 18 +- scripts/after-pack.cjs | 55 + scripts/build-extension-templates.cjs | 414 ++++++ .../extensions/extension-action-registry.ts | 30 +- src/main/extensions/extension-code-digest.ts | 124 ++ src/main/extensions/extension-host.ts | 346 ++++- src/main/extensions/extension-installer.ts | 230 ++- src/main/extensions/extension-ipc.ts | 196 +++ src/main/extensions/extension-manager.ts | 1270 +++++++++++++++-- src/main/extensions/extension-paths.ts | 22 +- .../extensions/extension-project-files.ts | 242 ++++ src/main/extensions/extension-protocol.ts | 14 +- src/main/extensions/extension-registry.ts | 459 +++++- .../extensions/extension-root-resolver.ts | 143 ++ src/main/extensions/extension-secret-store.ts | 174 +++ src/main/extensions/extension-service.ts | 26 + src/main/extensions/extension-storage.ts | 266 +++- .../extensions/extension-template-catalog.ts | 407 ++++++ src/main/extensions/host-runtime.ts | 114 +- src/main/index.ts | 14 +- src/preload/index.d.ts | 40 + src/preload/index.ts | 62 + src/renderer/src/App.tsx | 27 +- .../automation/AutomationWorkspace.tsx | 134 +- .../automation/ExtensionActionList.tsx | 216 +++ .../features/automation/RuleEditorPanel.tsx | 75 +- .../src/features/automation/RuleListPanel.tsx | 135 +- .../extensions/CreateProjectDialog.tsx | 85 ++ .../features/extensions/DevelopmentGuide.tsx | 135 ++ .../extensions/ExtensionTemplateGallery.tsx | 230 +++ .../extensions/ExtensionWorkspace.tsx | 647 ++++++++- src/renderer/src/styles/automation.scss | 31 + src/renderer/src/styles/extensions.scss | 433 ++++++ src/shared/automation.ts | 34 +- src/shared/extensions/action-schema.ts | 272 ++++ src/shared/extensions/errors.ts | 19 +- src/shared/extensions/ipc.ts | 19 + src/shared/extensions/permissions.ts | 9 +- src/shared/extensions/rpc.ts | 40 +- src/shared/extensions/source.ts | 25 + src/shared/extensions/templates.ts | 58 + src/shared/extensions/types.ts | 96 +- .../automation-rule-templates.test.tsx | 141 ++ .../extension-template-gallery.test.tsx | 151 ++ .../extension-workspace-deeplink.test.tsx | 154 ++ .../extension-workspace-health.test.tsx | 162 +++ .../integration/extension-development.test.ts | 383 +++++ tests/integration/extension-lifecycle.test.ts | 25 +- .../integration/extension-m4-runtime.test.ts | 337 +++++ tests/integration/extension-project.test.ts | 421 ++++++ .../extension-runtime-storage.test.ts | 314 ++++ .../extension-template-install.test.ts | 298 ++++ .../extension-templates-packaged.test.ts | 58 + .../extension-upgrade-transaction.test.ts | 469 ++++++ tests/unit/bootstrap-cache.test.ts | 72 +- tests/unit/extension-host-process.test.ts | 293 ++++ tests/unit/extension-host.test.ts | 19 +- tests/unit/extension-installer.test.ts | 184 ++- tests/unit/extension-m4.test.ts | 163 +++ tests/unit/extension-state.test.ts | 393 +++++ tests/unit/extension-template-catalog.test.ts | 189 +++ tests/unit/extension-templates.test.ts | 145 ++ tests/unit/keyword-bot-modes.test.ts | 153 ++ 74 files changed, 11738 insertions(+), 379 deletions(-) create mode 100644 examples/extensions/template-lock.json create mode 100644 index.html create mode 100644 scripts/build-extension-templates.cjs create mode 100644 src/main/extensions/extension-code-digest.ts create mode 100644 src/main/extensions/extension-project-files.ts create mode 100644 src/main/extensions/extension-root-resolver.ts create mode 100644 src/main/extensions/extension-secret-store.ts create mode 100644 src/main/extensions/extension-template-catalog.ts create mode 100644 src/renderer/src/features/automation/ExtensionActionList.tsx create mode 100644 src/renderer/src/features/extensions/CreateProjectDialog.tsx create mode 100644 src/renderer/src/features/extensions/DevelopmentGuide.tsx create mode 100644 src/renderer/src/features/extensions/ExtensionTemplateGallery.tsx create mode 100644 src/shared/extensions/action-schema.ts create mode 100644 src/shared/extensions/source.ts create mode 100644 src/shared/extensions/templates.ts create mode 100644 tests/component/automation-rule-templates.test.tsx create mode 100644 tests/component/extension-template-gallery.test.tsx create mode 100644 tests/component/extension-workspace-deeplink.test.tsx create mode 100644 tests/component/extension-workspace-health.test.tsx create mode 100644 tests/integration/extension-development.test.ts create mode 100644 tests/integration/extension-m4-runtime.test.ts create mode 100644 tests/integration/extension-project.test.ts create mode 100644 tests/integration/extension-runtime-storage.test.ts create mode 100644 tests/integration/extension-template-install.test.ts create mode 100644 tests/integration/extension-templates-packaged.test.ts create mode 100644 tests/integration/extension-upgrade-transaction.test.ts create mode 100644 tests/unit/extension-host-process.test.ts create mode 100644 tests/unit/extension-m4.test.ts create mode 100644 tests/unit/extension-template-catalog.test.ts create mode 100644 tests/unit/extension-templates.test.ts create mode 100644 tests/unit/keyword-bot-modes.test.ts diff --git a/.gitignore b/.gitignore index 25fd124..6ea0b95 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,6 @@ debug-originals # 去水印脚本 /examples/extensions/douyin-sender/scripts/douyin.py + +# 官方扩展模板构建产物(由 scripts/build-extension-templates.cjs 生成) +/build/extension-templates/ diff --git a/electron-builder.win.yml b/electron-builder.win.yml index 2f07f2e..510d4cd 100644 --- a/electron-builder.win.yml +++ b/electron-builder.win.yml @@ -39,6 +39,11 @@ extraResources: - runtime/win32/** - wcdb/win32/x64/** - '!wcdb/**/tm-wcdb-config-helper*' + # 官方扩展模板(构建期由 scripts/build-extension-templates.cjs 生成) + - from: build/extension-templates + to: extension-templates + filter: + - '**/*' # 默认不打包helper # - from: resources/wcdb/win32/x64 # to: resources/wcdb/win32/x64 diff --git a/electron-builder.yml b/electron-builder.yml index 5e1352f..13481fc 100644 --- a/electron-builder.yml +++ b/electron-builder.yml @@ -40,6 +40,12 @@ extraResources: to: skill/tracememo-reader filter: - '**/*' + # 官方扩展模板:构建期由 scripts/build-extension-templates.cjs 生成, + # 安装包必须自带,运行时不依赖源码树或网络。 + - from: build/extension-templates + to: extension-templates + filter: + - '**/*' nsis: oneClick: false allowToChangeInstallationDirectory: true diff --git a/examples/extensions/douyin-sender/background/index.js b/examples/extensions/douyin-sender/background/index.js index 9562120..7605708 100644 --- a/examples/extensions/douyin-sender/background/index.js +++ b/examples/extensions/douyin-sender/background/index.js @@ -29,6 +29,8 @@ const execFileAsync = promisify(execFile) const CONFIG_KEY = 'config' const STATS_KEY = 'stats' +/** 安全存储里的 Cookie 键名。 */ +const SECRET_COOKIE_KEY = 'douyinCookie' const PROGRESS_KEY = 'progress' const TEST_RESULT_KEY = 'testResult' const CONFIG_TTL_MS = 1000 @@ -312,23 +314,7 @@ function resolvePythonInvocation(pythonPath, scriptPath, args) { if (process.platform !== 'darwin') { return { file: pythonPath, args: [scriptPath, ...args] } } - let resolvedPython = pythonPath - if (pythonPath === 'python3') { - const venvPython = path.join( - os.homedir(), - 'Library', - 'Caches', - 'douyin-video', - 'venv', - 'bin', - 'python' - ) - try { - if (fsSync.existsSync(venvPython)) resolvedPython = venvPython - } catch { - // 缓存 venv 不可读时退回配置里的 pythonPath。 - } - } + const resolvedPython = pythonPath try { if (fsSync.existsSync('/usr/bin/arch')) { return { @@ -343,10 +329,10 @@ function resolvePythonInvocation(pythonPath, scriptPath, args) { } /** - * 解析可用的抖音 Cookie: - * 1. 优先使用调用方显式传入的 cookieHeader(测试发送 / 测试下载); - * 2. 尝试向宿主读取已保存的 Cookie(若宿主暴露接口); - * 3. 回退读取扩展私有目录或桌面上的 `douyin-cookie` 文件(供 @我自己 自动回复链路使用)。 + * 解析可用的抖音 Cookie。 + * + * 只认两个来源:调用方显式传入的 header,以及扩展私有目录里由用户配置生成的文件。 + * **不扫描桌面**——扩展不该去读用户没有明确交给它的文件。 */ async function resolveCookieHeader(explicitHeader) { const direct = String(explicitHeader || '').trim() @@ -356,25 +342,49 @@ async function resolveCookieHeader(explicitHeader) { const fromHost = String((await tm.douyin.getCookie()) || '').trim() if (fromHost) return fromHost } catch { - // 宿主未提供或读取失败时继续尝试本地文件。 + // 宿主未提供或读取失败时按「未配置」处理。 } } - const candidates = [ - path.join(tm.extension.dataDir, 'douyin-cookie.txt'), - path.join(os.homedir(), 'Desktop', 'douyin-cookie'), - path.join(os.homedir(), 'Desktop', 'douyin-cookie.txt') - ] - for (const file of candidates) { + // 优先用安全存储;未授权或不可用时再退回旧的扩展数据文件(迁移期兼容)。 + if (tm.secrets) { try { - const content = String(await fs.readFile(file, 'utf8')).trim() - if (content) return content + const stored = await tm.secrets.get(SECRET_COOKIE_KEY) + if (stored) return String(stored).trim() } catch { - // 文件不存在或无权限时跳过。 + // 未授予 secrets 权限或系统安全存储不可用:继续走兼容分支。 } } + try { + const content = String(await fs.readFile(path.join(tm.extension.dataDir, 'douyin-cookie.txt'), 'utf8')).trim() + if (content) return content + } catch { + // 未配置 Cookie 时走游客模式。 + } return '' } +/** + * 把旧的明文 Cookie 迁进安全存储,成功后删除明文文件。 + * + * 只在「安全存储可用 + 用户已授权 secrets」时执行;否则保持原样, + * 绝不把加密数据降级成明文,也不谎报迁移成功。 + */ +async function migrateLegacyCookie() { + if (!tm.secrets) return + try { + const existing = await tm.secrets.get(SECRET_COOKIE_KEY) + if (existing) return + const legacyPath = path.join(tm.extension.dataDir, 'douyin-cookie.txt') + const legacy = String(await fs.readFile(legacyPath, 'utf8')).trim() + if (!legacy) return + await tm.secrets.set(SECRET_COOKIE_KEY, legacy) + await fs.unlink(legacyPath).catch(() => undefined) + tm.log.info('已把旧版明文 Cookie 迁入系统安全存储,并删除明文文件') + } catch { + // 未授权或不可用时静默保留旧文件,由页面提示用户重新填写。 + } +} + function resolveScriptPath(value) { const expanded = expandHome(value) if (!expanded) return path.resolve(__dirname, '..', 'scripts', 'douyin.py') @@ -382,6 +392,27 @@ function resolveScriptPath(value) { return path.resolve(__dirname, '..', expanded) } +/** + * 解析脚本不随应用分发(来源与分发许可未确认),缺失时整条视频链路必须停住。 + * 缺失提示只打一次,避免每条消息刷日志。 + */ +let scriptMissingLogged = false + +function ensureScriptReady(config) { + let ready = false + try { + ready = fsSync.existsSync(resolveScriptPath(config.scriptPath)) + } catch { + ready = false + } + if (!ready && !scriptMissingLogged) { + scriptMissingLogged = true + safeLog('warn', '缺少解析脚本 scripts/douyin.py,视频处理已暂停;请按扩展说明自行提供后重启') + } + if (ready) scriptMissingLogged = false + return ready +} + /** 统一封装脚本调用:固定 cwd、超时、输出上限、UTF-8 与 macOS 原生 arm64 执行。 */ async function runPython(args, timeoutMs, config) { // 首次启用时 dataDir 可能还没被创建;execFile 的 cwd 不存在会直接 ENOENT。 @@ -544,6 +575,7 @@ async function reportFailure(event, config, message) { * 进度快照与统计都会落盘;失败原因只保留错误类型,不写 URL / 路径 / 标题。 */ async function processLink(event, config, url, options = {}) { + if (!ensureScriptReady(config)) return const jobId = event.eventId let awemeId = '' let stage = 'accepted' @@ -609,6 +641,7 @@ async function processLink(event, config, url, options = {}) { async function handleEvent(event) { try { const config = await loadConfig() + if (!ensureScriptReady(config)) return const decision = shouldHandle(event, config, cooldownUntil, Date.now()) if (!decision.handle) return diff --git a/examples/extensions/douyin-sender/manifest.json b/examples/extensions/douyin-sender/manifest.json index 59b62ae..fa0bc18 100644 --- a/examples/extensions/douyin-sender/manifest.json +++ b/examples/extensions/douyin-sender/manifest.json @@ -2,12 +2,13 @@ "manifestVersion": 1, "id": "com.example.douyin-sender", "name": "抖音视频搬运", - "version": "1.0.3", + "version": "1.0.5", "apiVersion": "1", "minAppVersion": "2.6.0", - "description": "被 @ 且消息里带抖音分享链接时,解析视频并发送回原会话。", + "description": "被 @ 且消息里带抖音分享链接时,解析视频并发送回原会话。需要本机 Python、Chrome 与解析脚本。", "author": "TraceMemo Examples", "permissions": [ + "secrets", "messages.subscribe", "contacts.list", "wechat.send.video", @@ -19,7 +20,9 @@ "background": "background/index.js" }, "subscriptions": { - "messageTypes": ["text"], + "messageTypes": [ + "text" + ], "conversationIds": [], "requireMentionMe": true, "includeSelf": false diff --git a/examples/extensions/douyin-sender/ui/app.js b/examples/extensions/douyin-sender/ui/app.js index 718aa15..677f55f 100644 --- a/examples/extensions/douyin-sender/ui/app.js +++ b/examples/extensions/douyin-sender/ui/app.js @@ -22,10 +22,7 @@ const ALLOWED_METHODS = new Set([ 'storage.list', 'capabilities.get', 'contacts.listGroups', - 'test.send', - 'douyin.cookie.get', - 'douyin.cookie.set', - 'douyin.cookie.clear', + 'extension.request', 'extension.info' ]) @@ -484,7 +481,7 @@ async function loadConfig() { async function loadCookieState() { try { - const result = await callHost('douyin.cookie.get', {}) + const result = await callHost('extension.request', { method: 'douyinCookie.status', params: {} }) cookieState.textContent = result && result.configured ? '已保存 Cookie(内容不可回显)' : '未配置' } catch { @@ -529,11 +526,9 @@ document.getElementById('test-send').addEventListener('click', async () => { activeTestId = `test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}` setTestResult('已提交,等待后台开始解析…', 'running') try { - const submitted = callHost('test.send', { - id: activeTestId, - to, - text, - at: Date.now() + const submitted = callHost('extension.request', { + method: 'testSend', + params: { id: activeTestId, to, text, at: Date.now() } }) void pollTestResult() await submitted @@ -550,7 +545,10 @@ document.getElementById('cookie-save').addEventListener('click', async () => { return } try { - await callHost('douyin.cookie.set', { cookieHeader: value }) + await callHost('extension.request', { + method: 'douyinCookie.set', + params: { cookieHeader: value } + }) cookieHeader.value = '' await loadCookieState() setStatus('Cookie 已安全保存。', 'ok') @@ -561,7 +559,7 @@ document.getElementById('cookie-save').addEventListener('click', async () => { document.getElementById('cookie-clear').addEventListener('click', async () => { try { - await callHost('douyin.cookie.clear', {}) + await callHost('extension.request', { method: 'douyinCookie.clear', params: {} }) cookieHeader.value = '' await loadCookieState() setStatus('Cookie 已清除。', 'ok') diff --git a/examples/extensions/keyword-bot/background/index.js b/examples/extensions/keyword-bot/background/index.js index 5134d1d..89f6709 100644 --- a/examples/extensions/keyword-bot/background/index.js +++ b/examples/extensions/keyword-bot/background/index.js @@ -149,6 +149,8 @@ function describeError(error) { async function onMessage(event) { try { const config = await loadConfig() + // 交给自动化规则处理时,订阅路径必须彻底闭嘴,否则同一条消息回复两次。 + if (config.executionMode === 'automation') return const now = Date.now() const verdict = shouldReply(event, config, cooldownUntil, now) if (!verdict.reply || !verdict.rule) return @@ -198,6 +200,10 @@ module.exports = function activate(api) { if (!config.enabled) { return { success: false, error: '机器人未启用' } } + // 订阅模式下这条路径同样会发送:直接跳过,避免与事件路径重复回复。 + if (config.executionMode === 'subscribe') { + return { success: true, output: { matched: false, skipped: 'subscribe-mode' } } + } const rule = pickRule(input.text, config) if (!rule) { return { success: true, output: { matched: false } } diff --git a/examples/extensions/keyword-bot/lib/matcher.js b/examples/extensions/keyword-bot/lib/matcher.js index dd3f4e2..32baee6 100644 --- a/examples/extensions/keyword-bot/lib/matcher.js +++ b/examples/extensions/keyword-bot/lib/matcher.js @@ -20,6 +20,15 @@ const MAX_GROUPS = 200 const MODES = new Set(['contains', 'exact', 'prefix']) +/** + * 两条回复入口的执行模式。 + * + * 同一条消息若同时被「事件订阅」和「自动化动作」处理,会回复两次。 + * 这里用互斥模式从根上避免:默认保留订阅(兼容旧用户), + * 切到 `automation` 后订阅路径完全不再发送。 + */ +const EXECUTION_MODES = new Set(['subscribe', 'automation']) + /** * 把任意来源的配置规范化为 `configVersion: 2`。 * @@ -49,6 +58,7 @@ function normalizeConfig(raw) { return { configVersion: CONFIG_VERSION, enabled: input.enabled === true, + executionMode: EXECUTION_MODES.has(input.executionMode) ? input.executionMode : 'subscribe', rules, scope: { groups: Array.isArray(scope.groups) @@ -204,6 +214,7 @@ function clampNumber(value, min, max) { module.exports = { CONFIG_VERSION, + EXECUTION_MODES, normalizeConfig, matchRule, pickRule, diff --git a/examples/extensions/keyword-bot/manifest.json b/examples/extensions/keyword-bot/manifest.json index af423ce..3072042 100644 --- a/examples/extensions/keyword-bot/manifest.json +++ b/examples/extensions/keyword-bot/manifest.json @@ -2,7 +2,7 @@ "manifestVersion": 1, "id": "com.example.keyword-bot", "name": "关键词回复机器人", - "version": "1.0.0", + "version": "1.0.1", "apiVersion": "1", "minAppVersion": "2.6.0", "description": "监听微信文本消息,命中关键词后经 TraceMemo Gateway 回复。", @@ -19,7 +19,9 @@ "background": "background/index.js" }, "subscriptions": { - "messageTypes": ["text"], + "messageTypes": [ + "text" + ], "conversationIds": [], "requireMentionMe": false, "includeSelf": false diff --git a/examples/extensions/template-lock.json b/examples/extensions/template-lock.json new file mode 100644 index 0000000..85ff745 --- /dev/null +++ b/examples/extensions/template-lock.json @@ -0,0 +1,25 @@ +{ + "version": 1, + "templates": { + "douyin-sender@1.0.3": { + "sha256": "01cd4b1a7af2b9e0208145b64e487af2a17f354ab7344f32cf9ff7565deb11a6", + "bytes": 32839 + }, + "douyin-sender@1.0.4": { + "sha256": "4fd4a478232d6b52a68187d2e0c3f42733acda1e65ce9f9594f99440e6edd3e5", + "bytes": 32981 + }, + "douyin-sender@1.0.5": { + "sha256": "d33559d6620ca173c97a19aafc8570521bf6426f6420e6fb8f90923333b554c8", + "bytes": 33471 + }, + "keyword-bot@1.0.0": { + "sha256": "3d8e5453e7ae6de7e29c16eb3c9e718a98bae27e9ed2edfd10399fb158e1c87d", + "bytes": 19121 + }, + "keyword-bot@1.0.1": { + "sha256": "ae379a10dac553b60cc8c823186734d917b604b6dff27e2e7d2d62f5cf5e4d41", + "bytes": 19517 + } + } +} diff --git a/index.html b/index.html new file mode 100644 index 0000000..fed8462 --- /dev/null +++ b/index.html @@ -0,0 +1,19 @@ + + + + + TraceMemo(迹忆) + + + + + + + + +
+ + diff --git a/package.json b/package.json index 2091366..4fcdf59 100644 --- a/package.json +++ b/package.json @@ -60,20 +60,22 @@ "build": "npm run typecheck && electron-vite build", "postinstall": "electron-builder install-app-deps && node scripts/prepare-electron-runtime.cjs && node scripts/ensure-electron-binary.cjs", "build:unpack": "npm run build && electron-builder --config electron-builder.yml --dir", - "build:win": "npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64", - "build:mac:arm64": "npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && electron-builder --config electron-builder.yml --mac --arm64", - "build:mac:arm64:send-runtime": "npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && cross-env TM_SEND_RUNTIME_BUILD=1 electron-builder --config electron-builder.send-runtime.yml --mac --arm64", + "build:win": "npm run build:templates && npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64", + "build:mac:arm64": "npm run build:templates && npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && electron-builder --config electron-builder.yml --mac --arm64", + "build:mac:arm64:send-runtime": "npm run build:templates && npm run typecheck && npm run prepare:ffmpeg:mac:arm64 && electron-vite build && cross-env TM_SEND_RUNTIME_BUILD=1 electron-builder --config electron-builder.send-runtime.yml --mac --arm64", "build:mac:public": "node scripts/build-macos-edition.cjs public", "build:mac:native": "node scripts/build-macos-edition.cjs native", - "build:mac:x64": "npm run typecheck && npm run prepare:ffmpeg:mac:x64 && electron-vite build && electron-builder --config electron-builder.yml --mac --x64", + "build:mac:x64": "npm run build:templates && npm run typecheck && npm run prepare:ffmpeg:mac:x64 && electron-vite build && electron-builder --config electron-builder.yml --mac --x64", "release": "npm run release:mac && npm run release:win", "release:mac": "npm run typecheck && electron-vite build && npm run release:mac:arm64 && npm run release:mac:x64", - "release:mac:arm64": "npm run prepare:ffmpeg:mac:arm64 && electron-builder --config electron-builder.yml --mac --arm64 --publish always --config.directories.output=dist/release/mac-arm64", - "release:mac:x64": "npm run prepare:ffmpeg:mac:x64 && electron-builder --config electron-builder.yml --mac --x64 --publish always --config.directories.output=dist/release/mac-x64", - "release:win": "npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64 --publish always", + "release:mac:arm64": "npm run build:templates && npm run prepare:ffmpeg:mac:arm64 && electron-builder --config electron-builder.yml --mac --arm64 --publish always --config.directories.output=dist/release/mac-arm64", + "release:mac:x64": "npm run build:templates && npm run prepare:ffmpeg:mac:x64 && electron-builder --config electron-builder.yml --mac --x64 --publish always --config.directories.output=dist/release/mac-x64", + "release:win": "npm run build:templates && npm run typecheck && npm run prepare:win-runtime && electron-vite build && electron-builder --config electron-builder.win.yml --win --x64 --publish always", "release:beta": "cross-env EP_PRE_RELEASE=true npm run release", "release:stable": "npm run release", - "build:linux": "electron-vite build && electron-builder --config electron-builder.yml --linux" + "build:linux": "electron-vite build && electron-builder --config electron-builder.yml --linux", + "build:templates": "node scripts/build-extension-templates.cjs", + "prebuild": "node scripts/build-extension-templates.cjs" }, "dependencies": { "@electron-toolkit/preload": "^3.0.2", diff --git a/scripts/after-pack.cjs b/scripts/after-pack.cjs index c63faaa..595e6c4 100644 --- a/scripts/after-pack.cjs +++ b/scripts/after-pack.cjs @@ -768,6 +768,60 @@ function enforceSendRuntimeBoundary( return null } + +/** + * 官方模板资源必须随包发布,且索引与 ZIP 的哈希一致。 + * + * 这一层挡的是「打包时忘了跑构建脚本」:没有它,安装包会静默少两个模板, + * 而用户看到的只是空列表。 + */ +function validateExtensionTemplates(runtimeResources) { + const root = path.join(runtimeResources, 'extension-templates') + const indexPath = path.join(root, 'index.json') + if (!existsSync(indexPath)) { + throw new Error( + 'Missing extension templates: ' + + indexPath + + '. Run `node scripts/build-extension-templates.cjs` before packaging.' + ) + } + let index + try { + index = JSON.parse(readFileSync(indexPath, 'utf8')) + } catch (error) { + throw new Error('Invalid extension template index: ' + error.message) + } + if (!index || index.version !== 1 || !Array.isArray(index.templates)) { + throw new Error('Invalid extension template index structure') + } + if (index.templates.length === 0) { + throw new Error('Extension template index is empty') + } + for (const template of index.templates) { + const fileName = String(template.file || '') + if (!fileName || fileName.includes('/') || fileName.includes('\\')) { + throw new Error('Invalid extension template file name: ' + fileName) + } + const zipPath = path.join(root, fileName) + if (!existsSync(zipPath)) { + throw new Error('Missing extension template archive: ' + fileName) + } + const digest = createHash('sha256').update(readFileSync(zipPath)).digest('hex') + if (digest !== template.sha256) { + throw new Error( + 'Extension template checksum mismatch: ' + + fileName + + ' (index=' + + template.sha256 + + ', actual=' + + digest + + ')' + ) + } + } + console.log('[afterPack] extension templates verified: ' + index.templates.length) +} + exports.default = async function afterPack(context) { const runtimeResources = getRuntimeResources(context) const arch = normalizeBuilderArch(context.arch) @@ -782,6 +836,7 @@ exports.default = async function afterPack(context) { } validateAsarRuntimeDependencies(runtimeResources) validateReaderSkillRuntime(runtimeResources) + validateExtensionTemplates(runtimeResources) validateSilkWasmRuntime(runtimeResources) const ffmpegPath = validateFfmpegRuntime(runtimeResources, context.electronPlatformName) validateElectronMainBinary( diff --git a/scripts/build-extension-templates.cjs b/scripts/build-extension-templates.cjs new file mode 100644 index 0000000..b1369da --- /dev/null +++ b/scripts/build-extension-templates.cjs @@ -0,0 +1,414 @@ +#!/usr/bin/env node +/* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/explicit-function-return-type */ +/** + * 把 `examples/extensions` 里的官方模板打成确定性 ZIP,并生成索引。 + * + * 为什么不用 archiver:ZIP 里的时间戳来自文件 mtime,同一份源码在不同机器上 + * 会产出不同字节,索引里的 sha256 就失去「内容是否变化」的意义。 + * 这里手写 ZIP:固定时间戳、固定权限、按路径排序,相同输入必然得到相同哈希。 + * + * 用法: + * node scripts/build-extension-templates.cjs 构建并校验 + * node scripts/build-extension-templates.cjs --update-lock 内容变了但版本未升时强制更新基线 + * node scripts/build-extension-templates.cjs --check 只校验产物是否为最新,不写盘 + */ +const fs = require('node:fs') +const path = require('node:path') +const zlib = require('node:zlib') +const crypto = require('node:crypto') + +const ROOT = path.resolve(__dirname, '..') +const SOURCE_ROOT = path.join(ROOT, 'examples', 'extensions') +const OUTPUT_DIR = path.join(ROOT, 'build', 'extension-templates') +const LOCK_FILE = path.join(SOURCE_ROOT, 'template-lock.json') + +/** + * 官方模板白名单。 + * + * 只有列在这里的目录才会进包;新增模板必须显式登记,避免「仓库里多一个目录 + * 就被静默发布」。 + */ +const TEMPLATE_SPECS = [ + { + id: 'keyword-bot', + dir: 'keyword-bot', + requires: { + python: false, + chrome: false, + externalScript: false + }, + platforms: ['darwin', 'win32'] + }, + { + id: 'douyin-sender', + dir: 'douyin-sender', + requires: { + python: { required: true, minVersion: '3.10', reason: '解析与下载依赖本机 Python 脚本' }, + chrome: { required: true, reason: '解析脚本通过本机 Chrome 读取页面' }, + externalScript: { + required: true, + path: 'scripts/douyin.py', + reason: '解析脚本不随应用分发,需用户自行提供后才能处理视频' + } + }, + platforms: ['darwin', 'win32'] + } +] + +/** 与安装器保持同一套路径规则:任何一段越界或不合法都会让安装失败。 */ +const SAFE_SEGMENT = /^[A-Za-z0-9._@+\- ]+$/ +const RESERVED_SEGMENT = /^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i + +const EXCLUDED_DIRECTORIES = new Set([ + '.git', + '.hg', + '.svn', + 'node_modules', + '__pycache__', + '.venv', + 'venv', + 'tests', + 'coverage' +]) +const EXCLUDED_FILES = new Set(['.DS_Store', 'Thumbs.db']) +/** 即使本机存在也不进包:来源与分发许可未确认,或属于本机私有脚本。 */ +const EXCLUDED_RELATIVE_PATHS = new Set(['scripts/douyin.py']) +const EXCLUDED_EXTENSIONS = new Set(['.pyc', '.log', '.env', '.local']) + +const CRC_TABLE = (() => { + const table = new Uint32Array(256) + for (let index = 0; index < 256; index += 1) { + let value = index + for (let bit = 0; bit < 8; bit += 1) { + value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1 + } + table[index] = value >>> 0 + } + return table +})() + +function crc32(buffer) { + let crc = 0xffffffff + for (const byte of buffer) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8) + return (crc ^ 0xffffffff) >>> 0 +} + +function isSafeRelativePath(value) { + if (typeof value !== 'string' || !value || value.length > 240) return false + if (value.includes('\0')) return false + const segments = value.split('/') + if (segments.length > 10) return false + for (const segment of segments) { + if (!segment || segment === '.' || segment === '..') return false + if (segment.length > 64) return false + if (!SAFE_SEGMENT.test(segment)) return false + if (/[. ]$/.test(segment)) return false + if (RESERVED_SEGMENT.test(segment)) return false + } + return true +} + +/** + * 收集模板文件。 + * + * 返回按路径排序的列表:ZIP 内条目顺序会影响字节,固定顺序是可重复构建的前提。 + */ +function collectTemplateFiles(spec, sourceRoot = SOURCE_ROOT) { + const root = path.join(sourceRoot, spec.dir) + if (!fs.existsSync(root)) { + throw new Error(`模板目录不存在:${spec.dir}`) + } + const files = [] + const walk = (directory, prefix) => { + for (const entry of fs + .readdirSync(directory, { withFileTypes: true }) + .sort((a, b) => a.name.localeCompare(b.name))) { + if (entry.isSymbolicLink()) { + throw new Error(`模板目录不能包含符号链接:${prefix}${entry.name}`) + } + if (entry.isDirectory()) { + if (EXCLUDED_DIRECTORIES.has(entry.name)) continue + walk(path.join(directory, entry.name), `${prefix}${entry.name}/`) + continue + } + if (!entry.isFile()) continue + if (EXCLUDED_FILES.has(entry.name)) continue + if (EXCLUDED_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) continue + const relative = `${prefix}${entry.name}` + if (EXCLUDED_RELATIVE_PATHS.has(relative)) continue + if (!isSafeRelativePath(relative)) { + throw new Error(`模板内文件路径不合法:${spec.dir}/${relative}`) + } + files.push({ path: relative, data: fs.readFileSync(path.join(directory, entry.name)) }) + } + } + walk(root, '') + return files.sort((left, right) => left.path.localeCompare(right.path)) +} + +function validateManifest(spec, files) { + const manifestFile = files.find((file) => file.path === 'manifest.json') + if (!manifestFile) throw new Error(`模板 ${spec.id} 缺少 manifest.json`) + let manifest + try { + manifest = JSON.parse(manifestFile.data.toString('utf8')) + } catch { + throw new Error(`模板 ${spec.id} 的 manifest.json 不是合法 JSON`) + } + const idPattern = + /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?)+$/ + if (manifest.manifestVersion !== 1) throw new Error(`模板 ${spec.id} 的 manifestVersion 必须是 1`) + if (!idPattern.test(String(manifest.id || ''))) { + throw new Error(`模板 ${spec.id} 的 id 不是反向域名格式`) + } + if ( + !/^\d{1,4}\.\d{1,4}\.\d{1,4}(?:-[0-9A-Za-z.-]{1,40})?$/.test(String(manifest.version || '')) + ) { + throw new Error(`模板 ${spec.id} 的 version 不是 x.y.z 格式`) + } + const names = new Set(files.map((file) => file.path)) + const entrypoints = manifest.entrypoints || {} + for (const [key, value] of Object.entries(entrypoints)) { + if (!value) continue + if (!names.has(value)) { + throw new Error(`模板 ${spec.id} 的入口 ${key} 指向不存在的文件:${value}`) + } + } + if (!entrypoints.page && !entrypoints.background) { + throw new Error(`模板 ${spec.id} 至少需要一个页面或后台入口`) + } + return manifest +} + +/** 固定时间戳(1980-01-01 00:00)与权限,保证相同内容得到相同字节。 */ +const DOS_TIME = 0 +const DOS_DATE = 0x21 + +function buildZip(entries) { + const locals = [] + const centrals = [] + let offset = 0 + for (const entry of entries) { + const name = Buffer.from(entry.path, 'utf8') + const data = entry.data + const compressed = zlib.deflateRawSync(data, { level: 9 }) + const checksum = crc32(data) + + const local = Buffer.alloc(30) + local.writeUInt32LE(0x04034b50, 0) + local.writeUInt16LE(20, 4) + local.writeUInt16LE(0x0800, 6) // UTF-8 文件名 + local.writeUInt16LE(8, 8) // deflate + local.writeUInt16LE(DOS_TIME, 10) + local.writeUInt16LE(DOS_DATE, 12) + local.writeUInt32LE(checksum, 14) + local.writeUInt32LE(compressed.length, 18) + local.writeUInt32LE(data.length, 22) + local.writeUInt16LE(name.length, 26) + local.writeUInt16LE(0, 28) + locals.push(local, name, compressed) + + const central = Buffer.alloc(46) + central.writeUInt32LE(0x02014b50, 0) + central.writeUInt16LE(20, 4) + central.writeUInt16LE(20, 6) + central.writeUInt16LE(0x0800, 8) + central.writeUInt16LE(8, 10) + central.writeUInt16LE(DOS_TIME, 12) + central.writeUInt16LE(DOS_DATE, 14) + central.writeUInt32LE(checksum, 16) + central.writeUInt32LE(compressed.length, 20) + central.writeUInt32LE(data.length, 24) + central.writeUInt16LE(name.length, 28) + central.writeUInt16LE(0, 30) + central.writeUInt16LE(0, 32) + central.writeUInt16LE(0, 34) + central.writeUInt16LE(0, 36) + central.writeUInt32LE((0o100644 << 16) >>> 0, 38) + central.writeUInt32LE(offset, 42) + centrals.push(central, name) + + offset += local.length + name.length + compressed.length + } + + const centralBuffer = Buffer.concat(centrals) + const end = Buffer.alloc(22) + end.writeUInt32LE(0x06054b50, 0) + end.writeUInt16LE(entries.length, 8) + end.writeUInt16LE(entries.length, 10) + end.writeUInt32LE(centralBuffer.length, 12) + end.writeUInt32LE(offset, 16) + return Buffer.concat([...locals, centralBuffer, end]) +} + +function sha256(buffer) { + return crypto.createHash('sha256').update(buffer).digest('hex') +} + +function readLock(lockFile = LOCK_FILE) { + try { + const parsed = JSON.parse(fs.readFileSync(lockFile, 'utf8')) + if (!parsed || typeof parsed !== 'object') return { version: 1, templates: {} } + return { version: 1, templates: parsed.templates || {} } + } catch { + return { version: 1, templates: {} } + } +} + +function writeLock(lock, lockFile = LOCK_FILE) { + const sorted = { version: 1, templates: {} } + for (const key of Object.keys(lock.templates).sort()) { + sorted.templates[key] = lock.templates[key] + } + fs.writeFileSync(lockFile, `${JSON.stringify(sorted, null, 2)}\n`, 'utf8') +} + +/** + * 构建入口。 + * + * 返回 `{ templates, warnings }`;校验失败直接抛错,调用方负责中止打包。 + */ +function buildTemplates(options = {}) { + const updateLock = options.updateLock === true + const checkOnly = options.check === true + const sourceRoot = options.sourceRoot || SOURCE_ROOT + const outputDir = options.outputDir || OUTPUT_DIR + const lockFile = options.lockFile || LOCK_FILE + const specs = options.specs || TEMPLATE_SPECS + const lock = readLock(lockFile) + const templates = [] + const warnings = [] + const seenIds = new Set() + const seenTemplateIds = new Set() + + for (const spec of specs) { + if (seenTemplateIds.has(spec.id)) { + throw new Error(`模板 id 重复:${spec.id}`) + } + seenTemplateIds.add(spec.id) + + const files = collectTemplateFiles(spec, sourceRoot) + if (!files.length) throw new Error(`模板 ${spec.id} 没有任何文件`) + const manifest = validateManifest(spec, files) + if (seenIds.has(manifest.id)) { + throw new Error(`模板扩展 id 重复:${manifest.id}`) + } + seenIds.add(manifest.id) + + const zip = buildZip(files) + const digest = sha256(zip) + const fileName = `${spec.id}-${manifest.version}.zip` + const lockKey = `${spec.id}@${manifest.version}` + const previous = lock.templates[lockKey] + + if (previous && previous.sha256 !== digest && !updateLock) { + throw new Error( + `模板 ${spec.id} 的版本仍为 ${manifest.version},但内容已变化。` + + `请升级 manifest.version,或确认后用 --update-lock 更新基线。` + ) + } + if (!previous) { + // 新版本(或首次构建):允许,并把基线更新到当前内容。 + lock.templates[lockKey] = { sha256: digest, bytes: zip.length } + } else if (updateLock) { + lock.templates[lockKey] = { sha256: digest, bytes: zip.length } + } + + // 缺少外部脚本的模板必须显式标记,不能对外宣称开箱即用。 + const externalScript = spec.requires.externalScript + if (externalScript && externalScript.required) { + const present = files.some((file) => file.path === externalScript.path) + if (present) { + warnings.push( + `模板 ${spec.id} 的依赖脚本 ${externalScript.path} 意外进入了发布包,请检查排除规则` + ) + } + } + + templates.push({ + templateId: spec.id, + extensionId: manifest.id, + name: String(manifest.name || spec.id), + version: String(manifest.version), + ...(manifest.description ? { description: String(manifest.description) } : {}), + permissions: Array.isArray(manifest.permissions) ? manifest.permissions : [], + file: fileName, + sha256: digest, + bytes: zip.length, + fileCount: files.length, + platforms: spec.platforms, + requires: spec.requires, + zip + }) + } + + if (!checkOnly) { + fs.mkdirSync(outputDir, { recursive: true }) + // 删掉不属于本次产物的旧 ZIP,避免「旧版本文件还在、索引却指向新版本」。 + const keep = new Set(templates.map((template) => template.file)) + for (const name of fs.readdirSync(outputDir)) { + if (!name.endsWith('.zip')) continue + if (keep.has(name)) continue + fs.unlinkSync(path.join(outputDir, name)) + } + for (const template of templates) { + fs.writeFileSync(path.join(outputDir, template.file), template.zip) + } + const index = { + version: 1, + templates: templates.map((template) => { + const copy = { ...template } + delete copy.zip + return copy + }) + } + fs.writeFileSync( + path.join(outputDir, 'index.json'), + `${JSON.stringify(index, null, 2)}\n`, + 'utf8' + ) + writeLock(lock, lockFile) + } + + return { + templates: templates.map((template) => { + const copy = { ...template } + delete copy.zip + return copy + }), + warnings + } +} + +function main() { + const argv = process.argv.slice(2) + const updateLock = argv.includes('--update-lock') + const checkOnly = argv.includes('--check') + try { + const result = buildTemplates({ updateLock, checkOnly }) + for (const template of result.templates) { + console.log( + `[templates] ${template.templateId} ${template.version} ` + + `${template.fileCount} files ${(template.bytes / 1024).toFixed(1)}KB ${template.sha256.slice(0, 12)}` + ) + } + for (const warning of result.warnings) { + console.error(`[templates] WARN ${warning}`) + } + console.log(`[templates] 输出目录 ${path.relative(ROOT, OUTPUT_DIR)}`) + } catch (error) { + console.error(`[templates] ${error instanceof Error ? error.message : String(error)}`) + process.exit(1) + } +} + +if (require.main === module) main() + +module.exports = { + buildTemplates, + buildZip, + collectTemplateFiles, + TEMPLATE_SPECS, + OUTPUT_DIR, + LOCK_FILE +} diff --git a/src/main/extensions/extension-action-registry.ts b/src/main/extensions/extension-action-registry.ts index b8d6fdf..0bead51 100644 --- a/src/main/extensions/extension-action-registry.ts +++ b/src/main/extensions/extension-action-registry.ts @@ -1,5 +1,6 @@ import type { ExtensionAutomationActionContribution } from '../../shared/extensions/manifest' import type { ExtensionAutomationActionSummary } from '../../shared/extensions/types' +import type { ExtensionActionInputSchema } from '../../shared/extensions/action-schema' export interface RegisteredExtensionAction { extensionId: string @@ -11,6 +12,9 @@ export interface RegisteredExtensionAction { registered: boolean /** manifest 是否声明了它(声明了但没注册 = 扩展代码有问题)。 */ declared: boolean + inputSchema?: ExtensionActionInputSchema + /** Schema 校验失败的原因;有值时动作不可配置。 */ + schemaError?: string } /** @@ -25,7 +29,15 @@ export interface RegisteredExtensionAction { export class ExtensionActionRegistry { private readonly registered = new Map< string, - Map + Map< + string, + { + title: string + description?: string + inputSchema?: ExtensionActionInputSchema + schemaError?: string + } + > >() private readonly declared = new Map< string, @@ -45,7 +57,13 @@ export class ExtensionActionRegistry { setRegistered( extensionId: string, extensionName: string, - actions: Array<{ id: string; title: string; description?: string }> + actions: Array<{ + id: string + title: string + description?: string + inputSchema?: ExtensionActionInputSchema + schemaError?: string + }> ): void { this.names.set(extensionId, extensionName) this.registered.set( @@ -55,7 +73,9 @@ export class ExtensionActionRegistry { action.id, { title: action.title, - ...(action.description ? { description: action.description } : {}) + ...(action.description ? { description: action.description } : {}), + ...(action.inputSchema ? { inputSchema: action.inputSchema } : {}), + ...(action.schemaError ? { schemaError: action.schemaError } : {}) } ]) ) @@ -91,7 +111,9 @@ export class ExtensionActionRegistry { ? { description: runtime?.description || declaredAction?.description } : {}), registered: Boolean(runtime), - declared: Boolean(declaredAction) + declared: Boolean(declaredAction), + ...(runtime?.inputSchema ? { inputSchema: runtime.inputSchema } : {}), + ...(runtime?.schemaError ? { schemaError: runtime.schemaError } : {}) } } diff --git a/src/main/extensions/extension-code-digest.ts b/src/main/extensions/extension-code-digest.ts new file mode 100644 index 0000000..1b1d91a --- /dev/null +++ b/src/main/extensions/extension-code-digest.ts @@ -0,0 +1,124 @@ +import { createHash } from 'node:crypto' +import fs from 'node:fs' +import path from 'node:path' + +/** 与安装器的排除规则保持一致:这些目录不属于扩展产物。 */ +const DEFAULT_IGNORED_DIRECTORIES = new Set([ + '.git', + '.hg', + '.svn', + 'node_modules', + '__pycache__', + '.venv', + 'venv' +]) + +const DEFAULT_IGNORED_FILES = new Set(['.DS_Store', 'Thumbs.db']) +const IGNORED_EXTENSIONS = new Set(['.pyc', '.log']) + +export interface CodeDigestOptions { + ignoreDirectories?: Iterable + ignoreFiles?: Iterable +} + +interface DigestEntry { + path: string + sha256: string +} + +/** + * 计算一个目录的代码指纹。 + * + * 只覆盖**代码与静态资源**:不包含 `extensions-data`、日志或缓存, + * 所以用户改配置不会让指纹变化,改一行 JS 就会。 + * + * 细则: + * - 相对路径参与哈希,因此改名与改内容都能被发现; + * - 文件按路径排序后再累加,结果与遍历顺序无关; + * - 符号链接按链接目标字符串参与哈希,不跟随(避免读到宿主私有文件)。 + */ +export function computeDirectoryDigest(root: string, options: CodeDigestOptions = {}): string { + const ignoreDirectories = new Set([ + ...DEFAULT_IGNORED_DIRECTORIES, + ...(options.ignoreDirectories ?? []) + ]) + const ignoreFiles = new Set([...DEFAULT_IGNORED_FILES, ...(options.ignoreFiles ?? [])]) + const entries: DigestEntry[] = [] + + const walk = (directory: string, prefix: string): void => { + let items: fs.Dirent[] + try { + items = fs.readdirSync(directory, { withFileTypes: true }) + } catch { + return + } + for (const item of items) { + if (item.isDirectory()) { + if (ignoreDirectories.has(item.name)) continue + walk(path.join(directory, item.name), prefix ? `${prefix}/${item.name}` : item.name) + continue + } + if (ignoreFiles.has(item.name)) continue + if (IGNORED_EXTENSIONS.has(path.extname(item.name).toLowerCase())) continue + + const relative = prefix ? `${prefix}/${item.name}` : item.name + const absolute = path.join(directory, item.name) + if (item.isSymbolicLink()) { + try { + const target = fs.readlinkSync(absolute) + entries.push({ + path: relative, + sha256: createHash('sha256').update(`link:${target}`).digest('hex') + }) + } catch { + entries.push({ path: relative, sha256: 'link:unreadable' }) + } + continue + } + if (!item.isFile()) continue + try { + const content = fs.readFileSync(absolute) + entries.push({ + path: relative, + sha256: createHash('sha256').update(content).digest('hex') + }) + } catch { + // 读不到的文件不应让整个指纹失效,但必须留下痕迹。 + entries.push({ path: relative, sha256: 'unreadable' }) + } + } + } + + walk(root, '') + entries.sort((left, right) => left.path.localeCompare(right.path)) + const hash = createHash('sha256') + for (const entry of entries) { + hash.update(`${entry.path}\0${entry.sha256}\n`) + } + return hash.digest('hex') +} + +/** 列出参与指纹的文件数量;用于诊断「是不是把缓存算进去了」。 */ +export function countDigestFiles(root: string): number { + let count = 0 + const walk = (directory: string): void => { + let items: fs.Dirent[] + try { + items = fs.readdirSync(directory, { withFileTypes: true }) + } catch { + return + } + for (const item of items) { + if (item.isDirectory()) { + if (DEFAULT_IGNORED_DIRECTORIES.has(item.name)) continue + walk(path.join(directory, item.name)) + continue + } + if (DEFAULT_IGNORED_FILES.has(item.name)) continue + if (IGNORED_EXTENSIONS.has(path.extname(item.name).toLowerCase())) continue + count += 1 + } + } + walk(root) + return count +} diff --git a/src/main/extensions/extension-host.ts b/src/main/extensions/extension-host.ts index ce24c84..63da182 100644 --- a/src/main/extensions/extension-host.ts +++ b/src/main/extensions/extension-host.ts @@ -1,4 +1,4 @@ -import { fork, type ChildProcess } from 'node:child_process' +import { fork, spawn, type ChildProcess } from 'node:child_process' import { randomUUID } from 'node:crypto' import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors' import type { ExtensionRuntimeSnapshot } from '../../shared/extensions/types' @@ -23,7 +23,12 @@ import { } from '../../shared/extensions/rpc' import type { ExtensionEventEnvelope } from '../../shared/extensions/events' import type { ExtensionCapabilitySnapshot } from '../../shared/extensions/types' +import { + parseActionInputSchema, + type ExtensionActionInputSchema +} from '../../shared/extensions/action-schema' import type { ExtensionStorage } from './extension-storage' +import type { ExtensionSecretStore } from './extension-secret-store' const DEFAULT_ACTIVATE_TIMEOUT_MS = 8_000 const DEFAULT_ACTION_TIMEOUT_MS = 15_000 @@ -33,14 +38,52 @@ const RESTART_BASE_DELAY_MS = 1_000 const EVENT_BUCKET_CAPACITY = 100 const EVENT_REFILL_PER_SECOND = 60 +/** 发出 shutdown 后等待扩展自行退出的时间。 */ +const GRACEFUL_EXIT_MS = 2_500 +/** 结束进程树之后等待 exit 事件的时间。 */ +const FORCE_EXIT_MS = 3_000 + +/** stderr 采样窗口:只把有代表性的片段写进日志,避免日志洪水拖住主进程。 */ +const STDERR_WINDOW_MS = 10_000 +const STDERR_WINDOW_BYTES = 64 * 1024 +const STDERR_WINDOW_ENTRIES = 20 +const STDERR_MAX_CHUNK_CHARS = 400 + +/** + * stderr 里常见的凭据写法。 + * + * 扩展的 stderr 是任意文本,可能包含用户配置的 Cookie / Token; + * 落日志前统一抹掉值,只保留键名。 + */ +const SECRET_ASSIGNMENT = + /\b(cookie|token|authorization|password|passwd|secret|api[_-]?key)\b(\s*[:=]\s*)(?!Bearer\b)([^\s,;"']{4,})/gi +const BEARER_TOKEN = /\bBearer\s+[A-Za-z0-9._~+/-]{8,}=*/gi + +export function redactSecrets(value: string): string { + // 顺序不能反:先抹 `Bearer ` 整体,再按「键=值」处理, + // 否则 `Authorization: Bearer xxx` 会只抹掉 `Bearer`,token 本体留在日志里。 + return String(value ?? '') + .replace(BEARER_TOKEN, 'Bearer ***') + .replace( + SECRET_ASSIGNMENT, + (_match, name: string, separator: string) => `${name}${separator}***` + ) +} + export interface ExtensionHostChild { send(message: unknown): void + /** 终止本扩展的整棵进程树;实现方负责平台差异。 */ kill(): void on(event: 'message', listener: (message: unknown) => void): void on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void on(event: 'error', listener: (error: Error) => void): void once?(event: 'exit', listener: () => void): void readonly pid?: number + /** + * 子进程的 stderr。必须被消费:管道写满会让子进程在 `write` 上阻塞, + * 表现为「扩展还活着但不再响应」。 + */ + readonly stderr?: NodeJS.ReadableStream | null } export interface ExtensionHostSpawnOptions { @@ -55,6 +98,7 @@ export interface ExtensionHostDependencies { dataDir: string permissions: ExtensionPermission[] storage: ExtensionStorage + secrets?: ExtensionSecretStore spawn: (options: ExtensionHostSpawnOptions) => ExtensionHostChild onLog?: (level: 'info' | 'warn' | 'error', message: string) => void onStateChange?: (snapshot: ExtensionRuntimeSnapshot) => void @@ -83,6 +127,10 @@ export interface ExtensionHostDependencies { now?: () => number activateTimeoutMs?: number actionTimeoutMs?: number + /** 覆盖「等扩展自行退出」的时间;生产默认 2.5s。 */ + gracefulExitMs?: number + /** 覆盖「结束进程树后等 exit」的时间;生产默认 3s。 */ + forceExitMs?: number } interface PendingAction { @@ -95,6 +143,9 @@ interface RegisteredAction { id: string title: string description?: string + /** 已校验的参数 Schema;非法时为 undefined 且 `schemaError` 有值。 */ + inputSchema?: ExtensionActionInputSchema + schemaError?: string } interface ActivationWaiter { @@ -133,17 +184,27 @@ export class ExtensionHost { } >() private readonly actions = new Map() + private readonly pendingPageRequests = new Map< + string, + { + resolve: (value: unknown) => void + reject: (error: Error) => void + timer: ReturnType + } + >() private eventTokens = EVENT_BUCKET_CAPACITY private eventTokensAt: number private droppedEvents = 0 private mutedDropLog = false private restartTimestamps: number[] = [] + private stderrWindow = { bytes: 0, entries: 0, dropped: 0, at: 0 } constructor(dependencies: ExtensionHostDependencies) { this.dependencies = dependencies this.storage = dependencies.storage this.now = dependencies.now ?? (() => Date.now()) this.eventTokensAt = this.now() + this.stderrWindow.at = this.now() this.state = { state: 'inactive', since: this.now(), restarts: 0 } } @@ -155,6 +216,51 @@ export class ExtensionHost { return Array.from(this.actions.values()).map((action) => ({ ...action })) } + /** + * 把页面请求转给同扩展的后台处理器。 + * + * 这是唯一入口:页面拿不到 Node,后台必须显式注册 `tm.page.onRequest`。 + * 响应大小与超时都在这里收口,避免页面被一个坏 handler 拖死。 + */ + async requestPage( + method: string, + params: Record, + timeoutMs = 10_000 + ): Promise { + const child = this.child + if (!child) throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE') + const requestId = randomUUID() + return new Promise((resolve, reject) => { + const timer = setTimeout( + () => { + this.pendingPageRequests.delete(requestId) + reject(new ExtensionError('ACTION_TIMEOUT', '页面请求超时')) + }, + Math.max(1_000, timeoutMs) + ) + this.pendingPageRequests.set(requestId, { resolve, reject, timer }) + try { + child.send({ + type: 'page-request', + version: EXTENSION_HOST_PROTOCOL_VERSION, + requestId, + method, + params, + timeoutMs + }) + } catch (error) { + clearTimeout(timer) + this.pendingPageRequests.delete(requestId) + reject( + new ExtensionError( + 'EXTENSION_HOST_UNAVAILABLE', + error instanceof Error ? error.message : '扩展进程不可用' + ) + ) + } + }) + } + async testSend(params: Record): Promise { return this.runTestMessage('test-send', params) } @@ -204,6 +310,13 @@ export class ExtensionHost { return this.activation } + /** + * 停止后台进程。 + * + * 三段式:先请扩展自行退出,超时后结束整棵进程树,再等真实的 exit 事件。 + * 只有收到 exit 才算停止完成——只发信号就返回,会让上层在进程仍占用 + * 文件时去替换扩展目录(Windows 上必然失败,POSIX 上会留下旧代码在跑)。 + */ async stop(): Promise { this.stopping = true if (this.restartTimer) { @@ -216,26 +329,66 @@ export class ExtensionHost { this.failPendingActions(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止')) this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止')) this.actions.clear() - this.setState('inactive') - if (!child) return + if (!child) { + this.setState('inactive') + return + } + try { child.send({ type: 'shutdown', version: EXTENSION_HOST_PROTOCOL_VERSION }) } catch { - // 进程可能已经断开;kill 兜底。 + // 进程可能已经断开;后续按「未退出」处理。 } - await new Promise((resolve) => { - const timer = setTimeout(() => { - try { - child.kill() - } catch { - // ignore - } - resolve() - }, 1_500) - child.once?.('exit', () => { + + if (await this.waitForExit(child, this.dependencies.gracefulExitMs ?? GRACEFUL_EXIT_MS)) { + this.setState('inactive') + return + } + + this.dependencies.onLog?.('warn', '扩展未在预期时间内退出,正在结束进程树') + this.killTree(child) + if (!(await this.waitForExit(child, this.dependencies.forceExitMs ?? FORCE_EXIT_MS))) { + this.dependencies.onLog?.('error', '扩展进程树未能退出,可能有子进程仍在运行') + } + this.setState('inactive') + } + + /** + * 结束扩展进程及其派生进程。 + * + * POSIX 依赖 `fork` 时的 `detached` 建立独立进程组,`kill(-pid)` 一次覆盖整组; + * 组不存在时退化为只杀直接子进程,并记一条降级日志。 + * + * Windows 用 `taskkill /T /F`,且必须**在父进程仍存活时**执行: + * 父进程先退出后,进程树的父子关系消失,`/T` 再也找不到孙进程。 + */ + private killTree(child: ExtensionHostChild): void { + const pid = child.pid + if (!pid) { + try { + child.kill() + } catch { + // ignore + } + return + } + const result = killProcessTree(pid) + if (result !== 'group' && process.platform !== 'win32') { + this.dependencies.onLog?.('warn', '未能结束扩展进程组,已退化为只结束主进程') + } + } + + private waitForExit(child: ExtensionHostChild, timeoutMs: number): Promise { + return new Promise((resolve) => { + let settled = false + const finish = (exited: boolean): void => { + if (settled) return + settled = true clearTimeout(timer) - resolve() - }) + resolve(exited) + } + const timer = setTimeout(() => finish(false), timeoutMs) + child.once?.('exit', () => finish(true)) }) } @@ -398,6 +551,62 @@ export class ExtensionHost { this.dependencies.onLog?.('error', `扩展进程错误:${error.message}`) }) child.on('exit', (code) => this.handleExit(child, code)) + this.consumeStderr(child) + } + + /** + * 消费子进程 stderr。 + * + * 两点必须同时成立:管道始终有人读(否则子进程写满缓冲会阻塞), + * 且进入日志的内容有速率与长度上限(否则一次日志风暴能把主进程拖垮)。 + * 凭据形态的字段在落日志前抹掉值。 + */ + private consumeStderr(child: ExtensionHostChild): void { + const stream = child.stderr + if (!stream || typeof stream.on !== 'function') return + + const onData = (chunk: Buffer | string): void => { + try { + const now = this.now() + if (now - this.stderrWindow.at >= STDERR_WINDOW_MS) { + const dropped = this.stderrWindow.dropped + this.stderrWindow = { bytes: 0, entries: 0, dropped: 0, at: now } + if (dropped > 0) { + this.dependencies.onLog?.('warn', `扩展 stderr 有 ${dropped} 字节省略未记录`) + } + } + const text = redactSecrets(String(chunk)).replace(/\s+/g, ' ').trim() + if (!text) return + const bytes = Buffer.byteLength(text, 'utf8') + if ( + this.stderrWindow.entries >= STDERR_WINDOW_ENTRIES || + this.stderrWindow.bytes + bytes > STDERR_WINDOW_BYTES + ) { + this.stderrWindow.dropped += bytes + return + } + this.stderrWindow.bytes += bytes + this.stderrWindow.entries += 1 + this.dependencies.onLog?.('warn', `[stderr] ${text.slice(0, STDERR_MAX_CHUNK_CHARS)}`) + } catch { + // stderr 处理失败不能影响扩展运行。 + } + } + + const onEnd = (): void => { + if (this.stderrWindow.dropped > 0) { + this.dependencies.onLog?.( + 'warn', + `扩展 stderr 有 ${this.stderrWindow.dropped} 字节省略未记录` + ) + this.stderrWindow.dropped = 0 + } + stream.removeListener?.('data', onData) + stream.removeListener?.('end', onEnd) + } + + stream.on('data', onData) + stream.on('end', onEnd) } private handleExit(child: ExtensionHostChild, code: number | null): void { @@ -450,14 +659,45 @@ export class ExtensionHost { case 'register-action': { const action = message.action if (!action || typeof action.id !== 'string') return + // Schema 不合法的动作仍然登记:界面上要能看到它,并显示具体原因, + // 而不是让它凭空消失。 + let inputSchema: ExtensionActionInputSchema | undefined + let schemaError: string | undefined + if (action.inputSchema !== undefined) { + const parsed = parseActionInputSchema(action.inputSchema) + if (parsed.ok) inputSchema = parsed.schema + else schemaError = parsed.reason + } this.actions.set(action.id, { id: action.id, title: String(action.title || action.id).slice(0, 60), - ...(action.description ? { description: String(action.description).slice(0, 200) } : {}) + ...(action.description ? { description: String(action.description).slice(0, 200) } : {}), + ...(inputSchema ? { inputSchema } : {}), + ...(schemaError ? { schemaError } : {}) }) + if (schemaError) { + this.dependencies.onLog?.( + 'warn', + `动作 ${action.id} 的参数 Schema 不可用:${schemaError}` + ) + } this.dependencies.onActionsChanged?.() return } + case 'page-result': { + const pending = this.pendingPageRequests.get(message.requestId) + if (!pending) return + clearTimeout(pending.timer) + this.pendingPageRequests.delete(message.requestId) + if (message.ok) { + pending.resolve(message.result) + } else { + pending.reject( + new ExtensionError('ACTION_FAILED', message.error?.message || '扩展页面请求失败') + ) + } + return + } case 'log': this.dependencies.onLog?.(message.level, message.message) return @@ -533,6 +773,31 @@ export class ExtensionHost { case 'storage.list': this.requirePermission('storage') return { entries: this.storage.list(extensionId) } + case 'secrets.get': { + this.requirePermission('secrets') + if (!this.dependencies.secrets) throw new ExtensionError('CAPABILITY_UNAVAILABLE') + return this.dependencies.secrets.get(extensionId, String(params.key ?? '')) + } + case 'secrets.set': { + this.requirePermission('secrets') + if (!this.dependencies.secrets) throw new ExtensionError('CAPABILITY_UNAVAILABLE') + this.dependencies.secrets.set( + extensionId, + String(params.key ?? ''), + String(params.value ?? '') + ) + return { ok: true } + } + case 'secrets.delete': { + this.requirePermission('secrets') + if (!this.dependencies.secrets) throw new ExtensionError('CAPABILITY_UNAVAILABLE') + return { removed: this.dependencies.secrets.delete(extensionId, String(params.key ?? '')) } + } + case 'secrets.has': { + this.requirePermission('secrets') + if (!this.dependencies.secrets) throw new ExtensionError('CAPABILITY_UNAVAILABLE') + return this.dependencies.secrets.has(extensionId, String(params.key ?? '')) + } case 'messages.query': { this.requirePermission('messages.query') if (!this.dependencies.queryMessages) throw new ExtensionError('CAPABILITY_UNAVAILABLE') @@ -642,6 +907,49 @@ export class ExtensionHost { } } +/** + * 结束 `pid` 对应的进程树。 + * + * 返回值表示实际使用的手段: + * - `group`:POSIX 进程组,覆盖扩展派生的全部子进程; + * - `taskkill`:Windows 进程树,必须在父进程仍存活时调用; + * - `fallback`:只能结束进程本身,调用方应记录降级。 + */ +export function killProcessTree( + pid: number | undefined, + options: { platform?: NodeJS.Platform; signal?: NodeJS.Signals } = {} +): 'group' | 'taskkill' | 'fallback' { + if (!pid) return 'fallback' + const platform = options.platform ?? process.platform + const signal = options.signal ?? 'SIGKILL' + + if (platform === 'win32') { + try { + const killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], { + windowsHide: true, + stdio: 'ignore' + }) + killer.on('error', () => undefined) + killer.unref?.() + return 'taskkill' + } catch { + return 'fallback' + } + } + + try { + process.kill(-pid, signal) + return 'group' + } catch { + try { + process.kill(pid, signal) + } catch { + // 进程已经退出。 + } + return 'fallback' + } +} + /** 真实子进程:`ELECTRON_RUN_AS_NODE` 让 Electron 二进制以 Node 模式运行。 */ export function forkExtensionHost( scriptPath: string @@ -650,6 +958,9 @@ export function forkExtensionHost( const child: ChildProcess = fork(scriptPath, [], { stdio: ['ignore', 'ignore', 'pipe', 'ipc'], serialization: 'advanced', + // POSIX 上建立独立进程组,停止时才能一次覆盖扩展派生的子进程。 + // Windows 用 taskkill /T,不需要(也不支持)detached。 + detached: process.platform !== 'win32', env: { ...process.env, ELECTRON_RUN_AS_NODE: '1', @@ -671,6 +982,7 @@ export function forkExtensionHost( once: (event, listener) => { child.once(event, listener) }, + stderr: child.stderr, ...(child.pid ? { pid: child.pid } : {}) } } diff --git a/src/main/extensions/extension-installer.ts b/src/main/extensions/extension-installer.ts index b1d137d..f5614d3 100644 --- a/src/main/extensions/extension-installer.ts +++ b/src/main/extensions/extension-installer.ts @@ -1,4 +1,5 @@ import { promises as fs } from 'node:fs' +import * as nodeFs from 'node:fs' import path from 'node:path' import { Open } from 'unzipper' import { ExtensionError } from '../../shared/extensions/errors' @@ -9,23 +10,61 @@ import { } from '../../shared/extensions/manifest' import type { ExtensionRegistry, ExtensionRegistryRecord } from './extension-registry' import { isPathInside, type ExtensionPaths } from './extension-paths' +import type { ExtensionSource } from '../../shared/extensions/source' +import { computeDirectoryDigest } from './extension-code-digest' const MAX_FILES = 2_000 const MAX_TOTAL_BYTES = 50 * 1024 * 1024 const MAX_FILE_BYTES = 20 * 1024 * 1024 const MAX_PACKAGE_BYTES = 100 * 1024 * 1024 +/** 从「文件夹安装」时跳过的目录名;与打包脚本的白名单保持同一套判断。 */ +const EXCLUDED_SOURCE_DIRECTORIES = new Set([ + '.git', + '.hg', + '.svn', + 'node_modules', + '__pycache__', + '.venv', + 'venv' +]) + export interface InstallOptions { /** 应用版本,用于 `minAppVersion` 兼容检查。 */ appVersion: string - source?: 'directory' | 'package' + source?: ExtensionSource + /** 模板安装时由可信入口填入;普通 ZIP/目录安装不得携带。 */ + template?: { id: string; version: string } + /** + * 代码被替换之前的最后一步:用于停止旧的 Host。 + * + * 抛错表示「不能安全替换」,安装整体中止,磁盘保持原样。 + */ + beforeReplace?: ( + manifest: ExtensionManifest, + previous: ExtensionRegistryRecord | undefined + ) => Promise } export interface InstallOutcome { manifest: ExtensionManifest installPath: string previousVersion?: string + /** 安装前的 Registry 记录;首次安装时为 undefined。 */ + previousRecord?: ExtensionRegistryRecord upgraded: boolean + /** + * 把磁盘与 Registry 一起恢复到本次安装之前。 + * + * 只在新版本启动失败时调用;调用后 `cleanup` 失效。 + */ + rollback: () => Promise + /** + * 删除旧版本的过渡备份。 + * + * 新版本确认可用后调用;调用后 `rollback` 失效。 + */ + cleanup: () => Promise } export interface ExtensionInstallerDependencies { @@ -71,7 +110,7 @@ export class ExtensionInstaller { await fs.mkdir(staging, { recursive: true }) try { await copyTree(root, staging, entries) - return await this.finalize(staging, manifest, options.source ?? 'directory') + return await this.finalize(staging, manifest, options.source ?? 'directory', options) } finally { await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined) } @@ -174,7 +213,7 @@ export class ExtensionInstaller { ) } } - return await this.finalize(staging, manifest, 'package') + return await this.finalize(staging, manifest, options.source ?? 'package', options) } finally { await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined) } @@ -192,13 +231,20 @@ export class ExtensionInstaller { throw new ExtensionError('EXTENSION_INVALID_PATH', '扩展安装路径越界') } const trash = `${target}.removed-${this.now()}` + // lstat 不跟随符号链接:目标断链时也要把链接本身清掉,否则会留下悬空目录项。 const exists = await fs - .stat(target) + .lstat(target) .then(() => true) .catch(() => false) if (exists) { await fs.rename(target, trash) - await fs.rm(trash, { recursive: true, force: true }).catch(() => undefined) + const trashStat = await fs.lstat(trash).catch(() => null) + if (trashStat?.isSymbolicLink()) { + // 只删链接本身;递归删除可能跟随链接进入用户自己的目录。 + await fs.unlink(trash).catch(() => undefined) + } else { + await fs.rm(trash, { recursive: true, force: true }).catch(() => undefined) + } } if (!options.keepData) { await fs @@ -255,6 +301,9 @@ export class ExtensionInstaller { const walk = async (directory: string, prefix: string): Promise => { const items = await fs.readdir(directory, { withFileTypes: true }) for (const item of items) { + // 版本库与依赖目录不属于扩展产物:复制它们既超体积上限, + // 也会把提交历史带进用户数据目录。 + if (item.isDirectory() && EXCLUDED_SOURCE_DIRECTORIES.has(item.name)) continue const relativePath = prefix ? `${prefix}/${item.name}` : item.name if (!isSafeRelativeEntryPath(relativePath)) { throw new ExtensionError('EXTENSION_INVALID_PATH', `文件名不受支持:${relativePath}`) @@ -292,11 +341,24 @@ export class ExtensionInstaller { return entries } - /** 临时目录 → 目标目录的原子替换。升级时保留 registry 里的启用状态与授权。 */ + /** + * 临时目录 → 目标目录的原子替换。升级时保留 registry 里的启用状态与授权。 + * + * 事务边界(只覆盖「同一文件系统内的目录改名 + 一次 JSON 写入」): + * - 改名前先停旧 Host:Windows 上被进程占用的目录无法改名,且旧进程 + * 继续运行会读到已被替换的代码。 + * - 旧目录保留为 `.backup-`,由调用方在新版本确认可用后清理; + * 启动失败时用 `rollback()` 换回来。 + * - Registry 写入失败时当场回滚目录,不把「代码已换、状态未换」留给上层。 + * + * 不保证跨进程的强原子性:如果进程在 rename 之后、Registry 写入之前被杀, + * 磁盘上是新代码配旧记录;下次启动会以 manifest 为准做兼容性检查。 + */ private async finalize( staging: string, manifest: ExtensionManifest, - source: 'directory' | 'package' + source: ExtensionSource, + options: InstallOptions ): Promise { const target = this.paths.installDir(manifest.id) if (!isPathInside(this.paths.extensionsDir, target)) { @@ -311,6 +373,9 @@ export class ExtensionInstaller { .then(() => true) .catch(() => false) + // 旧 Host 必须在代码被替换之前停下;这一步失败则不触碰磁盘。 + await options.beforeReplace?.(manifest, existingRecord) + if (targetExists) await fs.rename(target, backup) try { await fs.rename(staging, target) @@ -321,7 +386,6 @@ export class ExtensionInstaller { error instanceof Error ? error.message : '安装目录替换失败' ) } - if (targetExists) await fs.rm(backup, { recursive: true, force: true }).catch(() => undefined) const timestamp = this.now() const record: ExtensionRegistryRecord = { @@ -330,20 +394,162 @@ export class ExtensionInstaller { apiVersion: manifest.apiVersion, // 升级不改变启用状态:升级后突然开始跑代码是用户没有同意的行为变化。 enabled: existingRecord?.enabled ?? false, - grantedPermissions: existingRecord?.grantedPermissions ?? [], + // 只保留新 manifest 仍声明的授权:被删掉的权限必须立刻失效。 + grantedPermissions: (existingRecord?.grantedPermissions ?? []).filter((permission) => + manifest.permissions.includes(permission) + ), installedAt: existingRecord?.installedAt ?? timestamp, updatedAt: timestamp, - source + source, + // 安装完成后立刻记录基线:之后判断「用户改没改」全靠它。 + installedCodeDigest: computeDirectoryDigest(target), + ...(options.template + ? { templateId: options.template.id, templateVersion: options.template.version } + : existingRecord?.templateId + ? { + templateId: existingRecord.templateId, + ...(existingRecord.templateVersion + ? { templateVersion: existingRecord.templateVersion } + : {}) + } + : {}) } - this.registry.upsert(record) + try { + this.registry.upsert(record) + } catch (error) { + // 代码已经换进去了,但状态没写成:必须把磁盘也退回去,否则用户会看到 + // 「旧版本号 + 新代码」。新目录直接删除,内容仍在安装源里。 + await fs.rm(target, { recursive: true, force: true }).catch(() => undefined) + if (targetExists) await fs.rename(backup, target).catch(() => undefined) + if (existingRecord) { + await Promise.resolve(this.registry.upsert(existingRecord)).catch(() => undefined) + } + throw new ExtensionError( + 'EXTENSION_INSTALL_FAILED', + error instanceof Error + ? `扩展状态写入失败,已回滚:${error.message}` + : '扩展状态写入失败,已回滚' + ) + } + + let settled = false return { manifest, installPath: target, + previousRecord: existingRecord, ...(existingRecord ? { previousVersion: existingRecord.version } : {}), - upgraded: Boolean(existingRecord) + upgraded: Boolean(existingRecord), + rollback: async () => { + if (settled) { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', '该安装结果已完成清理,无法回滚') + } + settled = true + await fs.rm(target, { recursive: true, force: true }).catch(() => undefined) + if (targetExists) await fs.rename(backup, target).catch(() => undefined) + if (existingRecord) this.registry.upsert(existingRecord) + else this.registry.remove(manifest.id) + }, + cleanup: async () => { + if (settled) return + settled = true + if (targetExists) { + await fs.rm(backup, { recursive: true, force: true }).catch(() => undefined) + } + } } } + + /** + * 把最近一次升级留下的过渡备份换回原位。 + * + * 只在「新代码启动失败或状态不一致」时由用户显式触发;备份目录本身不删除, + * 换回来的旧目录会被移到 `.failed-` 后清理,留下的是可运行的旧版本。 + */ + async restoreLatestBackup( + extensionId: string + ): Promise<{ restored: boolean; manifest?: ExtensionManifest }> { + const target = this.paths.installDir(extensionId) + if (!isPathInside(this.paths.extensionsDir, target)) { + throw new ExtensionError('EXTENSION_INVALID_PATH', '扩展安装路径越界') + } + let backups: string[] = [] + try { + backups = (await fs.readdir(this.paths.extensionsDir)) + .filter((name) => name.startsWith(`${extensionId}.backup-`)) + .sort() + } catch { + return { restored: false } + } + if (!backups.length) return { restored: false } + + const latest = path.join(this.paths.extensionsDir, backups[backups.length - 1]) + // 空 appVersion = 跳过兼容性拦截:用户要的是「回到能跑的那个版本」。 + const manifest = await this.readManifest(latest, '') + const failed = `${target}.failed-${this.now()}` + const targetExists = await fs + .lstat(target) + .then(() => true) + .catch(() => false) + if (targetExists) await fs.rename(target, failed) + try { + await fs.rename(latest, target) + } catch (error) { + if (targetExists) await fs.rename(failed, target).catch(() => undefined) + throw new ExtensionError( + 'EXTENSION_INSTALL_FAILED', + error instanceof Error ? error.message : '恢复备份失败' + ) + } + if (targetExists) { + await fs.rm(failed, { recursive: true, force: true }).catch(() => undefined) + } + return { restored: true, manifest } + } + + /** + * 扫描已安装目录,重建最小 Registry 记录。 + * + * 只读取 manifest 的**身份字段**,不继承启用状态与授权:磁盘上有代码, + * 不等于用户同意运行它。manifest 无法解析的目录被跳过。 + * + * 同步实现:Registry 的加载是同步的,恢复入口不能引入异步间隙。 + */ + recoverFromDisk(): ExtensionRegistryRecord[] { + const records: ExtensionRegistryRecord[] = [] + let entries: nodeFs.Dirent[] = [] + try { + entries = nodeFs.readdirSync(this.paths.extensionsDir, { withFileTypes: true }) + } catch { + return records + } + for (const entry of entries) { + if (!entry.isDirectory()) continue + if (entry.name.includes('.backup-') || entry.name.includes('.removed')) continue + const root = path.join(this.paths.extensionsDir, entry.name) + try { + const raw = JSON.parse( + nodeFs.readFileSync(path.join(root, 'manifest.json'), 'utf8') + ) as unknown + const parsed = parseExtensionManifest(raw) + if (!parsed.ok || !parsed.manifest) continue + const stat = nodeFs.statSync(root) + records.push({ + id: parsed.manifest.id, + version: parsed.manifest.version, + apiVersion: parsed.manifest.apiVersion, + enabled: false, + grantedPermissions: [], + installedAt: Math.round(stat.birthtimeMs || stat.mtimeMs || 0), + updatedAt: Math.round(stat.mtimeMs || 0), + source: 'directory' + }) + } catch { + // 单个目录损坏不影响其余扩展的恢复。 + } + } + return records + } } function normalizeZipPath(value: string): string { diff --git a/src/main/extensions/extension-ipc.ts b/src/main/extensions/extension-ipc.ts index b97a3be..4010879 100644 --- a/src/main/extensions/extension-ipc.ts +++ b/src/main/extensions/extension-ipc.ts @@ -3,7 +3,9 @@ import path from 'node:path' import { BrowserWindow, dialog, ipcMain, shell } from 'electron' import { EXTENSION_IPC } from '../../shared/extensions/ipc' import type { + ExtensionActionInfo, ExtensionInstallResult, + ExtensionProjectResult, ExtensionLogEntry, ExtensionOperationResult, ExtensionPageDescriptor, @@ -120,6 +122,193 @@ export function registerExtensionIpc(options: ExtensionIpcOptions): void { }) ) + ipcMain.handle( + EXTENSION_IPC.health, + guard(() => manager().getHealth()) + ) + + ipcMain.handle( + EXTENSION_IPC.grantPermissions, + guard((payload: unknown): Promise => { + const input = (payload ?? {}) as { id?: unknown; permissions?: unknown } + const permissions = Array.isArray(input.permissions) + ? input.permissions.filter((item): item is string => typeof item === 'string') + : [] + return manager().grantPermissions( + requireId(input.id), + permissions as Parameters[1] + ) + }) + ) + + ipcMain.handle( + EXTENSION_IPC.revokePermission, + guard((payload: unknown): Promise => { + const input = (payload ?? {}) as { id?: unknown; permission?: unknown } + const permission = String(input.permission || '').trim() + if (!permission) throw new Error('权限名不合法') + return manager().revokePermission( + requireId(input.id), + permission as Parameters[1] + ) + }) + ) + + ipcMain.handle( + EXTENSION_IPC.resetStorage, + guard( + (extensionId: unknown): ExtensionOperationResult => + manager().resetStorage(requireId(extensionId)) + ) + ) + + ipcMain.handle( + EXTENSION_IPC.templates, + guard(() => manager().listTemplates()) + ) + + ipcMain.handle( + EXTENSION_IPC.installTemplate, + guard( + (templateId: unknown): Promise => + manager().installTemplate(requireTemplateId(templateId)) + ) + ) + + ipcMain.handle( + EXTENSION_IPC.acknowledgeRecovery, + guard((): ExtensionOperationResult => manager().acknowledgeRegistryRecovery()) + ) + + ipcMain.handle( + EXTENSION_IPC.acknowledgeStorage, + guard( + (extensionId: unknown): ExtensionOperationResult => + manager().acknowledgeStorageRecovery(requireId(extensionId)) + ) + ) + + ipcMain.handle( + EXTENSION_IPC.adoptInstalledCode, + guard( + (extensionId: unknown): ExtensionOperationResult => + manager().adoptInstalledCode(requireId(extensionId)) + ) + ) + + ipcMain.handle( + EXTENSION_IPC.pickProjectDirectory, + guard(async (): Promise => { + const window = BrowserWindow.getFocusedWindow() + const options: Electron.OpenDialogOptions = { + properties: ['openDirectory', 'createDirectory'], + title: '选择扩展项目目录' + } + const result = window + ? await dialog.showOpenDialog(window, options) + : await dialog.showOpenDialog(options) + return result.canceled || !result.filePaths.length ? null : result.filePaths[0] + }) + ) + + ipcMain.handle( + EXTENSION_IPC.linkDevelopment, + guard( + (directory: unknown): Promise => + manager().linkDevelopmentProject(requirePath(directory)) + ) + ) + + ipcMain.handle( + EXTENSION_IPC.reloadDevelopment, + guard( + (extensionId: unknown): Promise => + manager().reloadDevelopment(requireId(extensionId)) + ) + ) + + ipcMain.handle( + EXTENSION_IPC.unlinkDevelopment, + guard((payload: unknown): Promise => { + const input = (payload ?? {}) as { id?: unknown; keepData?: unknown } + return manager().unlinkDevelopment(requireId(input.id), { + keepData: input.keepData !== false + }) + }) + ) + + ipcMain.handle( + EXTENSION_IPC.convertDevelopment, + guard( + (extensionId: unknown): Promise => + manager().convertDevelopmentToInstalled(requireId(extensionId)) + ) + ) + + ipcMain.handle( + EXTENSION_IPC.createProjectFromTemplate, + guard((payload: unknown): Promise => { + const input = (payload ?? {}) as { + templateId?: unknown + targetDirectory?: unknown + extensionId?: unknown + name?: unknown + } + return manager().createProjectFromTemplate( + requireTemplateId(input.templateId), + requirePath(input.targetDirectory), + { + extensionId: requireId(input.extensionId), + ...(typeof input.name === 'string' && input.name.trim() + ? { name: input.name.trim().slice(0, 60) } + : {}) + } + ) + }) + ) + + ipcMain.handle( + EXTENSION_IPC.exportInstalledAsProject, + guard((payload: unknown): Promise => { + const input = (payload ?? {}) as { id?: unknown; targetDirectory?: unknown } + return manager().exportInstalledAsProject( + requireId(input.id), + requirePath(input.targetDirectory) + ) + }) + ) + + ipcMain.handle( + EXTENSION_IPC.actions, + guard((): ExtensionActionInfo[] => manager().listActions()) + ) + + ipcMain.handle( + EXTENSION_IPC.openDevelopmentSource, + guard(async (extensionId: unknown): Promise => { + const extension = manager().get(requireId(extensionId)) + if (!extension?.development?.available) { + return { + success: false, + error: { code: 'EXTENSION_SOURCE_MISSING', message: '源码目录不可用' } + } + } + // 路径来自主进程的 registry,渲染层只能传 id,无法指定任意目录。 + const error = await shell.openPath(extension.development.sourcePath) + return error + ? { success: false, error: { code: 'ACTION_FAILED', message: error } } + : { success: true } + }) + ) + + ipcMain.handle( + EXTENSION_IPC.rollbackUpgrade, + guard( + (extensionId: unknown): Promise => + manager().rollbackInterruptedUpgrade(requireId(extensionId)) + ) + ) + ipcMain.handle( EXTENSION_IPC.uninstall, guard((payload: unknown): Promise => { @@ -187,6 +376,13 @@ function requireId(value: unknown): string { return id } +/** 模板 id 只允许稳定的短标识,不允许携带路径片段。 */ +function requireTemplateId(value: unknown): string { + const id = String(value || '').trim() + if (!/^[a-z0-9][a-z0-9-]{1,63}$/.test(id)) throw new Error('模板 id 不合法') + return id +} + function requirePath(value: unknown): string { const target = String(value || '').trim() if (!target || target.length > 4_096) throw new Error('路径不合法') diff --git a/src/main/extensions/extension-manager.ts b/src/main/extensions/extension-manager.ts index c878b6a..becf1b9 100644 --- a/src/main/extensions/extension-manager.ts +++ b/src/main/extensions/extension-manager.ts @@ -1,15 +1,22 @@ import fs from 'fs-extra' -import os from 'node:os' import path from 'node:path' -import { safeStorage } from 'electron' import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors' +import { isPathInside } from './extension-paths' +import { computeDirectoryDigest } from './extension-code-digest' +import { ExtensionSecretStore, type ExtensionSecretCipher } from './extension-secret-store' +import { + createProjectFromTemplate as createProjectFiles, + exportInstalledCopy +} from './extension-project-files' import { autoGrantedPermissions, hasExtensionPermission, + normalizeExtensionPermissions, type ExtensionPermission } from '../../shared/extensions/permissions' import { checkExtensionCompatibility, + isValidExtensionId, parseExtensionManifest, type ExtensionManifest } from '../../shared/extensions/manifest' @@ -21,6 +28,9 @@ import type { ExtensionPageDescriptor, ExtensionPageMethod, ExtensionPageResponse, + ExtensionActionInfo, + ExtensionProjectResult, + ExtensionSystemHealth, InstalledExtension } from '../../shared/extensions/types' import type { @@ -44,7 +54,16 @@ import { type ExtensionHostChild, type ExtensionHostSpawnOptions } from './extension-host' -import { ExtensionInstaller } from './extension-installer' +import { ExtensionInstaller, type InstallOutcome } from './extension-installer' +import { + assertSafeDevelopmentRoot, + createExtensionRootResolver, + type ExtensionRootResolver +} from './extension-root-resolver' +import { + ExtensionTemplateCatalog, + type ExtensionTemplateStatus +} from './extension-template-catalog' import { ExtensionLogStore } from './extension-log' import { ExtensionRegistry, type ExtensionRegistryRecord } from './extension-registry' import { ExtensionSendGateway } from './extension-send-gateway' @@ -63,9 +82,15 @@ export interface ExtensionManagerDependencies { /** 群列表(id + 显示名);用于扩展配置页选择发送目标。 */ listGroups: () => Promise> aiChat: (messages: Array<{ role: string; content: string }>) => Promise<{ text: string }> + /** 当前 AI 是否已配置;不暴露 key、endpoint 或任何凭据。 */ + aiStatus?: () => { configured: boolean; modelName: string } getAccountId: () => string getSelfUsernames: () => string[] isDatabaseReady: () => boolean + /** 官方模板资源根目录;未提供时扩展中心只显示「我的扩展」。 */ + templatesRoot?: string + /** 扩展凭据的加密实现;未提供时凭据能力不可用(明确失败,不退化明文)。 */ + secretCipher: ExtensionSecretCipher now?: () => number onChange?: ( extensionId: string, @@ -73,6 +98,9 @@ export interface ExtensionManagerDependencies { ) => void } +/** 页面请求方法名:与 SDK 侧保持同一规则。 */ +const PAGE_REQUEST_METHOD = /^[a-z][a-zA-Z0-9]*(?:[._-][a-zA-Z0-9]+){0,3}$/ + const PAGE_METHODS: ExtensionPageMethod[] = [ 'storage.get', 'storage.set', @@ -80,10 +108,7 @@ const PAGE_METHODS: ExtensionPageMethod[] = [ 'storage.list', 'capabilities.get', 'contacts.listGroups', - 'test.send', - 'douyin.cookie.get', - 'douyin.cookie.set', - 'douyin.cookie.clear', + 'extension.request', 'extension.info' ] @@ -111,18 +136,51 @@ export class ExtensionManager { private readonly eventBus: ExtensionEventBus private readonly now: () => number private initialized = false + /** 代码与 Registry 版本不一致的扩展:值为面向用户的原因,存在即禁止启动。 */ + private readonly inconsistencies = new Map() + /** 配置从旧备份恢复、尚未被用户确认的扩展。 */ + private readonly storageHolds = new Set() + private readonly templates: ExtensionTemplateCatalog | null + /** 扩展代码根目录的唯一解析器:安装副本与外部开发目录共用一条路径。 */ + private readonly roots: ExtensionRootResolver + private readonly secrets: ExtensionSecretStore constructor(dependencies: ExtensionManagerDependencies) { this.dependencies = dependencies this.paths = dependencies.paths this.now = dependencies.now ?? (() => Date.now()) - this.registry = new ExtensionRegistry({ registryFile: this.paths.registryFile, now: this.now }) + this.registry = new ExtensionRegistry({ + registryFile: this.paths.registryFile, + now: this.now, + // 状态文件与备份都不可用时,用磁盘上的目录重建「有哪些扩展」; + // 重建结果不带启用状态与授权,用户必须重新确认。 + recover: () => this.installer.recoverFromDisk() + }) this.installer = new ExtensionInstaller({ paths: this.paths, registry: this.registry, now: this.now }) - this.storage = new ExtensionStorage({ dataRoot: this.paths.dataDir }) + this.templates = dependencies.templatesRoot + ? new ExtensionTemplateCatalog({ + templateRoot: dependencies.templatesRoot, + getRecord: (extensionId) => this.registry.get(extensionId), + resolveInstallDir: (extensionId) => this.paths.installDir(extensionId), + platform: dependencies.platform + }) + : null + this.roots = createExtensionRootResolver({ + paths: this.paths, + getRecord: (extensionId) => this.registry.get(extensionId) + }) + this.secrets = new ExtensionSecretStore({ + root: path.join(this.paths.stateDir, 'secrets'), + cipher: dependencies.secretCipher + }) + this.storage = new ExtensionStorage({ + dataRoot: this.paths.dataDir, + onHealthChange: (extensionId, health) => this.handleStorageHealthChange(extensionId, health) + }) this.logs = new ExtensionLogStore(this.paths.logsDir) this.sendGateway = new ExtensionSendGateway({ getCapability: dependencies.getCapability, @@ -153,6 +211,12 @@ export class ExtensionManager { fs.ensureDirSync(directory) } this.eventBus.setAccountId(this.dependencies.getAccountId()) + const health = this.registry.getHealth() + if (health.state !== 'ok') { + // 宿主级事件没有归属扩展,走主进程日志;界面通过 `getHealth()` 展示。 + console.warn(`[Extension] ${health.message || '扩展状态文件曾损坏,已进入恢复状态'}`) + } + for (const record of this.registry.list()) { const manifest = this.readManifest(record.id) if (!manifest) { @@ -160,7 +224,39 @@ export class ExtensionManager { continue } this.syncDeclared(record.id, manifest) + + // 代码与状态可能在上次升级中断时分叉:先判一致性,不一致就不启动。 + const drift = this.checkInstallConsistency(record, manifest) + if (drift) { + this.inconsistencies.set(record.id, drift) + this.logs.append(record.id, 'error', 'core', drift) + continue + } + this.inconsistencies.delete(record.id) + if (!record.enabled) continue + + // 配置从旧备份恢复过:先暂停,等用户确认「接受恢复的配置」。 + const storageHealth = this.storage.health(record.id) + if (storageHealth.state !== 'ok') { + this.storageHolds.add(record.id) + this.logs.append( + record.id, + 'warn', + 'core', + storageHealth.state === 'recovered-from-backup' + ? '扩展配置曾从备份恢复,已暂停启动;请在详情页确认后再启用' + : '扩展配置损坏且无可用备份,已暂停启动;请重置配置后重新启用' + ) + try { + this.registry.setEnabled(record.id, false) + } catch { + // 状态文件不可写时保持内存中的暂停状态即可。 + } + continue + } + this.storageHolds.delete(record.id) + const compatibility = checkExtensionCompatibility(manifest, this.dependencies.appVersion) if (!compatibility.compatible) { this.logs.append(record.id, 'error', 'core', compatibility.reason || '扩展不兼容') @@ -179,6 +275,28 @@ export class ExtensionManager { } } + /** + * 校验状态记录与磁盘上的 manifest 是否描述同一个版本。 + * + * 升级会在「换代码」与「写状态」之间留下一个窗口;进程在该窗口被杀时, + * 磁盘上是新代码、状态里是旧版本。这种扩展不能带着旧授权直接跑。 + */ + private checkInstallConsistency( + record: ExtensionRegistryRecord, + manifest: ExtensionManifest + ): string | null { + if (record.id !== manifest.id) { + return '扩展目录中的 manifest.id 与状态记录不一致' + } + if (record.version !== manifest.version) { + return `代码版本 ${manifest.version} 与状态记录 ${record.version} 不一致,上次升级可能中断` + } + if (record.apiVersion !== manifest.apiVersion) { + return `扩展 API 版本不一致(代码 ${manifest.apiVersion} / 状态 ${record.apiVersion})` + } + return null + } + list(): InstalledExtension[] { return this.registry .list() @@ -201,20 +319,649 @@ export class ExtensionManager { } async installFromDirectory(directory: string): Promise { - return this.install(() => - this.installer.installFromDirectory(directory, { appVersion: this.dependencies.appVersion }) + return this.install((beforeReplace) => + this.installer.installFromDirectory(directory, { + appVersion: this.dependencies.appVersion, + beforeReplace + }) ) } async installFromPackage(packagePath: string): Promise { - return this.install(() => + return this.install((beforeReplace) => this.installer.installFromPackage(packagePath, { appVersion: this.dependencies.appVersion, - source: 'package' + source: 'package', + beforeReplace }) ) } + /** 官方模板列表;模板资源缺失时返回空数组,不影响「我的扩展」。 */ + async listTemplates(): Promise { + if (!this.templates) return [] + return this.templates.list() + } + + /** + * 安装官方模板。 + * + * 三条硬约束: + * 1. 只接受模板索引里的 id,ZIP 路径由目录服务解析并校验哈希; + * 2. 同 id 已被非模板来源占用时拒绝接管; + * 3. 安装只落代码,不启用——启用仍需用户确认权限。 + */ + async installTemplate(templateId: string): Promise { + const templates = this.templates + if (!templates) { + return { + success: false, + error: { code: 'CAPABILITY_UNAVAILABLE', message: '模板目录不可用' } + } + } + let resolved: Awaited> + try { + resolved = await templates.resolveZip(templateId) + } catch (error) { + return { success: false, error: toExtensionErrorPayload(error) } + } + + const existing = this.registry.get(resolved.template.extensionId) + if (existing && (existing.source !== 'template' || existing.templateId !== templateId)) { + return { + success: false, + error: { + code: 'EXTENSION_ALREADY_INSTALLED', + message: '已存在同 ID 的非官方扩展,未自动替换' + } + } + } + if (existing && existing.version === resolved.template.version) { + return { + success: false, + error: { code: 'EXTENSION_ALREADY_INSTALLED', message: '该模板版本已安装' } + } + } + + return this.install((beforeReplace) => + this.installer.installFromPackage(resolved.path, { + appVersion: this.dependencies.appVersion, + source: 'template', + template: { id: resolved.template.templateId, version: resolved.template.version }, + beforeReplace + }) + ) + } + + /** + * 该扩展当前是否被暂停(配置待确认 / 版本不一致)。 + * + * 这是唯一的判断入口:事件投递、动作调用、发送出口都走它, + * 避免出现「某处放行、某处拦截」的不一致状态。 + */ + private isSuspended(extensionId: string): boolean { + return this.storageHolds.has(extensionId) || this.inconsistencies.has(extensionId) + } + + /** + * 运行期检测到配置回退:立刻收住这个扩展。 + * + * 顺序很重要:先停后台(切断正在跑的回复循环),再改状态、记日志。 + * 已经交给 Native Host 的发送请求无法撤回,属于已知边界。 + */ + private handleStorageHealthChange( + extensionId: string, + health: { state: string; message?: string } + ): void { + if (health.state === 'ok') return + if (this.storageHolds.has(extensionId)) return + this.storageHolds.add(extensionId) + void this.stopHost(extensionId).catch(() => undefined) + try { + this.registry.setEnabled(extensionId, false) + } catch { + // 状态文件不可写时保持内存中的暂停状态即可。 + } + this.logs.append( + extensionId, + 'warn', + 'core', + health.state === 'recovered-from-backup' + ? '扩展配置在运行期间从备份恢复,已暂停该扩展;请确认后再启用' + : '扩展配置在运行期间损坏,已暂停该扩展' + ) + this.dependencies.onChange?.(extensionId, 'runtime') + } + + /** 供自定义协议解析代码根目录;开发目录不可用时返回 null(页面 404 而不是 500)。 */ + resolveExtensionRoot(extensionId: string): string | null { + try { + return this.roots.resolve(extensionId).root + } catch { + return null + } + } + + /** + * 链接外部开发项目。 + * + * 只读用户显式选择的目录:校验 manifest、入口文件、路径边界与 ID 冲突, + * 然后登记为 `development` 来源。**不复制代码**,也不写回源码目录。 + */ + async linkDevelopmentProject(directory: string): Promise { + const raw = String(directory || '').trim() + if (!raw) { + return { success: false, error: { code: 'INVALID_REQUEST', message: '请选择项目目录' } } + } + let realRoot: string + try { + realRoot = fs.realpathSync(raw) + } catch { + return { + success: false, + error: { code: 'EXTENSION_SOURCE_MISSING', message: '目录不存在或无法访问' } + } + } + let isDirectory = false + try { + isDirectory = fs.statSync(realRoot).isDirectory() + } catch { + isDirectory = false + } + if (!isDirectory) { + return { + success: false, + error: { code: 'EXTENSION_INVALID_PATH', message: '所选路径不是目录' } + } + } + + const manifestPath = path.join(realRoot, 'manifest.json') + let parsedManifest: ReturnType + try { + parsedManifest = parseExtensionManifest(fs.readJsonSync(manifestPath) as unknown) + } catch { + return { + success: false, + error: { code: 'EXTENSION_INVALID_MANIFEST', message: '目录里没有可读的 manifest.json' } + } + } + if (!parsedManifest.ok || !parsedManifest.manifest) { + return { + success: false, + error: { + code: 'EXTENSION_INVALID_MANIFEST', + message: 'manifest.json 不合法' + } + } + } + const manifest = parsedManifest.manifest + + // 先判路径边界:指向宿主私有目录时,连入口检查都不该做。 + try { + assertSafeDevelopmentRoot(this.paths, manifest.id, realRoot) + } catch (error) { + return { success: false, error: toExtensionErrorPayload(error) } + } + + for (const [key, value] of Object.entries(manifest.entrypoints)) { + if (!value) continue + const entryPath = path.join(realRoot, value) + if (!this.isFileInside(realRoot, entryPath)) { + return { + success: false, + error: { code: 'EXTENSION_INVALID_MANIFEST', message: `入口 ${key} 无法解析` } + } + } + } + + const existing = this.registry.get(manifest.id) + if (existing && existing.source !== 'development') { + return { + success: false, + error: { + code: 'EXTENSION_ALREADY_INSTALLED', + message: '该扩展 ID 已被正式安装占用;请先「导出为开发项目」切换来源' + } + } + } + if (existing && existing.developmentSourcePath === realRoot) { + return { + success: false, + error: { code: 'EXTENSION_ALREADY_INSTALLED', message: '该目录已经链接过' } + } + } + + const timestamp = this.now() + this.registry.upsert({ + id: manifest.id, + version: manifest.version, + apiVersion: manifest.apiVersion, + // 链接不等于信任:默认停用;只自动授予低风险权限(与安装策略一致), + // 高风险能力仍需用户在启用时确认。 + enabled: false, + grantedPermissions: autoGrantedPermissions(manifest.permissions), + installedAt: existing?.installedAt ?? timestamp, + updatedAt: timestamp, + source: 'development', + developmentSourcePath: realRoot + }) + this.manifests.set(manifest.id, manifest) + this.syncDeclared(manifest.id, manifest) + this.logs.append(manifest.id, 'info', 'core', '已链接外部开发项目') + this.dependencies.onChange?.(manifest.id, 'installed') + const extension = this.get(manifest.id) + return { success: true, ...(extension ? { extension } : {}) } + } + + /** + * 重新加载开发项目。 + * + * 停后台 → 清 manifest 缓存 → 重新解析 → 权限取交集 → 原本启用则重启。 + * 页面侧由界面刷新 iframe 完成,两者互不依赖。 + */ + async reloadDevelopment(extensionId: string): Promise { + const record = this.registry.get(extensionId) + if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND')) + if (record.source !== 'development') { + return failure(new ExtensionError('INVALID_REQUEST', '该扩展不是开发模式')) + } + + await this.stopHost(extensionId) + this.manifests.delete(extensionId) + + try { + // 先确认源码目录仍然可达;不可达时给出「重新选择目录」而不是「manifest 读不到」。 + this.roots.resolve(extensionId) + } catch (error) { + return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) + } + const manifest = this.readManifest(extensionId) + if (!manifest) { + return failure(new ExtensionError('EXTENSION_INVALID_MANIFEST', 'manifest 无法读取')) + } + if (manifest.id !== extensionId) { + return failure( + new ExtensionError( + 'EXTENSION_INVALID_MANIFEST', + `目录内 manifest.id 为 ${manifest.id},与链接时不一致` + ) + ) + } + + try { + const drift = this.checkInstallConsistency(record, manifest) + if (drift && manifest.version !== record.version) { + // 开发模式允许版本自由变化:这里把状态对齐到磁盘,而不是拒绝启动。 + this.registry.upsert({ + ...record, + version: manifest.version, + apiVersion: manifest.apiVersion, + grantedPermissions: record.grantedPermissions.filter((permission) => + manifest.permissions.includes(permission) + ), + updatedAt: this.now() + }) + } + } catch (error) { + return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) + } + + this.manifests.set(extensionId, manifest) + this.syncDeclared(extensionId, manifest) + this.inconsistencies.delete(extensionId) + this.storageHolds.delete(extensionId) + + let startError: unknown = null + if (record.enabled) { + try { + await this.startHost(extensionId, manifest) + } catch (error) { + startError = error + } + } + this.logs.append(extensionId, 'info', 'core', '开发项目已重新加载') + this.dependencies.onChange?.(extensionId, 'installed') + if (startError) { + return failure(toExtensionErrorPayload(startError) as unknown as ExtensionError) + } + return { success: true } + } + + /** + * 移除开发链接。 + * + * 绝不删除外部源码目录。若安装副本还在,把来源退回安装副本; + * 否则移除 Registry 记录。用户数据按 `keepData` 决定。 + */ + async unlinkDevelopment( + extensionId: string, + options: { keepData: boolean } + ): Promise { + const record = this.registry.get(extensionId) + if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND')) + if (record.source !== 'development') { + return failure(new ExtensionError('INVALID_REQUEST', '该扩展不是开发模式')) + } + + await this.stopHost(extensionId) + this.manifests.delete(extensionId) + this.inconsistencies.delete(extensionId) + this.storageHolds.delete(extensionId) + + const installedRoot = this.paths.installDir(extensionId) + const hasInstalledCopy = fs.existsSync(path.join(installedRoot, 'manifest.json')) + try { + if (hasInstalledCopy) { + // 回到安装副本:不是删除,只是换来源。 + this.registry.upsert({ + ...record, + source: 'directory', + enabled: false, + updatedAt: this.now() + }) + const restored = this.readManifest(extensionId) + if (restored) { + this.manifests.set(extensionId, restored) + this.syncDeclared(extensionId, restored) + } + } else { + this.registry.remove(extensionId) + } + } catch (error) { + return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) + } + + if (!options.keepData) { + await fs + .rm(this.paths.extensionDataDir(extensionId), { recursive: true, force: true }) + .catch(() => undefined) + } + this.logs.append(extensionId, 'info', 'core', '已移除开发链接(外部源码未删除)') + this.dependencies.onChange?.(extensionId, hasInstalledCopy ? 'installed' : 'uninstalled') + return { success: true } + } + + /** + * 把开发项目转成正式安装副本。 + * + * 只复制代码;用户配置本来就在 `extensions-data`,不受影响。 + */ + async convertDevelopmentToInstalled(extensionId: string): Promise { + const record = this.registry.get(extensionId) + if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND')) + if (record.source !== 'development') { + return failure(new ExtensionError('INVALID_REQUEST', '该扩展不是开发模式')) + } + let root: string + try { + root = this.roots.resolve(extensionId).root + } catch (error) { + return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) + } + + await this.stopHost(extensionId) + // 转换后不自动运行:先把启用状态落成 false,安装器才会保留它。 + try { + this.registry.setEnabled(extensionId, false) + } catch (error) { + return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) + } + + try { + const outcome = await this.installer.installFromDirectory(root, { + appVersion: this.dependencies.appVersion, + source: 'directory', + beforeReplace: async () => { + await this.stopHost(extensionId) + } + }) + await outcome.cleanup() + this.manifests.delete(extensionId) + this.manifests.set(extensionId, outcome.manifest) + this.syncDeclared(extensionId, outcome.manifest) + } catch (error) { + return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) + } + + this.logs.append(extensionId, 'info', 'core', '开发项目已转为正式安装') + this.dependencies.onChange?.(extensionId, 'installed') + return { success: true } + } + + /** + * 从官方模板生成一个独立项目(不安装、不启用)。 + * + * ZIP 来自官方模板目录并已校验哈希;生成过程在暂存目录完成, + * 目标目录非空时不会写入任何文件。 + */ + async createProjectFromTemplate( + templateId: string, + targetDirectory: string, + options: { extensionId: string; name?: string } + ): Promise { + if (!this.templates) { + return { + success: false, + error: { code: 'CAPABILITY_UNAVAILABLE', message: '模板目录不可用' } + } + } + if (!isValidExtensionId(options.extensionId)) { + return { + success: false, + error: { code: 'INVALID_REQUEST', message: '扩展 id 必须是反向域名格式' } + } + } + if (this.registry.get(options.extensionId)) { + return { + success: false, + error: { code: 'EXTENSION_ALREADY_INSTALLED', message: '该扩展 id 已被占用' } + } + } + + let resolved: Awaited> + try { + resolved = await this.templates.resolveZip(templateId) + } catch (error) { + return { success: false, error: toExtensionErrorPayload(error) } + } + + try { + const outcome = await createProjectFiles({ + zipPath: resolved.path, + targetDir: targetDirectory, + extensionId: options.extensionId, + templateExtensionId: resolved.template.extensionId, + ...(options.name ? { name: options.name } : {}) + }) + this.logs.append( + options.extensionId, + 'info', + 'core', + `已从模板 ${resolved.template.templateId} 生成独立项目` + ) + return { + success: true, + projectPath: outcome.projectPath, + rewrittenFiles: outcome.rewrittenFiles + } + } catch (error) { + return { success: false, error: toExtensionErrorPayload(error) } + } + } + + /** + * 把已安装副本导出成外部项目,并把来源切换为 development。 + * + * 导出的必须是**用户改过的安装副本**,不能重新解压官方 ZIP—— + * 那样会把二开内容换回原版。原安装副本保留,作为显式恢复来源。 + */ + async exportInstalledAsProject( + extensionId: string, + targetDirectory: string + ): Promise { + const record = this.registry.get(extensionId) + if (!record) return { success: false, error: { code: 'EXTENSION_NOT_FOUND', message: '' } } + if (record.source === 'development') { + return { + success: false, + error: { code: 'INVALID_REQUEST', message: '该扩展已经是开发模式' } + } + } + const installRoot = this.paths.installDir(extensionId) + + await this.stopHost(extensionId) + let projectPath: string + try { + const outcome = await exportInstalledCopy(installRoot, targetDirectory) + projectPath = fs.realpathSync(outcome.projectPath) + } catch (error) { + // 导出失败时把旧 Host 拉回来,别让扩展停在半死状态。 + await this.restoreHostAfterFailure(extensionId) + return { success: false, error: toExtensionErrorPayload(error) } + } + + const parsed = (() => { + try { + return parseExtensionManifest(fs.readJsonSync(path.join(projectPath, 'manifest.json'))) + } catch { + return null + } + })() + if (!parsed?.ok || !parsed.manifest || parsed.manifest.id !== extensionId) { + return { + success: false, + error: { + code: 'EXTENSION_INVALID_MANIFEST', + message: '导出的项目 manifest 与原扩展不一致,未切换来源' + } + } + } + + const next = { + ...record, + source: 'development' as const, + developmentSourcePath: projectPath, + // 转换后不自动运行;授权按新 manifest 取交集。 + enabled: false, + grantedPermissions: record.grantedPermissions.filter((permission) => + parsed.manifest!.permissions.includes(permission) + ), + updatedAt: this.now() + } + // 模板身份与旧指纹在新来源下没有意义,必须清掉。 + delete next.templateId + delete next.templateVersion + delete next.installedCodeDigest + + try { + this.registry.upsert(next) + } catch { + return { + success: false, + error: { + code: 'EXTENSION_REGISTRY_UNREADABLE', + message: '项目已导出,但扩展状态写入失败;请用「链接本地项目」重新接入' + } + } + } + + this.manifests.delete(extensionId) + this.manifests.set(extensionId, parsed.manifest) + this.syncDeclared(extensionId, parsed.manifest) + this.logs.append(extensionId, 'info', 'core', '已导出为开发项目并切换来源') + this.dependencies.onChange?.(extensionId, 'installed') + return { success: true, projectPath } + } + + /** 目标文件必须真实落在扩展根目录内(跟随符号链接后仍在内)。 */ + private isFileInside(root: string, target: string): boolean { + try { + const realRoot = fs.realpathSync(root) + const realTarget = fs.realpathSync(target) + return isPathInside(realRoot, realTarget) && fs.statSync(realTarget).isFile() + } catch { + return false + } + } + + /** 状态文件的可信度;`unreadable` 时界面必须提示,而不是显示「没有扩展」。 */ + getHealth(): ExtensionSystemHealth { + const health = this.registry.getHealth() + return { + registry: { + state: health.state, + ...(health.message ? { message: health.message } : {}) + } + } + } + + /** + * 授予扩展已声明的权限。 + * + * 只接受 manifest 里出现过的权限:渲染层传来的字符串不能扩大扩展的能力面。 + * 权限在子进程启动时快照,因此已启用的扩展需要重启后台才会生效。 + */ + async grantPermissions( + extensionId: string, + permissions: ExtensionPermission[] + ): Promise { + const record = this.registry.get(extensionId) + if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND')) + const manifest = this.readManifest(extensionId) + if (!manifest) return failure(new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展文件缺失')) + + const granted = normalizeExtensionPermissions([ + ...record.grantedPermissions, + ...permissions.filter((permission) => manifest.permissions.includes(permission)) + ]) + try { + this.registry.setGrantedPermissions(extensionId, granted) + } catch (error) { + return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) + } + if (record.enabled && manifest.entrypoints.background) { + await this.startHost(extensionId, manifest).catch(() => undefined) + } + this.dependencies.onChange?.(extensionId, 'enabled') + return { success: true } + } + + /** 撤销单项授权;已启用时需要重启后台,正在运行的能力随之失效。 */ + async revokePermission( + extensionId: string, + permission: ExtensionPermission + ): Promise { + const record = this.registry.get(extensionId) + if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND')) + const manifest = this.readManifest(extensionId) + try { + this.registry.setGrantedPermissions( + extensionId, + record.grantedPermissions.filter((item) => item !== permission) + ) + } catch (error) { + return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) + } + if (record.enabled && manifest?.entrypoints.background) { + await this.startHost(extensionId, manifest).catch(() => undefined) + } + this.dependencies.onChange?.(extensionId, 'enabled') + return { success: true } + } + + /** 重置扩展私有存储;损坏现场已经由存储层另存为 `.corrupt-*`。 */ + resetStorage(extensionId: string): ExtensionOperationResult { + const record = this.registry.get(extensionId) + if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND')) + try { + this.storage.reset(extensionId) + } catch (error) { + return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) + } + this.dependencies.onChange?.(extensionId, 'runtime') + return { success: true } + } + async setEnabled(extensionId: string, enabled: boolean): Promise { const record = this.registry.get(extensionId) if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND')) @@ -229,6 +976,27 @@ export class ExtensionManager { return { success: true } } + const drift = this.checkInstallConsistency(record, manifest) + if (drift) { + this.inconsistencies.set(extensionId, drift) + return failure(new ExtensionError('EXTENSION_INCOMPATIBLE', drift)) + } + + // 配置还没被用户确认前不允许启动:恢复出来的开关可能还停在旧值上。 + const storageHealth = this.storage.health(extensionId) + if (storageHealth.state !== 'ok') { + this.storageHolds.add(extensionId) + return failure( + new ExtensionError( + 'EXTENSION_STORAGE_CORRUPTED', + storageHealth.state === 'recovered-from-backup' + ? '扩展配置曾从备份恢复,请先在详情页确认后再启用' + : '扩展配置已损坏,请先重置配置再启用' + ) + ) + } + this.storageHolds.delete(extensionId) + const compatibility = checkExtensionCompatibility(manifest, this.dependencies.appVersion) if (!compatibility.compatible) { return failure(new ExtensionError('EXTENSION_INCOMPATIBLE', compatibility.reason)) @@ -247,6 +1015,93 @@ export class ExtensionManager { return { success: true } } + /** 清除「状态文件曾恢复」的提示;不改动任何扩展的启用状态。 */ + acknowledgeRegistryRecovery(): ExtensionOperationResult { + try { + this.registry.acknowledgeRecovery() + } catch (error) { + return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) + } + this.dependencies.onChange?.('', 'runtime') + return { success: true } + } + + /** 接受从备份恢复出来的扩展配置,之后才允许启用该扩展。 */ + acknowledgeStorageRecovery(extensionId: string): ExtensionOperationResult { + const record = this.registry.get(extensionId) + if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND')) + try { + this.storage.acknowledge(extensionId) + } catch (error) { + return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) + } + this.storageHolds.delete(extensionId) + this.dependencies.onChange?.(extensionId, 'runtime') + return { success: true } + } + + /** + * 采用磁盘上的代码版本:把状态记录的版本对齐到 manifest。 + * + * 用于「上次升级中断」后的修复。授权按新 manifest 取交集,不会扩大能力。 + */ + adoptInstalledCode(extensionId: string): ExtensionOperationResult { + const record = this.registry.get(extensionId) + const manifest = this.readManifest(extensionId) + if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND')) + if (!manifest) return failure(new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展文件缺失')) + try { + this.registry.upsert({ + ...record, + version: manifest.version, + apiVersion: manifest.apiVersion, + grantedPermissions: record.grantedPermissions.filter((permission) => + manifest.permissions.includes(permission) + ), + updatedAt: this.now() + }) + } catch (error) { + return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) + } + this.inconsistencies.delete(extensionId) + this.manifests.delete(extensionId) + this.dependencies.onChange?.(extensionId, 'installed') + return { success: true } + } + + /** 把最近的升级过渡备份换回来,用于「新代码可疑、旧代码还在」的场景。 */ + async rollbackInterruptedUpgrade(extensionId: string): Promise { + const record = this.registry.get(extensionId) + if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND')) + await this.stopHost(extensionId) + let restored: { restored: boolean; manifest?: ExtensionManifest } + try { + restored = await this.installer.restoreLatestBackup(extensionId) + } catch (error) { + return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) + } + if (!restored.restored || !restored.manifest) { + return failure(new ExtensionError('EXTENSION_INSTALL_FAILED', '没有可用的升级备份')) + } + try { + this.registry.upsert({ + ...record, + version: restored.manifest.version, + apiVersion: restored.manifest.apiVersion, + grantedPermissions: record.grantedPermissions.filter((permission) => + restored.manifest!.permissions.includes(permission) + ), + updatedAt: this.now() + }) + } catch (error) { + return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) + } + this.inconsistencies.delete(extensionId) + this.manifests.delete(extensionId) + this.dependencies.onChange?.(extensionId, 'installed') + return { success: true } + } + async uninstall(extensionId: string, keepData: boolean): Promise { const record = this.registry.get(extensionId) if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND')) @@ -297,17 +1152,18 @@ export class ExtensionManager { if (!PAGE_METHODS.includes(method as ExtensionPageMethod)) { throw new ExtensionError('PERMISSION_DENIED', `页面不能调用 ${method}`) } - if (method.startsWith('douyin.cookie.') && extensionId !== 'com.example.douyin-sender') { - throw new ExtensionError('PERMISSION_DENIED', 'Cookie 能力不适用于此扩展') - } const record = this.registry.get(extensionId) if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND') const manifest = this.readManifest(extensionId) if (!manifest) throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展文件缺失') - if (!manifest.permissions.includes('storage') && method.startsWith('storage.')) { + // 页面桥只认「已授予」的权限:manifest 声明只是申请,不代表用户同意。 + if (!record.grantedPermissions.includes('storage') && method.startsWith('storage.')) { throw new ExtensionError('PERMISSION_DENIED', '扩展没有 storage 权限') } - if (method === 'contacts.listGroups' && !manifest.permissions.includes('contacts.list')) { + if ( + method === 'contacts.listGroups' && + !record.grantedPermissions.includes('contacts.list') + ) { throw new ExtensionError('PERMISSION_DENIED', '扩展没有 contacts.list 权限') } switch (method as ExtensionPageMethod) { @@ -334,38 +1190,34 @@ export class ExtensionManager { } } } - case 'test.send': { - if (extensionId !== 'com.example.douyin-sender') { - throw new ExtensionError('PERMISSION_DENIED', '测试能力不适用于此扩展') + case 'extension.request': { + // 通用转发:只进入**同一扩展**的后台,宿主不知道任何具体业务。 + const inner = String(params.method || '').trim() + if (!PAGE_REQUEST_METHOD.test(inner)) { + throw new ExtensionError('INVALID_REQUEST', '页面请求方法名不合法') + } + if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED') + if (this.isSuspended(extensionId)) { + throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,页面请求被拒绝') } const host = this.hosts.get(extensionId) - if (!host) throw new ExtensionError('EXTENSION_DISABLED') - const cookieHeader = String(params.cookieHeader || '') || this.readDouyinCookie() - try { - return { ok: true, result: await host.testSend({ ...params, cookieHeader }) } - } finally { - params.cookieHeader = '' + if (!host) throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE') + const rawParams = params.params + if ( + rawParams !== undefined && + (typeof rawParams !== 'object' || Array.isArray(rawParams)) + ) { + throw new ExtensionError('INVALID_REQUEST', 'params 必须是对象') + } + return { + ok: true, + result: await host.requestPage( + inner, + (rawParams as Record | undefined) ?? {}, + 10_000 + ) } } - case 'douyin.cookie.get': - return { ok: true, result: { configured: Boolean(this.readDouyinCookie()) } } - case 'douyin.cookie.set': { - const value = String(params.cookieHeader || '').trim() - if (!value) throw new ExtensionError('INVALID_REQUEST', 'Cookie 不能为空') - if (!safeStorage.isEncryptionAvailable()) - throw new ExtensionError('CAPABILITY_UNAVAILABLE', '系统安全存储不可用') - fs.writeFileSync( - path.join(this.paths.userData, 'douyin-cookie.bin'), - safeStorage.encryptString(value), - { mode: 0o600 } - ) - fs.chmodSync(path.join(this.paths.userData, 'douyin-cookie.bin'), 0o600) - this.syncDouyinCookieToExtensionData(value) - return { ok: true, result: { configured: true } } - } - case 'douyin.cookie.clear': - this.clearDouyinCookie() - return { ok: true, result: { configured: false } } case 'extension.info': return { ok: true, @@ -389,53 +1241,6 @@ export class ExtensionManager { this.eventBus.handleMessage(message) } - private syncDouyinCookieToExtensionData(value: string): void { - try { - const dataDir = this.paths.extensionDataDir('com.example.douyin-sender') - fs.ensureDirSync(dataDir) - const target = path.join(dataDir, 'douyin-cookie.txt') - fs.writeFileSync(target, value, { mode: 0o600 }) - fs.chmodSync(target, 0o600) - } catch { - // 扩展数据目录同步失败不影响加密主存储。 - } - } - - private readDouyinCookie(): string { - const file = path.join(this.paths.userData, 'douyin-cookie.bin') - if (fs.existsSync(file) && safeStorage.isEncryptionAvailable()) { - try { - const decrypted = safeStorage.decryptString(fs.readFileSync(file)).trim() - if (decrypted) { - this.syncDouyinCookieToExtensionData(decrypted) - return decrypted - } - } catch { - // 加密文件损坏或不可解密时继续尝试桌面 Cookie 文件。 - } - } - const desktopCookie = path.join(os.homedir(), 'Desktop', 'douyin-cookie') - if (fs.existsSync(desktopCookie)) { - try { - return fs.readFileSync(desktopCookie, 'utf8').trim() - } catch { - return '' - } - } - return '' - } - - private clearDouyinCookie(): void { - try { - fs.removeSync(path.join(this.paths.userData, 'douyin-cookie.bin')) - fs.removeSync( - path.join(this.paths.extensionDataDir('com.example.douyin-sender'), 'douyin-cookie.txt') - ) - } catch { - throw new ExtensionError('INVALID_REQUEST', '无法清除抖音 Cookie') - } - } - setAccountId(accountId: string): void { this.eventBus.setAccountId(accountId) } @@ -450,6 +1255,9 @@ export class ExtensionManager { const record = this.registry.get(extensionId) if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND') if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED') + if (this.isSuspended(extensionId)) { + throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展配置待确认,动作已暂停') + } if (!hasExtensionPermission(record.grantedPermissions, 'automation.action')) { throw new ExtensionError('PERMISSION_DENIED', '扩展没有 automation.action 权限') } @@ -465,27 +1273,97 @@ export class ExtensionManager { return this.actions.list() } + /** + * 供自动化编辑器使用的动作列表。 + * + * `registered` 只是「后台注册过」,是否可用要逐条判断:停用、代码缺失、 + * 权限未授予、Storage 暂停、Schema 非法,任一成立都不可执行。 + */ + listActions(): ExtensionActionInfo[] { + return this.actions.list().map((action) => { + const record = this.registry.get(action.extensionId) + const manifest = this.manifests.get(action.extensionId) + const base: ExtensionActionInfo = { + extensionId: action.extensionId, + extensionName: action.extensionName, + actionId: action.actionId, + title: action.title, + ...(action.description ? { description: action.description } : {}), + declared: action.declared, + registered: action.registered, + enabled: record?.enabled === true, + available: false, + ...(action.inputSchema ? { inputSchema: action.inputSchema } : {}) + } + const block = (reason: string): ExtensionActionInfo => ({ + ...base, + unavailableReason: reason + }) + + if (!record) return block('扩展已卸载') + if (!manifest) return block('扩展代码缺失或 manifest 无法读取') + const compatibility = checkExtensionCompatibility(manifest, this.dependencies.appVersion) + if (!compatibility.compatible) return block(compatibility.reason || '扩展与当前版本不兼容') + if (!record.enabled) return block('扩展未启用') + if (this.isSuspended(record.id)) return block('扩展已暂停(配置待确认)') + if (!hasExtensionPermission(record.grantedPermissions, 'automation.action')) { + return block('未授予「执行自动化动作」权限') + } + if (action.schemaError) return block(`参数 Schema 不可用:${action.schemaError}`) + if (!action.registered) { + return block(action.declared ? '后台未注册该动作(可能仍在启动或代码报错)' : '动作未注册') + } + return { ...base, available: true } + }) + } + async dispose(): Promise { const ids = Array.from(this.hosts.keys()) await Promise.all(ids.map((id) => this.stopHost(id))) } + /** + * 安装 / 升级的编排。 + * + * 顺序是「停旧进程 → 换代码 → 写状态 → 起新进程」,任何一步失败都要让 + * 磁盘与 Registry 回到同一个版本。仅靠多次 rename 不构成跨进程事务, + * 所以失败时显式回滚,并把错误原样返回给界面,不吞成成功。 + */ private async install( - run: () => Promise<{ manifest: ExtensionManifest; upgraded: boolean; previousVersion?: string }> + run: ( + beforeReplace: ( + manifest: ExtensionManifest, + previous: ExtensionRegistryRecord | undefined + ) => Promise + ) => Promise ): Promise { - let outcome: Awaited> + let upgradingId: string | null = null + const beforeReplace = async ( + manifest: ExtensionManifest, + previous: ExtensionRegistryRecord | undefined + ): Promise => { + upgradingId = manifest.id + // 模板来源的代码被用户改过时,不允许任何安装路径静默覆盖。 + if (previous?.source === 'template') this.assertTemplateCodeUntouched(previous) + // manifest 缓存必须先失效:否则后续读到的仍是旧版本的入口与权限。 + this.manifests.delete(manifest.id) + if (previous?.enabled) await this.stopHost(manifest.id) + } + + let outcome: InstallOutcome try { - outcome = await run() + outcome = await run(beforeReplace) } catch (error) { + // 失败可能发生在旧 Host 已停止之后:旧代码仍在磁盘上,尽量把它拉回来。 + if (upgradingId) await this.restoreHostAfterFailure(upgradingId) return { success: false, error: toExtensionErrorPayload(error) } } - const { manifest } = outcome - const wasEnabled = this.registry.get(manifest.id)?.enabled === true - if (wasEnabled) await this.stopHost(manifest.id) - this.manifests.delete(manifest.id) + + const { manifest, previousRecord } = outcome + const wasEnabled = previousRecord?.enabled === true this.manifests.set(manifest.id, manifest) this.syncDeclared(manifest.id, manifest) - // 新安装只自动授予低风险权限;升级保留用户已经授予的集合。 + // 新安装只自动授予低风险权限;升级保留用户已经授予的集合(已按新 manifest 取交集)。 if (!outcome.upgraded) { this.registry.setGrantedPermissions(manifest.id, autoGrantedPermissions(manifest.permissions)) } @@ -498,22 +1376,87 @@ export class ExtensionManager { : `扩展已安装:${manifest.version}` ) this.dependencies.onChange?.(manifest.id, 'installed') + if (wasEnabled && manifest.entrypoints.background) { - await this.startHost(manifest.id, manifest).catch(() => undefined) + try { + await this.startHost(manifest.id, manifest) + } catch (error) { + // 新版本起不来:代码与状态一起退回旧版本,并把旧版本重新拉起。 + await this.stopHost(manifest.id) + await outcome.rollback().catch(() => undefined) + this.manifests.delete(manifest.id) + await this.restoreHostAfterFailure(manifest.id) + const message = error instanceof Error ? error.message : '新版本启动失败' + this.logs.append(manifest.id, 'error', 'core', `新版本启动失败,已回滚:${message}`) + this.dependencies.onChange?.(manifest.id, 'installed') + return { + success: false, + error: { + code: 'EXTENSION_INSTALL_FAILED', + message: `扩展已回滚到上一版本:${message}` + } + } + } } + + await outcome.cleanup().catch(() => undefined) const installed = this.get(manifest.id) return { success: true, ...(installed ? { extension: installed } : {}) } } + /** + * 模板来源的「本地改动」检查。 + * + * 只保护 `template` 来源:用户自己装的 ZIP / 目录本来就会被覆盖, + * 开发模式根本没有安装副本可覆盖。 + */ + private assertTemplateCodeUntouched(record: ExtensionRegistryRecord): void { + const root = this.paths.installDir(record.id) + if (!fs.existsSync(path.join(root, 'manifest.json'))) return + if (!record.installedCodeDigest) { + throw new ExtensionError( + 'EXTENSION_MODIFIED_LOCALLY', + '无法确认该模板的代码是否被修改过;请先「导出为开发项目」再更新' + ) + } + const current = computeDirectoryDigest(root) + if (current !== record.installedCodeDigest) { + throw new ExtensionError( + 'EXTENSION_MODIFIED_LOCALLY', + '检测到安装代码已被修改,已阻止自动覆盖;请先「导出为开发项目」' + ) + } + } + + /** 安装流程中断后,把 Registry 里仍标记为启用的扩展重新拉起来。 */ + private async restoreHostAfterFailure(extensionId: string): Promise { + const record = this.registry.get(extensionId) + if (!record?.enabled) return + this.manifests.delete(extensionId) + const manifest = this.readManifest(extensionId) + if (!manifest?.entrypoints.background) return + await this.startHost(extensionId, manifest).catch(() => undefined) + } + private async startHost(extensionId: string, manifest: ExtensionManifest): Promise { if (!manifest.entrypoints.background) return + // 双保险:任何路径(含自动恢复、自动化触发)都不能绕过这两道闸。 + const drift = this.inconsistencies.get(extensionId) + if (drift) { + throw new ExtensionError('EXTENSION_INCOMPATIBLE', drift) + } + if (this.storageHolds.has(extensionId)) { + throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展配置尚未确认恢复,已阻止启动') + } await this.stopHost(extensionId) + const resolvedRoot = this.roots.resolve(extensionId) const host = new ExtensionHost({ extensionId, - extensionDir: this.paths.installDir(extensionId), + extensionDir: resolvedRoot.root, dataDir: this.paths.extensionDataDir(extensionId), permissions: this.registry.get(extensionId)?.grantedPermissions ?? [], storage: this.storage, + secrets: this.secrets, spawn: this.dependencies.spawn ?? this.defaultSpawn(), onLog: (level, message) => { this.logs.append(extensionId, level, 'core', message) @@ -577,6 +1520,8 @@ export class ExtensionManager { const record = this.registry.get(extensionId) const manifest = this.manifests.get(extensionId) if (!record?.enabled || !manifest) continue + // 暂停中的扩展不再收事件:否则它仍会用旧规则回复。 + if (this.isSuspended(extensionId)) continue if (!hasExtensionPermission(record.grantedPermissions, 'messages.subscribe')) continue if (host.snapshot().state !== 'active') continue subscribers.push({ @@ -625,6 +1570,9 @@ export class ExtensionManager { const record = this.registry.get(extensionId) if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND') if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED') + if (this.isSuspended(extensionId)) { + throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,发送被拒绝') + } const manifest = this.manifests.get(extensionId) return this.sendGateway.sendText( { @@ -643,6 +1591,9 @@ export class ExtensionManager { const record = this.registry.get(extensionId) if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND') if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED') + if (this.isSuspended(extensionId)) { + throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,发送被拒绝') + } const manifest = this.manifests.get(extensionId) return this.sendGateway.sendImage( { @@ -661,6 +1612,9 @@ export class ExtensionManager { const record = this.registry.get(extensionId) if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND') if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED') + if (this.isSuspended(extensionId)) { + throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,发送被拒绝') + } const manifest = this.manifests.get(extensionId) return this.sendGateway.sendVideo( { @@ -696,10 +1650,16 @@ export class ExtensionManager { licensed, message: capability?.message || '暂时无法获知微信发送能力' }, - ai: { - configured: false, - modelName: '' - } + ai: (() => { + try { + const status = this.dependencies.aiStatus?.() + return status + ? { configured: status.configured, modelName: status.modelName } + : { configured: false, modelName: '' } + } catch { + return { configured: false, modelName: '' } + } + })() } } @@ -709,13 +1669,11 @@ export class ExtensionManager { ? checkExtensionCompatibility(manifest, this.dependencies.appVersion) : { compatible: false, code: 'manifest' as const, reason: '扩展文件缺失或 manifest 无法读取' } const host = this.hosts.get(record.id) - const runtime = host - ? host.snapshot() - : { - state: record.enabled ? ('active' as const) : ('inactive' as const), - since: record.updatedAt, - restarts: 0 - } + const runtime = host ? host.snapshot() : this.deriveIdleRuntime(record, manifest) + const pendingPermissions = manifest + ? manifest.permissions.filter((permission) => !record.grantedPermissions.includes(permission)) + : [] + const storageHealth = this.storage.health(record.id) return { id: record.id, name: manifest?.name || record.id, @@ -728,21 +1686,101 @@ export class ExtensionManager { installedAt: record.installedAt, updatedAt: record.updatedAt, compatibility, + source: record.source, + ...(record.templateId + ? { + template: { + id: record.templateId, + version: record.templateVersion || '' + } + } + : {}), + ...(record.source === 'development' + ? { + development: { + sourcePath: record.developmentSourcePath || '', + available: this.isDevelopmentRootAvailable(record.id) + } + } + : {}), permissions: manifest?.permissions ?? [], grantedPermissions: record.grantedPermissions, + pendingPermissions, runtime, pages: (manifest?.contributions.pages ?? []).map((page) => ({ id: page.id, title: page.title })), automationActions: this.actions.summariesFor(record.id), - filesPresent: Boolean(manifest) + filesPresent: Boolean(manifest), + storage: { + state: storageHealth.state, + ...(storageHealth.message ? { message: storageHealth.message } : {}) + } + } + } + + /** + * 没有 Host 时的运行状态。 + * + * 只有页面入口的扩展本来就不会有后台进程,必须与「启用但启动失败」区分开: + * 前者是 `inactive` 加说明,后者是 `error` 加原因。 + */ + private deriveIdleRuntime( + record: ExtensionRegistryRecord, + manifest: ExtensionManifest | null + ): InstalledExtension['runtime'] { + const base = { since: record.updatedAt, restarts: 0 } + // 版本不一致优先展示:即使扩展已停用,用户也需要知道上一次升级可能中断。 + const drift = this.inconsistencies.get(record.id) + if (drift) return { state: 'error', ...base, lastError: drift } + if (this.storageHolds.has(record.id) && record.enabled) { + return { + state: 'error', + ...base, + lastError: '扩展配置曾从备份恢复,确认后才能启动' + } + } + if (!record.enabled) return { state: 'inactive', ...base } + if (!manifest) { + return { + state: 'error', + ...base, + lastError: '扩展文件缺失或 manifest 无法读取' + } + } + if (!manifest.entrypoints.background) { + return { state: 'inactive', ...base, note: '仅提供页面,没有后台任务' } + } + const compatibility = checkExtensionCompatibility(manifest, this.dependencies.appVersion) + if (!compatibility.compatible) { + return { + state: 'error', + ...base, + lastError: compatibility.reason || '扩展与当前版本不兼容' + } + } + return { state: 'error', ...base, lastError: '后台进程未启动' } + } + + private isDevelopmentRootAvailable(extensionId: string): boolean { + try { + return Boolean(this.roots.resolve(extensionId).root) + } catch { + return false } } private readManifest(extensionId: string): ExtensionManifest | null { if (this.manifests.has(extensionId)) return this.manifests.get(extensionId) ?? null - const file = path.join(this.paths.installDir(extensionId), 'manifest.json') + let root: string + try { + root = this.roots.resolve(extensionId).root + } catch { + // 开发目录不可用或扩展不存在:交给调用方按「没有 manifest」处理。 + return null + } + const file = path.join(root, 'manifest.json') let manifest: ExtensionManifest | null = null try { const parsed = parseExtensionManifest(fs.readJsonSync(file) as unknown) diff --git a/src/main/extensions/extension-paths.ts b/src/main/extensions/extension-paths.ts index 99a4259..a84e147 100644 --- a/src/main/extensions/extension-paths.ts +++ b/src/main/extensions/extension-paths.ts @@ -58,8 +58,26 @@ export function getExtensionPaths(): ExtensionPaths { return cached } -/** 判断 `child` 是否在 `parent` 内(含自身)。符号链接需调用方先 realpath。 */ +/** + * 判断 `child` 是否在 `parent` 内(含自身)。符号链接需调用方先 realpath。 + * + * Windows 上盘符大小写、分隔符与短文件名都可能让字符串比较失手, + * 这里统一把两侧规范化后再比:`path.resolve` 处理分隔符,Windows 额外折叠大小写。 + */ export function isPathInside(parent: string, child: string): boolean { - const relative = path.relative(path.resolve(parent), path.resolve(child)) + const normalize = (value: string): string => { + const resolved = path.resolve(value) + return process.platform === 'win32' ? resolved.toLowerCase() : resolved + } + const relative = path.relative(normalize(parent), normalize(child)) return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative)) } + +/** 只比路径本身,不跟随符号链接;用于判断两个字符串是否指向同一位置。 */ +export function isSamePath(left: string, right: string): boolean { + const normalize = (value: string): string => { + const resolved = path.resolve(value) + return process.platform === 'win32' ? resolved.toLowerCase() : resolved + } + return normalize(left) === normalize(right) +} diff --git a/src/main/extensions/extension-project-files.ts b/src/main/extensions/extension-project-files.ts new file mode 100644 index 0000000..0827584 --- /dev/null +++ b/src/main/extensions/extension-project-files.ts @@ -0,0 +1,242 @@ +import { promises as fs, existsSync } from 'node:fs' +import path from 'node:path' +import { Open } from 'unzipper' +import { ExtensionError } from '../../shared/extensions/errors' +import { isSafeRelativeEntryPath } from '../../shared/extensions/manifest' +import { isPathInside } from './extension-paths' + +const MAX_FILES = 2_000 +const MAX_TOTAL_BYTES = 50 * 1024 * 1024 + +/** 与安装器 / 指纹一致的排除规则:这些不属于扩展源码。 */ +const EXCLUDED_DIRECTORIES = new Set([ + '.git', + '.hg', + '.svn', + 'node_modules', + '__pycache__', + '.venv', + 'venv' +]) +const EXCLUDED_FILES = new Set(['.DS_Store', 'Thumbs.db']) +const EXCLUDED_EXTENSIONS = new Set(['.pyc', '.log']) + +/** 会被替换扩展 id 的文本文件类型。 */ +const TEXT_FILE_PATTERN = /\.(js|mjs|cjs|ts|tsx|jsx|html|htm|css|json)$/i + +export interface CreateProjectInput { + zipPath: string + targetDir: string + /** 新扩展 id(必须与模板里的旧 id 不同)。 */ + extensionId: string + /** 模板里的旧 id;用于替换代码中的身份引用。 */ + templateExtensionId: string + name?: string +} + +export interface CreateProjectOutcome { + projectPath: string + rewrittenFiles: string[] +} + +/** + * 目标目录必须是「不存在」或「空目录」。 + * + * 这条检查在复制之前做,避免中途发现冲突时已经写了一半。 + */ +export async function assertUsableTarget(targetDir: string): Promise { + const resolved = path.resolve(targetDir) + try { + const stat = await fs.stat(resolved) + if (!stat.isDirectory()) { + throw new ExtensionError('EXTENSION_PROJECT_EXISTS', '目标路径已存在且不是目录') + } + const entries = await fs.readdir(resolved) + if (entries.length > 0) { + throw new ExtensionError('EXTENSION_PROJECT_EXISTS', '目标目录不是空目录,未写入任何文件') + } + } catch (error) { + if (error instanceof ExtensionError) throw error + const code = (error as { code?: string }).code + if (code !== 'ENOENT') { + throw new ExtensionError('EXTENSION_PROJECT_EXISTS', '目标目录不可用') + } + } + return resolved +} + +/** 在目标旁边建暂存目录:同一磁盘才能用 rename 原子落位。 */ +async function createStaging(parent: string): Promise { + await fs.mkdir(parent, { recursive: true }) + return fs.mkdtemp(path.join(parent, '.tm-project-')) +} + +async function cleanup(directory: string): Promise { + await fs.rm(directory, { recursive: true, force: true }).catch(() => undefined) +} + +function shouldSkipFile(name: string): boolean { + return EXCLUDED_FILES.has(name) || EXCLUDED_EXTENSIONS.has(path.extname(name).toLowerCase()) +} + +/** 解压到暂存目录;条目路径逐条校验,拒绝穿越与非法字符。 */ +async function extractZip(zipPath: string, staging: string): Promise { + let archive: Awaited> + try { + archive = await Open.file(zipPath) + } catch { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', '模板压缩包无法读取') + } + + let files = 0 + let total = 0 + for (const entry of archive.files) { + const relative = String(entry.path || '').replace(/\\/g, '/') + if (entry.type === 'Directory') continue + if (!isSafeRelativeEntryPath(relative)) { + throw new ExtensionError('EXTENSION_INVALID_PATH', `模板条目路径不合法:${relative}`) + } + const size = Number(entry.uncompressedSize || 0) + total += size + if (total > MAX_TOTAL_BYTES) { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', '模板解压后体积超过限制') + } + files += 1 + if (files > MAX_FILES) { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', '模板文件数量超过限制') + } + + const destination = path.resolve(staging, relative) + if (!isPathInside(staging, destination)) { + throw new ExtensionError('EXTENSION_INVALID_PATH', `模板条目越界:${relative}`) + } + await fs.mkdir(path.dirname(destination), { recursive: true }) + const content = await entry.buffer() + await fs.writeFile(destination, content) + } + if (!files) throw new ExtensionError('EXTENSION_INSTALL_FAILED', '模板压缩包是空的') +} + +async function listTextFiles(root: string, prefix = ''): Promise { + const result: string[] = [] + const items = await fs.readdir(path.join(root, prefix), { withFileTypes: true }) + for (const item of items) { + if (item.isDirectory()) { + if (EXCLUDED_DIRECTORIES.has(item.name)) continue + const nested = prefix ? `${prefix}/${item.name}` : item.name + result.push(...(await listTextFiles(root, nested))) + continue + } + if (shouldSkipFile(item.name)) continue + const relative = prefix ? `${prefix}/${item.name}` : item.name + if (!TEXT_FILE_PATTERN.test(relative)) continue + result.push(relative) + } + return result.sort() +} + +/** + * 把代码里的扩展身份改成新 id。 + * + * 只替换精确字符串:模板示例里 id 至少出现在 manifest 与页面桥的 + * `EXTENSION_ID` 常量中,漏掉任何一处都会让页面桥失联。 + */ +export async function rewriteExtensionIdentity( + root: string, + oldId: string, + newId: string, + name?: string +): Promise { + const rewritten: string[] = [] + const manifestPath = path.join(root, 'manifest.json') + const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8')) as Record + if (String(manifest.id) !== oldId) { + throw new ExtensionError( + 'EXTENSION_INVALID_MANIFEST', + `模板 manifest.id 与索引不一致(${String(manifest.id)})` + ) + } + manifest.id = newId + if (name) manifest.name = name + await fs.writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8') + + for (const relative of await listTextFiles(root)) { + if (relative === 'manifest.json') continue + const full = path.join(root, relative) + const text = await fs.readFile(full, 'utf8') + if (!text.includes(oldId)) continue + await fs.writeFile(full, text.split(oldId).join(newId), 'utf8') + rewritten.push(relative) + } + return rewritten +} + +/** 生成后自检:任何残留的旧 id 都意味着页面桥或后台仍指向模板身份。 */ +export async function assertNoIdentityLeftover(root: string, oldId: string): Promise { + for (const relative of await listTextFiles(root)) { + const text = await fs.readFile(path.join(root, relative), 'utf8') + if (text.includes(oldId)) { + throw new ExtensionError( + 'EXTENSION_INVALID_MANIFEST', + `生成的项目里仍残留旧扩展 id:${relative}` + ) + } + } +} + +/** 从模板 ZIP 生成独立项目;全过程在暂存目录完成,成功后才落位。 */ +export async function createProjectFromTemplate( + input: CreateProjectInput +): Promise { + const target = await assertUsableTarget(input.targetDir) + if (input.extensionId === input.templateExtensionId) { + throw new ExtensionError('INVALID_REQUEST', '新项目必须使用不同的扩展 id') + } + + const staging = await createStaging(path.dirname(target)) + try { + await extractZip(input.zipPath, staging) + const rewritten = await rewriteExtensionIdentity( + staging, + input.templateExtensionId, + input.extensionId, + input.name + ) + await assertNoIdentityLeftover(staging, input.templateExtensionId) + await fs.rename(staging, target) + return { projectPath: target, rewrittenFiles: rewritten } + } catch (error) { + await cleanup(staging) + throw error + } +} + +/** 把已安装副本整体复制成外部项目(保留用户改过的代码)。 */ +export async function exportInstalledCopy( + sourceDir: string, + targetDir: string +): Promise<{ projectPath: string }> { + if (!existsSync(path.join(sourceDir, 'manifest.json'))) { + throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '安装副本不完整,无法导出') + } + const target = await assertUsableTarget(targetDir) + const staging = await createStaging(path.dirname(target)) + try { + await fs.cp(sourceDir, staging, { + recursive: true, + filter: (source) => { + const name = path.basename(source) + if (EXCLUDED_DIRECTORIES.has(name)) return false + if (shouldSkipFile(name)) return false + return true + } + }) + // 复制结果必须仍然可读,否则宁可失败也不留一个半成品项目。 + await fs.access(path.join(staging, 'manifest.json')) + await fs.rename(staging, target) + return { projectPath: target } + } catch (error) { + await cleanup(staging) + throw error + } +} diff --git a/src/main/extensions/extension-protocol.ts b/src/main/extensions/extension-protocol.ts index b5025e7..40f8ac9 100644 --- a/src/main/extensions/extension-protocol.ts +++ b/src/main/extensions/extension-protocol.ts @@ -46,7 +46,16 @@ export function registerExtensionScheme(): void { ]) } -export function installExtensionProtocolHandler(paths: ExtensionPaths): void { +export interface ExtensionProtocolDependencies { + paths: ExtensionPaths + /** + * 解析扩展代码根目录。开发模式下是外部源码目录, + * 必须与后台进程、Manifest 读取使用同一个解析器,否则页面会读到旧副本。 + */ + resolveRoot: (extensionId: string) => string | null +} + +export function installExtensionProtocolHandler(dependencies: ExtensionProtocolDependencies): void { protocol.handle(EXTENSION_SCHEME, async (request) => { try { const url = new URL(request.url) @@ -55,7 +64,8 @@ export function installExtensionProtocolHandler(paths: ExtensionPaths): void { const relative = decodeURIComponent(url.pathname).replace(/^\/+/, '') if (!isSafeRelativeEntryPath(relative)) return notFound() - const root = paths.installDir(extensionId) + const root = dependencies.resolveRoot(extensionId) + if (!root) return notFound() const resolved = path.resolve(root, relative) if (!isPathInside(root, resolved)) return notFound() const realRoot = await fs.realpath(root).catch(() => null) diff --git a/src/main/extensions/extension-registry.ts b/src/main/extensions/extension-registry.ts index 4a6bb99..fe0753a 100644 --- a/src/main/extensions/extension-registry.ts +++ b/src/main/extensions/extension-registry.ts @@ -4,7 +4,9 @@ import { normalizeExtensionPermissions, type ExtensionPermission } from '../../shared/extensions/permissions' -import { EXTENSION_API_VERSION } from '../../shared/extensions/manifest' +import { EXTENSION_API_VERSION, isValidExtensionId } from '../../shared/extensions/manifest' +import { ExtensionError } from '../../shared/extensions/errors' +import { normalizeExtensionSource, type ExtensionSource } from '../../shared/extensions/source' /** * 宿主侧的扩展安装状态。 @@ -20,49 +22,204 @@ export interface ExtensionRegistryRecord { grantedPermissions: ExtensionPermission[] installedAt: number updatedAt: number - source: 'directory' | 'package' + source: ExtensionSource + /** 来源为 `template` 时,记录是哪个官方模板装入的。 */ + templateId?: string + templateVersion?: string + /** + * 来源为 `development` 时的外部源码目录(本机绝对路径)。 + * + * 只属于这台机器的安装状态,不随扩展源码分发;换机器要重新链接。 + */ + developmentSourcePath?: string + /** + * 安装时的代码指纹;用于判断用户是否改过 `extensions/` 里的副本。 + * 缺失表示无法判断(旧版本安装或指纹计算失败),更新时必须保守处理。 + */ + installedCodeDigest?: string +} + +/** + * 一次恢复的记录。 + * + * 写进状态文件而不是只放在内存里:用户看到「状态曾损坏」之后重启, + * 提示必须还在,否则他永远不知道自己的启用状态被重置过。 + */ +export interface ExtensionRegistryRecovery { + at: number + kind: 'backup' | 'scan' + /** 损坏现场的**文件名**(不含目录)。 */ + corruptFile?: string } interface RegistryFile { version: number extensions: ExtensionRegistryRecord[] + recovery?: ExtensionRegistryRecovery } const REGISTRY_VERSION = 1 +/** 损坏现场最多保留的份数;超出时删除最旧的一份。 */ +const CORRUPT_KEEP_LIMIT = 3 -function normalizeRecord(value: unknown): ExtensionRegistryRecord | null { - if (!value || typeof value !== 'object') return null - const raw = value as Partial - const id = String(raw.id || '').trim() - if (!id) return null - const installedAt = Number(raw.installedAt) || 0 - return { - id, - version: String(raw.version || '0.0.0'), - apiVersion: String(raw.apiVersion || EXTENSION_API_VERSION), - // 缺字段一律视为未启用:不能因为文件被手工改坏就自动跑任意代码。 - enabled: raw.enabled === true, - grantedPermissions: normalizeExtensionPermissions(raw.grantedPermissions), - installedAt, - updatedAt: Number(raw.updatedAt) || installedAt, - source: raw.source === 'package' ? 'package' : 'directory' - } +/** + * 状态文件的可信度。 + * + * - `ok`:主文件有效,或文件不存在(全新安装,属于合法空状态)。 + * - `recovered-from-backup`:主文件损坏,用 `.bak` 重建过;记录已降级。 + * - `recovered-by-scan`:主文件与备份都不可用,由调用方扫描扩展目录重建; + * 记录一律降级为「未启用 + 无授权」。 + * - `unreadable`:无法读取且无法重建。此状态下**拒绝任何写入**, + * 否则会用空状态覆盖唯一可能人工抢救的现场。 + */ +export type ExtensionRegistryHealthState = + | 'ok' + | 'recovered-from-backup' + | 'recovered-by-scan' + | 'unreadable' + +export interface ExtensionRegistryHealth { + state: ExtensionRegistryHealthState + at: number + /** 损坏现场的**文件名**(不含目录);用于日志与排查,不渲染绝对路径。 */ + corruptFile?: string + message?: string } export interface ExtensionRegistryDependencies { registryFile: string now?: () => number + /** + * 主文件与备份均不可用时的重建来源。 + * + * 返回的记录会被强制改写为 `enabled: false`、`grantedPermissions: []`: + * 扫描到磁盘上有代码,不等于用户同意运行它。 + */ + recover?: () => ExtensionRegistryRecord[] +} + +type ParseResult = + | { ok: true; extensions: ExtensionRegistryRecord[]; recovery?: ExtensionRegistryRecovery } + | { ok: false; reason: string } + +function parseRegistryText(text: string): ParseResult { + if (!text.trim()) return { ok: false, reason: '状态文件为空' } + let raw: unknown + try { + raw = JSON.parse(text) + } catch { + return { ok: false, reason: '状态文件不是合法 JSON' } + } + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { + return { ok: false, reason: '状态文件顶层不是对象' } + } + const version = Number((raw as { version?: unknown }).version) + if (!Number.isInteger(version) || version < 1 || version > REGISTRY_VERSION) { + return { ok: false, reason: '状态文件版本不受支持' } + } + const list = (raw as { extensions?: unknown }).extensions + if (!Array.isArray(list)) return { ok: false, reason: 'extensions 不是数组' } + + const extensions: ExtensionRegistryRecord[] = [] + const seen = new Set() + for (const [index, item] of list.entries()) { + const parsed = parseRecord(item) + if (!parsed) return { ok: false, reason: `第 ${index + 1} 条扩展记录不合法` } + if (seen.has(parsed.id)) return { ok: false, reason: `扩展 id 重复:${parsed.id}` } + seen.add(parsed.id) + extensions.push(parsed) + } + return { ok: true, extensions, recovery: parseRecovery((raw as { recovery?: unknown }).recovery) } +} + +function parseRecovery(value: unknown): ExtensionRegistryRecovery | undefined { + if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined + const raw = value as Record + const at = Number(raw.at) + if (!Number.isFinite(at) || at <= 0) return undefined + const kind = raw.kind === 'backup' ? 'backup' : raw.kind === 'scan' ? 'scan' : null + if (!kind) return undefined + const corruptFile = + typeof raw.corruptFile === 'string' && raw.corruptFile.trim() + ? raw.corruptFile.trim().slice(0, 200) + : undefined + return { at, kind, ...(corruptFile ? { corruptFile } : {}) } +} + +/** + * 单条记录的严格解析。 + * + * 与「尽量兼容」相反:字段类型明显不对时整份文件判为损坏,由上层进入恢复流程。 + * 静默丢弃单条记录等于「部分数据丢失且不告知用户」。 + */ +function parseRecord(value: unknown): ExtensionRegistryRecord | null { + if (!value || typeof value !== 'object' || Array.isArray(value)) return null + const raw = value as Record + const id = String(raw.id ?? '').trim() + if (!isValidExtensionId(id)) return null + if (typeof raw.version !== 'string' || !raw.version.trim()) return null + + const installedAt = Number(raw.installedAt) + const updatedAt = Number(raw.updatedAt) + const templateId = + typeof raw.templateId === 'string' && raw.templateId.trim() + ? raw.templateId.trim().slice(0, 64) + : undefined + const templateVersion = + typeof raw.templateVersion === 'string' && raw.templateVersion.trim() + ? raw.templateVersion.trim().slice(0, 32) + : undefined + const developmentSourcePath = + typeof raw.developmentSourcePath === 'string' && raw.developmentSourcePath.trim() + ? raw.developmentSourcePath.trim().slice(0, 1024) + : undefined + const installedCodeDigest = + typeof raw.installedCodeDigest === 'string' && /^[a-f0-9]{64}$/.test(raw.installedCodeDigest) + ? raw.installedCodeDigest + : undefined + return { + id, + version: raw.version.trim().slice(0, 32), + apiVersion: + typeof raw.apiVersion === 'string' && raw.apiVersion.trim() + ? raw.apiVersion.trim().slice(0, 16) + : EXTENSION_API_VERSION, + // 缺字段一律视为未启用:不能因为文件被手工改坏就自动跑任意代码。 + enabled: raw.enabled === true, + grantedPermissions: normalizeExtensionPermissions(raw.grantedPermissions), + installedAt: Number.isFinite(installedAt) && installedAt > 0 ? installedAt : 0, + updatedAt: Number.isFinite(updatedAt) && updatedAt > 0 ? updatedAt : 0, + // 未知来源归为 `directory`:来源只能由可信的安装入口赋予,不能从文件里猜。 + source: normalizeExtensionSource(raw.source), + ...(templateId ? { templateId } : {}), + ...(templateVersion ? { templateVersion } : {}), + ...(developmentSourcePath ? { developmentSourcePath } : {}), + ...(installedCodeDigest ? { installedCodeDigest } : {}) + } } export class ExtensionRegistry { private readonly registryFile: string + private readonly backupFile: string private readonly now: () => number + private readonly recoverByScan: (() => ExtensionRegistryRecord[]) | null private state: RegistryFile = { version: REGISTRY_VERSION, extensions: [] } private loaded = false + /** + * 主文件当前是否含可解析内容。 + * + * 备份轮换只在这个标记为真时执行:主文件已经损坏时复制它,会把唯一的 + * 有效备份也换成坏数据。 + */ + private primaryValid = false + /** 只有 `unreadable` 需要内存态:连状态文件都写不进去,自然无法持久化。 */ + private unreadable: ExtensionRegistryHealth | null = null constructor(dependencies: ExtensionRegistryDependencies) { this.registryFile = dependencies.registryFile + this.backupFile = `${dependencies.registryFile}.bak` this.now = dependencies.now ?? (() => Date.now()) + this.recoverByScan = dependencies.recover ?? null } list(): ExtensionRegistryRecord[] { @@ -79,6 +236,43 @@ export class ExtensionRegistry { return this.list().find((record) => record.id === key) } + /** 状态文件的可信度;非 `ok` 时调用方必须向用户暴露,而不是当作「没装扩展」。 */ + getHealth(): ExtensionRegistryHealth { + this.ensureLoaded() + if (this.unreadable) return { ...this.unreadable } + const recovery = this.state.recovery + if (!recovery) return { state: 'ok', at: this.now() } + return { + state: recovery.kind === 'backup' ? 'recovered-from-backup' : 'recovered-by-scan', + at: recovery.at, + ...(recovery.corruptFile ? { corruptFile: recovery.corruptFile } : {}), + message: + recovery.kind === 'backup' + ? '扩展状态文件损坏,已从备份重建;所有扩展已暂停,请重新确认后启用' + : '扩展状态文件与备份均不可用,已按磁盘目录重建;所有扩展已暂停,请重新确认后启用' + } + } + + /** + * 用户确认「我知道发生过恢复」。 + * + * 只清除提示标记,不改动任何扩展的启用状态与授权——那些已经由恢复流程 + * 降级为「未启用 + 无授权」,需要用户逐个重新授权。 + */ + acknowledgeRecovery(): boolean { + this.ensureLoaded() + if (!this.state.recovery) return false + const previous = this.state + this.state = { version: REGISTRY_VERSION, extensions: this.state.extensions } + try { + this.persist() + } catch (error) { + this.state = previous + throw error + } + return true + } + upsert(record: ExtensionRegistryRecord): ExtensionRegistryRecord { this.ensureLoaded() const exists = this.state.extensions.some((item) => item.id === record.id) @@ -119,37 +313,242 @@ export class ExtensionRegistry { private ensureLoaded(): void { if (this.loaded) return this.loaded = true + this.load() + } + + private load(): void { + const stamp = this.now() + + if (!fs.existsSync(this.registryFile)) { + // 文件不存在是合法状态(首次安装),不是损坏。 + this.state = { version: REGISTRY_VERSION, extensions: [] } + this.primaryValid = false + return + } + + let text: string try { - const raw = fs.readJsonSync(this.registryFile) as unknown - if (!raw || typeof raw !== 'object') return - const list = (raw as { extensions?: unknown }).extensions - if (!Array.isArray(list)) return + text = fs.readFileSync(this.registryFile, 'utf8') + } catch (error) { + // 读取失败(权限、IO)与「内容损坏」是两件事:不移动文件,也不尝试覆盖。 + this.state = { version: REGISTRY_VERSION, extensions: [] } + this.primaryValid = false + this.unreadable = { + state: 'unreadable', + at: stamp, + message: error instanceof Error ? error.message.slice(0, 200) : '无法读取扩展状态文件' + } + return + } + + const parsed = parseRegistryText(text) + if (parsed.ok) { this.state = { version: REGISTRY_VERSION, - extensions: list - .map((item) => normalizeRecord(item)) - .filter((item): item is ExtensionRegistryRecord => item !== null) + extensions: parsed.extensions, + ...(parsed.recovery ? { recovery: parsed.recovery } : {}) + } + this.primaryValid = true + return + } + + const corruptFile = this.preserveCorrupt(text) + + const backup = this.tryLoadBackup() + if (backup) { + this.state = this.buildRecoveredState(backup, 'backup', corruptFile) + this.primaryValid = false + // 立即把降级后的状态写回主文件:恢复提示与「全部暂停」必须能跨重启保留。 + try { + this.writeState(this.state) + this.primaryValid = true + } catch { + // 保留内存状态即可,启动不应因为一次修复失败而中断。 + } + return + } + + const scanned = this.scan() + if (scanned) { + this.state = this.buildRecoveredState(scanned, 'scan', corruptFile) + this.primaryValid = false + // 刻意不写盘:损坏现场仍留在原位,用户可以在修复后重新读取。 + // 一旦用户执行任何写操作(启用/卸载),降级结果与恢复标记会一并落盘。 + return + } + + this.state = { version: REGISTRY_VERSION, extensions: [] } + this.primaryValid = false + this.unreadable = { + state: 'unreadable', + at: stamp, + ...(corruptFile ? { corruptFile } : {}), + message: '扩展状态文件损坏且无法恢复;为避免覆盖现场,已停止写入' + } + } + + /** + * 恢复出来的状态一律降级。 + * + * 备份最多落后一版,它可能记录着用户随后撤销的授权或关闭的开关。 + * 自动采纳等于「把用户已经收回的权限再发回去」,所以只保留身份与版本, + * 启用状态与授权全部清零,等用户重新确认。 + */ + private buildRecoveredState( + records: ExtensionRegistryRecord[], + kind: 'backup' | 'scan', + corruptFile?: string + ): RegistryFile { + return { + version: REGISTRY_VERSION, + extensions: records.map((record) => ({ + ...record, + enabled: false, + grantedPermissions: [], + updatedAt: this.now() + })), + recovery: { + at: this.now(), + kind, + ...(corruptFile ? { corruptFile } : {}) + } + } + } + + private tryLoadBackup(): ExtensionRegistryRecord[] | null { + try { + if (!fs.existsSync(this.backupFile)) return null + const parsed = parseRegistryText(fs.readFileSync(this.backupFile, 'utf8')) + return parsed.ok ? parsed.extensions : null + } catch { + return null + } + } + + private scan(): ExtensionRegistryRecord[] | null { + if (!this.recoverByScan) return null + let records: ExtensionRegistryRecord[] + try { + records = this.recoverByScan() + } catch { + return null + } + if (!Array.isArray(records)) return null + // 扫描结果只用于「知道有哪些扩展存在」,不继承任何授权或启用状态。 + return records.map((record) => ({ + ...record, + enabled: false, + grantedPermissions: [], + source: 'directory' as const + })) + } + + /** + * 把损坏内容写到 `.corrupt-<时间戳>`。 + * + * 保留现场是恢复的前提:用户可能手工修好它,或者授权更高版本的 TraceMemo 读取。 + */ + private preserveCorrupt(text: string): string | undefined { + const base = `${this.registryFile}.corrupt-${this.now().toString(36)}` + let target = base + let index = 1 + while (fs.existsSync(target)) { + target = `${base}-${index}` + index += 1 + } + try { + fs.writeFileSync(target, text, 'utf8') + this.pruneCorruptFiles() + return path.basename(target) + } catch { + return undefined + } + } + + private pruneCorruptFiles(): void { + try { + const directory = path.dirname(this.registryFile) + const prefix = `${path.basename(this.registryFile)}.corrupt-` + const files = fs + .readdirSync(directory) + .filter((name) => name.startsWith(prefix)) + .map((name) => ({ name, at: fs.statSync(path.join(directory, name)).mtimeMs })) + .sort((left, right) => left.at - right.at) + for (const file of files.slice(0, Math.max(0, files.length - CORRUPT_KEEP_LIMIT))) { + fs.removeSync(path.join(directory, file.name)) } } catch { - // 文件不存在 / 损坏都按「没有装过扩展」处理,不阻塞应用启动。 + // 清理失败不影响恢复本身。 } } private commit(extensions: ExtensionRegistryRecord[]): void { const previous = this.state - this.state = { version: REGISTRY_VERSION, extensions } + const previousValid = this.primaryValid + // 恢复标记必须跟着普通写入一起保留:否则用户启用一个扩展就把 + // 「其余扩展全部暂停过」的提示抹掉了。 + this.state = { + version: REGISTRY_VERSION, + extensions, + ...(previous.recovery ? { recovery: previous.recovery } : {}) + } try { this.persist() } catch (error) { this.state = previous + this.primaryValid = previousValid throw error } } private persist(): void { - fs.ensureDirSync(path.dirname(this.registryFile)) + if (this.unreadable) { + throw new ExtensionError( + 'EXTENSION_REGISTRY_UNREADABLE', + '扩展状态文件损坏且无法恢复,已拒绝写入以保留现场' + ) + } + this.rotateBackup() + this.writeState(this.state) + this.primaryValid = true + } + + /** + * 用当前主文件刷新 `.bak`。 + * + * 三重保护: + * 1. 主文件不可信(`primaryValid === false`)时直接跳过; + * 2. 先写 `.bak.tmp` 并重新解析,拒绝把坏内容升级成备份; + * 3. 成功后才 rename 覆盖旧备份,失败时旧备份原样保留。 + */ + private rotateBackup(): void { + if (!this.primaryValid) return + if (!fs.existsSync(this.registryFile)) return + const temporary = `${this.backupFile}.tmp` + try { + fs.copyFileSync(this.registryFile, temporary) + const parsed = parseRegistryText(fs.readFileSync(temporary, 'utf8')) + if (!parsed.ok) { + fs.removeSync(temporary) + return + } + fs.moveSync(temporary, this.backupFile, { overwrite: true }) + } catch { + fs.removeSync(temporary) + } + } + + /** 临时文件 → 读回校验 → 原子替换;中途失败不会留下半写的主文件。 */ + private writeState(state: RegistryFile): void { + const directory = path.dirname(this.registryFile) + fs.ensureDirSync(directory) const temporary = `${this.registryFile}.tmp` - fs.writeJsonSync(temporary, this.state, { spaces: 2 }) + fs.writeFileSync(temporary, JSON.stringify(state, null, 2), 'utf8') + const parsed = parseRegistryText(fs.readFileSync(temporary, 'utf8')) + if (!parsed.ok) { + fs.removeSync(temporary) + throw new ExtensionError('EXTENSION_REGISTRY_UNREADABLE', `写入前校验失败:${parsed.reason}`) + } fs.moveSync(temporary, this.registryFile, { overwrite: true }) } } diff --git a/src/main/extensions/extension-root-resolver.ts b/src/main/extensions/extension-root-resolver.ts new file mode 100644 index 0000000..5502bdb --- /dev/null +++ b/src/main/extensions/extension-root-resolver.ts @@ -0,0 +1,143 @@ +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { ExtensionError } from '../../shared/extensions/errors' +import type { ExtensionSource } from '../../shared/extensions/source' +import { isPathInside, isSamePath, type ExtensionPaths } from './extension-paths' +import type { ExtensionRegistryRecord } from './extension-registry' + +export interface ExtensionRootInfo { + extensionId: string + /** 代码根目录(已 realpath)。 */ + root: string + source: ExtensionSource + /** 开发模式下用户选择时的目录(同样是 realpath)。 */ + developmentSourcePath?: string +} + +export interface ExtensionRootResolver { + /** + * 解析扩展代码根目录。 + * + * 抛 `EXTENSION_SOURCE_MISSING` 表示开发目录不可用;调用方必须保留 Registry + * 与配置,把扩展标成「源码目录不可用」,而不是当成「没装过」。 + */ + resolve(extensionId: string): ExtensionRootInfo + /** 只看正式安装目录,用于导出、回滚等必须触碰安装副本的场景。 */ + installedRoot(extensionId: string): string +} + +export interface ExtensionRootResolverDependencies { + paths: ExtensionPaths + getRecord: (extensionId: string) => ExtensionRegistryRecord | undefined + /** 测试注入点。 */ + realpath?: (target: string) => string + stat?: (target: string) => { isDirectory: () => boolean } +} + +/** + * 所有扩展代码根目录的唯一来源。 + * + * 在这之前,代码目录被 manager、protocol、catalog 各自拼 `paths.installDir(id)`, + * 开发模式一旦接入就会出现「后台读外部目录、页面读安装副本」的错位。 + */ +export function createExtensionRootResolver( + dependencies: ExtensionRootResolverDependencies +): ExtensionRootResolver { + const realpath = dependencies.realpath ?? ((target: string) => fs.realpathSync(target)) + const stat = dependencies.stat ?? ((target: string) => fs.statSync(target)) + + function resolveInstalled(extensionId: string): string { + return dependencies.paths.installDir(extensionId) + } + + return { + installedRoot: resolveInstalled, + + resolve(extensionId: string): ExtensionRootInfo { + const record = dependencies.getRecord(extensionId) + if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND') + if (record.source !== 'development' || !record.developmentSourcePath) { + return { extensionId, root: resolveInstalled(extensionId), source: record.source } + } + + const configured = record.developmentSourcePath + let realRoot: string + try { + realRoot = realpath(configured) + } catch { + throw new ExtensionError( + 'EXTENSION_SOURCE_MISSING', + '开发源码目录不可用,请重新选择或移除链接' + ) + } + let isDirectory = false + try { + isDirectory = stat(realRoot).isDirectory() + } catch { + isDirectory = false + } + if (!isDirectory) { + throw new ExtensionError('EXTENSION_SOURCE_MISSING', '开发源码路径不是目录') + } + + assertSafeDevelopmentRoot(dependencies.paths, extensionId, realRoot) + return { + extensionId, + root: realRoot, + source: 'development', + developmentSourcePath: realRoot + } + } + } +} + +/** + * 开发目录的安全边界。 + * + * 拒绝三类位置: + * 1. 扩展自己的安装副本(否则「开发模式」等于原地打转,卸载还会误删); + * 2. 宿主的私有数据区(配置、状态、日志、暂存)——那里有用户凭据; + * 3. 文件系统根 / 用户主目录(自定义协议会把整个目录开放给 iframe)。 + */ +function safeRealpath(target: string): string { + try { + return fs.realpathSync(target) + } catch { + return path.resolve(target) + } +} + +export function assertSafeDevelopmentRoot( + paths: ExtensionPaths, + extensionId: string, + realRoot: string +): void { + const forbidden: Array<{ root: string; reason: string }> = [ + { root: paths.installDir(extensionId), reason: '不能指向扩展自己的安装目录' }, + { root: paths.extensionsDir, reason: '不能指向扩展安装根目录' }, + { root: paths.dataDir, reason: '不能指向宿主私有数据目录' }, + { root: paths.stateDir, reason: '不能指向宿主状态目录' }, + { root: paths.stagingDir, reason: '不能指向宿主暂存目录' } + ] + for (const item of forbidden) { + // 两侧都必须 realpath:macOS 上 `/tmp` 指向 `/private/tmp`, + // 只比较字符串会让「extensions-data 里的目录」冒充外部项目。 + const forbiddenRoot = safeRealpath(item.root) + if (isSamePath(forbiddenRoot, realRoot) || isPathInside(forbiddenRoot, realRoot)) { + throw new ExtensionError('EXTENSION_INVALID_PATH', item.reason) + } + } + + const parsed = path.parse(realRoot) + if (realRoot === parsed.root) { + throw new ExtensionError('EXTENSION_INVALID_PATH', '不能把文件系统根目录作为扩展源码') + } + try { + if (isSamePath(os.homedir(), realRoot)) { + throw new ExtensionError('EXTENSION_INVALID_PATH', '不能把用户主目录作为扩展源码') + } + } catch (error) { + if (error instanceof ExtensionError) throw error + } +} diff --git a/src/main/extensions/extension-secret-store.ts b/src/main/extensions/extension-secret-store.ts new file mode 100644 index 0000000..358cee1 --- /dev/null +++ b/src/main/extensions/extension-secret-store.ts @@ -0,0 +1,174 @@ +import fs from 'fs-extra' +import path from 'node:path' +import { ExtensionError } from '../../shared/extensions/errors' + +/** 加密实现由主进程注入(Electron `safeStorage`),本模块不直接依赖 electron。 */ +export interface ExtensionSecretCipher { + isAvailable: () => boolean + encrypt: (plain: string) => Buffer + decrypt: (payload: Buffer) => string +} + +export interface ExtensionSecretStoreDependencies { + /** 通常是 `/extensions-state/secrets`。 */ + root: string + cipher: ExtensionSecretCipher + now?: () => number +} + +interface SecretFile { + version: 1 + values: Record +} + +const MAX_KEY_LENGTH = 64 +const MAX_VALUE_BYTES = 8 * 1024 +const MAX_KEYS = 32 +const SECRET_KEY_PATTERN = /^[a-zA-Z][a-zA-Z0-9._-]{0,63}$/ + +/** + * 扩展私有凭据。 + * + * 设计取舍: + * - 每个扩展一个文件、一个命名空间,A 扩展拿不到 B 的键; + * - 落盘只有 `safeStorage` 加密后的密文,**不再产生明文 .txt**; + * - 加密不可用时直接失败,绝不退化成明文——宁可让用户知道「这台机器不支持」, + * 也不要把 Cookie 摊在磁盘上。 + * + * 这不是操作系统级沙箱:扩展后台是拥有 Node 权限的本地进程,能读别的文件。 + * 它能防的是「普通 SDK / 页面桥跨扩展取密钥」与「意外明文落盘」。 + */ +export class ExtensionSecretStore { + private readonly root: string + private readonly cipher: ExtensionSecretCipher + private readonly now: () => number + private readonly cache = new Map() + + constructor(dependencies: ExtensionSecretStoreDependencies) { + this.root = dependencies.root + this.cipher = dependencies.cipher + this.now = dependencies.now ?? (() => Date.now()) + } + + isAvailable(): boolean { + try { + return this.cipher.isAvailable() + } catch { + return false + } + } + + /** 只返回键名与数量,不返回值;供 UI 显示「是否已配置」。 */ + listKeys(extensionId: string): string[] { + return Object.keys(this.read(extensionId).values).sort() + } + + has(extensionId: string, key: string): boolean { + const name = assertKey(key) + return Object.prototype.hasOwnProperty.call(this.read(extensionId).values, name) + } + + get(extensionId: string, key: string): string | null { + const name = assertKey(key) + const values = this.read(extensionId).values + return Object.prototype.hasOwnProperty.call(values, name) ? values[name] : null + } + + set(extensionId: string, key: string, value: string): void { + const name = assertKey(key) + if (typeof value !== 'string') throw new ExtensionError('INVALID_REQUEST', '凭据值必须是字符串') + if (new TextEncoder().encode(value).length > MAX_VALUE_BYTES) { + throw new ExtensionError('INVALID_REQUEST', '凭据超过 8KB 上限') + } + const file = this.read(extensionId) + if ( + !Object.prototype.hasOwnProperty.call(file.values, name) && + Object.keys(file.values).length >= MAX_KEYS + ) { + throw new ExtensionError('INVALID_REQUEST', `单个扩展最多保存 ${MAX_KEYS} 个凭据`) + } + file.values[name] = value + this.write(extensionId, file) + } + + delete(extensionId: string, key: string): boolean { + const name = assertKey(key) + const file = this.read(extensionId) + if (!Object.prototype.hasOwnProperty.call(file.values, name)) return false + delete file.values[name] + this.write(extensionId, file) + return true + } + + /** 卸载扩展且用户选择清除数据时调用。 */ + clear(extensionId: string): void { + this.cache.delete(extensionId) + fs.removeSync(this.filePath(extensionId)) + } + + private filePath(extensionId: string): string { + return path.join(this.root, `${extensionId}.bin`) + } + + private read(extensionId: string): SecretFile { + const cached = this.cache.get(extensionId) + if (cached) return { version: 1, values: { ...cached.values } } + const file = this.filePath(extensionId) + if (!fs.existsSync(file)) { + const empty: SecretFile = { version: 1, values: {} } + this.cache.set(extensionId, empty) + return { version: 1, values: {} } + } + this.assertAvailable() + let parsed: SecretFile + try { + const payload = fs.readFileSync(file) + const text = this.cipher.decrypt(payload) + const raw = JSON.parse(text) as unknown + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('结构不合法') + const values: Record = {} + for (const [key, value] of Object.entries((raw as { values?: unknown }).values ?? {})) { + if (SECRET_KEY_PATTERN.test(key) && typeof value === 'string') values[key] = value + } + parsed = { version: 1, values } + } catch { + // 解不开就当作没有:不能把损坏的密文当成空口令去覆盖(写盘会覆盖原文件)。 + throw new ExtensionError( + 'EXTENSION_STORAGE_CORRUPTED', + '扩展凭据无法解密(可能换了机器或系统密钥变更),请在扩展页面重新填写' + ) + } + this.cache.set(extensionId, parsed) + return { version: 1, values: { ...parsed.values } } + } + + private write(extensionId: string, file: SecretFile): void { + this.assertAvailable() + const payload = this.cipher.encrypt(JSON.stringify({ version: 1, values: file.values })) + fs.ensureDirSync(this.root) + const target = this.filePath(extensionId) + const temporary = `${target}.tmp` + fs.writeFileSync(temporary, payload, { mode: 0o600 }) + fs.moveSync(temporary, target, { overwrite: true }) + try { + fs.chmodSync(target, 0o600) + } catch { + // Windows 不支持 POSIX 权限位;忽略即可。 + } + this.cache.set(extensionId, { version: 1, values: { ...file.values } }) + void this.now + } + + private assertAvailable(): void { + if (this.isAvailable()) return + throw new ExtensionError('CAPABILITY_UNAVAILABLE', '当前系统不支持安全存储,扩展凭据功能不可用') + } +} + +function assertKey(value: string): string { + const key = String(value ?? '').trim() + if (!SECRET_KEY_PATTERN.test(key) || key.length > MAX_KEY_LENGTH) { + throw new ExtensionError('INVALID_REQUEST', '凭据键名不合法') + } + return key +} diff --git a/src/main/extensions/extension-service.ts b/src/main/extensions/extension-service.ts index 67b48ae..d013163 100644 --- a/src/main/extensions/extension-service.ts +++ b/src/main/extensions/extension-service.ts @@ -1,3 +1,5 @@ +import { app, safeStorage } from 'electron' +import path from 'node:path' import { AIProviderService } from '../services/ai-provider-service' import { getChatDb, @@ -20,6 +22,19 @@ import { getExtensionPaths } from './extension-paths' let manager: ExtensionManager | null = null +/** + * 官方模板资源根目录。 + * + * 打包后是 `/extension-templates`;开发态读构建产物目录。 + * 两者都不指向 `examples/extensions`——源码树不是运行时依赖。 + */ +function resolveTemplateRoot(): string { + const override = process.env.TRACEMEMO_EXTENSION_TEMPLATES_DIR + if (override && override.trim()) return path.resolve(override.trim()) + if (app.isPackaged) return path.join(process.resourcesPath, 'extension-templates') + return path.join(app.getAppPath(), 'build', 'extension-templates') +} + export interface ExtensionSystemOptions { appVersion: string onChange: (extensionId: string, reason: string) => void @@ -53,6 +68,11 @@ export async function initExtensionSystem(options: ExtensionSystemOptions): Prom } }, aiChat: chatWithConfiguredProvider, + aiStatus: () => { + // 只读「是否已配置 + 模型显示名」,不返回 key 或 endpoint。 + const config = new AIProviderService().getRuntimeConfig() + return { configured: config.configured, modelName: config.modelName } + }, getAccountId: () => String(getSelfAccountInfo()?.wxid || ''), getSelfUsernames: () => { try { @@ -68,6 +88,12 @@ export async function initExtensionSystem(options: ExtensionSystemOptions): Prom return false } }, + templatesRoot: resolveTemplateRoot(), + secretCipher: { + isAvailable: () => safeStorage.isEncryptionAvailable(), + encrypt: (plain: string) => safeStorage.encryptString(plain), + decrypt: (payload: Buffer) => safeStorage.decryptString(payload) + }, onChange: (extensionId, reason) => options.onChange(extensionId, reason) }) await manager.initialize() diff --git a/src/main/extensions/extension-storage.ts b/src/main/extensions/extension-storage.ts index 1919073..00e93e3 100644 --- a/src/main/extensions/extension-storage.ts +++ b/src/main/extensions/extension-storage.ts @@ -1,6 +1,7 @@ import fs from 'fs-extra' import path from 'node:path' import { ExtensionError } from '../../shared/extensions/errors' +import type { ExtensionStorageHealthState } from '../../shared/extensions/types' const STORAGE_FILE = 'storage.json' const STORAGE_VERSION = 1 @@ -8,17 +9,59 @@ const MAX_KEY_LENGTH = 64 const MAX_VALUE_BYTES = 256 * 1024 const MAX_TOTAL_BYTES = 1024 * 1024 const KEY_PATTERN = /^[A-Za-z0-9._-]{1,64}$/ +/** 每个扩展最多保留的损坏现场份数;超出时删除最旧的。 */ +const CORRUPT_KEEP_LIMIT = 3 interface StorageFile { version: number values: Record } +export interface ExtensionStorageHealth { + state: ExtensionStorageHealthState + at: number + /** 损坏现场的**文件名**(不含目录);不渲染绝对路径。 */ + corruptFile?: string + message?: string +} + export interface ExtensionStorageDependencies { /** 通常是 `/extensions-data`。 */ dataRoot: string maxTotalBytes?: number maxValueBytes?: number + now?: () => number + /** + * 健康状态发生变化时的通知。 + * + * 运行期才发生损坏/回退时,宿主要靠这个立刻收住扩展—— + * 只等下一次启动才处理,那台机器人已经用旧配置发完消息了。 + */ + onHealthChange?: (extensionId: string, health: ExtensionStorageHealth) => void +} + +type ParseResult = { ok: true; values: Record } | { ok: false; reason: string } + +function parseStorageText(text: string): ParseResult { + if (!text.trim()) return { ok: false, reason: '存储文件为空' } + let raw: unknown + try { + raw = JSON.parse(text) + } catch { + return { ok: false, reason: '存储文件不是合法 JSON' } + } + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { + return { ok: false, reason: '存储文件顶层不是对象' } + } + const version = Number((raw as { version?: unknown }).version) + if (!Number.isInteger(version) || version !== STORAGE_VERSION) { + return { ok: false, reason: '存储文件版本不受支持' } + } + const values = (raw as { values?: unknown }).values + if (!values || typeof values !== 'object' || Array.isArray(values)) { + return { ok: false, reason: 'values 不是对象' } + } + return { ok: true, values: values as Record } } /** @@ -28,16 +71,25 @@ export interface ExtensionStorageDependencies { * - 每个扩展一个独立目录,键空间互不可见; * - 单值 / 总量都有上限,写入前先序列化,**不存无法序列化的值**; * - 卸载时由 `ExtensionInstaller` 决定是否删除,本类不主动清理。 + * + * 损坏语义:主文件解析失败时先尝试 `storage.json.bak`;两者都不可用时, + * 该扩展进入 `unrecovered` 状态,`set` 会被拒绝。宁可让扩展报错, + * 也不能用一次写入把用户唯一的一份配置覆盖成空。 */ export class ExtensionStorage { private readonly dataRoot: string private readonly maxTotalBytes: number private readonly maxValueBytes: number + private readonly now: () => number + private readonly onHealthChange?: ExtensionStorageDependencies['onHealthChange'] + private readonly healthByExtension = new Map() constructor(dependencies: ExtensionStorageDependencies) { this.dataRoot = dependencies.dataRoot this.maxTotalBytes = dependencies.maxTotalBytes ?? MAX_TOTAL_BYTES this.maxValueBytes = dependencies.maxValueBytes ?? MAX_VALUE_BYTES + this.now = dependencies.now ?? (() => Date.now()) + this.onHealthChange = dependencies.onHealthChange } filePath(extensionId: string): string { @@ -51,6 +103,7 @@ export class ExtensionStorage { get(extensionId: string, key: unknown): unknown { const name = assertKey(key) const values = this.read(extensionId).values + this.assertReadable(extensionId) return Object.prototype.hasOwnProperty.call(values, name) ? clone(values[name]) : undefined } @@ -61,6 +114,7 @@ export class ExtensionStorage { throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '单个存储值超出上限') } const file = this.read(extensionId) + this.assertReadable(extensionId) file.values[name] = JSON.parse(serialized) this.assertTotalSize(file) this.write(extensionId, file) @@ -69,6 +123,7 @@ export class ExtensionStorage { remove(extensionId: string, key: unknown): boolean { const name = assertKey(key) const file = this.read(extensionId) + this.assertReadable(extensionId) if (!Object.prototype.hasOwnProperty.call(file.values, name)) return false delete file.values[name] this.write(extensionId, file) @@ -77,6 +132,7 @@ export class ExtensionStorage { list(extensionId: string): Array<{ key: string; value: unknown }> { const values = this.read(extensionId).values + this.assertReadable(extensionId) return Object.keys(values).map((key) => ({ key, value: clone(values[key]) })) } @@ -84,29 +140,219 @@ export class ExtensionStorage { this.write(extensionId, { version: STORAGE_VERSION, values: {} }) } + /** + * 显式重置:保留损坏现场,然后把存储清空。 + * + * 只允许用户从界面触发;扩展自身不能调用(`tm.storage` 没有这个能力)。 + */ + reset(extensionId: string): void { + this.read(extensionId) + this.writeState(extensionId, { version: STORAGE_VERSION, values: {} }, { rotateBackup: false }) + this.healthByExtension.set(extensionId, { state: 'ok', at: this.now() }) + } + + /** + * 用户确认「接受从备份恢复出来的配置」。 + * + * 恢复出来的内容可能落后一版——比如机器人开关还停在 `true`。 + * 在用户点这一下之前,宿主不会启动该扩展(见 `ExtensionManager` 的启动前检查)。 + */ + acknowledge(extensionId: string): void { + const current = this.health(extensionId) + if (current.state !== 'recovered-from-backup') { + throw new ExtensionError('INVALID_REQUEST', '当前没有待确认的配置恢复') + } + this.healthByExtension.set(extensionId, { state: 'ok', at: this.now() }) + } + + /** + * 未确认的恢复 / 无法恢复时,读写一律拒绝。 + * + * 只让 `health()` 与 `reset()` / `acknowledge()` 能穿过这道闸: + * 前者给界面看状态,后两者是用户的显式处理动作。 + */ + private assertReadable(extensionId: string): void { + const health = this.healthByExtension.get(extensionId) + if (!health || health.state === 'ok') return + if (health.state === 'recovered-from-backup') { + throw new ExtensionError( + 'EXTENSION_STORAGE_CORRUPTED', + '扩展配置刚从备份恢复,用户确认前读写已暂停' + ) + } + throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展配置已损坏且没有可用备份') + } + + private reportHealth(extensionId: string, health: ExtensionStorageHealth): void { + this.healthByExtension.set(extensionId, health) + if (health.state === 'ok') return + try { + this.onHealthChange?.(extensionId, health) + } catch { + // 通知失败不能反过来影响存储读写。 + } + } + + health(extensionId: string): ExtensionStorageHealth { + this.read(extensionId) + return { ...(this.healthByExtension.get(extensionId) ?? { state: 'ok', at: this.now() }) } + } + private read(extensionId: string): StorageFile { const filePath = this.filePath(extensionId) - try { - const raw = fs.readJsonSync(filePath) as unknown - if (!raw || typeof raw !== 'object') return { version: STORAGE_VERSION, values: {} } - const values = (raw as { values?: unknown }).values - if (!values || typeof values !== 'object' || Array.isArray(values)) { - return { version: STORAGE_VERSION, values: {} } - } - return { version: STORAGE_VERSION, values: values as Record } - } catch { + if (!fs.existsSync(filePath)) { + this.reportHealth(extensionId, { state: 'ok', at: this.now() }) return { version: STORAGE_VERSION, values: {} } } + + let text: string + try { + text = fs.readFileSync(filePath, 'utf8') + } catch (error) { + this.reportHealth(extensionId, { + state: 'unrecovered', + at: this.now(), + message: error instanceof Error ? error.message.slice(0, 200) : '无法读取扩展配置' + }) + return { version: STORAGE_VERSION, values: {} } + } + + const parsed = parseStorageText(text) + if (parsed.ok) { + // `recovered-from-backup` 要保留到用户看到它为止:恢复成功后立刻改回 `ok`, + // 界面就再也不会提示「这份配置曾经损坏过」。 + const current = this.healthByExtension.get(extensionId) + if (current?.state !== 'recovered-from-backup') { + this.reportHealth(extensionId, { state: 'ok', at: this.now() }) + } + return { version: STORAGE_VERSION, values: parsed.values } + } + + const corruptFile = this.preserveCorrupt(extensionId, text) + const backup = this.tryLoadBackup(extensionId) + if (backup) { + this.reportHealth(extensionId, { + state: 'recovered-from-backup', + at: this.now(), + ...(corruptFile ? { corruptFile } : {}), + message: '扩展配置损坏,已从备份恢复' + }) + try { + // 主文件此刻是坏的,不能让它进入备份轮换,否则会覆盖刚读到的有效备份。 + this.writeState( + extensionId, + { version: STORAGE_VERSION, values: backup }, + { rotateBackup: false } + ) + } catch { + // 提升备份失败时仍返回备份内容,下次写入会再试。 + } + return { version: STORAGE_VERSION, values: backup } + } + + this.reportHealth(extensionId, { + state: 'unrecovered', + at: this.now(), + ...(corruptFile ? { corruptFile } : {}), + message: '扩展配置损坏且没有可用备份;写入已停止以保留现场' + }) + return { version: STORAGE_VERSION, values: {} } + } + + private tryLoadBackup(extensionId: string): Record | null { + const backupPath = `${this.filePath(extensionId)}.bak` + try { + if (!fs.existsSync(backupPath)) return null + const parsed = parseStorageText(fs.readFileSync(backupPath, 'utf8')) + return parsed.ok ? parsed.values : null + } catch { + return null + } + } + + private preserveCorrupt(extensionId: string, text: string): string | undefined { + const filePath = this.filePath(extensionId) + const base = `${filePath}.corrupt-${this.now().toString(36)}` + let target = base + let index = 1 + while (fs.existsSync(target)) { + target = `${base}-${index}` + index += 1 + } + try { + fs.ensureDirSync(path.dirname(filePath)) + fs.writeFileSync(target, text, 'utf8') + this.pruneCorruptFiles(extensionId) + return path.basename(target) + } catch { + return undefined + } + } + + private pruneCorruptFiles(extensionId: string): void { + try { + const directory = path.dirname(this.filePath(extensionId)) + const prefix = `${STORAGE_FILE}.corrupt-` + const files = fs + .readdirSync(directory) + .filter((name) => name.startsWith(prefix)) + .map((name) => ({ name, at: fs.statSync(path.join(directory, name)).mtimeMs })) + .sort((left, right) => left.at - right.at) + for (const file of files.slice(0, Math.max(0, files.length - CORRUPT_KEEP_LIMIT))) { + fs.removeSync(path.join(directory, file.name)) + } + } catch { + // 清理失败不影响恢复本身。 + } } private write(extensionId: string, file: StorageFile): void { + this.writeState(extensionId, file, { rotateBackup: true }) + this.reportHealth(extensionId, { state: 'ok', at: this.now() }) + } + + /** + * 主文件 → `.bak` → 新内容。 + * + * `rotateBackup` 只在主文件可信时为真:从备份恢复、显式重置这两条路径 + * 面对的主文件都是坏的,让它们参与轮换会把有效备份一起换掉。 + */ + private writeState( + extensionId: string, + file: StorageFile, + options: { rotateBackup: boolean } + ): void { const filePath = this.filePath(extensionId) fs.ensureDirSync(path.dirname(filePath)) + if (options.rotateBackup) this.rotateBackup(extensionId) const temporary = `${filePath}.tmp` - fs.writeJsonSync(temporary, file, { spaces: 2 }) + fs.writeFileSync(temporary, JSON.stringify(file, null, 2), 'utf8') + const parsed = parseStorageText(fs.readFileSync(temporary, 'utf8')) + if (!parsed.ok) { + fs.removeSync(temporary) + throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', `写入前校验失败:${parsed.reason}`) + } fs.moveSync(temporary, filePath, { overwrite: true }) } + private rotateBackup(extensionId: string): void { + const filePath = this.filePath(extensionId) + if (!fs.existsSync(filePath)) return + const backupPath = `${filePath}.bak` + const temporary = `${backupPath}.tmp` + try { + fs.copyFileSync(filePath, temporary) + const parsed = parseStorageText(fs.readFileSync(temporary, 'utf8')) + if (!parsed.ok) { + fs.removeSync(temporary) + return + } + fs.moveSync(temporary, backupPath, { overwrite: true }) + } catch { + fs.removeSync(temporary) + } + } + private assertTotalSize(file: StorageFile): void { const bytes = Buffer.byteLength(JSON.stringify(file.values), 'utf8') if (bytes > this.maxTotalBytes) { diff --git a/src/main/extensions/extension-template-catalog.ts b/src/main/extensions/extension-template-catalog.ts new file mode 100644 index 0000000..6742b5c --- /dev/null +++ b/src/main/extensions/extension-template-catalog.ts @@ -0,0 +1,407 @@ +import { existsSync, promises as fs } from 'node:fs' +import path from 'node:path' +import { createHash } from 'node:crypto' +import { ExtensionError } from '../../shared/extensions/errors' +import { compareSemver } from '../../shared/extensions/manifest' +import type { ExtensionRegistryRecord } from './extension-registry' +import { normalizeExtensionPermissions } from '../../shared/extensions/permissions' + +import type { + ExtensionTemplateEntry, + ExtensionTemplateRequirement, + ExtensionTemplateStatus, + TemplateDependencyCheck +} from '../../shared/extensions/templates' + +export type { + ExtensionTemplateEntry, + ExtensionTemplateRequirement, + ExtensionTemplateState, + ExtensionTemplateStatus, + TemplateDependencyCheck +} from '../../shared/extensions/templates' + +export interface ExtensionTemplateCatalogDependencies { + /** 模板资源根目录;打包后是 `/extension-templates`。 */ + templateRoot: string + getRecord: (extensionId: string) => ExtensionRegistryRecord | undefined + /** 已安装扩展的代码目录;用来看依赖脚本在不在。 */ + resolveInstallDir: (extensionId: string) => string + platform?: NodeJS.Platform + /** 测试注入点:默认用真实文件系统。 */ + exists?: (filePath: string) => boolean + readFile?: (filePath: string) => Promise + /** 依赖探测注入点:默认读本机 PATH 与常见安装位置。 */ + probePython?: () => string | null + probeChrome?: () => string | null +} + +const INDEX_FILE = 'index.json' +const SUPPORTED_INDEX_VERSION = 1 + +interface TemplateIndexFile { + version: number + templates: unknown[] +} + +function parseRequirement(input: unknown): ExtensionTemplateRequirement { + if (!input || typeof input !== 'object' || Array.isArray(input)) return {} + const raw = input as Record + const result: ExtensionTemplateRequirement = {} + for (const key of ['python', 'chrome', 'externalScript'] as const) { + const value = raw[key] + if (value === true || value === false) { + result[key] = value as never + continue + } + if (value && typeof value === 'object' && !Array.isArray(value)) { + const item = value as Record + const required = item.required === true + if (key === 'externalScript') { + const scriptPath = typeof item.path === 'string' ? item.path.trim() : '' + if (!scriptPath) continue + result.externalScript = { + required, + path: scriptPath, + ...(typeof item.reason === 'string' ? { reason: item.reason.slice(0, 200) } : {}) + } + continue + } + if (key === 'python') { + result.python = { + required, + ...(typeof item.minVersion === 'string' ? { minVersion: item.minVersion } : {}), + ...(typeof item.reason === 'string' ? { reason: item.reason.slice(0, 200) } : {}) + } + continue + } + result.chrome = { + required, + ...(typeof item.reason === 'string' ? { reason: item.reason.slice(0, 200) } : {}) + } + } + } + return result +} + +function parseEntry(input: unknown): ExtensionTemplateEntry | null { + if (!input || typeof input !== 'object' || Array.isArray(input)) return null + const raw = input as Record + const templateId = String(raw.templateId ?? '').trim() + const extensionId = String(raw.extensionId ?? '').trim() + const name = String(raw.name ?? '').trim() + const version = String(raw.version ?? '').trim() + const file = String(raw.file ?? '').trim() + const sha256 = String(raw.sha256 ?? '').trim() + if (!templateId || !extensionId || !name || !version || !file || !sha256) return null + // 索引来自资源目录,但依然不接受任何路径片段:读取时只拼在模板根目录下。 + if (file.includes('/') || file.includes('\\') || file.includes('..')) return null + if (!/^[a-f0-9]{64}$/.test(sha256)) return null + const platforms = Array.isArray(raw.platforms) + ? raw.platforms.filter((item): item is NodeJS.Platform => typeof item === 'string') + : [] + return { + templateId, + extensionId, + name, + version, + ...(typeof raw.description === 'string' ? { description: raw.description.slice(0, 500) } : {}), + permissions: normalizeExtensionPermissions(raw.permissions), + file, + sha256, + bytes: Number(raw.bytes) || 0, + fileCount: Number(raw.fileCount) || 0, + platforms, + requires: parseRequirement(raw.requires) + } +} + +/** + * 官方模板目录。 + * + * 只做三件事:读索引、校验资源、把模板与已安装状态对上。 + * 安装动作本身不在这里——它由 `ExtensionManager` 走统一的安装器, + * 避免出现第二套 ZIP 解压逻辑。 + */ +export class ExtensionTemplateCatalog { + private readonly dependencies: ExtensionTemplateCatalogDependencies + private readonly platform: NodeJS.Platform + private cachedIndex: ExtensionTemplateEntry[] | null = null + + constructor(dependencies: ExtensionTemplateCatalogDependencies) { + this.dependencies = dependencies + this.platform = dependencies.platform ?? process.platform + } + + /** 索引读取失败时返回空列表:模板资源缺失不应该让扩展中心整页崩掉。 */ + async list(): Promise { + const entries = await this.loadIndex() + const result: ExtensionTemplateStatus[] = [] + for (const template of entries) { + result.push(await this.describe(template)) + } + return result.sort((left, right) => + left.template.templateId.localeCompare(right.template.templateId) + ) + } + + get(templateId: string): ExtensionTemplateEntry | undefined { + return this.cachedIndex?.find((item) => item.templateId === templateId) + } + + /** + * 取模板 ZIP 的绝对路径,并校验内容哈希。 + * + * 这一步是安装前的最后一道闸:索引与 ZIP 若被单独替换,哈希就对不上, + * 直接拒绝安装而不是把未知内容装进用户目录。 + */ + async resolveZip( + templateId: string + ): Promise<{ path: string; template: ExtensionTemplateEntry }> { + const entries = await this.loadIndex() + const template = entries.find((item) => item.templateId === templateId) + if (!template) { + throw new ExtensionError('EXTENSION_NOT_FOUND', `找不到模板:${templateId}`) + } + const zipPath = path.join(this.dependencies.templateRoot, template.file) + const exists = this.dependencies.exists ?? defaultExists + if (!exists(zipPath)) { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', `模板资源缺失:${template.file}`) + } + const readFile = this.dependencies.readFile ?? fs.readFile + let buffer: Buffer + try { + buffer = await readFile(zipPath) + } catch { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', `模板资源不可读:${template.file}`) + } + const digest = createHash('sha256').update(buffer).digest('hex') + if (digest !== template.sha256) { + throw new ExtensionError( + 'EXTENSION_INSTALL_FAILED', + '模板资源校验失败:文件内容与索引不一致,已拒绝安装' + ) + } + return { path: zipPath, template } + } + + private async loadIndex(): Promise { + if (this.cachedIndex) return this.cachedIndex + const indexPath = path.join(this.dependencies.templateRoot, INDEX_FILE) + const readFile = this.dependencies.readFile ?? fs.readFile + let parsed: TemplateIndexFile + try { + const text = await readFile(indexPath) + parsed = JSON.parse(text.toString('utf8')) as TemplateIndexFile + } catch { + this.cachedIndex = [] + return this.cachedIndex + } + if ( + !parsed || + Number(parsed.version) !== SUPPORTED_INDEX_VERSION || + !Array.isArray(parsed.templates) + ) { + this.cachedIndex = [] + return this.cachedIndex + } + const entries: ExtensionTemplateEntry[] = [] + const seen = new Set() + for (const item of parsed.templates) { + const entry = parseEntry(item) + if (!entry) continue + if (seen.has(entry.templateId)) continue + seen.add(entry.templateId) + entries.push(entry) + } + this.cachedIndex = entries + return entries + } + + private async describe(template: ExtensionTemplateEntry): Promise { + const record = this.dependencies.getRecord(template.extensionId) + const dependencies = await this.checkDependencies(template, record) + const base = { + template, + ...(record ? { installedVersion: record.version, installedSource: record.source } : {}), + dependencies + } + + if (template.platforms.length > 0 && !template.platforms.includes(this.platform)) { + return { + ...base, + state: 'unsupported', + message: `当前平台(${this.platform})不在模板支持范围内` + } + } + + const damaged = await this.isDamaged(template) + if (damaged) { + return { ...base, state: 'damaged', message: '模板资源缺失或校验失败,请重新安装 TraceMemo' } + } + + if (!record) return { ...base, state: 'not-installed' } + + // 同 id 但不是这个模板装的:不能静默接管用户自己的扩展。 + if (record.source !== 'template' || record.templateId !== template.templateId) { + return { + ...base, + state: 'conflict', + message: '已安装同 ID 的非官方扩展,不会自动替换' + } + } + + const compared = compareSemver(template.version, record.version) + if (compared !== null && compared > 0) { + return { ...base, state: 'update-available' } + } + return { ...base, state: 'installed' } + } + + private async isDamaged(template: ExtensionTemplateEntry): Promise { + const zipPath = path.join(this.dependencies.templateRoot, template.file) + const exists = this.dependencies.exists ?? defaultExists + if (!exists(zipPath)) return true + const readFile = this.dependencies.readFile ?? fs.readFile + try { + const buffer = await readFile(zipPath) + if (template.bytes > 0 && buffer.length !== template.bytes) return true + return createHash('sha256').update(buffer).digest('hex') !== template.sha256 + } catch { + return true + } + } + + /** + * 依赖检测只做本地文件探测:不执行脚本、不访问网络、不触发解析。 + * + * `externalScript` 只在扩展已安装后才能判断——安装前它一定不存在, + * 报「缺失」只会让用户以为模板坏了。 + */ + private async checkDependencies( + template: ExtensionTemplateEntry, + record: ExtensionRegistryRecord | undefined + ): Promise { + const checks: TemplateDependencyCheck[] = [] + const requires = template.requires + + const python = requires.python + if (python) { + const required = typeof python === 'boolean' ? python : python.required + const executable = (this.dependencies.probePython ?? (() => findPython(this.platform)))() + checks.push({ + id: 'python', + label: 'Python', + ok: Boolean(executable), + blocking: required, + ...(executable + ? { detail: '已找到可执行文件' } + : { + detail: + typeof python === 'object' && python.reason + ? python.reason + : '未在 PATH 中找到 Python' + }) + }) + } + + const chrome = requires.chrome + if (chrome) { + const required = typeof chrome === 'boolean' ? chrome : chrome.required + const found = (this.dependencies.probeChrome ?? (() => findChrome(this.platform)))() + checks.push({ + id: 'chrome', + label: 'Chrome', + ok: Boolean(found), + blocking: required, + ...(found + ? { detail: '已找到 Chrome' } + : { + detail: typeof chrome === 'object' && chrome.reason ? chrome.reason : '未找到 Chrome' + }) + }) + } + + const externalScript = requires.externalScript + if (externalScript) { + const spec = typeof externalScript === 'object' ? externalScript : null + const relative = spec?.path ?? 'scripts/douyin.py' + if (!record) { + checks.push({ + id: 'externalScript', + label: '解析脚本', + ok: false, + blocking: false, + detail: '安装后检测;该脚本不随应用分发' + }) + } else { + const scriptPath = path.join( + this.dependencies.resolveInstallDir(template.extensionId), + relative + ) + const exists = this.dependencies.exists ?? defaultExists + checks.push({ + id: 'externalScript', + label: '解析脚本', + ok: exists(scriptPath), + blocking: spec?.required !== false, + detail: exists(scriptPath) + ? '已找到解析脚本' + : spec?.reason || '缺少解析脚本,模板暂时无法处理视频' + }) + } + } + + const blockingMissing = checks.some((check) => check.blocking && !check.ok) + return { ready: !blockingMissing, checks } + } +} + +function defaultExists(filePath: string): boolean { + // 只查存在性,不读内容:检测阶段不触碰文件内容。 + return existsSync(filePath) +} + +/** 只在 PATH 里找可执行文件,**不执行**它——检测阶段不能启动任何外部进程。 */ +function findPython(platform: NodeJS.Platform): string | null { + const names = + platform === 'win32' ? ['python.exe', 'python3.exe', 'py.exe'] : ['python3', 'python'] + return findOnPath(names, platform) +} + +function findChrome(platform: NodeJS.Platform): string | null { + const candidates: string[] = [] + if (platform === 'darwin') { + candidates.push( + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + path.join( + process.env.HOME || '', + 'Applications/Google Chrome.app/Contents/MacOS/Google Chrome' + ) + ) + } else if (platform === 'win32') { + for (const root of [ + process.env['PROGRAMFILES'] || '', + process.env['PROGRAMFILES(X86)'] || '', + process.env['LOCALAPPDATA'] || '' + ]) { + if (!root) continue + candidates.push(path.join(root, 'Google', 'Chrome', 'Application', 'chrome.exe')) + } + } + return candidates.find((candidate) => defaultExists(candidate)) || null +} + +function findOnPath(names: string[], platform: NodeJS.Platform): string | null { + const separator = platform === 'win32' ? ';' : ':' + const directories = String(process.env.PATH || '') + .split(separator) + .filter(Boolean) + for (const name of names) { + for (const directory of directories) { + const candidate = path.join(directory, name) + if (defaultExists(candidate)) return candidate + } + } + return null +} diff --git a/src/main/extensions/host-runtime.ts b/src/main/extensions/host-runtime.ts index f3e2b4d..25dbb1c 100644 --- a/src/main/extensions/host-runtime.ts +++ b/src/main/extensions/host-runtime.ts @@ -10,6 +10,7 @@ import fs from 'node:fs' import path from 'node:path' import { randomUUID } from 'node:crypto' +import { validateActionInput as validateWithSchema } from '../../shared/extensions/action-schema' import { EXTENSION_HOST_PROTOCOL_VERSION, type ExtensionAutomationActionOutput, @@ -18,6 +19,7 @@ import { type ExtensionHostCallResult, type ExtensionHostEvent, type ExtensionHostInboundMessage, + type ExtensionHostPageRequest, type ExtensionHostInvokeAction, type ExtensionHostTestSend, type ExtensionHostOutboundMessage, @@ -44,6 +46,10 @@ interface PendingCall { const pendingCalls = new Map() const eventHandlers = new Set() const actions = new Map() +const pageHandlers = new Map) => unknown>() +/** 页面请求方法名:小写开头,允许点号分段,长度受限。 */ +const PAGE_REQUEST_METHOD = /^[a-z][a-zA-Z0-9]*(?:[._-][a-zA-Z0-9]+){0,3}$/ +const PAGE_RESULT_MAX_BYTES = 64 * 1024 let permissions: string[] = [] let activated = false let extensionDir = '' @@ -102,6 +108,45 @@ const tm = { return [...permissions] } }, + /** + * 页面 → 同扩展后台的通用请求处理器注册。 + * + * 不需要额外权限:注册本身不产生任何能力,handler 内部若调用 + * `tm.wechat.send` 等能力,仍然各自走权限检查。 + */ + page: { + onRequest(method: string, handler: (params: Record) => unknown): void { + const name = String(method || '').trim() + if (!PAGE_REQUEST_METHOD.test(name)) throw new Error(`页面请求方法名不合法:${name}`) + if (typeof handler !== 'function') throw new Error('页面请求必须提供 handler') + if (pageHandlers.has(name)) throw new Error(`页面请求重复注册:${name}`) + pageHandlers.set(name, handler) + } + }, + /** + * 扩展私有凭据。 + * + * 真正加密发生在主进程(`safeStorage`);子进程只在需要时拿到明文。 + * 每个扩展一个命名空间,A 扩展拿不到 B 的密钥。 + */ + secrets: { + async get(key: string): Promise { + requirePermission('secrets') + return (await callHost('secrets.get', { key })) as string | null + }, + async set(key: string, value: string): Promise { + requirePermission('secrets') + await callHost('secrets.set', { key, value }) + }, + async delete(key: string): Promise { + requirePermission('secrets') + await callHost('secrets.delete', { key }) + }, + async has(key: string): Promise { + requirePermission('secrets') + return (await callHost('secrets.has', { key })) as boolean + } + }, events: { on(name: 'message.received', handler: MessageHandler): () => void { if (name !== 'message.received' || typeof handler !== 'function') return () => undefined @@ -338,27 +383,62 @@ async function dispatchEvent(message: ExtensionHostEvent): Promise { } } +/** + * 与 UI 共用同一套校验规则。 + * + * 两套实现一定会在某个边界上分叉,用户看到的就是「表单填得进去、执行时说参数错」。 + */ function validateActionInput( schema: Record | undefined, input: Record ): void { if (!schema) return - const required = Array.isArray(schema.required) ? schema.required : [] - for (const key of required) { - if (typeof key === 'string' && !(key in input)) { - throw new Error(`缺少必填参数:${key}`) - } + const result = validateWithSchema(schema as never, input) + if (result.ok) return + const [key, message] = Object.entries(result.errors)[0] ?? ['参数', '不合法'] + throw new Error(`参数 ${key} ${message}`) +} + +async function handlePageRequest(message: ExtensionHostPageRequest): Promise { + const handler = pageHandlers.get(message.method) + if (!handler) { + post({ + type: 'page-result', + version: EXTENSION_HOST_PROTOCOL_VERSION, + requestId: message.requestId, + ok: false, + error: { code: 'ACTION_FAILED', message: `页面请求未注册:${message.method}` } + }) + return } - const properties = schema.properties - if (!properties || typeof properties !== 'object') return - for (const [key, definition] of Object.entries(properties as Record)) { - if (!(key in input)) continue - const type = (definition as { type?: unknown })?.type - const value = input[key] - if (type === 'string' && typeof value !== 'string') throw new Error(`参数 ${key} 必须是字符串`) - if (type === 'number' && typeof value !== 'number') throw new Error(`参数 ${key} 必须是数字`) - if (type === 'boolean' && typeof value !== 'boolean') - throw new Error(`参数 ${key} 必须是布尔值`) + try { + const raw = await withTimeout( + Promise.resolve(handler(message.params ?? {})), + Math.max(1_000, Math.min(message.timeoutMs - 500, 30_000)) + ) + // 只允许纯 JSON:函数、循环引用、类实例都在这一步被拒绝。 + const serialized = JSON.stringify(raw ?? null) + if (new TextEncoder().encode(serialized).length > PAGE_RESULT_MAX_BYTES) { + throw new Error('页面请求响应超过 64KB') + } + post({ + type: 'page-result', + version: EXTENSION_HOST_PROTOCOL_VERSION, + requestId: message.requestId, + ok: true, + result: JSON.parse(serialized) as unknown + }) + } catch (error) { + post({ + type: 'page-result', + version: EXTENSION_HOST_PROTOCOL_VERSION, + requestId: message.requestId, + ok: false, + error: { + code: 'ACTION_FAILED', + message: error instanceof Error ? error.message.slice(0, 200) : '页面请求失败' + } + }) } } @@ -465,9 +545,13 @@ process.on('message', (raw: unknown) => { void invokeAction(message) return case 'test-send': + // 旧协议:只有抖音扩展认这个入口。新代码统一走 page-request。 if (extensionId !== 'com.example.douyin-sender') return void dispatchTestSend(message) return + case 'page-request': + void handlePageRequest(message) + return case 'call-result': { const result = message as ExtensionHostCallResult const pending = pendingCalls.get(result.callId) diff --git a/src/main/index.ts b/src/main/index.ts index 6a911c9..76998a9 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1454,7 +1454,19 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) { // Create the renderer before native WCDB bootstrap so startup progress is visible immediately. await reportTemplateService.recover() registerReportTemplateIpc() - installExtensionProtocolHandler(getExtensionPaths()) + installExtensionProtocolHandler({ + paths: getExtensionPaths(), + // 开发模式下代码在用户自己的目录里:协议必须走同一个解析器, + // 否则页面会读到旧的安装副本。管理器尚未就绪时回退到安装目录。 + resolveRoot: (extensionId) => { + if (!hasExtensionManager()) return getExtensionPaths().installDir(extensionId) + try { + return getExtensionManager().resolveExtensionRoot(extensionId) + } catch { + return null + } + } + }) registerExtensionIpc({ getManager: getExtensionManager, paths: getExtensionPaths(), diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index 984161f..51e0a3d 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -10,8 +10,12 @@ import type { ExtensionOperationResult, ExtensionPageDescriptor, ExtensionPageResponse, + ExtensionActionInfo, + ExtensionProjectResult, + ExtensionSystemHealth, InstalledExtension } from '../shared/extensions/types' +import type { ExtensionTemplateStatus } from '../shared/extensions/templates' import { GroupReportExportRequest, GroupReportExportResult, @@ -840,6 +844,42 @@ declare global { extensionId: string, enabled: boolean ) => Promise + getExtensionHealth: () => Promise + grantExtensionPermissions: ( + extensionId: string, + permissions: string[] + ) => Promise + revokeExtensionPermission: ( + extensionId: string, + permission: string + ) => Promise + resetExtensionStorage: (extensionId: string) => Promise + listExtensionTemplates: () => Promise + installExtensionTemplate: (templateId: string) => Promise + acknowledgeExtensionRecovery: () => Promise + acknowledgeExtensionStorage: (extensionId: string) => Promise + adoptExtensionCode: (extensionId: string) => Promise + rollbackExtensionUpgrade: (extensionId: string) => Promise + pickExtensionProjectDirectory: () => Promise + linkExtensionDevelopment: (directory: string) => Promise + reloadExtensionDevelopment: (extensionId: string) => Promise + unlinkExtensionDevelopment: ( + extensionId: string, + keepData?: boolean + ) => Promise + convertExtensionDevelopment: (extensionId: string) => Promise + createExtensionProject: (input: { + templateId: string + targetDirectory: string + extensionId: string + name?: string + }) => Promise + listExtensionActions: () => Promise + openExtensionDevelopmentSource: (extensionId: string) => Promise + exportExtensionAsProject: ( + extensionId: string, + targetDirectory: string + ) => Promise uninstallExtension: ( extensionId: string, keepData?: boolean diff --git a/src/preload/index.ts b/src/preload/index.ts index 553c6c4..71cc670 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -139,8 +139,12 @@ import type { ExtensionPageDescriptor, ExtensionPageRequest, ExtensionPageResponse, + ExtensionActionInfo, + ExtensionProjectResult, + ExtensionSystemHealth, InstalledExtension } from '../shared/extensions/types' +import type { ExtensionTemplateStatus } from '../shared/extensions/templates' // 渲染器的自定义 API const api = { @@ -287,6 +291,64 @@ const api = { ipcRenderer.invoke('extension:installPackage', packagePath), setExtensionEnabled: (extensionId: string, enabled: boolean): Promise => ipcRenderer.invoke('extension:setEnabled', { id: extensionId, enabled }), + getExtensionHealth: (): Promise => + ipcRenderer.invoke('extension:health'), + grantExtensionPermissions: ( + extensionId: string, + permissions: string[] + ): Promise => + ipcRenderer.invoke('extension:grantPermissions', { id: extensionId, permissions }), + revokeExtensionPermission: ( + extensionId: string, + permission: string + ): Promise => + ipcRenderer.invoke('extension:revokePermission', { id: extensionId, permission }), + resetExtensionStorage: (extensionId: string): Promise => + ipcRenderer.invoke('extension:resetStorage', extensionId), + listExtensionTemplates: (): Promise => + ipcRenderer.invoke('extension:templates'), + installExtensionTemplate: (templateId: string): Promise => + ipcRenderer.invoke('extension:installTemplate', templateId), + acknowledgeExtensionRecovery: (): Promise => + ipcRenderer.invoke('extension:acknowledgeRecovery'), + acknowledgeExtensionStorage: (extensionId: string): Promise => + ipcRenderer.invoke('extension:acknowledgeStorage', extensionId), + adoptExtensionCode: (extensionId: string): Promise => + ipcRenderer.invoke('extension:adoptInstalledCode', extensionId), + rollbackExtensionUpgrade: (extensionId: string): Promise => + ipcRenderer.invoke('extension:rollbackUpgrade', extensionId), + pickExtensionProjectDirectory: (): Promise => + ipcRenderer.invoke('extension:pickProjectDirectory'), + linkExtensionDevelopment: (directory: string): Promise => + ipcRenderer.invoke('extension:linkDevelopment', directory), + reloadExtensionDevelopment: (extensionId: string): Promise => + ipcRenderer.invoke('extension:reloadDevelopment', extensionId), + unlinkExtensionDevelopment: ( + extensionId: string, + keepData = true + ): Promise => + ipcRenderer.invoke('extension:unlinkDevelopment', { id: extensionId, keepData }), + convertExtensionDevelopment: (extensionId: string): Promise => + ipcRenderer.invoke('extension:convertDevelopment', extensionId), + createExtensionProject: (input: { + templateId: string + targetDirectory: string + extensionId: string + name?: string + }): Promise => + ipcRenderer.invoke('extension:createProjectFromTemplate', input), + listExtensionActions: (): Promise => + ipcRenderer.invoke('extension:actions'), + openExtensionDevelopmentSource: (extensionId: string): Promise => + ipcRenderer.invoke('extension:openDevelopmentSource', extensionId), + exportExtensionAsProject: ( + extensionId: string, + targetDirectory: string + ): Promise => + ipcRenderer.invoke('extension:exportInstalledAsProject', { + id: extensionId, + targetDirectory + }), uninstallExtension: (extensionId: string, keepData = true): Promise => ipcRenderer.invoke('extension:uninstall', { id: extensionId, keepData }), getExtensionLogs: (extensionId: string, limit?: number): Promise => diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index d0c52f3..423a2c8 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -44,9 +44,16 @@ import { switchGeneratedReportTemplate } from './utils/report-template-switch' import { runtimePlatform } from './utils/runtime-environment' import { Button, useToast } from './components/ui' import { AppUpdatePrompt } from './features/app-update/AppUpdatePrompt' -import { GroupExitMonitorWorkspace, type GroupExitMonitorOpenViewRequest } from './features/group-exit-monitor/GroupExitMonitorWorkspace' -import { AutomationWorkspace, type AutomationOpenRuleRequest } from './features/automation/AutomationWorkspace' +import { + GroupExitMonitorWorkspace, + type GroupExitMonitorOpenViewRequest +} from './features/group-exit-monitor/GroupExitMonitorWorkspace' +import { + AutomationWorkspace, + type AutomationOpenRuleRequest +} from './features/automation/AutomationWorkspace' import { ExtensionWorkspace } from './features/extensions/ExtensionWorkspace' +import type { ExtensionDeepLink } from '../../shared/extensions/types' import { selectContactAvatarRefreshUsernames } from './utils/contact-avatar' import { buildContactSearchIndex, @@ -258,6 +265,8 @@ function App(): React.ReactElement { const [databaseEnvironment, setDatabaseEnvironment] = useState() const connectionOperationRef = React.useRef(0) const [activePage, setActivePage] = useState('archive') + /** 从其它页面跳到扩展中心时的定位目标;扩展中心消费后清空。 */ + const [extensionDeepLink, setExtensionDeepLink] = useState(null) /** * 「退群监控 ⇄ 自动化」之间的跨页深链。 * @@ -1612,6 +1621,12 @@ function App(): React.ReactElement { const isGroupContact = (contact: Contact | null): boolean => Boolean(contact?.type === 'group' || contact?.m_nsUsrName?.endsWith('@chatroom')) + /** 跳到扩展中心并带上定位目标(模板 / 扩展)。 */ + const openExtensionDeepLink = (target: ExtensionDeepLink): void => { + setExtensionDeepLink(target) + handlePageChange('extensions') + } + const handlePageChange = (page: AppPage): void => { setActivePage(page) if (page === 'archive' && selectedContact) void handleSelectContact(selectedContact) @@ -2136,12 +2151,18 @@ function App(): React.ReactElement { openRuleRequest={automationOpenRuleRequest} onOpenModelSettings={openModelSettings} onOpenAgentHub={openAgentHub} + onOpenExtension={openExtensionDeepLink} /> ) case 'agent-hub': return case 'extensions': - return + return ( + setExtensionDeepLink(null)} + /> + ) case 'api': return ( (loader: () => Promise | undefined, fallback: T): Promise { + try { + const result = await loader() + return result ?? fallback + } catch { + return fallback + } +} + export interface AutomationWorkspaceProps { dbReady: boolean /** 发送能力不可用时,引导用户去设置页。 */ @@ -75,6 +88,8 @@ export interface AutomationWorkspaceProps { onOpenAgentHub?: () => void /** 深链请求(来自退群监控页的「退群通知自动化」入口)。 */ openRuleRequest?: AutomationOpenRuleRequest | null + /** 跳到扩展中心并定位模板 / 扩展 / 开发引导(规则模板卡片用)。 */ + onOpenExtension?: (target: ExtensionDeepLink) => void } interface EditorState { @@ -90,7 +105,8 @@ export function AutomationWorkspace({ onOpenExitMonitorGroups, onOpenModelSettings, onOpenAgentHub, - openRuleRequest + openRuleRequest, + onOpenExtension }: AutomationWorkspaceProps): React.ReactElement { const { toast } = useToast() const apiAvailable = React.useMemo(() => isAutomationApiAvailable(), []) @@ -100,7 +116,9 @@ export function AutomationWorkspace({ const [rules, setRules] = React.useState([]) const [groups, setGroups] = React.useState([]) const [executions, setExecutions] = React.useState([]) - const [sendableContacts, setSendableContacts] = React.useState([]) + const [sendableContacts, setSendableContacts] = React.useState( + [] + ) const [monitoredGroupCount, setMonitoredGroupCount] = React.useState(0) /** 已监控群聊清单(含显示名)—— 退群通知「通知群聊」二次勾选的候选项。 */ const [monitoredGroups, setMonitoredGroups] = React.useState([]) @@ -109,6 +127,63 @@ export function AutomationWorkspace({ const [saving, setSaving] = React.useState(false) const [busyRuleId, setBusyRuleId] = React.useState(null) const [editor, setEditor] = React.useState(null) + /** 规则模板依赖的本机事实:官方模板目录 + 已安装扩展。 */ + const [extensionTemplates, setExtensionTemplates] = React.useState([]) + const [installedExtensions, setInstalledExtensions] = React.useState([]) + + /** + * 规则模板卡片的真实状态。 + * + * 只读「官方模板目录 + 已装扩展」,不在自动化页维护第二份安装状态。 + */ + const ruleTemplates = React.useMemo(() => { + return AUTOMATION_RULE_TEMPLATES.map((template) => { + const installed = installedExtensions.find((item) => item.id === template.extensionId) + const catalog = extensionTemplates.find( + (item) => item.template.templateId === template.templateId + ) + if (!installed) { + const reason = + catalog?.state === 'damaged' + ? catalog.message + : catalog?.state === 'conflict' + ? catalog.message + : undefined + return { ...template, state: 'not-installed', ...(reason ? { reason } : {}) } + } + if (!installed.compatibility.compatible) { + return { + ...template, + state: 'unavailable', + reason: installed.compatibility.reason || '扩展与当前 TraceMemo 版本不兼容' + } + } + if (installed.runtime.state === 'error') { + return { + ...template, + state: 'unavailable', + reason: installed.runtime.lastError || '扩展运行异常' + } + } + if (!installed.enabled) { + return { ...template, state: 'installed-disabled', reason: '已安装但未启用' } + } + return { ...template, state: 'ready' } + }) + }, [extensionTemplates, installedExtensions]) + + const useRuleTemplate = (template: RuleTemplateCardModel): void => { + if (!template.actionId) return + // 打开的是「新建」,不复用上一次日报的编辑目标。 + setEditor({ mode: 'create', rule: null, ruleType: 'daily_report' }) + toast({ + title: '已打开新建规则', + description: + `在执行动作里添加「${template.name}」,选择扩展动作 ${template.actionId}。` + + '若机器人当前是主动订阅模式,规则路径会自动跳过,不会双回复。', + variant: 'default' + }) + } const [selectedExecution, setSelectedExecution] = React.useState(null) const [pendingDelete, setPendingDelete] = React.useState(null) @@ -131,6 +206,15 @@ export function AutomationWorkspace({ automationApi.getMonitoredGroupCount(), automationApi.getMonitoredGroups() ]) + // 扩展状态是「模板能不能用」的唯一依据:不自己维护第二份。 + // 扩展 API 在旧版宿主或测试环境里可能整体缺失,缺失时按空列表处理, + // 卡片会退化成「未安装」,而不是让整个自动化页崩掉。 + const [nextTemplates, nextExtensions] = await Promise.all([ + safeLoad(() => window.api?.listExtensionTemplates?.(), []), + safeLoad(() => window.api?.listExtensions?.(), []) + ]) + setExtensionTemplates(nextTemplates) + setInstalledExtensions(nextExtensions) setStatus(nextStatus) setRules(nextRules) setGroups(nextGroups) @@ -186,7 +270,6 @@ export function AutomationWorkspace({ const leaveNotificationRule = rules.find((item) => item.id === BUILTIN_LEAVE_NOTIFICATION_RULE_ID) ?? null - /** 「指定好友」目标的显示名(首页卡片用;拿不到时留空,不伪造)。 */ const leaveContactName = React.useMemo((): string => { const target = leaveNotificationRule?.leaveNotification?.target @@ -413,9 +496,7 @@ export function AutomationWorkspace({ * 走独立的 singleton upsert 通道:这条规则 id 固定,保存永远不会多出一条。 * 保存成功后清掉迁移遗留的 `targetNeedsReview`(用户已经做过选择)。 */ - const handleLeaveNotificationSave = async ( - input: LeaveNotificationSaveInput - ): Promise => { + const handleLeaveNotificationSave = async (input: LeaveNotificationSaveInput): Promise => { // 静默 return 会让"点保存没反应"变成用户眼里的坏掉,必须说出来。 if (!leaveNotificationRule) { toast({ @@ -522,7 +603,11 @@ export function AutomationWorkspace({
发送能力 - {capabilityReady ? '可以发送文字和图片' : capability.ready ? '发送能力不完整' : '尚未就绪'} + {capabilityReady + ? '可以发送文字和图片' + : capability.ready + ? '发送能力不完整' + : '尚未就绪'} {capability.message} {!capabilityReady && onOpenSendSettings ? ( @@ -637,9 +722,7 @@ export function AutomationWorkspace({ {...(onOpenModelSettings ? { onOpenModelSettings } : {})} {...(scheduledEditor.ruleId ? (() => { - const rule = scheduledRules.find( - (item) => item.id === scheduledEditor.ruleId - ) + const rule = scheduledRules.find((item) => item.id === scheduledEditor.ruleId) const legacy = rule?.scheduledReport?.legacyTarget return legacy ? { legacyTarget: legacy } : {} })() @@ -709,8 +792,8 @@ export function AutomationWorkspace({

没有找到内置的退群通知规则。

- 这条规则应由主进程在首次启动时自动创建。如果你刚更新过版本, - 请重启 TraceMemo —— 已经跑起来的主进程不会自动换成新代码。 + 这条规则应由主进程在首次启动时自动创建。如果你刚更新过版本, 请重启 TraceMemo —— + 已经跑起来的主进程不会自动换成新代码。 +
+
+ + ) + }) + )} + +
+ + + +
+ + ) +} diff --git a/src/renderer/src/features/automation/RuleEditorPanel.tsx b/src/renderer/src/features/automation/RuleEditorPanel.tsx index ff0722b..bdd0112 100644 --- a/src/renderer/src/features/automation/RuleEditorPanel.tsx +++ b/src/renderer/src/features/automation/RuleEditorPanel.tsx @@ -13,7 +13,9 @@ import { } from '../../../../shared/automation' import { Button, Input, SegmentedControl, SegmentedControlItem, Switch } from '../../components/ui' import { EffectPreview } from './EffectPreview' +import { ExtensionActionList } from './ExtensionActionList' import type { AutomationGroupOption } from './model/api' +import type { ExtensionActionInfo } from '../../../../shared/extensions/types' /** * RuleEditorPanel —— 规则编辑页(对应 Stitch 设计稿 1)。 @@ -90,19 +92,56 @@ export function RuleEditorPanel({ setValidationError('') }, [rule]) + /** 扩展动作列表:随扩展启用/停用自动刷新,规则里保存的引用不会被清掉。 */ + const [extensionActions, setExtensionActions] = React.useState([]) + React.useEffect(() => { + let active = true + const load = (): void => { + // 旧宿主或测试环境可能没有扩展 API:此时退化成「没有扩展动作」, + // 不能让整个规则编辑器崩掉。 + const loader = window.api?.listExtensionActions + if (!loader) { + setExtensionActions([]) + return + } + void Promise.resolve(loader.call(window.api)) + .then((list) => { + if (active) setExtensionActions(Array.isArray(list) ? list : []) + }) + .catch(() => undefined) + } + load() + const subscribe = window.api?.onExtensionChanged + const unsubscribe = subscribe ? subscribe.call(window.api, () => load()) : () => undefined + return () => { + active = false + unsubscribe() + } + }, []) + const patchConditions = (patch: Partial): void => { setDraft((current) => ({ ...current, conditions: { ...current.conditions, ...patch } })) } - const patchAction = (type: AutomationActionType, patch: { enabled?: boolean; text?: string }): void => { + /** + * 按**索引**更新动作。 + * + * 固定动作每类只有一条,但扩展动作可以有多条同类型: + * 按 `type` 批量更新会把它们一起改掉。 + */ + const patchActionAt = (index: number, patch: { enabled?: boolean; text?: string }): void => { + if (index < 0) return setDraft((current) => ({ ...current, - actions: current.actions.map((action) => - action.type === type ? { ...action, ...patch } : action + actions: current.actions.map((action, currentIndex) => + currentIndex === index ? { ...action, ...patch } : action ) })) } + const indexOfType = (type: AutomationActionType): number => + draft.actions.findIndex((action) => action.type === type) + const actionOf = (type: AutomationActionType): { enabled: boolean; text?: string } => draft.actions.find((action) => action.type === type) ?? { enabled: false } @@ -268,7 +307,11 @@ export function RuleEditorPanel({ key={group.id} className={`automation-group-option ${checked ? 'selected' : ''}`} > - toggleGroup(group.id)} /> + toggleGroup(group.id)} + /> {group.name} ) @@ -305,9 +348,7 @@ export function RuleEditorPanel({ const next = Number(event.target.value) setDraft((current) => ({ ...current, - replyDelaySeconds: normalizeReplyDelaySeconds( - Number.isFinite(next) ? next : 0 - ) + replyDelaySeconds: normalizeReplyDelaySeconds(Number.isFinite(next) ? next : 0) })) }} className="automation-number-input" @@ -326,13 +367,17 @@ export function RuleEditorPanel({ patchAction(meta.type, { enabled: checked })} + onCheckedChange={(checked) => + patchActionAt(indexOfType(meta.type), { enabled: checked }) + } /> {meta.type === 'replyText' && action.enabled ? ( patchAction(meta.type, { text: event.target.value })} + onChange={(event) => + patchActionAt(indexOfType(meta.type), { text: event.target.value }) + } placeholder={DEFAULT_REPLY_TEXT} aria-label="回复内容" /> @@ -341,6 +386,18 @@ export function RuleEditorPanel({ ) })} + +
+
+

执行扩展动作

+ 由扩展注册,参数按扩展声明的 Schema 填写 +
+ setDraft((current) => ({ ...current, actions: next }))} + /> +
diff --git a/src/renderer/src/features/automation/RuleListPanel.tsx b/src/renderer/src/features/automation/RuleListPanel.tsx index 88dd16b..f749de0 100644 --- a/src/renderer/src/features/automation/RuleListPanel.tsx +++ b/src/renderer/src/features/automation/RuleListPanel.tsx @@ -1,6 +1,5 @@ import * as React from 'react' import { - AUTOMATION_RULE_TEMPLATES, BUILTIN_LEAVE_NOTIFICATION_RULE_ID, describeLeaveNotificationNotifyScope, describeLeaveNotificationTarget, @@ -8,6 +7,7 @@ import { describeRuleTrigger, type AutomationRule } from '../../../../shared/automation' +import type { ExtensionDeepLink } from '../../../../shared/extensions/types' import { Button, Spinner, Switch } from '../../components/ui' /** @@ -40,6 +40,25 @@ export interface ScheduledReportCardModel { nextRunLabel: string } +/** + * 规则模板卡片的本机状态。 + * + * 由工作区根据「官方模板目录 + 已安装扩展 + 运行状态」算出, + * 面板只负责渲染,不自己判断可用性。 + */ +export interface RuleTemplateCardModel { + id: string + name: string + description: string + templateId: string + extensionId: string + /** 没有动作的模板只能打开配置,不能「用规则触发」。 */ + actionId?: string + state: 'not-installed' | 'installed-disabled' | 'ready' | 'unavailable' + /** 不可用/需要处理时的真实原因。 */ + reason?: string +} + export interface RuleListPanelProps { rules: AutomationRule[] groups: Array<{ id: string; name: string }> @@ -55,6 +74,12 @@ export interface RuleListPanelProps { onEditLeaveNotification: () => void /** 打开「定时日报」规则类型(多条,所以是"管理"而不是"编辑")。 */ onManageScheduledReport: () => void + /** 规则模板卡片(真实状态)。 */ + ruleTemplates?: RuleTemplateCardModel[] + /** 跳到扩展中心并定位模板/扩展/开发引导。 */ + onOpenExtension?: (target: ExtensionDeepLink) => void + /** 用该模板预填一条引用扩展动作的规则。 */ + onUseRuleTemplate?: (template: RuleTemplateCardModel) => void } /** 把规则里的 conversationIds 翻成群名;找不到时显示占位而不是裸 id。 */ @@ -92,7 +117,10 @@ export function RuleListPanel({ onDelete, onCreate, onEditLeaveNotification, - onManageScheduledReport + onManageScheduledReport, + ruleTemplates, + onOpenExtension, + onUseRuleTemplate }: RuleListPanelProps): React.ReactElement { // 退群通知有自己的卡片,别在「已配置的自动化」里重复渲染一遍。 const configuredRules = rules.filter((rule) => rule.id !== BUILTIN_LEAVE_NOTIFICATION_RULE_ID) @@ -267,16 +295,99 @@ export function RuleListPanel({

更多模板

- {AUTOMATION_RULE_TEMPLATES.map((template) => ( -
-
-

{template.name}

- 即将支持 -
-

{template.description}

- {template.unavailableReason ? {template.unavailableReason} : null} -
- ))} + {(ruleTemplates ?? []).map((template) => { + const badge = + template.state === 'ready' + ? '已就绪' + : template.state === 'installed-disabled' + ? '已安装 · 未启用' + : template.state === 'not-installed' + ? '未安装' + : '不可用' + return ( +
+
+

{template.name}

+ + {badge} + +
+

{template.description}

+ {template.reason ? {template.reason} : null} + +
+ {template.state === 'not-installed' && ( + + )} + {template.state === 'installed-disabled' && ( + + )} + {template.state === 'ready' && ( + <> + + {template.actionId ? ( + + ) : ( + + 该扩展没有注册自动化动作,靠消息事件触发 + + )} + + )} +
+
+ ) + })} + + {/* 模板之外还要有出口:没有现成模板可用时,用户应该能自己做一个。 */} +
+
+

做自己的扩展

+
+

+ 从官方模板克隆一份代码,改完直接在本地调试;官方升级不会覆盖你的改动。 也可以链接已经 + clone 到别处的项目。 +

+
+ +
+
diff --git a/src/renderer/src/features/extensions/CreateProjectDialog.tsx b/src/renderer/src/features/extensions/CreateProjectDialog.tsx new file mode 100644 index 0000000..5099946 --- /dev/null +++ b/src/renderer/src/features/extensions/CreateProjectDialog.tsx @@ -0,0 +1,85 @@ +import * as React from 'react' +import { Button } from '../../components/ui' +import type { ExtensionTemplateEntry } from '../../../../shared/extensions/templates' + +interface CreateProjectDialogProps { + template: ExtensionTemplateEntry + busy: boolean + onCancel: () => void + onSubmit: (input: { extensionId: string; name: string }) => void +} + +const ID_PATTERN = + /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?)+$/ + +/** 默认 id 从模板 id 派生,用户可以直接改。 */ +function suggestExtensionId(templateId: string): string { + const suffix = templateId.replace(/[^a-z0-9-]/gi, '-').toLowerCase() + return `com.example.${suffix}-dev` +} + +/** + * 从模板创建独立项目。 + * + * 只收集「新 id」和「名称」:目录由调用方先选好,创建过程在主进程完成, + * 这里不做任何文件操作。 + */ +export function CreateProjectDialog({ + template, + busy, + onCancel, + onSubmit +}: CreateProjectDialogProps): React.ReactElement { + const [extensionId, setExtensionId] = React.useState(() => + suggestExtensionId(template.templateId) + ) + const [name, setName] = React.useState(`${template.name}(我的版本)`) + + const trimmedId = extensionId.trim().toLowerCase() + const idValid = ID_PATTERN.test(trimmedId) + const conflictsWithTemplate = trimmedId === template.extensionId + const canSubmit = idValid && !conflictsWithTemplate && !busy + + return ( +
+

从「{template.name}」创建独立项目

+

+ 会在你选择的目录里生成完整源码;不会复制任何配置、Cookie 或聊天数据。 +

+ + + {!idValid && ( +

id 必须是反向域名格式(小写字母、数字、连字符)

+ )} + {conflictsWithTemplate && ( +

不能沿用模板原 id,否则会和官方模板冲突

+ )} + + + +
+ + +
+
+ ) +} diff --git a/src/renderer/src/features/extensions/DevelopmentGuide.tsx b/src/renderer/src/features/extensions/DevelopmentGuide.tsx new file mode 100644 index 0000000..33c8302 --- /dev/null +++ b/src/renderer/src/features/extensions/DevelopmentGuide.tsx @@ -0,0 +1,135 @@ +import * as React from 'react' +import { Button } from '../../components/ui' + +interface DevelopmentGuideProps { + /** 回到扩展列表。 */ + onBack: () => void + /** 打开「从模板创建项目」:切到模板画廊并展开第一条可用模板。 */ + onCreateProject: () => void + /** 链接已有本地项目。 */ + onLinkProject: () => void +} + +/** + * 二次开发引导。 + * + * 这里**不复制文档正文**:文档在 `docs/extensions/`,正文改一次要同步两处必然不一致。 + * 界面只负责把「从哪开始、做完在哪看效果」讲清楚,并指到文档。 + */ +const DOCS: Array<{ name: string; file: string; description: string }> = [ + { + name: '快速开始', + file: 'docs/extensions/getting-started.md', + description: '最小 manifest、目录结构、第一次跑起来' + }, + { + name: '克隆与改造成自己的扩展', + file: 'docs/extensions/clone-and-customize.md', + description: '从官方模板复制代码、改 id、改成自己的逻辑' + }, + { + name: 'API 参考', + file: 'docs/extensions/api-reference.md', + description: 'manifest 字段、权限表、tm.* 能力清单' + }, + { + name: '架构与安全边界', + file: 'docs/extensions/architecture.md', + description: '代码在哪、数据在哪、页面为什么在 iframe 里' + } +] + +export function DevelopmentGuide({ + onBack, + onCreateProject, + onLinkProject +}: DevelopmentGuideProps): React.ReactElement { + return ( +
+
+
+

二次开发

+

+ 扩展代码放在你自己的目录,TraceMemo 直接运行它。改完点「重新加载」即可生效, + 不需要重新安装;官方升级也不会覆盖你的代码。 +

+
+ +
+ +
    +
  1. + 1 +
    + 拿到一份代码 +

    + 从官方模板生成独立项目(会替换成你自己的扩展 id),或直接链接已经在别处 clone + 好的目录。 +

    +
    +
  2. +
  3. + 2 +
    + 链接到 TraceMemo +

    + 链接后代码不复制:宿主直接读你选的目录。配置、日志、缓存仍然写在 TraceMemo + 的用户数据目录,不会污染你的仓库。 +

    +
    +
  4. +
  5. + 3 +
    + 改完重新加载 +

    + 后台代码改动点「重新加载」;页面改动刷新 iframe 即可。Manifest 新增权限不会自动授予, + 需要在详情页逐项确认。 +

    +
    +
  6. +
+ +
+ + +
+ +
+

开发文档

+
    + {DOCS.map((doc) => ( +
  • +
    + {doc.name} + {doc.description} +
    + {doc.file} +
  • + ))} +
+

+ 文档随仓库分发,路径以上方为准;打包后的应用里不包含 docs 目录。 +

+
+ +
+

几个边界

+
    +
  • 不会自动安装、自动启用或自动创建规则——每一步都要你点。
  • +
  • 移除链接只断开引用,不会删除你的项目目录。
  • +
  • + 页面跑在 sandbox iframe 里,只能调用你自己后台注册的处理器,拿不到 Node 或 + window.api。 +
  • +
+
+
+ ) +} diff --git a/src/renderer/src/features/extensions/ExtensionTemplateGallery.tsx b/src/renderer/src/features/extensions/ExtensionTemplateGallery.tsx new file mode 100644 index 0000000..a345ac3 --- /dev/null +++ b/src/renderer/src/features/extensions/ExtensionTemplateGallery.tsx @@ -0,0 +1,230 @@ +import * as React from 'react' +import { + EXTENSION_PERMISSION_INFO, + sortPermissionsByRisk, + type ExtensionPermission +} from '../../../../shared/extensions/permissions' +import type { ExtensionTemplateStatus } from '../../../../shared/extensions/templates' +import { Button, Spinner } from '../../components/ui' + +interface ExtensionTemplateGalleryProps { + templates: ExtensionTemplateStatus[] + loading: boolean + busyId: string | null + onInstall: (templateId: string) => void + /** 从该模板生成独立项目;未提供时不显示入口。 */ + onCreateProject?: (templateId: string) => void + /** 深链定位:自动展开该模板的详情。 */ + focusTemplateId?: string | null +} + +const STATE_LABELS: Record = { + 'not-installed': '未安装', + installed: '已安装', + 'update-available': '有更新', + conflict: '已被占用', + unsupported: '不支持当前平台', + damaged: '资源损坏' +} + +function stateTone(state: ExtensionTemplateStatus['state']): string { + if (state === 'not-installed' || state === 'installed') return 'muted' + if (state === 'update-available') return 'warning' + return 'danger' +} + +function formatBytes(bytes: number): string { + if (!bytes) return '—' + if (bytes < 1024) return `${bytes} B` + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB` + return `${(bytes / 1024 / 1024).toFixed(1)} MB` +} + +/** + * 官方模板画廊。 + * + * 只负责展示与触发安装;是否可安装、装完是什么状态全部来自主进程, + * 这里不做第二套判断,避免界面和实际能力说两套话。 + */ +export function ExtensionTemplateGallery({ + templates, + loading, + busyId, + onInstall, + onCreateProject, + focusTemplateId +}: ExtensionTemplateGalleryProps): React.ReactElement { + const [expanded, setExpanded] = React.useState(null) + + // 深链进来时展开目标模板;滚动交给浏览器默认行为即可。 + React.useEffect(() => { + if (focusTemplateId) setExpanded(focusTemplateId) + }, [focusTemplateId]) + + if (loading) { + return ( +
+ +

正在读取官方模板…

+
+ ) + } + + if (templates.length === 0) { + return ( +
+

官方模板

+

当前安装包没有携带模板资源。如果你是从源码运行,请先执行模板构建脚本。

+
+ ) + } + + return ( +
+
+
+

官方模板

+

安装后仍需你确认权限并手动启用,不会自动运行。

+
+
+ +
    + {templates.map((item) => { + const { template } = item + const isOpen = expanded === template.templateId + const canInstall = item.state === 'not-installed' || item.state === 'update-available' + const blocked = + item.state === 'conflict' || item.state === 'damaged' || item.state === 'unsupported' + const missingBlocking = item.dependencies.checks.filter( + (check) => check.blocking && !check.ok + ) + + return ( +
  • +
    +
    +
    + {template.name} + v{template.version} + + {STATE_LABELS[item.state]} + +
    +

    + {template.description || '官方提供的扩展示例。'} +

    +

    + {template.fileCount} 个文件 · {formatBytes(template.bytes)} + {item.installedVersion && item.state !== 'not-installed' + ? ` · 已安装 v${item.installedVersion}` + : ''} +

    +
    +
    + + {onCreateProject && ( + + )} + +
    +
    + + {item.message &&

    {item.message}

    } + + {missingBlocking.length > 0 && ( +

    + 缺少 {missingBlocking.map((check) => check.label).join('、')} + :安装后可以查看配置页,但主要功能暂时不可用。 +

    + )} + + {isOpen && ( +
    +
    +

    权限

    +
      + {sortPermissionsByRisk(template.permissions).map( + (permission: ExtensionPermission) => ( +
    • +
      + + {EXTENSION_PERMISSION_INFO[permission].label} + + + {EXTENSION_PERMISSION_INFO[permission].risk === 'high' + ? '高' + : EXTENSION_PERMISSION_INFO[permission].risk === 'medium' + ? '中' + : '低'} + +
      +

      {EXTENSION_PERMISSION_INFO[permission].description}

      +
    • + ) + )} +
    +
    + +
    +

    依赖

    + {item.dependencies.checks.length === 0 ? ( +

    该模板不需要额外依赖。

    + ) : ( +
      + {item.dependencies.checks.map((check) => ( +
    • + + {check.label} + {check.detail} +
    • + ))} +
    + )} +
    +
    + )} + + {item.state === 'conflict' && ( +

    + 你之前用同一扩展 ID 安装过其他来源的扩展。请先卸载它,或改用「安装 ZIP」手动更新。 +

    + )} + {blocked && item.state === 'damaged' && ( +

    + 模板资源与你安装的版本不匹配,建议重新安装 TraceMemo。 +

    + )} +
  • + ) + })} +
+
+ ) +} diff --git a/src/renderer/src/features/extensions/ExtensionWorkspace.tsx b/src/renderer/src/features/extensions/ExtensionWorkspace.tsx index 19d0c26..9003474 100644 --- a/src/renderer/src/features/extensions/ExtensionWorkspace.tsx +++ b/src/renderer/src/features/extensions/ExtensionWorkspace.tsx @@ -7,10 +7,19 @@ import { import type { ExtensionLogEntry, ExtensionPageDescriptor, + ExtensionSystemHealth, InstalledExtension } from '../../../../shared/extensions/types' +import type { + ExtensionTemplateEntry, + ExtensionTemplateStatus +} from '../../../../shared/extensions/templates' +import type { ExtensionDeepLink } from '../../../../shared/extensions/types' import { Button, Spinner, useToast } from '../../components/ui' import { ExtensionPageHost } from './ExtensionPageHost' +import { CreateProjectDialog } from './CreateProjectDialog' +import { DevelopmentGuide } from './DevelopmentGuide' +import { ExtensionTemplateGallery } from './ExtensionTemplateGallery' const STATUS_LABELS: Record = { inactive: '未运行', @@ -32,7 +41,17 @@ function statusTone(extension: InstalledExtension): 'success' | 'warning' | 'dan return 'warning' } -export function ExtensionWorkspace(): React.ReactElement { +export interface ExtensionWorkspaceProps { + /** 从其它页面跳过来时的定位目标。 */ + deepLink?: ExtensionDeepLink | null + /** 消费后清空,避免返回再进来又跳一次。 */ + onConsumeDeepLink?: () => void +} + +export function ExtensionWorkspace({ + deepLink, + onConsumeDeepLink +}: ExtensionWorkspaceProps = {}): React.ReactElement { const { toast } = useToast() const [extensions, setExtensions] = React.useState([]) const [selectedId, setSelectedId] = React.useState(null) @@ -41,10 +60,36 @@ export function ExtensionWorkspace(): React.ReactElement { const [page, setPage] = React.useState(null) const [pendingEnable, setPendingEnable] = React.useState(null) const [pendingUninstall, setPendingUninstall] = React.useState(null) + const [health, setHealth] = React.useState(null) + const [templates, setTemplates] = React.useState([]) + const [templatesLoading, setTemplatesLoading] = React.useState(true) + const [installingTemplate, setInstallingTemplate] = React.useState(null) + /** 右侧主区域:扩展列表 or 官方模板画廊。 */ + const [view, setView] = React.useState<'extensions' | 'templates' | 'guide'>('extensions') + /** 深链定位的模板:进入画廊时自动展开它。 */ + const [focusedTemplateId, setFocusedTemplateId] = React.useState(null) + /** 正在创建项目的模板;非空时显示创建对话框。 */ + const [creatingTemplate, setCreatingTemplate] = React.useState( + null + ) + /** 高风险权限的二次确认;低风险直接授权。 */ + const [pendingGrant, setPendingGrant] = React.useState<{ + extensionId: string + permission: ExtensionPermission + } | null>(null) + /** 「转为正式安装」的二次确认。 */ + const [pendingConvert, setPendingConvert] = React.useState(null) const refresh = React.useCallback(async (): Promise => { - const list = await window.api.listExtensions() + const [list, systemHealth, templateList] = await Promise.all([ + window.api.listExtensions(), + window.api.getExtensionHealth().catch(() => null), + window.api.listExtensionTemplates().catch(() => []) + ]) setExtensions(list) + setHealth(systemHealth) + setTemplates(templateList) + setTemplatesLoading(false) setSelectedId((current) => { if (current && list.some((item) => item.id === current)) return current return list[0]?.id ?? null @@ -59,6 +104,26 @@ export function ExtensionWorkspace(): React.ReactElement { return unsubscribe }, [refresh]) + /** + * 消费深链:只切视图与选中项,不触发任何安装/启用动作。 + * 真正的操作仍要用户在界面上点。 + */ + React.useEffect(() => { + if (!deepLink) return + if (deepLink.development) { + setView('guide') + } + if (deepLink.templateId) { + setView('templates') + setFocusedTemplateId(deepLink.templateId) + } + if (deepLink.extensionId) { + setView('extensions') + setSelectedId(deepLink.extensionId) + } + onConsumeDeepLink?.() + }, [deepLink, onConsumeDeepLink]) + const selected = React.useMemo( () => extensions.find((item) => item.id === selectedId) ?? null, [extensions, selectedId] @@ -179,6 +244,284 @@ export function ExtensionWorkspace(): React.ReactElement { } } + /** 授权 manifest 新声明的权限;后台会重启,新能力立即生效。 */ + const grantPending = async (extension: InstalledExtension): Promise => { + if (extension.pendingPermissions.length === 0) return + const result = await run(() => + window.api.grantExtensionPermissions(extension.id, extension.pendingPermissions) + ) + if (result?.success) { + toast({ title: '权限已更新', description: extension.name, variant: 'success' }) + await refresh() + } else if (result && !result.success) { + toast({ + title: '授权失败', + description: result.error?.message || '操作失败', + variant: 'destructive' + }) + } + } + + /** 重置损坏的扩展配置;损坏现场已经由存储层另存。 */ + const resetStorage = async (extension: InstalledExtension): Promise => { + const result = await run(() => window.api.resetExtensionStorage(extension.id)) + if (result?.success) { + toast({ title: '配置已重置', description: extension.name, variant: 'success' }) + await refresh() + } else if (result && !result.success) { + toast({ + title: '重置失败', + description: result.error?.message || '操作失败', + variant: 'destructive' + }) + } + } + + const grantPermission = async ( + extension: InstalledExtension, + permission: ExtensionPermission + ): Promise => { + const result = await run(() => window.api.grantExtensionPermissions(extension.id, [permission])) + setPendingGrant(null) + if (result?.success) { + toast({ + title: '已授权', + description: EXTENSION_PERMISSION_INFO[permission].label, + variant: 'success' + }) + await refresh() + } else if (result && !result.success) { + toast({ + title: '授权失败', + description: result.error?.message || '操作失败', + variant: 'destructive' + }) + } + } + + const revokePermission = async ( + extension: InstalledExtension, + permission: ExtensionPermission + ): Promise => { + const result = await run(() => window.api.revokeExtensionPermission(extension.id, permission)) + if (result?.success) { + toast({ + title: '已撤销', + description: EXTENSION_PERMISSION_INFO[permission].label, + variant: 'success' + }) + await refresh() + } else if (result && !result.success) { + toast({ + title: '撤销失败', + description: result.error?.message || '操作失败', + variant: 'destructive' + }) + } + } + + /** 接受从备份恢复出来的配置;之后才允许启用该扩展。 */ + const acknowledgeStorage = async (extension: InstalledExtension): Promise => { + const result = await run(() => window.api.acknowledgeExtensionStorage(extension.id)) + if (result?.success) { + toast({ title: '已接受恢复的配置', description: '现在可以启用该扩展', variant: 'success' }) + await refresh() + } + } + + /** 把状态记录的版本对齐到磁盘上的 manifest。 */ + const adoptInstalledCode = async (extension: InstalledExtension): Promise => { + const result = await run(() => window.api.adoptExtensionCode(extension.id)) + if (result?.success) { + toast({ title: '已采用当前代码版本', description: extension.name, variant: 'success' }) + await refresh() + } + } + + /** 把升级过渡备份换回来。 */ + const rollbackUpgrade = async (extension: InstalledExtension): Promise => { + const result = await run(() => window.api.rollbackExtensionUpgrade(extension.id)) + if (result?.success) { + toast({ title: '已回滚到备份版本', description: extension.name, variant: 'success' }) + await refresh() + } + } + + /** 确认「状态文件曾损坏并恢复」,只清除提示。 */ + const acknowledgeRecovery = async (): Promise => { + const result = await run(() => window.api.acknowledgeExtensionRecovery()) + if (result?.success) await refresh() + } + + const installTemplate = async (templateId: string): Promise => { + setInstallingTemplate(templateId) + try { + const result = await window.api.installExtensionTemplate(templateId) + if (!result.success) { + toast({ + title: '模板安装失败', + description: result.error?.message || '安装失败', + variant: 'destructive' + }) + return + } + await refresh() + setView('extensions') + if (result.extension) setSelectedId(result.extension.id) + toast({ + title: '模板已安装', + description: `${result.extension?.name || ''} 需要你确认权限后手动启用`.trim(), + variant: 'success' + }) + } catch (error) { + toast({ + title: '模板安装失败', + description: error instanceof Error ? error.message : String(error), + variant: 'destructive' + }) + } finally { + setInstallingTemplate(null) + } + } + + /** 链接外部开发项目;目录由主进程再校验一次。 */ + const linkProject = async (): Promise => { + const directory = await window.api.pickExtensionProjectDirectory() + if (!directory) return + const result = await run(() => window.api.linkExtensionDevelopment(directory)) + if (result?.success) { + toast({ + title: '已链接开发项目', + description: '确认权限后即可启用;修改代码后可点「重新加载」', + variant: 'success' + }) + await refresh() + setView('extensions') + if (result.extension) setSelectedId(result.extension.id) + } else if (result && !result.success) { + toast({ + title: '链接失败', + description: result.error?.message || '操作失败', + variant: 'destructive' + }) + } + } + + const submitCreateProject = async (input: { + extensionId: string + name: string + }): Promise => { + const template = creatingTemplate + if (!template) return + const targetDirectory = await window.api.pickExtensionProjectDirectory() + if (!targetDirectory) return + setInstallingTemplate(`create:${template.templateId}`) + try { + const result = await window.api.createExtensionProject({ + templateId: template.templateId, + targetDirectory, + extensionId: input.extensionId, + name: input.name + }) + if (!result.success) { + toast({ + title: '创建项目失败', + description: result.error?.message || '操作失败', + variant: 'destructive' + }) + return + } + setCreatingTemplate(null) + toast({ + title: '项目已生成', + description: result.projectPath || '', + variant: 'success' + }) + await refresh() + } finally { + setInstallingTemplate(null) + } + } + + const reloadDevelopment = async (extension: InstalledExtension): Promise => { + const result = await run(() => window.api.reloadExtensionDevelopment(extension.id)) + if (result?.success) { + toast({ title: '已重新加载', description: extension.name, variant: 'success' }) + } else if (result && !result.success) { + toast({ + title: '重新加载失败', + description: result.error?.message || '操作失败', + variant: 'destructive' + }) + } + await refresh() + } + + const unlinkDevelopment = async (extension: InstalledExtension): Promise => { + const result = await run(() => window.api.unlinkExtensionDevelopment(extension.id, true)) + if (result?.success) { + toast({ + title: '已移除开发链接', + description: '外部源码目录没有被删除', + variant: 'success' + }) + await refresh() + } else if (result && !result.success) { + toast({ + title: '移除失败', + description: result.error?.message || '操作失败', + variant: 'destructive' + }) + } + } + + const convertDevelopment = async (extension: InstalledExtension): Promise => { + const result = await run(() => window.api.convertExtensionDevelopment(extension.id)) + if (result?.success) { + toast({ title: '已转为正式安装', description: extension.name, variant: 'success' }) + await refresh() + } else if (result && !result.success) { + toast({ + title: '转换失败', + description: result.error?.message || '操作失败', + variant: 'destructive' + }) + } + } + + const exportProject = async (extension: InstalledExtension): Promise => { + const targetDirectory = await window.api.pickExtensionProjectDirectory() + if (!targetDirectory) return + const result = await run(() => + window.api.exportExtensionAsProject(extension.id, targetDirectory) + ) + if (result?.success) { + toast({ + title: '已导出为开发项目', + description: result.projectPath || '', + variant: 'success' + }) + await refresh() + } else if (result && !result.success) { + toast({ + title: '导出失败', + description: result.error?.message || '操作失败', + variant: 'destructive' + }) + } + } + + const openDevelopmentSource = async (extension: InstalledExtension): Promise => { + const result = await window.api.openExtensionDevelopmentSource(extension.id) + if (!result.success) { + toast({ + title: '无法打开源码目录', + description: result.error?.message || '目录不可用', + variant: 'destructive' + }) + } + } + if (page) { return ( {extensions.length} + {health && health.registry.state !== 'ok' && ( +
+ + {health.registry.state === 'unreadable' + ? '扩展状态文件损坏且无法恢复,已停止写入以保留现场。请保留 extensions-state 下的损坏文件。' + : health.registry.message || '扩展状态文件曾损坏,已自动恢复。'} + + {health.registry.state !== 'unreadable' && ( + + )} +
+ )} + + +
+ )} +
+ )} + {selected.runtime.note && ( +

{selected.runtime.note}

+ )} {selected.runtime.lastError && ( -

{selected.runtime.lastError}

+
+ {selected.runtime.lastError} + {selected.runtime.lastError.includes('升级可能中断') && ( + <> + + + + )} +
)}
@@ -344,8 +795,107 @@ export function ExtensionWorkspace(): React.ReactElement { )} + {selected.development && ( +
+
+

开发模式

+ + {selected.development.available ? '源码可用' : '源码不可用'} + +
+

+ {selected.development.sourcePath || '未记录源码路径'} +

+ {!selected.development.available && ( +

+ 源码目录被移动或删除。扩展配置与规则都还在,重新链接后即可继续。 +

+ )} + {pendingConvert?.id === selected.id && ( +
+

+ 将把当前源码复制到 TraceMemo + 用户数据目录,之后运行的是这份安装副本。 + 外部源码目录不会被删除,但你之后对它的修改不会 + 自动同步过去。 + 转换会停止当前后台,转换后保持「未启用」;已有配置、规则与缓存都保留。 +

+
+ + +
+
+ )} +
+ + + + +
+
+ )} +
-

权限

+
+

权限

+ {selected.pendingPermissions.length > 0 && ( + + )} +
+ {selected.pendingPermissions.length > 0 && ( +

+ 新版本申请了 {selected.pendingPermissions.length} 项尚未授予的权限,当前不可用。 +

+ )} {selected.permissions.length === 0 ? (

未申请任何权限。

) : ( @@ -367,11 +917,59 @@ export function ExtensionWorkspace(): React.ReactElement {

{EXTENSION_PERMISSION_INFO[permission].description}

- - {selected.grantedPermissions.includes(permission) ? '已授予' : '未授予'} - + {selected.grantedPermissions.includes(permission) ? ( +
+ 已授予 + +
+ ) : ( +
+ +
+ )} + {pendingGrant?.extensionId === selected.id && + pendingGrant.permission === permission && ( +
+ + 该权限可以代替你执行敏感操作,确认授予「 + {EXTENSION_PERMISSION_INFO[permission].label}」? + + + +
+ )} ))} @@ -431,6 +1029,26 @@ export function ExtensionWorkspace(): React.ReactElement {